@10x-media/analytics 1.0.0-beta.6 → 1.0.0-beta.7
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 +25 -0
- package/README.md +5 -1
- package/dist/adapters/http/fetchJson.js +1 -1
- package/dist/adapters/plausible/plausible.d.ts +10 -0
- package/dist/adapters/plausible/plausible.js +40 -0
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.d.ts +10 -1
- package/dist/adapters/posthog/posthog.js +47 -0
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +5 -1
- package/dist/adapters/umami/umami.js +26 -0
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/getTrackerConfig.d.ts +20 -0
- package/dist/capture/getTrackerConfig.js +31 -0
- package/dist/capture/getTrackerConfig.js.map +1 -0
- package/dist/capture/mountPath.js +14 -0
- package/dist/capture/mountPath.js.map +1 -0
- package/dist/capture/proxyEndpoint.js +123 -0
- package/dist/capture/proxyEndpoint.js.map +1 -0
- package/dist/capture/proxyRoutes.js +108 -0
- package/dist/capture/proxyRoutes.js.map +1 -0
- package/dist/capture/requestBody.js +68 -0
- package/dist/capture/requestBody.js.map +1 -0
- package/dist/capture/slots.d.ts +8 -0
- package/dist/capture/slots.js +43 -0
- package/dist/capture/slots.js.map +1 -0
- package/dist/capture/trackerConfig.d.ts +32 -0
- package/dist/capture/trackerConfig.js +70 -0
- package/dist/capture/trackerConfig.js.map +1 -0
- package/dist/capture/trackerEndpoint.js +35 -0
- package/dist/capture/trackerEndpoint.js.map +1 -0
- package/dist/core/capture.d.ts +49 -0
- package/dist/core/contract.d.ts +26 -2
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +97 -2
- package/dist/core/options.js +63 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/registry.d.ts +1 -0
- package/dist/core/scopeList.js +32 -0
- package/dist/core/scopeList.js.map +1 -0
- package/dist/core/scopedRead.js +13 -6
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/exports/next.d.ts +2 -1
- package/dist/exports/next.js +2 -1
- package/dist/exports/react.d.ts +4 -0
- package/dist/exports/react.js +5 -0
- package/dist/exports/rsc.d.ts +4 -1
- package/dist/exports/rsc.js +3 -1
- package/dist/exports/tracker.d.ts +18 -0
- package/dist/exports/tracker.js +12 -0
- package/dist/exports/types.d.ts +5 -2
- package/dist/fields/AnalyticsPanelClient.js +1 -1
- package/dist/fields/config/narrow.js +2 -0
- package/dist/fields/config/narrow.js.map +1 -1
- package/dist/fields/readForDocument.js +1 -1
- package/dist/goals/match.js +64 -0
- package/dist/goals/match.js.map +1 -0
- package/dist/goals/types.d.ts +33 -0
- package/dist/goals/types.js +7 -0
- package/dist/goals/types.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +33 -9
- package/dist/index.js.map +1 -1
- package/dist/native/collections/events.js +21 -1
- package/dist/native/collections/events.js.map +1 -1
- package/dist/native/collections/rollups.js +24 -0
- package/dist/native/collections/rollups.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +2 -4
- package/dist/native/geo/maxmindResolver.js.map +1 -1
- package/dist/native/ingest/clientIp.js +15 -0
- package/dist/native/ingest/clientIp.js.map +1 -0
- package/dist/native/ingest/endpoint.js +40 -4
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/flushBatch.js +4 -13
- package/dist/native/ingest/flushBatch.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.js +76 -9
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/nativeAdapter.js +20 -4
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/query/eventAgg.js +39 -13
- package/dist/native/query/eventAgg.js.map +1 -1
- package/dist/native/rollupAcc.js +12 -1
- package/dist/native/rollupAcc.js.map +1 -1
- package/dist/native/rollups/bumpRollup.js +5 -1
- package/dist/native/rollups/bumpRollup.js.map +1 -1
- package/dist/native/rollups/deltas.js +28 -6
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/next/captureRewrites.d.ts +41 -0
- package/dist/next/captureRewrites.js +56 -0
- package/dist/next/captureRewrites.js.map +1 -0
- package/dist/next/posthogProxyRewrites.d.ts +5 -0
- package/dist/next/posthogProxyRewrites.js +16 -21
- package/dist/next/posthogProxyRewrites.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +1 -1
- package/dist/plugin/paths.js +11 -1
- package/dist/plugin/paths.js.map +1 -1
- package/dist/plugin/runtime.d.ts +1 -0
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/sourcesEndpoint.js +16 -4
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/plugin/warmTask.js +0 -0
- package/dist/plugin/warmTask.js.map +1 -1
- package/dist/providers/collection.js +56 -16
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.js +8 -2
- package/dist/providers/factory.js.map +1 -1
- package/dist/react/AnalyticsProvider.d.ts +43 -0
- package/dist/react/AnalyticsProvider.js +66 -0
- package/dist/react/AnalyticsProvider.js.map +1 -0
- package/dist/react/TrackerBoot.d.ts +22 -0
- package/dist/react/TrackerBoot.js +30 -0
- package/dist/react/TrackerBoot.js.map +1 -0
- package/dist/react/useAnalytics.d.ts +17 -0
- package/dist/react/useAnalytics.js +36 -0
- package/dist/react/useAnalytics.js.map +1 -0
- package/dist/rsc/AnalyticsScripts.d.ts +30 -0
- package/dist/rsc/AnalyticsScripts.js +41 -0
- package/dist/rsc/AnalyticsScripts.js.map +1 -0
- package/dist/surfacing/cacheStore.d.ts +1 -0
- package/dist/surfacing/cacheStore.js +18 -2
- package/dist/surfacing/cacheStore.js.map +1 -1
- package/dist/surfacing/engine.d.ts +1 -0
- package/dist/surfacing/engine.js +44 -4
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/queue.js +22 -6
- package/dist/surfacing/queue.js.map +1 -1
- package/dist/surfacing/rateLimiter.js +130 -0
- package/dist/surfacing/rateLimiter.js.map +1 -0
- package/dist/surfacing/retryPolicy.js +15 -0
- package/dist/surfacing/retryPolicy.js.map +1 -0
- package/dist/sync/syncTask.js +60 -33
- package/dist/sync/syncTask.js.map +1 -1
- package/dist/testing/memoryAdapter.d.ts +2 -0
- package/dist/testing/memoryAdapter.js +10 -0
- package/dist/testing/memoryAdapter.js.map +1 -1
- package/dist/tracker/autoCapture.d.ts +48 -0
- package/dist/tracker/autoCapture.js +129 -0
- package/dist/tracker/autoCapture.js.map +1 -0
- package/dist/tracker/consent.d.ts +24 -0
- package/dist/tracker/consent.js +48 -0
- package/dist/tracker/consent.js.map +1 -0
- package/dist/tracker/createTracker.d.ts +18 -0
- package/dist/tracker/createTracker.js +163 -0
- package/dist/tracker/createTracker.js.map +1 -0
- package/dist/tracker/initTracker.d.ts +22 -0
- package/dist/tracker/initTracker.js +33 -0
- package/dist/tracker/initTracker.js.map +1 -0
- package/dist/tracker/loadScript.d.ts +14 -0
- package/dist/tracker/loadScript.js +41 -0
- package/dist/tracker/loadScript.js.map +1 -0
- package/dist/tracker/pageTracking.d.ts +17 -0
- package/dist/tracker/pageTracking.js +38 -0
- package/dist/tracker/pageTracking.js.map +1 -0
- package/dist/tracker/registry.d.ts +27 -0
- package/dist/tracker/registry.js +73 -0
- package/dist/tracker/registry.js.map +1 -0
- package/dist/tracker/sinks/native.d.ts +22 -0
- package/dist/tracker/sinks/native.js +56 -0
- package/dist/tracker/sinks/native.js.map +1 -0
- package/dist/tracker/sinks/plausible.d.ts +14 -0
- package/dist/tracker/sinks/plausible.js +25 -0
- package/dist/tracker/sinks/plausible.js.map +1 -0
- package/dist/tracker/sinks/posthog.d.ts +14 -0
- package/dist/tracker/sinks/posthog.js +18 -0
- package/dist/tracker/sinks/posthog.js.map +1 -0
- package/dist/tracker/sinks/umami.d.ts +13 -0
- package/dist/tracker/sinks/umami.js +17 -0
- package/dist/tracker/sinks/umami.js.map +1 -0
- package/dist/tracker/sinks/vendor.d.ts +14 -0
- package/dist/tracker/sinks/vendor.js +66 -0
- package/dist/tracker/sinks/vendor.js.map +1 -0
- package/dist/tracker/transport.js +28 -0
- package/dist/tracker/transport.js.map +1 -0
- package/dist/tracker/types.d.ts +66 -0
- package/dist/translations/ar.js +6 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +6 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +6 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +6 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +6 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +6 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +6 -0
- package/dist/translations/keys.js +6 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +6 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +6 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +6 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +6 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +6 -0
- package/dist/translations/zh.js.map +1 -1
- package/dist/widgets/breakdownTypes.js +5 -0
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/readForWidget.js +24 -14
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.js +23 -14
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.js +1 -1
- package/dist/widgets/readForWidgetSeries.js +26 -16
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +10 -4
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.js +4 -1
- package/dist/widgets/types.js.map +1 -1
- package/package.json +21 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# @10x-media/analytics
|
|
2
2
|
|
|
3
|
+
## 1.0.0-beta.7
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- **Breaking: first-class event capture.** Capture-capable adapters (native, PostHog, Plausible, Umami) now declare a `capture` descriptor: proxy routes, a snippet, and a public client config. An adapter declares one only when the public config capture needs is present, so a read-only PostHog (no `projectToken`) or a Plausible with neither `domain` nor `scriptId` gets no proxy route, no snippet, and fills no slot; reads are unaffected. The descriptor drives three new surfaces:
|
|
8
|
+
|
|
9
|
+
- A first-party runtime proxy at `/api/analytics/p/<slot>/*` (public; declared routes only; GET, POST and OPTIONS served, and PUT, PATCH and DELETE answered 405; cookies and authorization never forwarded and `set-cookie` never returned; body cap and timeout via `capture.proxy.{maxBodyBytes,timeoutMs}`; 404 for unknown slots or paths, 413 over the cap, 400 on a body that dies in transit, 502 on upstream failure). No rate limiting yet.
|
|
10
|
+
- `captureRewrites([{ path, adapter }])` from `@10x-media/analytics/next` for installs that prefer Next rewrites. `posthogProxyRewrites` now wraps it and is deprecated; its emitted param name changed from `:path*` to `:p*` (equivalent for Next). Root mounts and nested or duplicate mount paths throw.
|
|
11
|
+
- A public `GET /api/analytics/tracker` endpoint plus `getTrackerConfig(payload, { headers })` and the `AnalyticsScripts` server component (`@10x-media/analytics/rsc`) that resolve per-request capture config for up to two slots, `global` and `tenant`, one adapter each, deduped when both resolve to the same adapter. Vendor snippets are rendered only for slots that do not require consent; consent-gated vendors load after `consent('granted')`.
|
|
12
|
+
|
|
13
|
+
**Breaking: native engine.** Ingest accepts `type: 'goal'`, plus `value`, `currency` and `scrollDepth` on any event; a missing or non-string `name` on events and goals answers 400 (a nameless `type: 'event'` previously ingested); `name` is capped at 128 characters and `props`, previously stored verbatim, is sanitized to at most 20 flat scalar keys. Config `goals` (`{ slug, name, match: { kind: 'goal' | 'event' | 'path' }, value?, currency? }`) are matched at ingest into `goal` rollup buckets and stamped onto the stored event. `DimensionKey` gains `goal`, `RollupDelta.inc` widens to the full counter set, and `AdapterRegisterContext` gains a required `resolveGoals(req, scope)` that any code building that context by hand must supply. Existing native installs need a migration adding four numeric rollup counters, the `value`, `currency`, `scrollDepth` and `goals` event fields, and the `goal` event type (snippet in the native docs; on Postgres the enum change is irreversible).
|
|
14
|
+
|
|
15
|
+
**Behavioral:** native serves `conversions`, `revenue` (summed in the event's currency, no conversion) and `scrollDepth` (average over the pageviews that reported one), and a `goal` dimension that is groupable but not filterable. A `goal` event counts under `events` and never appears in the `event` dimension breakdown. Goal buckets also accrue visitor and session rows. The native ingest endpoint now caps the request body at 64 KiB (`413` above it), answers `400` on unparseable or non-object JSON (previously a logged `500`), drops a non-finite, negative or over-a-day `durationMs`, and truncates `path` to 512 and `hostname` to 253 characters. `autoCapture` is on by default except `scrollDepth`. Consent defaults per tracker family: vendors require it, native does not.
|
|
16
|
+
|
|
17
|
+
**Additive:** new subpaths `@10x-media/analytics/tracker` (dependency-free browser tracker: `page`, `track`, `trackGoal`, a consent gate whose decision persists under the `analytics:consent` storage key and whose pending events wait in a bounded in-memory queue, SPA route tracking, scroll depth, outbound links, file downloads, `data-analytics-goal` on click and submit) and `@10x-media/analytics/react` (`AnalyticsProvider`, `useAnalytics`, `TrackerBoot`). `useAnalytics()` also works without a provider once `TrackerBoot` has booted. Vendor snippets are self-sequencing (PostHog's official queued stub, Plausible's per-site stub) and carry the CSP nonce, which the PostHog stub propagates onto the bundle it injects. New options: `capture.{slots, paths, consent, autoCapture, proxy}` and `goals` (array, or `{ defaults }`); `capture.slots.<slot>: false` disables a slot; `capture.consent` overrides per slot, per adapter id, or through a resolver. `AnalyticsAdapter` gains optional `capture` and `ingest` members; PostHog gains `region` and `projectToken`; Plausible gains `domain` and `scriptId`; Umami's `host` also serves as the app origin for capture. The widget pickers offer `conversions`, `revenue` and `scrollDepth`, and a new `analytics-breakdown-goals` block lists goal completions.
|
|
18
|
+
|
|
19
|
+
- Engine hardening. Provider reads now run under a real timeout (`cache.timeoutMs`, default 15s) delivered to adapters as `AdapterContext.signal`, retry with backoff only on 429/5xx (one retry for network failures, none for other 4xx or aborts), and respect each adapter's declared rate limits through per-adapter token buckets (`requestsPerMinute`/`requestsPerHour`/`maxConcurrent`). When a refresh fails and an expired cache entry is still within a 24 hour stale window, the read serves it flagged `meta.stale: true` instead of degrading, and failures are logged with the adapter id. Also: native `realtime()` now honors `hostname` and `path` the way aggregate reads do, multiple filters on one dimension compose as AND instead of last-wins, and the client-side capability check mirrors the server's filter requirements.
|
|
20
|
+
|
|
21
|
+
- Multi-tenancy completes. A new `scopes` option enumerates tenant scopes so the cache-warm and sync cron tiers fan out per tenant (each scope resolves its own runtime providers and sync rows carry that scope); without it both tiers keep running install-wide only. Installs with runtime providers (`providers.collection` or `providers.resolve`) no longer treat the config-adapter capability union as a ceiling: every built-in widget registers, the metric pickers offer every metric, and the realtime endpoint is always available, with the per-request sources endpoint and pickers narrowing to what each tenant's sources actually serve. The dev app gains a `TENANCY=on` mode wired through `@payloadcms/plugin-multi-tenant` with two seeded tenants, and the e2e suite runs in both tenancy shapes. The sync task no longer derives a scope from the job request (it fans out over `scopes` and otherwise runs install-wide), and reads on a scoped install that resolve no scope now fail closed unless `access.platformRead` grants.
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- Updated dependencies:
|
|
26
|
+
- @10x-media/fields@0.1.0-beta.7
|
|
27
|
+
|
|
3
28
|
## 1.0.0-beta.6
|
|
4
29
|
|
|
5
30
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -12,6 +12,7 @@ Part of the [@10x-media Payload plugins](https://github.com/10x-media/payload-pl
|
|
|
12
12
|
|
|
13
13
|
- **One adapter contract** with a capabilities model; adapters ship as code-split subpaths (`@10x-media/analytics/adapters/*`) plus a `memoryAdapter` for tests.
|
|
14
14
|
- **Native engine**: self-hosted, cookieless analytics in your own database, with atomic rollups, exact daily uniques, geo resolution (platform headers or MaxMind), retention pruning, and opt-in write batching.
|
|
15
|
+
- **Capture**: a dependency-free browser tracker (`@10x-media/analytics/tracker`) with SPA pageviews, consent gating, auto-capture, and goals, booted from React (`@10x-media/analytics/react`) or a server component; capture-capable adapters are served through a first-party proxy so a vendor's SDK loads from your own origin.
|
|
15
16
|
- **Dashboard widgets** for Payload's Modular Dashboard: metric, trend, four breakdowns, and realtime, all capability-gated, plus a public API for custom widgets.
|
|
16
17
|
- **Display fields**: `analyticsStat`, `analyticsStatRow`, `analyticsFields`, `analyticsTab`, `analyticsTabsField` place per-document stats on your collections; typed per-collection bindings resolve each document's URL path.
|
|
17
18
|
- **Caching** through `payload.kv` with request coalescing, plus an opt-in scheduled warm job.
|
|
@@ -47,7 +48,7 @@ export default buildConfig({
|
|
|
47
48
|
})
|
|
48
49
|
```
|
|
49
50
|
|
|
50
|
-
Run `payload generate:importmap`,
|
|
51
|
+
Run `payload generate:importmap`, render `<AnalyticsScripts config={await getTrackerConfig(payload, { headers: await headers() })} />` from `@10x-media/analytics/rsc` in your root layout, and the dashboard fills in.
|
|
51
52
|
|
|
52
53
|
## Documentation
|
|
53
54
|
|
|
@@ -57,6 +58,9 @@ Full documentation at [docs.10xmedia.de](https://docs.10xmedia.de/analytics):
|
|
|
57
58
|
- [Quick start](https://docs.10xmedia.de/analytics/quick-start)
|
|
58
59
|
- [Adapters](https://docs.10xmedia.de/analytics/adapters)
|
|
59
60
|
- [Native engine](https://docs.10xmedia.de/analytics/native)
|
|
61
|
+
- [Capture](https://docs.10xmedia.de/analytics/capture)
|
|
62
|
+
- [Goals](https://docs.10xmedia.de/analytics/goals)
|
|
63
|
+
- [First-party proxy](https://docs.10xmedia.de/analytics/proxy)
|
|
60
64
|
- [Geo resolution](https://docs.10xmedia.de/analytics/geo)
|
|
61
65
|
- [Display fields](https://docs.10xmedia.de/analytics/display-fields)
|
|
62
66
|
- [Dashboard widgets](https://docs.10xmedia.de/analytics/widgets)
|
|
@@ -8,6 +8,16 @@ interface PlausibleConfig {
|
|
|
8
8
|
host?: string;
|
|
9
9
|
/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */
|
|
10
10
|
maxLookbackDays?: number | null;
|
|
11
|
+
/**
|
|
12
|
+
* Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.
|
|
13
|
+
* The adapter declares `capture` only when one of the two is set.
|
|
14
|
+
*/
|
|
15
|
+
domain?: string;
|
|
16
|
+
/**
|
|
17
|
+
* Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter
|
|
18
|
+
* declares `capture` only when one of it and `domain` is set.
|
|
19
|
+
*/
|
|
20
|
+
scriptId?: string;
|
|
11
21
|
}
|
|
12
22
|
declare function plausible(config: PlausibleConfig): AnalyticsAdapter;
|
|
13
23
|
//#endregion
|
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
import { dayIso } from "../series.js";
|
|
2
2
|
import { fetchJson } from "../http/fetchJson.js";
|
|
3
3
|
//#region src/adapters/plausible/plausible.ts
|
|
4
|
+
/**
|
|
5
|
+
* Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`
|
|
6
|
+
* queues calls the tracker replays on load, and `plausible.init` parks the options on
|
|
7
|
+
* `plausible.o` for it to read. It makes the inline safe next to the async loader in either
|
|
8
|
+
* order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`
|
|
9
|
+
* (the official one assigns unconditionally) because here the tracker is a separate async
|
|
10
|
+
* tag and may win the race, and overwriting the real `init` with the stub would lose the
|
|
11
|
+
* endpoint.
|
|
12
|
+
*/
|
|
13
|
+
const PLAUSIBLE_STUB = "window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};";
|
|
14
|
+
function buildCapture(config) {
|
|
15
|
+
const base = config.host ?? "https://plausible.io";
|
|
16
|
+
const scripts = (path) => {
|
|
17
|
+
if (config.domain) return [{
|
|
18
|
+
src: `${path}/js/script.js`,
|
|
19
|
+
defer: true,
|
|
20
|
+
attrs: {
|
|
21
|
+
"data-domain": config.domain,
|
|
22
|
+
"data-api": `${path}/api/event`
|
|
23
|
+
}
|
|
24
|
+
}];
|
|
25
|
+
if (config.scriptId) return [{
|
|
26
|
+
src: `${path}/js/pa-${config.scriptId}.js`,
|
|
27
|
+
async: true
|
|
28
|
+
}, { inline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})` }];
|
|
29
|
+
return [];
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
proxy: { routes: [{
|
|
33
|
+
source: "/js/:script*",
|
|
34
|
+
upstream: `${base}/js/:script*`
|
|
35
|
+
}, {
|
|
36
|
+
source: "/api/event",
|
|
37
|
+
upstream: `${base}/api/event`
|
|
38
|
+
}] },
|
|
39
|
+
snippet: ({ path }) => ({ scripts: scripts(path) }),
|
|
40
|
+
client: { kind: "plausible" }
|
|
41
|
+
};
|
|
42
|
+
}
|
|
4
43
|
const METRIC_MAP = {
|
|
5
44
|
pageviews: "pageviews",
|
|
6
45
|
visitors: "visitors",
|
|
@@ -51,6 +90,7 @@ function plausible(config) {
|
|
|
51
90
|
aggregate: 3600
|
|
52
91
|
}
|
|
53
92
|
},
|
|
93
|
+
...config.domain || config.scriptId ? { capture: buildCapture(config) } : {},
|
|
54
94
|
isConfigured: () => Boolean(config.siteId && config.apiKey),
|
|
55
95
|
async query(q, ctx) {
|
|
56
96
|
const fetchedAt = q.dateRange.end.toISOString();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\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\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\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}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\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\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${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: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tq.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\t\tq.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAsBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,WAAW;CACX,WAAW;CACX,aAAa;AACd;AAEA,MAAM,mBAA2C,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AAC/F,MAAM,sBAAiD,IAAI,IAC1D,OAAO,KAAK,aAAa,CAC1B;AAOA,MAAM,mBAAmB,QAAmB,QAC3C,WAAW,gBAAgB,KAAK,MAAM,MAAM,GAAI,IAAI;AAErD,SAAgB,UAAU,QAA2C;CACpE,MAAM,OAAO,OAAO,QAAQ;CAkB5B,OAAO;EACN,IAAI;EACJ,OAAO;EACP,cAAA;GAjBA,cAAc;GACd,UAAU;GACV,YAAY;GACZ,gBAAgB;GAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;GAQvF,SAAS;GACT,YAAY;GACZ,SAAS;GACT,iBAAiB,IAAI,IAAI,CAAC,IAAI,CAAC;GAC/B,iBAAiB;GACjB,WAAW,EAAE,iBAAi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AAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\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. The adapter\n\t * declares `capture` only when one of it and `domain` is set.\n\t */\n\tscriptId?: string\n}\n\n/**\n * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`\n * queues calls the tracker replays on load, and `plausible.init` parks the options on\n * `plausible.o` for it to read. It makes the inline safe next to the async loader in either\n * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`\n * (the official one assigns unconditionally) because here the tracker is a separate async\n * tag and may win the race, and overwriting the real `init` with the stub would lose the\n * endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(config: PlausibleConfig): CaptureSupport {\n\tconst base = config.host ?? 'https://plausible.io'\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 (config.scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${config.scriptId}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${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*` },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\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}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\t...(config.domain || config.scriptId ? { capture: buildCapture(config) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\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\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${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: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tq.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\t\tq.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,MAAM,iBACL;AAED,SAAS,aAAa,QAAyC;CAC9D,MAAM,OAAO,OAAO,QAAQ;CAC5B,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;EACx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,IAAI,KAAK;MACf,IAAI,MAAM,KAAA,GACT,UAAU,KAAK,IAAI,WAAW,MAAM;KAEtC;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
|
|
@@ -4,7 +4,7 @@ import { AnalyticsAdapter } from "../../core/contract.js";
|
|
|
4
4
|
interface PosthogConfig {
|
|
5
5
|
/** PostHog project id (numeric). */
|
|
6
6
|
projectId: string;
|
|
7
|
-
/** Personal API key with the "Query Read" scope (phx_...). */
|
|
7
|
+
/** Personal API key with the "Query Read" scope (phx_...). Never exposed to the browser. */
|
|
8
8
|
apiKey: string;
|
|
9
9
|
/** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */
|
|
10
10
|
host?: string;
|
|
@@ -16,6 +16,15 @@ interface PosthogConfig {
|
|
|
16
16
|
* read filters on it. Both the property name and value are escaped literals.
|
|
17
17
|
*/
|
|
18
18
|
scopeProperty?: string;
|
|
19
|
+
/** Cloud region for the proxied capture routes. Derived from `host` when omitted. */
|
|
20
|
+
region?: 'us' | 'eu';
|
|
21
|
+
/**
|
|
22
|
+
* The public browser key (phc_...) sent to `posthog.init`. Distinct from `apiKey`, the
|
|
23
|
+
* private Query API key, which must never reach the client. The adapter declares
|
|
24
|
+
* `capture` only when this is set: without it the install reads dashboards and captures
|
|
25
|
+
* nothing, so it gets no public proxy and no snippet.
|
|
26
|
+
*/
|
|
27
|
+
projectToken?: string;
|
|
19
28
|
}
|
|
20
29
|
declare function posthog(config: PosthogConfig): AnalyticsAdapter;
|
|
21
30
|
//#endregion
|
|
@@ -2,6 +2,52 @@ import { dayIso, hourIso } from "../series.js";
|
|
|
2
2
|
import { fetchJson } from "../http/fetchJson.js";
|
|
3
3
|
//#region src/adapters/posthog/posthog.ts
|
|
4
4
|
const US_CLOUD = "https://us.posthog.com";
|
|
5
|
+
const resolveRegion = (config) => {
|
|
6
|
+
if (config.region) return config.region;
|
|
7
|
+
return config.host?.includes("eu.posthog.com") ? "eu" : "us";
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* PostHog's official install stub (https://posthog.com/docs/libraries/js), trimmed to the
|
|
11
|
+
* methods this plugin and a host are likely to call before the SDK lands. It has to be one
|
|
12
|
+
* self-sequencing script: `init` is what injects `array.js`, deriving the URL from
|
|
13
|
+
* `api_host` (the `.i.posthog.com` rewrite is a no-op on a first-party proxy path, so it
|
|
14
|
+
* resolves to `<path>/static/array.js`, exactly the route the proxy declares). Every call
|
|
15
|
+
* made before the SDK arrives is queued on the stub and replayed by it.
|
|
16
|
+
*
|
|
17
|
+
* One addition to the official code: the injected tag inherits the nonce of the inline that
|
|
18
|
+
* injected it, or a nonce CSP without `strict-dynamic` would pass the inline and block the
|
|
19
|
+
* bundle. `document.currentScript` is the inline itself during its own synchronous run, on
|
|
20
|
+
* the server-rendered path and the loader's path alike. The IDL property is read first
|
|
21
|
+
* because browsers blank the content attribute once the document is parsed.
|
|
22
|
+
*/
|
|
23
|
+
const POSTHOG_STUB = "!function(t,e){var o,n,p,r,c;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"init capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);";
|
|
24
|
+
function buildCapture(config, token) {
|
|
25
|
+
const region = resolveRegion(config);
|
|
26
|
+
return {
|
|
27
|
+
proxy: {
|
|
28
|
+
trailingSlashes: true,
|
|
29
|
+
routes: [
|
|
30
|
+
{
|
|
31
|
+
source: "/static/:p*",
|
|
32
|
+
upstream: `https://${region}-assets.i.posthog.com/static/:p*`
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
source: "/array/:p*",
|
|
36
|
+
upstream: `https://${region}-assets.i.posthog.com/array/:p*`
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
source: "/:p*",
|
|
40
|
+
upstream: `https://${region}.i.posthog.com/:p*`
|
|
41
|
+
}
|
|
42
|
+
]
|
|
43
|
+
},
|
|
44
|
+
snippet: ({ path }) => ({ scripts: [{ inline: `${POSTHOG_STUB}posthog.init(${JSON.stringify(token)},{api_host:${JSON.stringify(path)},ui_host:${JSON.stringify(`https://${region}.posthog.com`)}})` }] }),
|
|
45
|
+
client: {
|
|
46
|
+
kind: "posthog",
|
|
47
|
+
token
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
5
51
|
const METRIC_SQL_PAGEVIEW = {
|
|
6
52
|
pageviews: "count()",
|
|
7
53
|
visitors: "count(DISTINCT person_id)",
|
|
@@ -54,6 +100,7 @@ function posthog(config) {
|
|
|
54
100
|
},
|
|
55
101
|
...config.scopeProperty ? { scopedQueries: true } : {}
|
|
56
102
|
},
|
|
103
|
+
...config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {},
|
|
57
104
|
isConfigured: () => Boolean(config.projectId && config.apiKey),
|
|
58
105
|
async query(q, ctx) {
|
|
59
106
|
const fetchedAt = q.dateRange.end.toISOString();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso, hourIso } from '../series'\n\nexport interface PosthogConfig {\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). */\n\tapiKey: string\n\t/** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a query's scope (e.g. 'tenant'). Enables scoped queries:\n\t * one platform project captures every scope with this property set, and a scoped\n\t * read filters on it. Both the property name and value are escaped literals.\n\t */\n\tscopeProperty?: string\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\n// Pageview-scoped expressions, used when the read filters the WHERE to `$pageview`.\n// visits and sessions share the distinct-session expression and are deduped before the\n// SELECT, then read back by the expression's position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, used when `events` (total captured events, matching PostHog's own\n// Events definition) or an `event`-name breakdown is requested. The WHERE is not filtered to\n// `$pageview`, so the pageview-family metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tevent: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_SQL_ALL) as MetricKey[])\nconst posthogDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_SQL) as DimensionKey[]\n)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE treats % and _ as wildcards and backslash as its own escape char; backslash-escape\n// backslash first (so a raw \\ in the value doesn't get read as escaping the next char),\n// then % and _, before the whole thing is wrapped in % ... % and quoted.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\nconst sqlDateTimeLiteral = (d: Date): string =>\n\tsqlString(d.toISOString().slice(0, 19).replace('T', ' '))\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = config.host ?? US_CLOUD\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogDimensions,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\tlabel: 'PostHog',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d])\n\t\t\t// A total-events metric, an event-name breakdown, or a filter on the event\n\t\t\t// dimension must scan every event, not just pageviews (a `$pageview` WHERE\n\t\t\t// clause combined with an `event = 'x'` filter would be self-contradictory and\n\t\t\t// zero every metric); those reads switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tbreakdownDim === 'event' ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event' && DIMENSION_SQL[f.dimension])\n\t\t\tconst metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW\n\t\t\tconst wanted = q.metrics.filter((m) => metricSql[m])\n\t\t\tconst exprs = [...new Set(wanted.map((m) => metricSql[m] as string))]\n\n\t\t\tconst where = [\n\t\t\t\t`timestamp >= toDateTime(${sqlDateTimeLiteral(q.dateRange.start)})`,\n\t\t\t\t`timestamp <= toDateTime(${sqlDateTimeLiteral(q.dateRange.end)})`,\n\t\t\t]\n\t\t\tif (!scanAllEvents) {\n\t\t\t\twhere.unshift(\"event = '$pageview'\")\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension is dropped here as the safety net so it never throws.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst expr = DIMENSION_SQL[filter.dimension]\n\t\t\t\tif (!expr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (filter.operator === 'eq') {\n\t\t\t\t\twhere.push(`${expr} = ${sqlString(filter.value)}`)\n\t\t\t\t} else if (filter.operator === 'contains') {\n\t\t\t\t\twhere.push(`${expr} ILIKE ${sqlString(`%${escapeLikeValue(filter.value)}%`)}`)\n\t\t\t\t} else if (filter.operator === 'matches') {\n\t\t\t\t\twhere.push(`match(${expr}, ${sqlString(filter.value)})`)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`)\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tfetchJson<PosthogQueryResponse>(`${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t})\n\n\t\t\tconst readRow = (row: unknown[], offset: number): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = exprs.indexOf(metricSql[m] as string)\n\t\t\t\t\tout[m] = Number(row[offset + idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')}`\n\t\t\t\t)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !breakdownDim) {\n\t\t\t\t// HogQL buckets in the timezone argument when given; without it PostHog falls back\n\t\t\t\t// to the project's own timezone, so the resolved reporting timezone (UTC included)\n\t\t\t\t// is always passed to keep day buckets deterministic across projects. The window\n\t\t\t\t// literals stay UTC instants (already aligned to the reporting-timezone day\n\t\t\t\t// boundary by the caller).\n\t\t\t\tconst dayExpr = `toStartOfDay(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${dayExpr} AS day, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY day ORDER BY day`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (q.granularity === 'hour' && !breakdownDim) {\n\t\t\t\t// Same timezone-bucketing rationale as the day branch above, at hour resolution.\n\t\t\t\tconst hourExpr = `toStartOfHour(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${hourExpr} AS hour, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY hour ORDER BY hour`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = hourIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (breakdownDim) {\n\t\t\t\tconst dimSql = DIMENSION_SQL[breakdownDim] as string\n\t\t\t\tconst sql = `SELECT ${dimSql} AS dim, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\tconst data = await runSql(sql)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdownDim]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AA8BA,MAAM,WAAW;AAKjB,MAAM,sBAA0D;CAC/D,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;AACX;AAKA,MAAM,iBAAqD;CAC1D,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,QAAQ;AACT;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,OAAO;AACR;AAEA,MAAM,iBAAyC,IAAI,IAAI,OAAO,KAAK,cAAc,CAAgB;AACjG,MAAM,oBAA+C,IAAI,IACxD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,aAAa,UAClB,IAAI,MAAM,QAAQ,OAAO,MAAM,EAAE,QAAQ,MAAM,KAAK,EAAE;AAKvD,MAAM,mBAAmB,UAA0B,MAAM,QAAQ,YAAY,MAAM,KAAK,GAAG;AAE3F,MAAM,sBAAsB,MAC3B,UAAU,EAAE,YAAY,E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,cAAc,cACA,WAAW,cAAc,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,OAAO,EAAE,uCAAuC,EAAE,SAAS,KAC/H,GACK,QAAQ,KAAK,SAAS;KACvD,YAAY,GAAG,eAAe,OAAO,IAAI,MAAM,EAAE,EAAE;KACnD,SAAS,QAAQ,KAAK,CAAC;IACxB,EACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;GAG5E,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;EACxF;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso, hourIso } from '../series'\n\nexport interface PosthogConfig {\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). Never exposed to the browser. */\n\tapiKey: string\n\t/** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a query's scope (e.g. 'tenant'). Enables scoped queries:\n\t * one platform project captures every scope with this property set, and a scoped\n\t * read filters on it. Both the property name and value are escaped literals.\n\t */\n\tscopeProperty?: string\n\t/** Cloud region for the proxied capture routes. Derived from `host` when omitted. */\n\tregion?: 'us' | 'eu'\n\t/**\n\t * The public browser key (phc_...) sent to `posthog.init`. Distinct from `apiKey`, the\n\t * private Query API key, which must never reach the client. The adapter declares\n\t * `capture` only when this is set: without it the install reads dashboards and captures\n\t * nothing, so it gets no public proxy and no snippet.\n\t */\n\tprojectToken?: string\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\nconst resolveRegion = (config: PosthogConfig): 'us' | 'eu' => {\n\tif (config.region) {\n\t\treturn config.region\n\t}\n\treturn config.host?.includes('eu.posthog.com') ? 'eu' : 'us'\n}\n\n/**\n * PostHog's official install stub (https://posthog.com/docs/libraries/js), trimmed to the\n * methods this plugin and a host are likely to call before the SDK lands. It has to be one\n * self-sequencing script: `init` is what injects `array.js`, deriving the URL from\n * `api_host` (the `.i.posthog.com` rewrite is a no-op on a first-party proxy path, so it\n * resolves to `<path>/static/array.js`, exactly the route the proxy declares). Every call\n * made before the SDK arrives is queued on the stub and replayed by it.\n *\n * One addition to the official code: the injected tag inherits the nonce of the inline that\n * injected it, or a nonce CSP without `strict-dynamic` would pass the inline and block the\n * bundle. `document.currentScript` is the inline itself during its own synchronous run, on\n * the server-rendered path and the loader's path alike. The IDL property is read first\n * because browsers blank the content attribute once the document is parsed.\n */\nconst POSTHOG_STUB =\n\t'!function(t,e){var o,n,p,r,c;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"init capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);'\n\nfunction buildCapture(config: PosthogConfig, token: string): CaptureSupport {\n\tconst region = resolveRegion(config)\n\treturn {\n\t\tproxy: {\n\t\t\ttrailingSlashes: true,\n\t\t\troutes: [\n\t\t\t\t{\n\t\t\t\t\tsource: '/static/:p*',\n\t\t\t\t\tupstream: `https://${region}-assets.i.posthog.com/static/:p*`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsource: '/array/:p*',\n\t\t\t\t\tupstream: `https://${region}-assets.i.posthog.com/array/:p*`,\n\t\t\t\t},\n\t\t\t\t{ source: '/:p*', upstream: `https://${region}.i.posthog.com/:p*` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tinline: `${POSTHOG_STUB}posthog.init(${JSON.stringify(token)},{api_host:${JSON.stringify(path)},ui_host:${JSON.stringify(`https://${region}.posthog.com`)}})`,\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'posthog', token },\n\t}\n}\n\n// Pageview-scoped expressions, used when the read filters the WHERE to `$pageview`.\n// visits and sessions share the distinct-session expression and are deduped before the\n// SELECT, then read back by the expression's position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, used when `events` (total captured events, matching PostHog's own\n// Events definition) or an `event`-name breakdown is requested. The WHERE is not filtered to\n// `$pageview`, so the pageview-family metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tevent: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_SQL_ALL) as MetricKey[])\nconst posthogDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_SQL) as DimensionKey[]\n)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE treats % and _ as wildcards and backslash as its own escape char; backslash-escape\n// backslash first (so a raw \\ in the value doesn't get read as escaping the next char),\n// then % and _, before the whole thing is wrapped in % ... % and quoted.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\nconst sqlDateTimeLiteral = (d: Date): string =>\n\tsqlString(d.toISOString().slice(0, 19).replace('T', ' '))\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = config.host ?? US_CLOUD\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogDimensions,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\tlabel: 'PostHog',\n\t\tcapabilities,\n\t\t...(config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d])\n\t\t\t// A total-events metric, an event-name breakdown, or a filter on the event\n\t\t\t// dimension must scan every event, not just pageviews (a `$pageview` WHERE\n\t\t\t// clause combined with an `event = 'x'` filter would be self-contradictory and\n\t\t\t// zero every metric); those reads switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tbreakdownDim === 'event' ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event' && DIMENSION_SQL[f.dimension])\n\t\t\tconst metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW\n\t\t\tconst wanted = q.metrics.filter((m) => metricSql[m])\n\t\t\tconst exprs = [...new Set(wanted.map((m) => metricSql[m] as string))]\n\n\t\t\tconst where = [\n\t\t\t\t`timestamp >= toDateTime(${sqlDateTimeLiteral(q.dateRange.start)})`,\n\t\t\t\t`timestamp <= toDateTime(${sqlDateTimeLiteral(q.dateRange.end)})`,\n\t\t\t]\n\t\t\tif (!scanAllEvents) {\n\t\t\t\twhere.unshift(\"event = '$pageview'\")\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension is dropped here as the safety net so it never throws.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst expr = DIMENSION_SQL[filter.dimension]\n\t\t\t\tif (!expr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (filter.operator === 'eq') {\n\t\t\t\t\twhere.push(`${expr} = ${sqlString(filter.value)}`)\n\t\t\t\t} else if (filter.operator === 'contains') {\n\t\t\t\t\twhere.push(`${expr} ILIKE ${sqlString(`%${escapeLikeValue(filter.value)}%`)}`)\n\t\t\t\t} else if (filter.operator === 'matches') {\n\t\t\t\t\twhere.push(`match(${expr}, ${sqlString(filter.value)})`)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`)\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tfetchJson<PosthogQueryResponse>(`${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t})\n\n\t\t\tconst readRow = (row: unknown[], offset: number): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = exprs.indexOf(metricSql[m] as string)\n\t\t\t\t\tout[m] = Number(row[offset + idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')}`\n\t\t\t\t)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !breakdownDim) {\n\t\t\t\t// HogQL buckets in the timezone argument when given; without it PostHog falls back\n\t\t\t\t// to the project's own timezone, so the resolved reporting timezone (UTC included)\n\t\t\t\t// is always passed to keep day buckets deterministic across projects. The window\n\t\t\t\t// literals stay UTC instants (already aligned to the reporting-timezone day\n\t\t\t\t// boundary by the caller).\n\t\t\t\tconst dayExpr = `toStartOfDay(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${dayExpr} AS day, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY day ORDER BY day`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (q.granularity === 'hour' && !breakdownDim) {\n\t\t\t\t// Same timezone-bucketing rationale as the day branch above, at hour resolution.\n\t\t\t\tconst hourExpr = `toStartOfHour(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${hourExpr} AS hour, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY hour ORDER BY hour`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = hourIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (breakdownDim) {\n\t\t\t\tconst dimSql = DIMENSION_SQL[breakdownDim] as string\n\t\t\t\tconst sql = `SELECT ${dimSql} AS dim, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\tconst data = await runSql(sql)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdownDim]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAwCA,MAAM,WAAW;AAEjB,MAAM,iBAAiB,WAAuC;CAC7D,IAAI,OAAO,QACV,OAAO,OAAO;CAEf,OAAO,OAAO,MAAM,SAAS,gBAAgB,IAAI,OAAO;AACzD;;;;;;;;;;;;;;;AAgBA,MAAM,eACL;AAED,SAAS,aAAa,QAAuB,OAA+B;CAC3E,MAAM,SAAS,cAAc,MAAM;CACnC,OAAO;EACN,OAAO;GACN,iBAAiB;GACjB,QAAQ;IACP;KACC,QAAQ;KACR,UAAU,WAAW,OAAO;IAC7B;IACA;KACC,QAAQ;KACR,UAAU,WAAW,OAAO;IAC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AM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;EACxF;CACD;AACD"}
|
|
@@ -7,7 +7,11 @@ interface UmamiConfig {
|
|
|
7
7
|
apiKey?: string;
|
|
8
8
|
/** Self-hosted bearer token (from POST /api/auth/login). */
|
|
9
9
|
token?: string;
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is
|
|
12
|
+
* e.g. https://site/api. Capture derives the app origin from this (a trailing `/api`
|
|
13
|
+
* is stripped), so one `host` value serves both the Stats API and the tracker.
|
|
14
|
+
*/
|
|
11
15
|
host?: string;
|
|
12
16
|
/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */
|
|
13
17
|
maxLookbackDays?: number | null;
|
|
@@ -2,6 +2,31 @@ import { dayIso } from "../series.js";
|
|
|
2
2
|
import { fetchJson } from "../http/fetchJson.js";
|
|
3
3
|
//#region src/adapters/umami/umami.ts
|
|
4
4
|
const CLOUD_BASE = "https://api.umami.is/v1";
|
|
5
|
+
const CLOUD_SCRIPT = "https://cloud.umami.is/script.js";
|
|
6
|
+
const CLOUD_SEND = "https://gateway.umami.is/api/send";
|
|
7
|
+
function buildCapture(config) {
|
|
8
|
+
const origin = config.host ? config.host.replace(/\/api\/?$/, "").replace(/\/+$/, "") : null;
|
|
9
|
+
const scriptUpstream = origin ? `${origin}/script.js` : CLOUD_SCRIPT;
|
|
10
|
+
const sendUpstream = origin ? `${origin}/api/send` : CLOUD_SEND;
|
|
11
|
+
return {
|
|
12
|
+
proxy: { routes: [{
|
|
13
|
+
source: "/script.js",
|
|
14
|
+
upstream: scriptUpstream
|
|
15
|
+
}, {
|
|
16
|
+
source: "/api/send",
|
|
17
|
+
upstream: sendUpstream
|
|
18
|
+
}] },
|
|
19
|
+
snippet: ({ path }) => ({ scripts: [{
|
|
20
|
+
src: `${path}/script.js`,
|
|
21
|
+
defer: true,
|
|
22
|
+
attrs: {
|
|
23
|
+
"data-website-id": config.websiteId,
|
|
24
|
+
"data-host-url": path
|
|
25
|
+
}
|
|
26
|
+
}] }),
|
|
27
|
+
client: { kind: "umami" }
|
|
28
|
+
};
|
|
29
|
+
}
|
|
5
30
|
const umamiMetrics = new Set([
|
|
6
31
|
"pageviews",
|
|
7
32
|
"visitors",
|
|
@@ -43,6 +68,7 @@ function umami(config) {
|
|
|
43
68
|
id: "umami",
|
|
44
69
|
label: "Umami",
|
|
45
70
|
capabilities,
|
|
71
|
+
capture: buildCapture(config),
|
|
46
72
|
isConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),
|
|
47
73
|
async query(q, ctx) {
|
|
48
74
|
const fetchedAt = q.dateRange.end.toISOString();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface UmamiConfig {\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/** API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is e.g. https://site/api. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst CLOUD_BASE = 'https://api.umami.is/v1'\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>(['page'])\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst base = config.host ?? CLOUD_BASE\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tfilters: new Set(),\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\t// NOTE: the cloud header name and the per-URL `path` filter (set in params(), also\n\t// sent to /metrics) match the documented v2 shape but are unvalidated against a live\n\t// instance; confirm both before relying on per-URL provider data in production.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\tconst params = (q: AnalyticsQuery): URLSearchParams => {\n\t\tconst p = new URLSearchParams({\n\t\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\t\tendAt: String(q.dateRange.end.getTime()),\n\t\t})\n\t\tif (q.path) {\n\t\t\tp.set('path', q.path)\n\t\t}\n\t\treturn p\n\t}\n\n\treturn {\n\t\tid: 'umami',\n\t\tlabel: 'Umami',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst headers = authHeaders()\n\t\t\tconst wantsPageBreakdown = (q.dimensions ?? []).includes('page')\n\n\t\t\tif (wantsPageBreakdown) {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('type', 'url')\n\t\t\t\tconst data = await fetchJson<Array<{ x: string; y: number }>>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/metrics?${p.toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst metric: MetricKey = q.metrics.includes('pageviews') ? 'pageviews' : 'visitors'\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { page: row.x },\n\t\t\t\t\tmetrics: { [metric]: row.y } as Partial<Record<MetricKey, number>>,\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst stats = await fetchJson<UmamiStats>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/stats?${params(q).toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios are omitted (not zeroed) when there are no visits, so the\n\t\t\t\t\t// display layer shows a \"no data\" state instead of a misleading 0.\n\t\t\t\t\tbounceRate:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : undefined,\n\t\t\t\t\tavgDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : undefined,\n\t\t\t\t}\n\t\t\t\tconst totals: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\ttotals[m] = all[m]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn totals\n\t\t\t}\n\n\t\t\t// Umami's only time-series endpoint reports pageviews and sessions per interval;\n\t\t\t// visitors/bounceRate/avgDuration have no per-day source, so a trend on those\n\t\t\t// metrics keeps a correct headline (from /stats) but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('unit', 'day')\n\t\t\t\tp.set('timezone', q.timezone ?? 'UTC')\n\t\t\t\tconst fetchSeries = () =>\n\t\t\t\t\tfetchJson<{\n\t\t\t\t\t\tpageviews: Array<{ x: string; y: number }>\n\t\t\t\t\t\tsessions: Array<{ x: string; y: number }>\n\t\t\t\t\t}>(`${base}/websites/${config.websiteId}/pageviews?${p.toString()}`, {\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\t})\n\t\t\t\tconst [series, totals] = await Promise.all([fetchSeries(), fetchTotals()])\n\t\t\t\tconst sessionsByX = new Map(series.sessions.map((s) => [s.x, s.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const pv of series.pageviews) {\n\t\t\t\t\tconst ts = dayIso(pv.x)\n\t\t\t\t\tif (!ts) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst dayMetrics = sessionsByX.get(pv.x) ?? 0\n\t\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\t\tpageviews: pv.y,\n\t\t\t\t\t\tvisits: dayMetrics,\n\t\t\t\t\t\tsessions: dayMetrics,\n\t\t\t\t\t}\n\t\t\t\t\tconst metrics: Partial<Record<MetricKey, number>> = {}\n\t\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\t\tmetrics[m] = all[m]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trows.push({ timestamp: ts, metrics })\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'umami', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAyBA,MAAM,aAAa;AAEnB,MAAM,eAAuC,IAAI,IAAe;CAC/D;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,kBAA6C,IAAI,IAAkB,CAAC,MAAM,CAAC;AAUjF,SAAgB,MAAM,QAAuC;CAC5D,MAAM,OAAO,OAAO,QAAQ;CAG5B,MAAM,eAAsC;EAC3C,cAAc;EACd,UAAU;EACV,YAAY;EACZ,gBAAgB;EAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;EAQvF,SAAS;EACT,YAAY;EACZ,yBAAS,IAAI,IAAI;EACjB,iBAAiB,IAAI,IAAI,CAAC,IAAI,CAAC;EAC/B,iBAAiB;EACjB,WAAW;EACX,gBAAgB;GAAE,UAAU;GAAK,WAAW;EAAK;CAClD;CAKA,MAAM,oBACL,OAAO,SACJ,EAAE,mBAAmB,OAAO,OAAO,IACnC,OAAO,QACN,EAAE,eAAe,UAAU,OAAO,QAAQ,IAC1C,CAAC;CAEN,MAAM,UAAU,MAAuC;EACtD,MAAM,IAAI,IAAI,gBAAgB;GAC7B,SAAS,OAAO,EAAE,UAAU,MAAM,QAAQ,CAAC;GAC3C,OAAO,OAAO,EAAE,UAAU,IAAI,QAAQ,CAAC;EACxC,CAAC;EACD,IAAI,EAAE,MACL,EAAE,IAAI,QAAQ,EAAE,IAAI;EAErB,OAAO;CACR;CAEA,OAAO;EACN,IAAI;EACJ,OAAO;EACP;EACA,oBAAoB,QAAQ,OAAO,cAAc,OAAO,UAAU,OAAO,MAAM;EAC/E,MAAM,MAAM,GAAmB,KAA+C;GAC7E,MAAM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nB,EAAE,IAAI,YAAY,EAAE,YAAY,KAAK;IACrC,MAAM,oBACL,UAGG,GAAG,KAAK,YAAY,OAAO,UAAU,aAAa,EAAE,SAAS,KAAK;KACpE;KACA,QAAQ,IAAI;KACZ,UAAU;IACX,CAAC;IACF,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC,CAAC;IACzE,MAAM,cAAc,IAAI,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAClE,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,MAAM,OAAO,WAAW;KAClC,MAAM,KAAK,OAAO,GAAG,CAAC;KACtB,IAAI,CAAC,IACJ;KAED,MAAM,aAAa,YAAY,IAAI,GAAG,CAAC,KAAK;KAC5C,MAAM,MAA0C;MAC/C,WAAW,GAAG;MACd,QAAQ;MACR,UAAU;KACX;KACA,MAAM,UAA8C,CAAC;KACrD,KAAK,MAAM,KAAK,EAAE,SACjB,IAAI,IAAI,OAAO,KAAA,GACd,QAAQ,KAAK,IAAI;KAGnB,KAAK,KAAK;MAAE,WAAW;MAAI;KAAQ,CAAC;IACrC;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAS;KAAU;IAAE;GAC/D;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAS;IAAU;GAAE;EACtF;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface UmamiConfig {\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is\n\t * e.g. https://site/api. Capture derives the app origin from this (a trailing `/api`\n\t * is stripped), so one `host` value serves both the Stats API and the tracker.\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}\n\nconst CLOUD_BASE = 'https://api.umami.is/v1'\nconst CLOUD_SCRIPT = 'https://cloud.umami.is/script.js'\nconst CLOUD_SEND = 'https://gateway.umami.is/api/send'\n\nfunction buildCapture(config: UmamiConfig): CaptureSupport {\n\tconst origin = config.host ? config.host.replace(/\\/api\\/?$/, '').replace(/\\/+$/, '') : null\n\tconst scriptUpstream = origin ? `${origin}/script.js` : CLOUD_SCRIPT\n\tconst sendUpstream = origin ? `${origin}/api/send` : CLOUD_SEND\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: scriptUpstream },\n\t\t\t\t{ source: '/api/send', upstream: sendUpstream },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>(['page'])\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst base = config.host ?? CLOUD_BASE\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tfilters: new Set(),\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\t// NOTE: the cloud header name and the per-URL `path` filter (set in params(), also\n\t// sent to /metrics) match the documented v2 shape but are unvalidated against a live\n\t// instance; confirm both before relying on per-URL provider data in production.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\tconst params = (q: AnalyticsQuery): URLSearchParams => {\n\t\tconst p = new URLSearchParams({\n\t\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\t\tendAt: String(q.dateRange.end.getTime()),\n\t\t})\n\t\tif (q.path) {\n\t\t\tp.set('path', q.path)\n\t\t}\n\t\treturn p\n\t}\n\n\treturn {\n\t\tid: 'umami',\n\t\tlabel: 'Umami',\n\t\tcapabilities,\n\t\tcapture: buildCapture(config),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst headers = authHeaders()\n\t\t\tconst wantsPageBreakdown = (q.dimensions ?? []).includes('page')\n\n\t\t\tif (wantsPageBreakdown) {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('type', 'url')\n\t\t\t\tconst data = await fetchJson<Array<{ x: string; y: number }>>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/metrics?${p.toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst metric: MetricKey = q.metrics.includes('pageviews') ? 'pageviews' : 'visitors'\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { page: row.x },\n\t\t\t\t\tmetrics: { [metric]: row.y } as Partial<Record<MetricKey, number>>,\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst stats = await fetchJson<UmamiStats>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/stats?${params(q).toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios are omitted (not zeroed) when there are no visits, so the\n\t\t\t\t\t// display layer shows a \"no data\" state instead of a misleading 0.\n\t\t\t\t\tbounceRate:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : undefined,\n\t\t\t\t\tavgDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : undefined,\n\t\t\t\t}\n\t\t\t\tconst totals: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\ttotals[m] = all[m]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn totals\n\t\t\t}\n\n\t\t\t// Umami's only time-series endpoint reports pageviews and sessions per interval;\n\t\t\t// visitors/bounceRate/avgDuration have no per-day source, so a trend on those\n\t\t\t// metrics keeps a correct headline (from /stats) but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('unit', 'day')\n\t\t\t\tp.set('timezone', q.timezone ?? 'UTC')\n\t\t\t\tconst fetchSeries = () =>\n\t\t\t\t\tfetchJson<{\n\t\t\t\t\t\tpageviews: Array<{ x: string; y: number }>\n\t\t\t\t\t\tsessions: Array<{ x: string; y: number }>\n\t\t\t\t\t}>(`${base}/websites/${config.websiteId}/pageviews?${p.toString()}`, {\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\t})\n\t\t\t\tconst [series, totals] = await Promise.all([fetchSeries(), fetchTotals()])\n\t\t\t\tconst sessionsByX = new Map(series.sessions.map((s) => [s.x, s.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const pv of series.pageviews) {\n\t\t\t\t\tconst ts = dayIso(pv.x)\n\t\t\t\t\tif (!ts) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst dayMetrics = sessionsByX.get(pv.x) ?? 0\n\t\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\t\tpageviews: pv.y,\n\t\t\t\t\t\tvisits: dayMetrics,\n\t\t\t\t\t\tsessions: dayMetrics,\n\t\t\t\t\t}\n\t\t\t\t\tconst metrics: Partial<Record<MetricKey, number>> = {}\n\t\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\t\tmetrics[m] = all[m]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trows.push({ timestamp: ts, metrics })\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'umami', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AA8BA,MAAM,aAAa;AACnB,MAAM,eAAe;AACrB,MAAM,aAAa;AAEnB,SAAS,aAAa,QAAqC;CAC1D,MAAM,SAAS,OAAO,OAAO,OAAO,KAAK,QAAQ,aAAa,EAAE,EAAE,QAAQ,QAAQ,EAAE,IAAI;CACxF,MAAM,iBAAiB,SAAS,GAAG,OAAO,cAAc;CACxD,MAAM,eAAe,SAAS,GAAG,OAAO,aAAa;CACrD,OAAO;EACN,OAAO,EACN,QAAQ,CACP;GAAE,QAAQ;GAAc,UAAU;EAAe,GACjD;GAAE,QAAQ;GAAa,UAAU;EAAa,CAC/C,EACD;EACA,UAAU,EAAE,YAAY,EACvB,SAAS,CACR;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,OAAO;IAAE,mBAAmB,OAAO;IAAW,iBAAiB;GAAK;EACrE,CACD,EACD;EACA,QAAQ,EAAE,MAAM,QAAQ;CACzB;AACD;AAEA,MAAM,eAAuC,IAAI,IAAe;CAC/D;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,kBAA6C,IAAI,IAAkB,CAAC,MAAM,CAAC;AAUjF,SAAgB,MAAM,QAAuC;CAC5D,MAAM,OAAO,OAAO,QAAQ;CAG5B,MAAM,eAAsC;EAC3C,cAAc;EACd,UAAU;EACV,YAAY;EACZ,gBAAgB;EAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;EAQvF,SAAS;EACT,YAAY;EACZ,yBAAS,IAAI,IAAI;EACjB,iBAAiB,IAAI,IAAI,CAAC,IAAI,CAAC;EAC/B,iBAAiB;EACjB,WAAW;EACX,gBAAgB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ACd,QAAQ,KAAK,IAAI;KAGnB,KAAK,KAAK;MAAE,WAAW;MAAI;KAAQ,CAAC;IACrC;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAS;KAAU;IAAE;GAC/D;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAS;IAAU;GAAE;EACtF;CACD;AACD"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { TrackerConfig } from "./trackerConfig.js";
|
|
2
|
+
import { Payload } from "payload";
|
|
3
|
+
|
|
4
|
+
//#region src/capture/getTrackerConfig.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Server-side twin of the tracker endpoint, for a Next app that renders `AnalyticsScripts`
|
|
7
|
+
* itself: pass the incoming request's `headers()` and the host's `scopeResolver` sees the
|
|
8
|
+
* same request it would over HTTP. `host` is lifted onto the request because Payload
|
|
9
|
+
* derives `req.host` from the URL rather than the header, and hostname-derived scoping is
|
|
10
|
+
* the common case.
|
|
11
|
+
*
|
|
12
|
+
* A fresh request object is built on every call: `createLocalReq` mutates the one it is
|
|
13
|
+
* given, so a shared literal would accumulate another caller's locale, user, and loader.
|
|
14
|
+
*/
|
|
15
|
+
declare const getTrackerConfig: (payload: Payload, args?: {
|
|
16
|
+
headers?: Headers;
|
|
17
|
+
}) => Promise<TrackerConfig>;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { getTrackerConfig };
|
|
20
|
+
//# sourceMappingURL=getTrackerConfig.d.ts.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { getRuntime } from "../plugin/runtime.js";
|
|
2
|
+
import { emptyTrackerConfig, resolveTrackerConfig } from "./trackerConfig.js";
|
|
3
|
+
import { createLocalReq } from "payload";
|
|
4
|
+
//#region src/capture/getTrackerConfig.ts
|
|
5
|
+
/**
|
|
6
|
+
* Server-side twin of the tracker endpoint, for a Next app that renders `AnalyticsScripts`
|
|
7
|
+
* itself: pass the incoming request's `headers()` and the host's `scopeResolver` sees the
|
|
8
|
+
* same request it would over HTTP. `host` is lifted onto the request because Payload
|
|
9
|
+
* derives `req.host` from the URL rather than the header, and hostname-derived scoping is
|
|
10
|
+
* the common case.
|
|
11
|
+
*
|
|
12
|
+
* A fresh request object is built on every call: `createLocalReq` mutates the one it is
|
|
13
|
+
* given, so a shared literal would accumulate another caller's locale, user, and loader.
|
|
14
|
+
*/
|
|
15
|
+
const getTrackerConfig = async (payload, args) => {
|
|
16
|
+
const headers = args?.headers ?? new Headers();
|
|
17
|
+
const host = headers.get("host");
|
|
18
|
+
const req = await createLocalReq({ req: {
|
|
19
|
+
headers,
|
|
20
|
+
...host ? { host } : {}
|
|
21
|
+
} }, payload);
|
|
22
|
+
const runtime = getRuntime(payload);
|
|
23
|
+
return runtime ? resolveTrackerConfig({
|
|
24
|
+
runtime,
|
|
25
|
+
req
|
|
26
|
+
}) : emptyTrackerConfig(req);
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
export { getTrackerConfig };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=getTrackerConfig.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getTrackerConfig.js","names":[],"sources":["../../src/capture/getTrackerConfig.ts"],"sourcesContent":["import { createLocalReq, type Payload, type PayloadRequest } from 'payload'\nimport { getRuntime } from '../plugin/runtime'\nimport { emptyTrackerConfig, resolveTrackerConfig, type TrackerConfig } from './trackerConfig'\n\n/**\n * Server-side twin of the tracker endpoint, for a Next app that renders `AnalyticsScripts`\n * itself: pass the incoming request's `headers()` and the host's `scopeResolver` sees the\n * same request it would over HTTP. `host` is lifted onto the request because Payload\n * derives `req.host` from the URL rather than the header, and hostname-derived scoping is\n * the common case.\n *\n * A fresh request object is built on every call: `createLocalReq` mutates the one it is\n * given, so a shared literal would accumulate another caller's locale, user, and loader.\n */\nexport const getTrackerConfig = async (\n\tpayload: Payload,\n\targs?: { headers?: Headers }\n): Promise<TrackerConfig> => {\n\tconst headers = args?.headers ?? new Headers()\n\tconst host = headers.get('host')\n\tconst req = await createLocalReq(\n\t\t{ req: { headers, ...(host ? { host } : {}) } as Partial<PayloadRequest> },\n\t\tpayload\n\t)\n\tconst runtime = getRuntime(payload)\n\treturn runtime ? resolveTrackerConfig({ runtime, req }) : emptyTrackerConfig(req)\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,mBAAmB,OAC/B,SACA,SAC4B;CAC5B,MAAM,UAAU,MAAM,WAAW,IAAI,QAAQ;CAC7C,MAAM,OAAO,QAAQ,IAAI,MAAM;CAC/B,MAAM,MAAM,MAAM,eACjB,EAAE,KAAK;EAAE;EAAS,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;CAAG,EAA6B,GACzE,OACD;CACA,MAAM,UAAU,WAAW,OAAO;CAClC,OAAO,UAAU,qBAAqB;EAAE;EAAS;CAAI,CAAC,IAAI,mBAAmB,GAAG;AACjF"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/capture/mountPath.ts
|
|
2
|
+
/**
|
|
3
|
+
* One mount path, canonical: a leading slash, no trailing one, `/` for what reduces to
|
|
4
|
+
* the site root. Shared by the Next rewrites helper and the tracker config resolver so a
|
|
5
|
+
* `capture.paths` override and the rewrite it was mounted at cannot disagree over a slash.
|
|
6
|
+
*/
|
|
7
|
+
const normalizeMountPath = (path) => {
|
|
8
|
+
const trimmed = (path.startsWith("/") ? path : `/${path}`).replace(/\/+$/, "");
|
|
9
|
+
return trimmed === "" ? "/" : trimmed;
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { normalizeMountPath };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=mountPath.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mountPath.js","names":[],"sources":["../../src/capture/mountPath.ts"],"sourcesContent":["/**\n * One mount path, canonical: a leading slash, no trailing one, `/` for what reduces to\n * the site root. Shared by the Next rewrites helper and the tracker config resolver so a\n * `capture.paths` override and the rewrite it was mounted at cannot disagree over a slash.\n */\nexport const normalizeMountPath = (path: string): string => {\n\tconst withLeading = path.startsWith('/') ? path : `/${path}`\n\tconst trimmed = withLeading.replace(/\\/+$/, '')\n\treturn trimmed === '' ? '/' : trimmed\n}\n"],"mappings":";;;;;;AAKA,MAAa,sBAAsB,SAAyB;CAE3D,MAAM,WADc,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,QAC1B,QAAQ,QAAQ,EAAE;CAC9C,OAAO,YAAY,KAAK,MAAM;AAC/B"}
|