@10x-media/analytics 1.0.0-beta.15 → 1.0.0-beta.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +1 -1
- package/dist/adapters/ga4/ga4.js +33 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +4 -1
- package/dist/adapters/ga4/measurementId.js.map +1 -1
- package/dist/adapters/ga4/propertyId.js +17 -0
- package/dist/adapters/ga4/propertyId.js.map +1 -0
- package/dist/adapters/http/fetchJson.js +24 -1
- package/dist/adapters/http/fetchJson.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +16 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/plausible/siteId.js +31 -0
- package/dist/adapters/plausible/siteId.js.map +1 -0
- package/dist/adapters/posthog/cloud.js +20 -0
- package/dist/adapters/posthog/cloud.js.map +1 -0
- package/dist/adapters/posthog/credentials.js +20 -0
- package/dist/adapters/posthog/credentials.js.map +1 -0
- package/dist/adapters/posthog/posthog.d.ts +3 -3
- package/dist/adapters/posthog/posthog.js +24 -10
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.js +34 -7
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/contract.d.ts +16 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +1 -1
- package/dist/core/options.js +1 -1
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +62 -14
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceErrors.js +12 -1
- package/dist/core/sourceErrors.js.map +1 -1
- package/dist/core/sourceOptions.js +1 -1
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +8 -1
- package/dist/core/sourcePolicy.js.map +1 -1
- package/dist/core/throttle.js +3 -1
- package/dist/core/throttle.js.map +1 -1
- package/dist/exports/adapters/contract.d.ts +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -2
- package/dist/exports/adapters/native.d.ts +2 -2
- package/dist/exports/adapters/plausible.d.ts +2 -2
- package/dist/exports/adapters/posthog.d.ts +2 -2
- package/dist/exports/adapters/umami.d.ts +2 -2
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/next.d.ts +2 -2
- package/dist/exports/testing.d.ts +2 -2
- package/dist/exports/types.d.ts +3 -3
- package/dist/fields/config/fetchSources.js +1 -1
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/goals/collection.js +3 -2
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +50 -4
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/nativeAdapter.js +1 -1
- package/dist/plugin/createRuntime.js +57 -13
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/pluginCollections.js +4 -1
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/providerStatusEndpoint.js +80 -0
- package/dist/plugin/providerStatusEndpoint.js.map +1 -0
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +4 -3
- package/dist/plugin/readContextForRequest.js +2 -2
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/refreshEndpoint.js +1 -1
- package/dist/plugin/routes.d.ts +5 -0
- package/dist/plugin/routes.js +1 -0
- package/dist/plugin/routes.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/providers/ProviderConnection.d.ts +12 -0
- package/dist/providers/ProviderConnection.js +105 -0
- package/dist/providers/ProviderConnection.js.map +1 -0
- package/dist/providers/ProviderConnectionTest.d.ts +12 -0
- package/dist/providers/ProviderConnectionTest.js +55 -0
- package/dist/providers/ProviderConnectionTest.js.map +1 -0
- package/dist/providers/ProvidersListNotice.d.ts +1 -1
- package/dist/providers/ProvidersListNotice.js +3 -2
- package/dist/providers/ProvidersListNotice.js.map +1 -1
- package/dist/providers/collection.d.ts +1 -1
- package/dist/providers/collection.js +106 -41
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/connectionCheck.d.ts +1 -0
- package/dist/providers/connectionCheck.js +80 -0
- package/dist/providers/connectionCheck.js.map +1 -0
- package/dist/providers/connectionState.js +53 -0
- package/dist/providers/connectionState.js.map +1 -0
- package/dist/providers/factory.d.ts +1 -3
- package/dist/providers/factory.js +18 -21
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/hosts.js +31 -9
- package/dist/providers/hosts.js.map +1 -1
- package/dist/providers/ids.d.ts +6 -0
- package/dist/providers/ids.js +32 -0
- package/dist/providers/ids.js.map +1 -0
- package/dist/providers/providerStatusClient.js +60 -0
- package/dist/providers/providerStatusClient.js.map +1 -0
- package/dist/providers/registry.js +56 -20
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/retarget.js +39 -8
- package/dist/providers/retarget.js.map +1 -1
- package/dist/providers/secrets.d.ts +1 -1
- package/dist/providers/secrets.js.map +1 -1
- package/dist/providers/status.d.ts +1 -0
- package/dist/providers/status.js +181 -0
- package/dist/providers/status.js.map +1 -0
- package/dist/surfacing/classifyError.js +37 -5
- package/dist/surfacing/classifyError.js.map +1 -1
- package/dist/surfacing/engine.js +2 -2
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/lanes.js +29 -22
- package/dist/surfacing/lanes.js.map +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/testing/settle.d.ts +2 -1
- package/dist/testing/settle.js +6 -2
- package/dist/testing/settle.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/translations/ar.js +43 -8
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +43 -8
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +43 -8
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +43 -8
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +43 -8
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +43 -8
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +35 -0
- package/dist/translations/keys.js +35 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +43 -8
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +43 -8
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +43 -8
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +43 -8
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +43 -8
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +63 -0
- package/dist/ui/components/SourcesNoticeBanner.js +4 -3
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -1
- package/dist/view/ViewSections.js +9 -2
- package/dist/view/ViewSections.js.map +1 -1
- package/dist/view/sections/EmptyStates.js +5 -4
- package/dist/view/sections/EmptyStates.js.map +1 -1
- package/dist/view/sections/OverviewCards.js +6 -2
- package/dist/view/sections/OverviewCards.js.map +1 -1
- package/dist/view/sections/SourceConnectionNote.js +56 -0
- package/dist/view/sections/SourceConnectionNote.js.map +1 -0
- package/dist/view/viewProps.d.ts +2 -0
- package/dist/view/viewProps.js +2 -1
- package/dist/view/viewProps.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,61 @@
|
|
|
1
1
|
# @10x-media/analytics
|
|
2
2
|
|
|
3
|
+
## 1.0.0-beta.17
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- **Additive: a Test connection button on provider documents.** The sidebar of a vendor document shows what its connection last came to (Connected, Not connected, No answer, Not checked), when it last worked and failed, the vendor's own words and until when reads rest. A **Test connection** button beside **Save** checks the saved settings with the vendor's cheapest read. Ordinary reads keep the result current. A save that changes how the document connects (a key sent again, another host, ID, provider or scope) clears the result; any other save keeps it. Where the vendor did not word a failure itself (a refused host, a network error), the panel shows translated advice alone, which names what to check for each vendor: the Region for PostHog, the Property ID and the property access for GA4. A reader who may not edit the document sees the button disabled, with the reason in its tooltip, as do a new document and unsaved changes. The analytics view shows the vendor's words under a source's setup error, and when the source last worked, to a reader who may read its document. The result is kept in `payload.kv` under `analytics:provider-status:<document ID>`, so no table and no migration are added, and answered by `GET` and `POST /api/_x/provider-status?id=`, which take the caller's own read and update access to the document. When the plugin knows why a check failed, `errorReason` says so and the panel says it in the admin's language: a key or an ID the check needs is empty (`incomplete`), or the vendor does not know the site (`unknownSite`, self-hosted Umami). Adapters may implement `checkConnection(ctx)` (`ConnectionCheckContext`); every built-in vendor adapter does. Upgrade: run `pnpm payload generate:importmap`, so the provider form renders the Connection panel and its button.
|
|
8
|
+
|
|
9
|
+
- **Behavioral: under a `fallback` policy, a tenant whose own sources all fail reads the shared source.** A provider document that was configured but failing used to switch its tenant off the shared platform source, so one bad key cost the tenant every number. A document now counts as failing while its last result is a refusal, or a vendor that did not answer while its reads rest. While every one of a tenant's documents is failing, the shared source is listed beside them, opens as the default in place of a failing one, and the view and the providers list say why (`notice: 'ownSourceFailing'` on `GET /api/_x/sources`). A document failing for more than 10 minutes is checked again in the background when its tenant's listing is read, at most once every 10 minutes, so it takes its tenant back once it works.
|
|
10
|
+
|
|
11
|
+
- **Behavioral (GA4): Property ID takes the number alone.** `properties/<id>` saved, and every read answered "3 INVALID_ARGUMENT: ... A numeric Property ID is required." The field now refuses it. A stored document with such a value saves again once it is corrected.
|
|
12
|
+
|
|
13
|
+
- **Behavioral: a provider document's Host outside `providers.hosts.allow` is refused on save.** The form saved an address the plugin then refused to call. The **Host** field now says the site does not allow the address. A document saved before keeps reading as refused, and its next save is refused until the Host is changed or allowed. Upgrade: check the Host of every provider document against `providers.hosts.allow`.
|
|
14
|
+
|
|
15
|
+
- **Behavioral (Plausible): Site ID and Website address take the site as Plausible stores it.** An address with `https://`, `www.`, a trailing slash or capital letters saved, and every read answered "Invalid API key or site ID". Both fields now refuse it with a field error; a site in a subfolder (`example.com/blog`) is accepted, and Website address takes several sites separated by commas, each counting the pageview on its own dashboard. A stored document with such a value saves again once it is corrected.
|
|
16
|
+
|
|
17
|
+
- **Additive: a policy function can ask which own sources fail.** Each of `ownSources` carries `failing()`, which resolves to true while the source counts as failing for `'fallback'`. The statuses are read on its first call, so a function that never asks costs no read.
|
|
18
|
+
|
|
19
|
+
- **Behavioral (PostHog): a provider document with a blank Host needs a Region.** The Region then decides where reads and capture go, and leaving it unset used to read from US Cloud without anyone picking it. A stored document without one saves again once a Region is picked. Picking US keeps its personal API key, because reads stay on US Cloud. Picking EU moves the reads, so the key has to be entered again. Upgrade: pick a **Region** on every PostHog provider document whose **Host** is blank ([From 1.0.0-beta.16](https://docs.10xmedia.de/analytics/upgrading/beta-17#posthogs-region)).
|
|
20
|
+
|
|
21
|
+
- **Behavioral: a vendor's error names its own message.** A refused read carries the vendor's JSON `detail`, `message` or `error` rather than the first 200 characters of the body.
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- **Fixed: credential fields are labelled in the reader's language.** The **API key**, **API token** and **Private key** fields kept their English label in every admin language. They now carry a label per locale, as their help already did.
|
|
26
|
+
|
|
27
|
+
- **Fixed: a refused save names the field by its label.** A second **Default for this site** in one site, and a goal slug already taken, toasted "The following field is invalid: isDefault" or "slug". The toast now reads the field's label, in the admin's language.
|
|
28
|
+
|
|
29
|
+
- **Fixed (GA4): a Measurement ID pasted with spaces around it saves.** The field refused it.
|
|
30
|
+
|
|
31
|
+
- **Fixed (GA4): a private key that cannot be parsed reads as a setup error.** A service account key pasted incompletely read as an outage ("The analytics tool is busy right now.") and was retried. It now reads as not set up correctly, as a wrong key does.
|
|
32
|
+
|
|
33
|
+
- **Fixed: a Host that only gains or loses a trailing slash keeps the stored key.** The save counted it as a move to another address and cleared the document's key.
|
|
34
|
+
|
|
35
|
+
- **Fixed (Umami, PostHog): an ID with `/`, `?` or `#` no longer breaks the request path.** Umami's website ID and PostHog's project ID are sent URL-encoded.
|
|
36
|
+
|
|
37
|
+
- **Fixed: provider fields say what to paste and where to find it.** PostHog's **Project ID**, **API key** (a personal `phx_...` key with the Query Read scope) and **Region**, Plausible's **API key** (a Stats API key), GA4's **Project ID**, **Client email** (added as a Viewer on the property) and **Measurement ID** have help text, and every **Host** says it is only for a self-hosted instance. **Region** says it is required when **Host** is blank, and the form's description says that changing the Host, an ID or the Region of a saved entry clears its keys. All 11 locales.
|
|
38
|
+
|
|
39
|
+
- **Fixed: the providers list's notice lines up with the list.** It rendered outside the page's gutter, edge to edge. It now sits inside it.
|
|
40
|
+
|
|
41
|
+
- **Fixed: read failures name their scope.** The engine's `analytics: read failed for adapter "<id>"` warning and the query endpoint's warning now say the scope they read for, or `install-wide`.
|
|
42
|
+
|
|
43
|
+
- **Fixed: an ID or a key pasted with spaces around it reads.** A Plausible Site ID or an Umami Website ID saved with a space before or after it failed every read, and Plausible's answer pointed at the key. Provider documents now read and capture with their IDs, keys and tokens trimmed, stored documents included.
|
|
44
|
+
|
|
45
|
+
- **Fixed (Umami): the key fields say which key goes where.** **API token** said "Umami Cloud token" though it is the self-hosted key, sent as `Bearer`. It now names self-hosted Umami, and **API key** on an Umami document names Umami Cloud, in all 11 locales.
|
|
46
|
+
|
|
47
|
+
- **Fixed (Umami): a Website ID Umami does not know fails the read.** Self-hosted Umami answers the stats of an unknown website with zeros, so the source read as working and showed no visits. The adapter now asks for the website before it reads, until Umami has answered once, and refuses an unknown one. An adapter that `providers.resolve` builds for each read asks on each read.
|
|
48
|
+
|
|
49
|
+
## 1.0.0-beta.16
|
|
50
|
+
|
|
51
|
+
### Minor Changes
|
|
52
|
+
|
|
53
|
+
- **Fixed (PostHog): hourly series read again.** The adapter bucketed hours with `toStartOfHour(timestamp, '<zone>')`, which HogQL refuses ("Function 'toStartOfHour' expects 1 argument, found 2"), so every hourly read failed, the platform source's included, and the today and 24-hour views showed nothing. Hours are now bucketed as `toStartOfHour(toTimeZone(timestamp, '<zone>'))`, still in the reporting timezone. Day series are unchanged.
|
|
54
|
+
|
|
55
|
+
**Behavioral (PostHog): with no `host`, reads go to the region's cloud.** `region` used to steer capture alone, and reads went to US Cloud whenever `host` was unset, so a provider document on EU Cloud with a blank **Host** sent its EU key to `us.posthog.com`, was refused with a 403 and was rested. Reads now go to `https://<region>.posthog.com`, the cloud capture already used; US Cloud stays the default with neither set. A stored document reads from its region as it is: nothing to migrate, and its key is kept.
|
|
56
|
+
|
|
57
|
+
**Additive: a PostHog provider document refuses three paste mistakes.** A **Host** on the other PostHog Cloud region than the **Region** picked, a project token (`phc_...`) in **API key**, and a private key (`phx_...`, `phs_...`) in **Project token**, which the browser receives, are refused with a field error in all 11 locales.
|
|
58
|
+
|
|
3
59
|
## 1.0.0-beta.15
|
|
4
60
|
|
|
5
61
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Analytics for Payload v3 behind one adapter contract: a self-hosted native engin
|
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/@10x-media/analytics)
|
|
8
8
|
|
|
9
|
-
Part of the [@10x-media Payload plugins](https://github.com/10x-media/payload-plugins) collection. In beta:
|
|
9
|
+
Part of the [@10x-media Payload plugins](https://github.com/10x-media/payload-plugins) collection. In beta until a stable 1.0: `-beta.N` releases on the `latest` dist-tag.
|
|
10
10
|
|
|
11
11
|
## What it does
|
|
12
12
|
|
package/dist/adapters/ga4/ga4.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { DIMENSION_KEYS } from "../../core/contract.js";
|
|
2
|
+
import { SourceMisconfiguredError } from "../../core/sourceErrors.js";
|
|
2
3
|
import { adapterLabel } from "../../core/sourceLabel.js";
|
|
3
4
|
import { jsLiteral } from "../../capture/jsLiteral.js";
|
|
4
5
|
import { WITHOUT_CONSENT_LEVELS, adapterWithoutConsent, cookielessCapture } from "../../capture/withoutConsent.js";
|
|
5
6
|
import { MEASUREMENT_ID_PATTERN } from "./measurementId.js";
|
|
6
7
|
import { CURRENCY_PATTERN, currencyOption } from "../../goals/currency.js";
|
|
7
|
-
import { vendorReading } from "../../core/metricValues.js";
|
|
8
8
|
import { GA4_SDK_WARNING, isProductionBuild, loadGa4 } from "../../plugin/peers.js";
|
|
9
|
+
import { vendorReading } from "../../core/metricValues.js";
|
|
9
10
|
import { emptyGoalBreakdown, goalHint, hintSlugs, mergeGoalRows, mergeGoalTotals, readGoalPair, splitGoalMetrics } from "../goalRead.js";
|
|
10
11
|
import { calendarDays, declaredFilters, everyOperatorOn, mappedKeys, providerMetricKeys, readableMetrics } from "../mapping.js";
|
|
11
12
|
import { readTime } from "../readTime.js";
|
|
@@ -14,6 +15,20 @@ import { upstream } from "../upstream.js";
|
|
|
14
15
|
import { ga4ExcludeGuard } from "./disableKey.js";
|
|
15
16
|
import { ga4EventName } from "./eventName.js";
|
|
16
17
|
//#region src/adapters/ga4/ga4.ts
|
|
18
|
+
/**
|
|
19
|
+
* Awaits a Data API call, answering a private key OpenSSL cannot read as a setup to fix: gRPC
|
|
20
|
+
* reports it as UNKNOWN from its metadata plugin, a code that otherwise reads as an outage. A key
|
|
21
|
+
* Google refuses (deleted, or another account's) answers UNAUTHENTICATED, refused already.
|
|
22
|
+
*/
|
|
23
|
+
const keyChecked = async (call) => {
|
|
24
|
+
try {
|
|
25
|
+
return await call;
|
|
26
|
+
} catch (err) {
|
|
27
|
+
const message = err instanceof Error ? err.message : "";
|
|
28
|
+
if (message.includes("Getting metadata from plugin failed") && message.includes("DECODER routines")) throw new SourceMisconfiguredError("ga4: the private key cannot be read; paste it again from the service account file", { cause: err });
|
|
29
|
+
throw err;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
17
32
|
/** How long one report may take when the adapter is called outside the engine, which sets its own. */
|
|
18
33
|
const DEFAULT_REPORT_TIMEOUT_MS = 6e4;
|
|
19
34
|
/**
|
|
@@ -258,6 +273,22 @@ function ga4(config) {
|
|
|
258
273
|
}, withoutConsent)
|
|
259
274
|
} } : {},
|
|
260
275
|
isConfigured: () => Boolean(config.propertyId && config.credentials?.client_email && config.credentials?.private_key),
|
|
276
|
+
async checkConnection(ctx) {
|
|
277
|
+
const call = (await getClient(ctx.payload)).runReport({
|
|
278
|
+
property: `properties/${config.propertyId}`,
|
|
279
|
+
dateRanges: [{
|
|
280
|
+
startDate: "today",
|
|
281
|
+
endDate: "today"
|
|
282
|
+
}],
|
|
283
|
+
metrics: [{ name: "activeUsers" }],
|
|
284
|
+
limit: 1
|
|
285
|
+
}, {
|
|
286
|
+
timeout: ctx.timeoutMs,
|
|
287
|
+
retry: null
|
|
288
|
+
});
|
|
289
|
+
cancelWhenAborted(call, ctx.signal);
|
|
290
|
+
await keyChecked(call);
|
|
291
|
+
},
|
|
261
292
|
register(_config, context) {
|
|
262
293
|
pluginSdk = context?.sdks?.ga4;
|
|
263
294
|
},
|
|
@@ -341,7 +372,7 @@ function ga4(config) {
|
|
|
341
372
|
retry: null
|
|
342
373
|
});
|
|
343
374
|
cancelWhenAborted(call, signal);
|
|
344
|
-
const [response] = await call;
|
|
375
|
+
const [response] = await keyChecked(call);
|
|
345
376
|
if ((response.metadata?.samplingMetadatas?.length ?? 0) > 0) sampled = true;
|
|
346
377
|
const code = response.metadata?.currencyCode?.toUpperCase();
|
|
347
378
|
if (code && CURRENCY_PATTERN.test(code)) reportedCurrency = code;
|
|
@@ -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 {\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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U,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\ttype ConnectionCheckContext,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport { vendorReading } from '../../core/metricValues'\nimport type { Ga4Client, Ga4ReportResponse, Ga4ReportRow, Ga4Sdk } from '../../core/sdks'\nimport { SourceMisconfiguredError } from '../../core/sourceErrors'\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/**\n * Awaits a Data API call, answering a private key OpenSSL cannot read as a setup to fix: gRPC\n * reports it as UNKNOWN from its metadata plugin, a code that otherwise reads as an outage. A key\n * Google refuses (deleted, or another account's) answers UNAUTHENTICATED, refused already.\n */\nconst keyChecked = async <T>(call: Promise<T>): Promise<T> => {\n\ttry {\n\t\treturn await call\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : ''\n\t\tif (\n\t\t\tmessage.includes('Getting metadata from plugin failed') &&\n\t\t\tmessage.includes('DECODER routines')\n\t\t) {\n\t\t\tthrow new SourceMisconfiguredError(\n\t\t\t\t'ga4: the private key cannot be read; paste it again from the service account file',\n\t\t\t\t{ cause: err }\n\t\t\t)\n\t\t}\n\t\tthrow err\n\t}\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\t// The smallest report GA4 serves: one metric, one day, one row, a few quota tokens.\n\t\tasync checkConnection(ctx: ConnectionCheckContext): Promise<void> {\n\t\t\tconst client = await getClient(ctx.payload)\n\t\t\tconst call = client.runReport(\n\t\t\t\t{\n\t\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\t\tdateRanges: [{ startDate: 'today', endDate: 'today' }],\n\t\t\t\t\tmetrics: [{ name: 'activeUsers' }],\n\t\t\t\t\tlimit: 1,\n\t\t\t\t},\n\t\t\t\t{ timeout: ctx.timeoutMs, retry: null }\n\t\t\t)\n\t\t\tcancelWhenAborted(call, ctx.signal)\n\t\t\tawait keyChecked(call)\n\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 keyChecked(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":";;;;;;;;;;;;;;;;;;;;;;AAiGA,MAAM,aAAa,OAAU,SAAiC;CAC7D,IAAI;EACH,OAAO,MAAM;CACd,SAAS,KAAK;EACb,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU;EACrD,IACC,QAAQ,SAAS,qCAAqC,KACtD,QAAQ,SAAS,kBAAkB,GAEnC,MAAM,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,OAAO;KACN,MAAM,UAAU,OAAO,MAAM,SAAS;KACtC,QAAQ,OAAO,UAAU,CAAC;KAC1B,MAAM,KAAK;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"}
|
|
@@ -7,7 +7,10 @@ const MEASUREMENT_ID_PATTERN = /^[A-Za-z0-9-]+$/;
|
|
|
7
7
|
* Validates the id as the adapter admits it, without loading the adapter's `@google-analytics/data`
|
|
8
8
|
* peer. Empty passes: the id is optional and only turns capture on.
|
|
9
9
|
*/
|
|
10
|
-
const validateMeasurementId = (value, { req }) =>
|
|
10
|
+
const validateMeasurementId = (value, { req }) => {
|
|
11
|
+
const id = value?.trim();
|
|
12
|
+
return !id || MEASUREMENT_ID_PATTERN.test(id) ? true : asTranslate(req.t)(keys.providerErrorMeasurementId);
|
|
13
|
+
};
|
|
11
14
|
//#endregion
|
|
12
15
|
export { MEASUREMENT_ID_PATTERN, validateMeasurementId };
|
|
13
16
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"measurementId.js","names":[],"sources":["../../../src/adapters/ga4/measurementId.ts"],"sourcesContent":["import type { TextFieldSingleValidation } from 'payload'\nimport { keys } from '../../translations/keys'\nimport { asTranslate } from '../../translations/server'\n\n/** What Google's own ids look like, and all the inline snippet and the tag URL may carry. */\nexport const MEASUREMENT_ID_PATTERN = /^[A-Za-z0-9-]+$/\n\n/**\n * Validates the id as the adapter admits it, without loading the adapter's `@google-analytics/data`\n * peer. Empty passes: the id is optional and only turns capture on.\n */\nexport const validateMeasurementId: TextFieldSingleValidation = (value, { req })
|
|
1
|
+
{"version":3,"file":"measurementId.js","names":[],"sources":["../../../src/adapters/ga4/measurementId.ts"],"sourcesContent":["import type { TextFieldSingleValidation } from 'payload'\nimport { keys } from '../../translations/keys'\nimport { asTranslate } from '../../translations/server'\n\n/** What Google's own ids look like, and all the inline snippet and the tag URL may carry. */\nexport const MEASUREMENT_ID_PATTERN = /^[A-Za-z0-9-]+$/\n\n/**\n * Validates the id as the adapter admits it, without loading the adapter's `@google-analytics/data`\n * peer. Empty passes: the id is optional and only turns capture on.\n */\nexport const validateMeasurementId: TextFieldSingleValidation = (value, { req }) => {\n\tconst id = value?.trim()\n\treturn !id || MEASUREMENT_ID_PATTERN.test(id)\n\t\t? true\n\t\t: asTranslate(req.t)(keys.providerErrorMeasurementId)\n}\n"],"mappings":";;;;AAKA,MAAa,yBAAyB;;;;;AAMtC,MAAa,yBAAoD,OAAO,EAAE,UAAU;CACnF,MAAM,KAAK,OAAO,KAAK;CACvB,OAAO,CAAC,MAAM,uBAAuB,KAAK,EAAE,IACzC,OACA,YAAY,IAAI,CAAC,EAAE,KAAK,0BAA0B;AACtD"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { keys } from "../../translations/keys.js";
|
|
2
|
+
import { asTranslate } from "../../translations/server.js";
|
|
3
|
+
//#region src/adapters/ga4/propertyId.ts
|
|
4
|
+
/**
|
|
5
|
+
* A GA4 property as the Data API takes it: the number alone. `properties/<id>` saves fine but every
|
|
6
|
+
* read answers "3 INVALID_ARGUMENT: ... A numeric Property ID is required".
|
|
7
|
+
*/
|
|
8
|
+
const PROPERTY_ID_PATTERN = /^\d+$/;
|
|
9
|
+
/** Empty is allowed: the field is optional. */
|
|
10
|
+
const validatePropertyId = (value, { req }) => {
|
|
11
|
+
const id = value?.trim();
|
|
12
|
+
return !id || PROPERTY_ID_PATTERN.test(id) ? true : asTranslate(req.t)(keys.providerErrorPropertyId);
|
|
13
|
+
};
|
|
14
|
+
//#endregion
|
|
15
|
+
export { validatePropertyId };
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=propertyId.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"propertyId.js","names":[],"sources":["../../../src/adapters/ga4/propertyId.ts"],"sourcesContent":["import type { TextFieldSingleValidation } from 'payload'\nimport { keys } from '../../translations/keys'\nimport { asTranslate } from '../../translations/server'\n\n/**\n * A GA4 property as the Data API takes it: the number alone. `properties/<id>` saves fine but every\n * read answers \"3 INVALID_ARGUMENT: ... A numeric Property ID is required\".\n */\nconst PROPERTY_ID_PATTERN = /^\\d+$/\n\n/** Empty is allowed: the field is optional. */\nexport const validatePropertyId: TextFieldSingleValidation = (value, { req }) => {\n\tconst id = value?.trim()\n\treturn !id || PROPERTY_ID_PATTERN.test(id)\n\t\t? true\n\t\t: asTranslate(req.t)(keys.providerErrorPropertyId)\n}\n"],"mappings":";;;;;;;AAQA,MAAM,sBAAsB;;AAG5B,MAAa,sBAAiD,OAAO,EAAE,UAAU;CAChF,MAAM,KAAK,OAAO,KAAK;CACvB,OAAO,CAAC,MAAM,oBAAoB,KAAK,EAAE,IACtC,OACA,YAAY,IAAI,CAAC,EAAE,KAAK,uBAAuB;AACnD"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isRecord } from "../../core/values.js";
|
|
1
2
|
import { BREAKER_MAX_MS } from "../../surfacing/breaker.js";
|
|
2
3
|
//#region src/adapters/http/fetchJson.ts
|
|
3
4
|
var ProviderHttpError = class extends Error {
|
|
@@ -24,6 +25,28 @@ const parseRetryAfter = (value, now = Date.now()) => {
|
|
|
24
25
|
const at = /[a-z]/i.test(text) ? Date.parse(text) : NaN;
|
|
25
26
|
return Number.isNaN(at) ? void 0 : Math.min(Math.max(0, at - now), BREAKER_MAX_MS);
|
|
26
27
|
};
|
|
28
|
+
/** The keys vendors put their message under: PostHog `detail`, Plausible and Umami `error`. */
|
|
29
|
+
const MESSAGE_KEYS = [
|
|
30
|
+
"detail",
|
|
31
|
+
"message",
|
|
32
|
+
"error"
|
|
33
|
+
];
|
|
34
|
+
const textOf = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
35
|
+
/** A vendor's own words in an error body: its JSON message when it sent one, else the body. */
|
|
36
|
+
const vendorMessageOf = (body) => {
|
|
37
|
+
let parsed;
|
|
38
|
+
try {
|
|
39
|
+
parsed = JSON.parse(body);
|
|
40
|
+
} catch {
|
|
41
|
+
return body.trim();
|
|
42
|
+
}
|
|
43
|
+
if (isRecord(parsed)) for (const key of MESSAGE_KEYS) {
|
|
44
|
+
const value = parsed[key];
|
|
45
|
+
const found = textOf(value) ?? (isRecord(value) ? textOf(value.message) : void 0);
|
|
46
|
+
if (found) return found;
|
|
47
|
+
}
|
|
48
|
+
return body.trim();
|
|
49
|
+
};
|
|
27
50
|
/**
|
|
28
51
|
* Thin JSON fetch used by provider adapters. Throws ProviderHttpError (carrying the status and
|
|
29
52
|
* any `Retry-After`) on a non-2xx response; the surfacing engine owns retries, pauses and caching.
|
|
@@ -41,7 +64,7 @@ const fetchJson = async (url, opts) => {
|
|
|
41
64
|
});
|
|
42
65
|
if (!res.ok) {
|
|
43
66
|
const retryAfterMs = parseRetryAfter(res.headers.get("retry-after"));
|
|
44
|
-
const detail = await res.text().catch(() => "");
|
|
67
|
+
const detail = vendorMessageOf(await res.text().catch(() => ""));
|
|
45
68
|
throw new ProviderHttpError(res.status, opts.provider, {
|
|
46
69
|
message: `${opts.provider}: HTTP ${res.status} ${detail.slice(0, 200)}`,
|
|
47
70
|
...retryAfterMs === void 0 ? {} : { retryAfterMs }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchJson.js","names":[],"sources":["../../../src/adapters/http/fetchJson.ts"],"sourcesContent":["import type { FetchLike } from '../../core/fetch'\nimport { BREAKER_MAX_MS } from '../../surfacing/breaker'\n\nexport class ProviderHttpError extends Error {\n\treadonly status: number\n\treadonly provider: string\n\t/** The vendor's `Retry-After`, in milliseconds from when the answer arrived; absent when it sent none. */\n\treadonly retryAfterMs?: number\n\tconstructor(\n\t\tstatus: number,\n\t\tprovider: string,\n\t\tdetail: string | { message: string; retryAfterMs?: number }\n\t) {\n\t\tsuper(typeof detail === 'string' ? detail : detail.message)\n\t\tthis.name = 'ProviderHttpError'\n\t\tthis.status = status\n\t\tthis.provider = provider\n\t\tif (typeof detail !== 'string' && detail.retryAfterMs !== undefined) {\n\t\t\tthis.retryAfterMs = detail.retryAfterMs\n\t\t}\n\t}\n}\n\n/**\n * A `Retry-After` (whole seconds or an HTTP date) in ms from `now`, capped at the breaker's longest\n * wait; anything else reads as absent. `now` is the real clock: the vendor stamped the date.\n */\nexport const parseRetryAfter = (\n\tvalue: string | null | undefined,\n\tnow: number = Date.now()\n): number | undefined => {\n\tconst text = value?.trim()\n\tif (!text) {\n\t\treturn undefined\n\t}\n\tif (/^\\d+$/.test(text)) {\n\t\treturn Math.min(Number(text) * 1000, BREAKER_MAX_MS)\n\t}\n\t// Every HTTP date form names its month in letters; a bare number Date.parse would read as a year.\n\tconst at = /[a-z]/i.test(text) ? Date.parse(text) : Number.NaN\n\treturn Number.isNaN(at) ? undefined : Math.min(Math.max(0, at - now), BREAKER_MAX_MS)\n}\n\nexport interface FetchJsonOptions {\n\tmethod?: 'GET' | 'POST'\n\theaders?: Record<string, string>\n\tbody?: unknown\n\tsignal?: AbortSignal\n\tprovider: string\n\t/** Reaches the vendor; the global fetch unless the adapter was handed another. */\n\tfetch?: FetchLike\n}\n\n/**\n * Thin JSON fetch used by provider adapters. Throws ProviderHttpError (carrying the status and\n * any `Retry-After`) on a non-2xx response; the surfacing engine owns retries, pauses and caching.\n * The body is taken as `T` unchecked, so `T` states the vendor's documented answer.\n */\nexport const fetchJson = async <T>(url: string, opts: FetchJsonOptions): Promise<T> => {\n\tconst send: FetchLike = opts.fetch ?? fetch\n\tconst res = await send(url, {\n\t\tmethod: opts.method ?? 'GET',\n\t\theaders: {\n\t\t\t...(opts.body === undefined ? {} : { 'content-type': 'application/json' }),\n\t\t\t...opts.headers,\n\t\t},\n\t\tbody: opts.body === undefined ? undefined : JSON.stringify(opts.body),\n\t\tsignal: opts.signal,\n\t})\n\tif (!res.ok) {\n\t\tconst retryAfterMs = parseRetryAfter(res.headers.get('retry-after'))\n\t\tconst detail = await res.text().catch(() => '')\n\t\tthrow new ProviderHttpError(res.status, opts.provider, {\n\t\t\tmessage: `${opts.provider}: HTTP ${res.status} ${detail.slice(0, 200)}`,\n\t\t\t...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n\t\t})\n\t}\n\treturn (await res.json()) as T\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"fetchJson.js","names":[],"sources":["../../../src/adapters/http/fetchJson.ts"],"sourcesContent":["import type { FetchLike } from '../../core/fetch'\nimport { isRecord } from '../../core/values'\nimport { BREAKER_MAX_MS } from '../../surfacing/breaker'\n\nexport class ProviderHttpError extends Error {\n\treadonly status: number\n\treadonly provider: string\n\t/** The vendor's `Retry-After`, in milliseconds from when the answer arrived; absent when it sent none. */\n\treadonly retryAfterMs?: number\n\tconstructor(\n\t\tstatus: number,\n\t\tprovider: string,\n\t\tdetail: string | { message: string; retryAfterMs?: number }\n\t) {\n\t\tsuper(typeof detail === 'string' ? detail : detail.message)\n\t\tthis.name = 'ProviderHttpError'\n\t\tthis.status = status\n\t\tthis.provider = provider\n\t\tif (typeof detail !== 'string' && detail.retryAfterMs !== undefined) {\n\t\t\tthis.retryAfterMs = detail.retryAfterMs\n\t\t}\n\t}\n}\n\n/**\n * A `Retry-After` (whole seconds or an HTTP date) in ms from `now`, capped at the breaker's longest\n * wait; anything else reads as absent. `now` is the real clock: the vendor stamped the date.\n */\nexport const parseRetryAfter = (\n\tvalue: string | null | undefined,\n\tnow: number = Date.now()\n): number | undefined => {\n\tconst text = value?.trim()\n\tif (!text) {\n\t\treturn undefined\n\t}\n\tif (/^\\d+$/.test(text)) {\n\t\treturn Math.min(Number(text) * 1000, BREAKER_MAX_MS)\n\t}\n\t// Every HTTP date form names its month in letters; a bare number Date.parse would read as a year.\n\tconst at = /[a-z]/i.test(text) ? Date.parse(text) : Number.NaN\n\treturn Number.isNaN(at) ? undefined : Math.min(Math.max(0, at - now), BREAKER_MAX_MS)\n}\n\n/** The keys vendors put their message under: PostHog `detail`, Plausible and Umami `error`. */\nconst MESSAGE_KEYS = ['detail', 'message', 'error'] as const\n\nconst textOf = (value: unknown): string | undefined =>\n\ttypeof value === 'string' && value.trim() !== '' ? value.trim() : undefined\n\n/** A vendor's own words in an error body: its JSON message when it sent one, else the body. */\nconst vendorMessageOf = (body: string): string => {\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(body)\n\t} catch {\n\t\treturn body.trim()\n\t}\n\tif (isRecord(parsed)) {\n\t\tfor (const key of MESSAGE_KEYS) {\n\t\t\tconst value = parsed[key]\n\t\t\tconst found = textOf(value) ?? (isRecord(value) ? textOf(value.message) : undefined)\n\t\t\tif (found) {\n\t\t\t\treturn found\n\t\t\t}\n\t\t}\n\t}\n\treturn body.trim()\n}\n\nexport interface FetchJsonOptions {\n\tmethod?: 'GET' | 'POST'\n\theaders?: Record<string, string>\n\tbody?: unknown\n\tsignal?: AbortSignal\n\tprovider: string\n\t/** Reaches the vendor; the global fetch unless the adapter was handed another. */\n\tfetch?: FetchLike\n}\n\n/**\n * Thin JSON fetch used by provider adapters. Throws ProviderHttpError (carrying the status and\n * any `Retry-After`) on a non-2xx response; the surfacing engine owns retries, pauses and caching.\n * The body is taken as `T` unchecked, so `T` states the vendor's documented answer.\n */\nexport const fetchJson = async <T>(url: string, opts: FetchJsonOptions): Promise<T> => {\n\tconst send: FetchLike = opts.fetch ?? fetch\n\tconst res = await send(url, {\n\t\tmethod: opts.method ?? 'GET',\n\t\theaders: {\n\t\t\t...(opts.body === undefined ? {} : { 'content-type': 'application/json' }),\n\t\t\t...opts.headers,\n\t\t},\n\t\tbody: opts.body === undefined ? undefined : JSON.stringify(opts.body),\n\t\tsignal: opts.signal,\n\t})\n\tif (!res.ok) {\n\t\tconst retryAfterMs = parseRetryAfter(res.headers.get('retry-after'))\n\t\tconst detail = vendorMessageOf(await res.text().catch(() => ''))\n\t\tthrow new ProviderHttpError(res.status, opts.provider, {\n\t\t\tmessage: `${opts.provider}: HTTP ${res.status} ${detail.slice(0, 200)}`,\n\t\t\t...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n\t\t})\n\t}\n\treturn (await res.json()) as T\n}\n"],"mappings":";;;AAIA,IAAa,oBAAb,cAAuC,MAAM;CAC5C;CACA;;CAEA;CACA,YACC,QACA,UACA,QACC;EACD,MAAM,OAAO,WAAW,WAAW,SAAS,OAAO,OAAO;EAC1D,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,IAAI,OAAO,WAAW,YAAY,OAAO,iBAAiB,KAAA,GACzD,KAAK,eAAe,OAAO;CAE7B;AACD;;;;;AAMA,MAAa,mBACZ,OACA,MAAc,KAAK,IAAI,MACC;CACxB,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,CAAC,MACJ;CAED,IAAI,QAAQ,KAAK,IAAI,GACpB,OAAO,KAAK,IAAI,OAAO,IAAI,IAAI,KAAM,cAAc;CAGpD,MAAM,KAAK,SAAS,KAAK,IA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GACpE,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa;EACtD,CAAC;CACF;CACA,OAAQ,MAAM,IAAI,KAAK;AACxB"}
|
|
@@ -4,13 +4,14 @@ import { jsLiteral } from "../../capture/jsLiteral.js";
|
|
|
4
4
|
import { WITHOUT_CONSENT_LEVELS, adapterWithoutConsent, cookielessCapture } from "../../capture/withoutConsent.js";
|
|
5
5
|
import { isScriptId } from "./scriptId.js";
|
|
6
6
|
import { currencyOption } from "../../goals/currency.js";
|
|
7
|
+
import { withoutTrailingSlash } from "../http/baseUrl.js";
|
|
7
8
|
import { vendorReading } from "../../core/metricValues.js";
|
|
8
9
|
import { emptyGoalBreakdown, goalHint, hintSlugs, mergeGoalRows, readGoalPair, splitGoalMetrics } from "../goalRead.js";
|
|
9
10
|
import { calendarDays, declaredFilters, everyOperatorOn, mappedKeys, providerMetricKeys, readableMetrics } from "../mapping.js";
|
|
10
11
|
import { readTime } from "../readTime.js";
|
|
11
12
|
import { datedRows, dayIso } from "../series.js";
|
|
13
|
+
import { fetchJson } from "../http/fetchJson.js";
|
|
12
14
|
import { upstreamJson } from "../upstream.js";
|
|
13
|
-
import { withoutTrailingSlash } from "../http/baseUrl.js";
|
|
14
15
|
//#region src/adapters/plausible/plausible.ts
|
|
15
16
|
const PLAUSIBLE_CLOUD = "https://plausible.io";
|
|
16
17
|
/**
|
|
@@ -176,6 +177,20 @@ function plausible(config) {
|
|
|
176
177
|
capabilities,
|
|
177
178
|
...config.domain || scriptId ? { capture: buildCapture(config, scriptId, withoutConsent) } : {},
|
|
178
179
|
isConfigured: () => Boolean(config.siteId && config.apiKey),
|
|
180
|
+
async checkConnection(ctx) {
|
|
181
|
+
await fetchJson(`${host}/api/v2/query`, {
|
|
182
|
+
method: "POST",
|
|
183
|
+
headers: { authorization: `Bearer ${config.apiKey}` },
|
|
184
|
+
body: {
|
|
185
|
+
site_id: config.siteId,
|
|
186
|
+
metrics: ["visitors"],
|
|
187
|
+
date_range: "day"
|
|
188
|
+
},
|
|
189
|
+
provider: "plausible",
|
|
190
|
+
signal: ctx.signal,
|
|
191
|
+
...config.fetch ? { fetch: config.fetch } : {}
|
|
192
|
+
});
|
|
193
|
+
},
|
|
179
194
|
async query(q, ctx) {
|
|
180
195
|
const fetchedAt = readTime(ctx);
|
|
181
196
|
const dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d]);
|
|
@@ -1 +1 @@
|
|
|
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,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;EAC5B,GAAG,kBAAkB,EAAE,MAAM,WAAW,GAAG,cAAc;CAC1D;AACD;AAEA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,eAAe;CACf,QAAQ;CACR,aAAa;CAGb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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\ttype ConnectionCheckContext,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { 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 { fetchJson } from '../http/fetchJson'\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 checkConnection(ctx: ConnectionCheckContext): Promise<void> {\n\t\t\tawait fetchJson<unknown>(`${host}/api/v2/query`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\tbody: { site_id: config.siteId, metrics: ['visitors'], date_range: 'day' },\n\t\t\t\tprovider: 'plausible',\n\t\t\t\tsignal: ctx.signal,\n\t\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t\t})\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst 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":";;;;;;;;;;;;;;;AA0FA,MAAM,kBAAkB;;;;;AAMxB,MAAM,iBACL;AAED,SAAS,aACR,QACA,UACA,gBACiB;CACjB,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;EAC5B,GAAG,kBAAkB,EAAE,MAAM,WAAW,GAAG,cAAc;CAC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,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"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { keys } from "../../translations/keys.js";
|
|
2
|
+
import { asTranslate } from "../../translations/server.js";
|
|
3
|
+
//#region src/adapters/plausible/siteId.ts
|
|
4
|
+
/** Segments of letters, digits, dots and hyphens in any script, slash-separated for a subfolder site. */
|
|
5
|
+
const SITE_DOMAIN_PATTERN = /^[\p{L}\p{N}.-]+(?:\/[\p{L}\p{N}.-]+)*$/u;
|
|
6
|
+
/**
|
|
7
|
+
* A Plausible site as Plausible stores it: lowercase, without a scheme, `www.` or a trailing slash,
|
|
8
|
+
* a subfolder site with its path (`example.com/blog`). Plausible's own form strips the rest, so a
|
|
9
|
+
* pasted address saves here but every read answers "Invalid API key or site ID". Empty is allowed:
|
|
10
|
+
* the field is optional.
|
|
11
|
+
*/
|
|
12
|
+
const validateSiteDomain = (value, { req }) => {
|
|
13
|
+
const site = value?.trim();
|
|
14
|
+
return !site || SITE_DOMAIN_PATTERN.test(site) && site === site.toLowerCase() && !site.startsWith("www.") ? true : asTranslate(req.t)(keys.providerErrorSiteDomain);
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The Website address the tracker sends to: one site, or several separated by commas, each counting
|
|
18
|
+
* the pageview on its own dashboard. Each one follows {@link validateSiteDomain}.
|
|
19
|
+
*/
|
|
20
|
+
const validateSiteDomains = (value, args) => {
|
|
21
|
+
if (!value?.trim()) return true;
|
|
22
|
+
for (const site of value.split(",")) {
|
|
23
|
+
const valid = site.trim() !== "" && validateSiteDomain(site, args);
|
|
24
|
+
if (valid !== true) return valid || asTranslate(args.req.t)(keys.providerErrorSiteDomain);
|
|
25
|
+
}
|
|
26
|
+
return true;
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
export { validateSiteDomain, validateSiteDomains };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=siteId.js.map
|