@10x-media/analytics 1.0.0-beta.14 → 1.0.0-beta.16
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 +55 -0
- package/README.md +1 -1
- package/dist/adapters/ga4/ga4.d.ts +7 -0
- package/dist/adapters/ga4/ga4.js +17 -3
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.d.ts +6 -0
- package/dist/adapters/plausible/plausible.js +6 -3
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/cloud.js +20 -0
- package/dist/adapters/posthog/cloud.js.map +1 -0
- package/dist/adapters/posthog/credentials.js +20 -0
- package/dist/adapters/posthog/credentials.js.map +1 -0
- package/dist/adapters/posthog/posthog.d.ts +10 -3
- package/dist/adapters/posthog/posthog.js +100 -27
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/posthog/projectCheck.js +56 -0
- package/dist/adapters/posthog/projectCheck.js.map +1 -0
- package/dist/adapters/umami/umami.d.ts +6 -0
- package/dist/adapters/umami/umami.js +3 -1
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/trackerConfig.js +29 -6
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/capture/withoutConsent.js +91 -0
- package/dist/capture/withoutConsent.js.map +1 -0
- package/dist/core/capture.d.ts +41 -11
- package/dist/core/captureOptions.js +97 -8
- package/dist/core/captureOptions.js.map +1 -1
- package/dist/core/contract.d.ts +25 -0
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +24 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/sourceOptions.js +2 -1
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/exports/adapters/contract.d.ts +3 -3
- package/dist/exports/adapters/ga4.d.ts +4 -4
- package/dist/exports/adapters/native.d.ts +5 -5
- package/dist/exports/adapters/plausible.d.ts +4 -4
- package/dist/exports/adapters/posthog.d.ts +4 -4
- package/dist/exports/adapters/umami.d.ts +4 -4
- package/dist/exports/next.d.ts +4 -4
- package/dist/exports/react.d.ts +3 -2
- package/dist/exports/site.d.ts +2 -2
- package/dist/exports/testing.d.ts +4 -4
- package/dist/exports/tracker.d.ts +3 -2
- package/dist/exports/types.d.ts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/native/collections/hits.js +1 -0
- package/dist/native/collections/hits.js.map +1 -1
- package/dist/native/engine/engine.js +5 -1
- package/dist/native/engine/engine.js.map +1 -1
- package/dist/native/engine/planner.js +2 -1
- package/dist/native/engine/planner.js.map +1 -1
- package/dist/native/engine/toHit.js +4 -2
- package/dist/native/engine/toHit.js.map +1 -1
- package/dist/native/ingest/endpoint.js +5 -2
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.d.ts +6 -1
- package/dist/native/ingest/normalizeEvent.js +17 -7
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/serverTrack.js +2 -1
- package/dist/native/ingest/serverTrack.js.map +1 -1
- package/dist/native/ingest/validate.js +3 -0
- package/dist/native/ingest/validate.js.map +1 -1
- package/dist/native/nativeAdapter.d.ts +10 -1
- package/dist/native/nativeAdapter.js +11 -1
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/store/aggregate.js +1 -1
- package/dist/native/store/aggregate.js.map +1 -1
- package/dist/native/store/hitRow.js +3 -0
- package/dist/native/store/hitRow.js.map +1 -1
- package/dist/native/store/hits.js +3 -1
- package/dist/native/store/hits.js.map +1 -1
- package/dist/native/store/mongo/aggregatePipelines.js +10 -2
- package/dist/native/store/mongo/aggregatePipelines.js.map +1 -1
- package/dist/native/store/mongo/pipelines.js +15 -5
- package/dist/native/store/mongo/pipelines.js.map +1 -1
- package/dist/native/store/parts.js +9 -3
- package/dist/native/store/parts.js.map +1 -1
- package/dist/native/store/rawRead.js +6 -3
- package/dist/native/store/rawRead.js.map +1 -1
- package/dist/native/store/sql/aggregateSql.js +6 -2
- package/dist/native/store/sql/aggregateSql.js.map +1 -1
- package/dist/native/store/sql/columns.js +1 -0
- package/dist/native/store/sql/columns.js.map +1 -1
- package/dist/native/store/sql/compile.js +19 -7
- package/dist/native/store/sql/compile.js.map +1 -1
- package/dist/native/store/types.d.ts +7 -1
- package/dist/native/store/types.js +10 -0
- package/dist/native/store/types.js.map +1 -0
- package/dist/plugin/createRuntime.js +10 -1
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/providers/collection.d.ts +2 -0
- package/dist/providers/collection.js +36 -9
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.d.ts +9 -1
- package/dist/providers/factory.js +14 -5
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/hosts.js +14 -6
- package/dist/providers/hosts.js.map +1 -1
- package/dist/providers/registry.js +2 -1
- package/dist/providers/registry.js.map +1 -1
- package/dist/react/AnalyticsProvider.d.ts +6 -0
- package/dist/react/AnalyticsProvider.js.map +1 -1
- package/dist/react/useAnalytics.js +9 -5
- package/dist/react/useAnalytics.js.map +1 -1
- package/dist/site/AnalyticsScripts.d.ts +4 -3
- package/dist/site/AnalyticsScripts.js +18 -4
- package/dist/site/AnalyticsScripts.js.map +1 -1
- package/dist/surfacing/todaySplit.js +7 -1
- package/dist/surfacing/todaySplit.js.map +1 -1
- package/dist/tracker/config.d.ts +26 -1
- package/dist/tracker/config.js.map +1 -1
- package/dist/tracker/createTracker.d.ts +2 -1
- package/dist/tracker/createTracker.js +91 -59
- package/dist/tracker/createTracker.js.map +1 -1
- package/dist/tracker/gate.d.ts +8 -0
- package/dist/tracker/gate.js +61 -11
- package/dist/tracker/gate.js.map +1 -1
- package/dist/tracker/loadScript.js +2 -1
- package/dist/tracker/loadScript.js.map +1 -1
- package/dist/tracker/registry.js +14 -3
- package/dist/tracker/registry.js.map +1 -1
- package/dist/tracker/sinks/createSink.js +27 -8
- package/dist/tracker/sinks/createSink.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +38 -6
- package/dist/tracker/sinks/ga4.js.map +1 -1
- package/dist/tracker/sinks/native.js +17 -3
- package/dist/tracker/sinks/native.js.map +1 -1
- package/dist/tracker/sinks/plausible.js +8 -2
- package/dist/tracker/sinks/plausible.js.map +1 -1
- package/dist/tracker/sinks/posthog.js +108 -16
- package/dist/tracker/sinks/posthog.js.map +1 -1
- package/dist/tracker/sinks/umami.js +2 -2
- package/dist/tracker/sinks/umami.js.map +1 -1
- package/dist/tracker/sinks/vendor.js +25 -11
- package/dist/tracker/sinks/vendor.js.map +1 -1
- package/dist/tracker/types.d.ts +10 -3
- package/dist/translations/ar.js +10 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +10 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +10 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +10 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +10 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +10 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +10 -0
- package/dist/translations/keys.js +11 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +10 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +10 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +10 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +10 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +10 -0
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/consentShare.js +15 -0
- package/dist/view/consentShare.js.map +1 -0
- package/dist/view/sections/OverviewCards.js +38 -28
- package/dist/view/sections/OverviewCards.js.map +1 -1
- package/dist/widgets/notices.js +6 -1
- package/dist/widgets/notices.js.map +1 -1
- package/dist/widgets/readMeta.d.ts +4 -0
- package/dist/widgets/readMeta.js +5 -0
- package/dist/widgets/readMeta.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import { filterableDimensions } from '../../core/capabilities'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsFilter,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\n\nexport interface UmamiConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Umami'`.\n\t */\n\tlabel?: AdapterLabelOption\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * The self-hosted Umami app's address, base path included (`https://example.com/umami`), whose\n\t * API is read under `/api`; a trailing `/api` is dropped. Unset, or Umami Cloud's, reads the cloud.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/** The fetch reads and the capture proxy reach Umami with. Unset, the global fetch. */\n\tfetch?: FetchLike\n}\n\n/** Where one Umami install answers: its Stats API, its tracker script, and its event sink. */\nexport interface UmamiEndpoints {\n\tapi: string\n\tscript: string\n\tsend: string\n}\n\nconst CLOUD: UmamiEndpoints = {\n\tapi: 'https://api.umami.is/v1',\n\tscript: 'https://cloud.umami.is/script.js',\n\tsend: 'https://gateway.umami.is/api/send',\n}\n\n/** Umami Cloud's own hosts, which mean the cloud rather than an app address under them. */\nconst CLOUD_HOSTNAMES: ReadonlySet<string> = new Set(['api.umami.is', 'cloud.umami.is'])\n\n/**\n * The endpoints `host` names: the cloud for nothing or for Umami Cloud's own address, otherwise\n * the app address (trailing slashes and a trailing `/api` dropped) with the API under `/api`.\n */\nexport const umamiEndpoints = (host: string | undefined): UmamiEndpoints => {\n\tconst trimmed = withoutTrailingSlash(host?.trim() ?? '')\n\tconst address = withoutTrailingSlash(trimmed.replace(/\\/api$/, ''))\n\tif (address === '' || CLOUD_HOSTNAMES.has(hostnameOf(address))) {\n\t\treturn CLOUD\n\t}\n\treturn { api: `${address}/api`, script: `${address}/script.js`, send: `${address}/api/send` }\n}\n\nfunction buildCapture(config: UmamiConfig, endpoints: UmamiEndpoints): CaptureSupport {\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: endpoints.script, kind: 'script' },\n\t\t\t\t{ source: '/api/send', upstream: endpoints.send, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'visitDuration',\n\t'conversions',\n])\n\ninterface UmamiDimension {\n\t/** Umami filter param, which doubles as the /metrics `type` value. */\n\tparam: string\n\t/** The one metric /metrics reports for this type: y is nothing else. */\n\tmetric: MetricKey\n}\n\n// y is count(distinct session_id) on every pageview and session type, and event\n// occurrences on `type=event`.\nconst DIMENSION_MAP: Partial<Record<DimensionKey, UmamiDimension>> = {\n\tpage: { param: 'path', metric: 'visitors' },\n\treferrer: { param: 'referrer', metric: 'visitors' },\n\tbrowser: { param: 'browser', metric: 'visitors' },\n\tos: { param: 'os', metric: 'visitors' },\n\tdevice: { param: 'device', metric: 'visitors' },\n\tcountry: { param: 'country', metric: 'visitors' },\n\tregion: { param: 'region', metric: 'visitors' },\n\tcity: { param: 'city', metric: 'visitors' },\n\tlanguage: { param: 'language', metric: 'visitors' },\n\tevent: { param: 'event', metric: 'events' },\n\tutmSource: { param: 'utmSource', metric: 'visitors' },\n\tutmMedium: { param: 'utmMedium', metric: 'visitors' },\n\tutmCampaign: { param: 'utmCampaign', metric: 'visitors' },\n\tutmContent: { param: 'utmContent', metric: 'visitors' },\n\tutmTerm: { param: 'utmTerm', metric: 'visitors' },\n}\n\n/**\n * Goals are custom events, so a goal's slug must equal the captured event's name. Only this shape\n * answers `conversions`: other breakdowns and the daily series report none.\n */\nconst GOAL_DIMENSION: UmamiDimension = { param: 'event', metric: 'conversions' }\n\n/**\n * The /metrics types a read groups by. `channel` is Umami's acquisition classification, a type\n * with no filter param, which is why it sits outside {@link DIMENSION_MAP}.\n */\nconst BREAKDOWNS: Partial<Record<DimensionKey, UmamiDimension>> = {\n\t...DIMENSION_MAP,\n\tchannel: { param: 'channel', metric: 'visitors' },\n}\n\n/**\n * Umami's `re.` is `~*`: a case-insensitive partial match, so an unanchored pattern hits\n * anywhere in the value. `c.` is `ilike`, also case-insensitive.\n */\nconst OPERATOR_PREFIX: Record<FilterOperator, string> = {\n\teq: 'eq.',\n\tcontains: 'c.',\n\tmatches: 're.',\n}\n\n/** A filter as its param value, always prefixed so a value starting like an operator stays literal. */\nconst paramValue = (filter: AnalyticsFilter): string =>\n\t`${OPERATOR_PREFIX[filter.operator]}${filter.value}`\n\n/**\n * Every filter param takes equals, contains and a regular expression\n * (https://docs.umami.is/docs/filters), written as the `eq.`, `c.` and `re.` prefixes.\n */\nconst umamiFilters = everyOperatorOn(mappedKeys(DIMENSION_KEYS, DIMENSION_MAP))\n\n// `event` filters but does not group, since /stats reports no `events` number to declare;\n// `goal` and `channel` are the reverse, /metrics types with no matching filter param.\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>([\n\t...filterableDimensions({ filters: umamiFilters }).filter((dimension) => dimension !== 'event'),\n\t'goal',\n\t'channel',\n])\n\n/**\n * /stats answers site totals and /metrics one count per row, so other metrics are site-wide only.\n * Nothing reports time per pageview, so no time on page is offered.\n */\nconst siteOnly: MetricReach = { dimensions: [] }\nconst umamiReach: Partial<Record<MetricKey, MetricReach>> = {\n\tpageviews: siteOnly,\n\tvisits: siteOnly,\n\tsessions: siteOnly,\n\tbounceRate: siteOnly,\n\tvisitDuration: siteOnly,\n\tvisitors: { dimensions: [...umamiDimensions].filter((dimension) => dimension !== 'goal') },\n\tconversions: { dimensions: ['goal'] },\n}\n\ninterface UmamiParams {\n\tsearch: URLSearchParams\n\t/** Filters a one-value-per-param request could not carry. */\n\tunapplied: AnalyticsFilter[]\n\t/** Two `eq` values on one param: the AND matches nothing, so the read serves no rows. */\n\tempty: boolean\n}\n\n/**\n * The read's range and filters as query params, one value per param: clashing `eq` values match\n * nothing (an empty read), and other clashes keep the first, the page path always winning.\n */\nconst paramsFor = (q: AnalyticsQuery): UmamiParams => {\n\tconst search = new URLSearchParams({\n\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\tendAt: String(q.dateRange.end.getTime()),\n\t})\n\tconst filters = declaredFilters({ filters: umamiFilters }, q.filters, DIMENSION_MAP)\n\tconst eqValues = new Map<string, string>()\n\tfor (const { filter, field } of filters) {\n\t\tif (filter.operator !== 'eq') {\n\t\t\tcontinue\n\t\t}\n\t\tconst held = eqValues.get(field.param)\n\t\tif (held !== undefined && held !== filter.value) {\n\t\t\treturn { search, unapplied: [], empty: true }\n\t\t}\n\t\teqValues.set(field.param, filter.value)\n\t}\n\tconst unapplied: AnalyticsFilter[] = []\n\tconst held = new Map<string, { value: string; filter: AnalyticsFilter }>()\n\tfor (const { filter, field } of filters) {\n\t\t// Umami splits an `eq.` value on commas with no escape, which would widen the question.\n\t\tif (filter.operator === 'eq' && filter.value.includes(',')) {\n\t\t\tunapplied.push(filter)\n\t\t\tcontinue\n\t\t}\n\t\tconst value = paramValue(filter)\n\t\tconst first = held.get(field.param)\n\t\tif (first === undefined) {\n\t\t\theld.set(field.param, { value, filter })\n\t\t\tsearch.set(field.param, value)\n\t\t} else if (first.value !== value) {\n\t\t\tunapplied.push(filter)\n\t\t}\n\t}\n\tif (q.path) {\n\t\tconst value = `eq.${q.path}`\n\t\tconst first = held.get('path')\n\t\tif (first !== undefined && first.value !== value) {\n\t\t\tunapplied.push(first.filter)\n\t\t}\n\t\tsearch.set('path', value)\n\t}\n\treturn { search, unapplied, empty: false }\n}\n\n/** `values` narrowed to the metrics a read asked for. */\nconst requested = (metrics: readonly MetricKey[], values: MetricValues): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tif (values[metric] !== undefined) {\n\t\t\tout[metric] = values[metric]\n\t\t}\n\t}\n\treturn out\n}\n\ninterface UmamiPoint {\n\tx: string\n\ty: number\n}\n\ninterface UmamiSeries {\n\tpageviews: UmamiPoint[]\n\tsessions: UmamiPoint[]\n}\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\n/**\n * The Umami 3.x adapter, cloud and self-hosted. Filter values always carry an explicit `eq.` prefix,\n * so a value starting like an operator is never read as one.\n */\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst endpoints = umamiEndpoints(config.host)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tmetricReach: umamiReach,\n\t\tfilters: umamiFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\treturn {\n\t\tid: 'umami',\n\t\t...adapterLabel(config.label, 'Umami', 'umami({ label })'),\n\t\tcapabilities,\n\t\tcapture: buildCapture(config, endpoints),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst headers = authHeaders()\n\t\t\tconst goalBreakdown = (q.dimensions ?? []).includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst plan = paramsFor(q)\n\t\t\tconst breakdown = firstMapped(q.dimensions, BREAKDOWNS)\n\t\t\t// Umami splits an `eq.` list on commas with no escape, so a slug carrying one is left out\n\t\t\t// and reported rather than widening the read to every event.\n\t\t\tconst askable = (slugs ?? []).filter((slug) => !slug.includes(','))\n\t\t\tconst unaskable = (slugs ?? []).filter((slug) => slug.includes(','))\n\t\t\tconst eventValue = `eq.${askable.join(',')}`\n\t\t\t// Goal rows come from the `event` param, so on a read that fetches them the hint wins and a\n\t\t\t// caller's own event filter is reported unapplied; any other breakdown sends it as written.\n\t\t\tconst eventFilter = (q.filters ?? []).find((f) => f.dimension === 'event')\n\t\t\tconst readsGoals =\n\t\t\t\tgoalBreakdown || (!breakdown && q.metrics.includes('conversions') && slugs !== null)\n\t\t\tconst unapplied: AnalyticsFilter[] = [\n\t\t\t\t...plan.unapplied,\n\t\t\t\t...unaskable.map(\n\t\t\t\t\t(slug): AnalyticsFilter => ({ dimension: 'goal', operator: 'eq', value: slug })\n\t\t\t\t),\n\t\t\t\t...(readsGoals && eventFilter && paramValue(eventFilter) !== eventValue\n\t\t\t\t\t? [eventFilter]\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst unappliedMeta = unapplied.length > 0 ? { unappliedFilters: unapplied } : {}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'umami', fetchedAt, hint, meta: unappliedMeta })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'umami',\n\t\t\t\tfetchedAt,\n\t\t\t\t...unappliedMeta,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\t\t\t// Totals are left undefined rather than zeroed, the same as every other number this\n\t\t\t// adapter cannot report, so the display layer shows \"no data\" instead of a real 0.\n\t\t\tif (plan.empty) {\n\t\t\t\treturn { rows: [], totals: undefined, meta }\n\t\t\t}\n\n\t\t\t/** The read's params plus `extra`, on a fresh copy so no request sees another's. */\n\t\t\tconst search = (extra: Record<string, string> = {}): URLSearchParams => {\n\t\t\t\tconst params = new URLSearchParams(plan.search)\n\t\t\t\tfor (const [name, value] of Object.entries(extra)) {\n\t\t\t\t\tparams.set(name, value)\n\t\t\t\t}\n\t\t\t\treturn params\n\t\t\t}\n\t\t\tconst getJson = <T>(endpoint: string, params: URLSearchParams): Promise<T> =>\n\t\t\t\tupstreamJson<T>(\n\t\t\t\t\tctx,\n\t\t\t\t\t`${endpoints.api}/websites/${config.websiteId}/${endpoint}?${params.toString()}`,\n\t\t\t\t\t{ headers, provider: 'umami', fetch: config.fetch }\n\t\t\t\t)\n\n\t\t\t/**\n\t\t\t * The goal rows for the hint, narrowed to it again on the way back so nothing the API\n\t\t\t * did not restrict can arrive as a goal.\n\t\t\t */\n\t\t\tconst fetchGoalRows = async (): Promise<UmamiPoint[]> => {\n\t\t\t\tif (askable.length === 0) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\t\t\t\tconst data = await getJson<UmamiPoint[]>(\n\t\t\t\t\t'metrics',\n\t\t\t\t\tsearch({ type: GOAL_DIMENSION.param, [GOAL_DIMENSION.param]: eventValue })\n\t\t\t\t)\n\t\t\t\tconst wanted = new Set(askable)\n\t\t\t\treturn data.filter((row) => wanted.has(row.x))\n\t\t\t}\n\n\t\t\tif (goalBreakdown) {\n\t\t\t\tconst rows: AnalyticsRow[] = (await fetchGoalRows()).map((row) => ({\n\t\t\t\t\tdimensions: { goal: row.x },\n\t\t\t\t\tmetrics: { [GOAL_DIMENSION.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst { dimension, field } = breakdown\n\t\t\t\tconst data = await getJson<UmamiPoint[]>('metrics', search({ type: field.param }))\n\t\t\t\t// /metrics reports one number per row, under the name it holds: a requested metric with no\n\t\t\t\t// per-row source is absent rather than labelled with a number it is not.\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { [dimension]: row.x },\n\t\t\t\t\tmetrics: { [field.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\t// Conversions have no place in /stats: their total is the goal rows summed.\n\t\t\t\tconst [stats, goalRows] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiStats>('stats', search()),\n\t\t\t\t\tq.metrics.includes('conversions') && slugs ? fetchGoalRows() : undefined,\n\t\t\t\t])\n\t\t\t\treturn requested(q.metrics, {\n\t\t\t\t\t...(goalRows ? { conversions: goalRows.reduce((sum, row) => sum + row.y, 0) } : {}),\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios read null (not zero) when there are no visits: a bounce rate of\n\t\t\t\t\t// nobody is no data, and a 0 would read as every visitor staying.\n\t\t\t\t\tbounceRate: stats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : null,\n\t\t\t\t\tvisitDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : null,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Umami's only series endpoint reports pageviews and sessions, so a trend on any other\n\t\t\t// metric keeps its /stats headline but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiSeries>(\n\t\t\t\t\t\t'pageviews',\n\t\t\t\t\t\tsearch({ unit: 'day', timezone: q.timezone ?? DEFAULT_TIMEZONE })\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst sessionsByDay = new Map(series.sessions.map((point) => [point.x, point.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const point of series.pageviews) {\n\t\t\t\t\tconst timestamp = dayIso(point.x)\n\t\t\t\t\tif (!timestamp) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst sessions = sessionsByDay.get(point.x) ?? 0\n\t\t\t\t\trows.push({\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tmetrics: requested(q.metrics, { pageviews: point.y, visits: sessions, sessions }),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;AAwDA,MAAM,QAAwB;CAC7B,KAAK;CACL,QAAQ;CACR,MAAM;AACP;;AAGA,MAAM,kBAAuC,IAAI,IAAI,CAAC,gBAAgB,gBAAgB,CAAC;;;;;AAMvF,MAAa,kBAAkB,SAA6C;CAE3E,MAAM,UAAU,qBADA,qBAAqB,MAAM,KAAK,KAAK,EACV,EAAE,QAAQ,UAAU,EAAE,CAAC;CAClE,IAAI,YAAY,MAAM,gBAAgB,IAAI,WAAW,OAAO,CAAC,GAC5D,OAAO;CAER,OAAO;EAAE,KAAK,GAAG,QAAQ;EAAO,QAAQ,GAAG,QAAQ;EAAa,MAAM,GAAG,QAAQ;CAAW;AAC7F;AAEA,SAAS,aAAa,QAAqB,WAA2C;CACrF,OAAO;EACN,OAAO;GACN,QAAQ,CACP;IAAE,QAAQ;IAAc,UAAU,UAAU;IAAQ,MAAM;GAAS,GACnE;IAAE,QAAQ;IAAa,UAAU,UAAU;IAAM,MAAM;GAAO,CAC/D;GACA,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;EAC/C;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;CACA;AACD,CAAC;AAWD,MAAM,gBAA+D;CACpE,MAAM;EAAE,OAAO;EAAQ,QAAQ;CAAW;CAC1C,UAAU;EAAE,O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IAAI,KAAK,MAAO,MAAM,YAAY,MAAM,SAAU,GAAI,IAAI;IAC3E,CAAC;GACF;GAIA,IAAI,EAAE,gBAAgB,OAAO;IAC5B,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAC1C,QACC,aACA,OAAO;KAAE,MAAM;KAAO,UAAU,EAAE,YAAA;IAA6B,CAAC,CACjE,GACA,YAAY,CACb,CAAC;IACD,MAAM,gBAAgB,IAAI,IAAI,OAAO,SAAS,KAAK,UAAU,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC;IAChF,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,SAAS,OAAO,WAAW;KACrC,MAAM,YAAY,OAAO,MAAM,CAAC;KAChC,IAAI,CAAC,WACJ;KAED,MAAM,WAAW,cAAc,IAAI,MAAM,CAAC,KAAK;KAC/C,KAAK,KAAK;MACT;MACA,SAAS,UAAU,EAAE,SAAS;OAAE,WAAW,MAAM;OAAG,QAAQ;OAAU;MAAS,CAAC;KACjF,CAAC;IACF;IACA,OAAO;KAAE;KAAM;KAAQ;IAAK;GAC7B;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK;EACpD;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport { filterableDimensions } from '../../core/capabilities'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsFilter,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport type { WithoutConsentLevel } from '../../tracker/config'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\n\nexport interface UmamiConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Umami'`.\n\t */\n\tlabel?: AdapterLabelOption\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * The self-hosted Umami app's address, base path included (`https://example.com/umami`), whose\n\t * API is read under `/api`; a trailing `/api` is dropped. Unset, or Umami Cloud's, reads the cloud.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/** The fetch reads and the capture proxy reach Umami with. Unset, the global fetch. */\n\tfetch?: FetchLike\n\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`. Umami stores\n\t * nothing on the device, so `'cookieless'` loads the script as it is; `'off'` holds it.\n\t */\n\twithoutConsent?: WithoutConsentLevel\n}\n\n/** Where one Umami install answers: its Stats API, its tracker script, and its event sink. */\nexport interface UmamiEndpoints {\n\tapi: string\n\tscript: string\n\tsend: string\n}\n\nconst CLOUD: UmamiEndpoints = {\n\tapi: 'https://api.umami.is/v1',\n\tscript: 'https://cloud.umami.is/script.js',\n\tsend: 'https://gateway.umami.is/api/send',\n}\n\n/** Umami Cloud's own hosts, which mean the cloud rather than an app address under them. */\nconst CLOUD_HOSTNAMES: ReadonlySet<string> = new Set(['api.umami.is', 'cloud.umami.is'])\n\n/**\n * The endpoints `host` names: the cloud for nothing or for Umami Cloud's own address, otherwise\n * the app address (trailing slashes and a trailing `/api` dropped) with the API under `/api`.\n */\nexport const umamiEndpoints = (host: string | undefined): UmamiEndpoints => {\n\tconst trimmed = withoutTrailingSlash(host?.trim() ?? '')\n\tconst address = withoutTrailingSlash(trimmed.replace(/\\/api$/, ''))\n\tif (address === '' || CLOUD_HOSTNAMES.has(hostnameOf(address))) {\n\t\treturn CLOUD\n\t}\n\treturn { api: `${address}/api`, script: `${address}/script.js`, send: `${address}/api/send` }\n}\n\nfunction buildCapture(config: UmamiConfig, endpoints: UmamiEndpoints): CaptureSupport {\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: endpoints.script, kind: 'script' },\n\t\t\t\t{ source: '/api/send', upstream: endpoints.send, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t\t...cookielessCapture(\n\t\t\t{ kind: 'inherent' },\n\t\t\tadapterWithoutConsent(\n\t\t\t\tconfig.withoutConsent,\n\t\t\t\t'umami({ withoutConsent })',\n\t\t\t\tWITHOUT_CONSENT_LEVELS\n\t\t\t)\n\t\t),\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'visitDuration',\n\t'conversions',\n])\n\ninterface UmamiDimension {\n\t/** Umami filter param, which doubles as the /metrics `type` value. */\n\tparam: string\n\t/** The one metric /metrics reports for this type: y is nothing else. */\n\tmetric: MetricKey\n}\n\n// y is count(distinct session_id) on every pageview and session type, and event\n// occurrences on `type=event`.\nconst DIMENSION_MAP: Partial<Record<DimensionKey, UmamiDimension>> = {\n\tpage: { param: 'path', metric: 'visitors' },\n\treferrer: { param: 'referrer', metric: 'visitors' },\n\tbrowser: { param: 'browser', metric: 'visitors' },\n\tos: { param: 'os', metric: 'visitors' },\n\tdevice: { param: 'device', metric: 'visitors' },\n\tcountry: { param: 'country', metric: 'visitors' },\n\tregion: { param: 'region', metric: 'visitors' },\n\tcity: { param: 'city', metric: 'visitors' },\n\tlanguage: { param: 'language', metric: 'visitors' },\n\tevent: { param: 'event', metric: 'events' },\n\tutmSource: { param: 'utmSource', metric: 'visitors' },\n\tutmMedium: { param: 'utmMedium', metric: 'visitors' },\n\tutmCampaign: { param: 'utmCampaign', metric: 'visitors' },\n\tutmContent: { param: 'utmContent', metric: 'visitors' },\n\tutmTerm: { param: 'utmTerm', metric: 'visitors' },\n}\n\n/**\n * Goals are custom events, so a goal's slug must equal the captured event's name. Only this shape\n * answers `conversions`: other breakdowns and the daily series report none.\n */\nconst GOAL_DIMENSION: UmamiDimension = { param: 'event', metric: 'conversions' }\n\n/**\n * The /metrics types a read groups by. `channel` is Umami's acquisition classification, a type\n * with no filter param, which is why it sits outside {@link DIMENSION_MAP}.\n */\nconst BREAKDOWNS: Partial<Record<DimensionKey, UmamiDimension>> = {\n\t...DIMENSION_MAP,\n\tchannel: { param: 'channel', metric: 'visitors' },\n}\n\n/**\n * Umami's `re.` is `~*`: a case-insensitive partial match, so an unanchored pattern hits\n * anywhere in the value. `c.` is `ilike`, also case-insensitive.\n */\nconst OPERATOR_PREFIX: Record<FilterOperator, string> = {\n\teq: 'eq.',\n\tcontains: 'c.',\n\tmatches: 're.',\n}\n\n/** A filter as its param value, always prefixed so a value starting like an operator stays literal. */\nconst paramValue = (filter: AnalyticsFilter): string =>\n\t`${OPERATOR_PREFIX[filter.operator]}${filter.value}`\n\n/**\n * Every filter param takes equals, contains and a regular expression\n * (https://docs.umami.is/docs/filters), written as the `eq.`, `c.` and `re.` prefixes.\n */\nconst umamiFilters = everyOperatorOn(mappedKeys(DIMENSION_KEYS, DIMENSION_MAP))\n\n// `event` filters but does not group, since /stats reports no `events` number to declare;\n// `goal` and `channel` are the reverse, /metrics types with no matching filter param.\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>([\n\t...filterableDimensions({ filters: umamiFilters }).filter((dimension) => dimension !== 'event'),\n\t'goal',\n\t'channel',\n])\n\n/**\n * /stats answers site totals and /metrics one count per row, so other metrics are site-wide only.\n * Nothing reports time per pageview, so no time on page is offered.\n */\nconst siteOnly: MetricReach = { dimensions: [] }\nconst umamiReach: Partial<Record<MetricKey, MetricReach>> = {\n\tpageviews: siteOnly,\n\tvisits: siteOnly,\n\tsessions: siteOnly,\n\tbounceRate: siteOnly,\n\tvisitDuration: siteOnly,\n\tvisitors: { dimensions: [...umamiDimensions].filter((dimension) => dimension !== 'goal') },\n\tconversions: { dimensions: ['goal'] },\n}\n\ninterface UmamiParams {\n\tsearch: URLSearchParams\n\t/** Filters a one-value-per-param request could not carry. */\n\tunapplied: AnalyticsFilter[]\n\t/** Two `eq` values on one param: the AND matches nothing, so the read serves no rows. */\n\tempty: boolean\n}\n\n/**\n * The read's range and filters as query params, one value per param: clashing `eq` values match\n * nothing (an empty read), and other clashes keep the first, the page path always winning.\n */\nconst paramsFor = (q: AnalyticsQuery): UmamiParams => {\n\tconst search = new URLSearchParams({\n\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\tendAt: String(q.dateRange.end.getTime()),\n\t})\n\tconst filters = declaredFilters({ filters: umamiFilters }, q.filters, DIMENSION_MAP)\n\tconst eqValues = new Map<string, string>()\n\tfor (const { filter, field } of filters) {\n\t\tif (filter.operator !== 'eq') {\n\t\t\tcontinue\n\t\t}\n\t\tconst held = eqValues.get(field.param)\n\t\tif (held !== undefined && held !== filter.value) {\n\t\t\treturn { search, unapplied: [], empty: true }\n\t\t}\n\t\teqValues.set(field.param, filter.value)\n\t}\n\tconst unapplied: AnalyticsFilter[] = []\n\tconst held = new Map<string, { value: string; filter: AnalyticsFilter }>()\n\tfor (const { filter, field } of filters) {\n\t\t// Umami splits an `eq.` value on commas with no escape, which would widen the question.\n\t\tif (filter.operator === 'eq' && filter.value.includes(',')) {\n\t\t\tunapplied.push(filter)\n\t\t\tcontinue\n\t\t}\n\t\tconst value = paramValue(filter)\n\t\tconst first = held.get(field.param)\n\t\tif (first === undefined) {\n\t\t\theld.set(field.param, { value, filter })\n\t\t\tsearch.set(field.param, value)\n\t\t} else if (first.value !== value) {\n\t\t\tunapplied.push(filter)\n\t\t}\n\t}\n\tif (q.path) {\n\t\tconst value = `eq.${q.path}`\n\t\tconst first = held.get('path')\n\t\tif (first !== undefined && first.value !== value) {\n\t\t\tunapplied.push(first.filter)\n\t\t}\n\t\tsearch.set('path', value)\n\t}\n\treturn { search, unapplied, empty: false }\n}\n\n/** `values` narrowed to the metrics a read asked for. */\nconst requested = (metrics: readonly MetricKey[], values: MetricValues): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tif (values[metric] !== undefined) {\n\t\t\tout[metric] = values[metric]\n\t\t}\n\t}\n\treturn out\n}\n\ninterface UmamiPoint {\n\tx: string\n\ty: number\n}\n\ninterface UmamiSeries {\n\tpageviews: UmamiPoint[]\n\tsessions: UmamiPoint[]\n}\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\n/**\n * The Umami 3.x adapter, cloud and self-hosted. Filter values always carry an explicit `eq.` prefix,\n * so a value starting like an operator is never read as one.\n */\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst endpoints = umamiEndpoints(config.host)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tmetricReach: umamiReach,\n\t\tfilters: umamiFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\treturn {\n\t\tid: 'umami',\n\t\t...adapterLabel(config.label, 'Umami', 'umami({ label })'),\n\t\tcapabilities,\n\t\tcapture: buildCapture(config, endpoints),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst headers = authHeaders()\n\t\t\tconst goalBreakdown = (q.dimensions ?? []).includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst plan = paramsFor(q)\n\t\t\tconst breakdown = firstMapped(q.dimensions, BREAKDOWNS)\n\t\t\t// Umami splits an `eq.` list on commas with no escape, so a slug carrying one is left out\n\t\t\t// and reported rather than widening the read to every event.\n\t\t\tconst askable = (slugs ?? []).filter((slug) => !slug.includes(','))\n\t\t\tconst unaskable = (slugs ?? []).filter((slug) => slug.includes(','))\n\t\t\tconst eventValue = `eq.${askable.join(',')}`\n\t\t\t// Goal rows come from the `event` param, so on a read that fetches them the hint wins and a\n\t\t\t// caller's own event filter is reported unapplied; any other breakdown sends it as written.\n\t\t\tconst eventFilter = (q.filters ?? []).find((f) => f.dimension === 'event')\n\t\t\tconst readsGoals =\n\t\t\t\tgoalBreakdown || (!breakdown && q.metrics.includes('conversions') && slugs !== null)\n\t\t\tconst unapplied: AnalyticsFilter[] = [\n\t\t\t\t...plan.unapplied,\n\t\t\t\t...unaskable.map(\n\t\t\t\t\t(slug): AnalyticsFilter => ({ dimension: 'goal', operator: 'eq', value: slug })\n\t\t\t\t),\n\t\t\t\t...(readsGoals && eventFilter && paramValue(eventFilter) !== eventValue\n\t\t\t\t\t? [eventFilter]\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst unappliedMeta = unapplied.length > 0 ? { unappliedFilters: unapplied } : {}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'umami', fetchedAt, hint, meta: unappliedMeta })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'umami',\n\t\t\t\tfetchedAt,\n\t\t\t\t...unappliedMeta,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\t\t\t// Totals are left undefined rather than zeroed, the same as every other number this\n\t\t\t// adapter cannot report, so the display layer shows \"no data\" instead of a real 0.\n\t\t\tif (plan.empty) {\n\t\t\t\treturn { rows: [], totals: undefined, meta }\n\t\t\t}\n\n\t\t\t/** The read's params plus `extra`, on a fresh copy so no request sees another's. */\n\t\t\tconst search = (extra: Record<string, string> = {}): URLSearchParams => {\n\t\t\t\tconst params = new URLSearchParams(plan.search)\n\t\t\t\tfor (const [name, value] of Object.entries(extra)) {\n\t\t\t\t\tparams.set(name, value)\n\t\t\t\t}\n\t\t\t\treturn params\n\t\t\t}\n\t\t\tconst getJson = <T>(endpoint: string, params: URLSearchParams): Promise<T> =>\n\t\t\t\tupstreamJson<T>(\n\t\t\t\t\tctx,\n\t\t\t\t\t`${endpoints.api}/websites/${config.websiteId}/${endpoint}?${params.toString()}`,\n\t\t\t\t\t{ headers, provider: 'umami', fetch: config.fetch }\n\t\t\t\t)\n\n\t\t\t/**\n\t\t\t * The goal rows for the hint, narrowed to it again on the way back so nothing the API\n\t\t\t * did not restrict can arrive as a goal.\n\t\t\t */\n\t\t\tconst fetchGoalRows = async (): Promise<UmamiPoint[]> => {\n\t\t\t\tif (askable.length === 0) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\t\t\t\tconst data = await getJson<UmamiPoint[]>(\n\t\t\t\t\t'metrics',\n\t\t\t\t\tsearch({ type: GOAL_DIMENSION.param, [GOAL_DIMENSION.param]: eventValue })\n\t\t\t\t)\n\t\t\t\tconst wanted = new Set(askable)\n\t\t\t\treturn data.filter((row) => wanted.has(row.x))\n\t\t\t}\n\n\t\t\tif (goalBreakdown) {\n\t\t\t\tconst rows: AnalyticsRow[] = (await fetchGoalRows()).map((row) => ({\n\t\t\t\t\tdimensions: { goal: row.x },\n\t\t\t\t\tmetrics: { [GOAL_DIMENSION.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst { dimension, field } = breakdown\n\t\t\t\tconst data = await getJson<UmamiPoint[]>('metrics', search({ type: field.param }))\n\t\t\t\t// /metrics reports one number per row, under the name it holds: a requested metric with no\n\t\t\t\t// per-row source is absent rather than labelled with a number it is not.\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { [dimension]: row.x },\n\t\t\t\t\tmetrics: { [field.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\t// Conversions have no place in /stats: their total is the goal rows summed.\n\t\t\t\tconst [stats, goalRows] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiStats>('stats', search()),\n\t\t\t\t\tq.metrics.includes('conversions') && slugs ? fetchGoalRows() : undefined,\n\t\t\t\t])\n\t\t\t\treturn requested(q.metrics, {\n\t\t\t\t\t...(goalRows ? { conversions: goalRows.reduce((sum, row) => sum + row.y, 0) } : {}),\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios read null (not zero) when there are no visits: a bounce rate of\n\t\t\t\t\t// nobody is no data, and a 0 would read as every visitor staying.\n\t\t\t\t\tbounceRate: stats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : null,\n\t\t\t\t\tvisitDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : null,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Umami's only series endpoint reports pageviews and sessions, so a trend on any other\n\t\t\t// metric keeps its /stats headline but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiSeries>(\n\t\t\t\t\t\t'pageviews',\n\t\t\t\t\t\tsearch({ unit: 'day', timezone: q.timezone ?? DEFAULT_TIMEZONE })\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst sessionsByDay = new Map(series.sessions.map((point) => [point.x, point.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const point of series.pageviews) {\n\t\t\t\t\tconst timestamp = dayIso(point.x)\n\t\t\t\t\tif (!timestamp) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst sessions = sessionsByDay.get(point.x) ?? 0\n\t\t\t\t\trows.push({\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tmetrics: requested(q.metrics, { pageviews: point.y, visits: sessions, sessions }),\n\t\t\t\t\t})\n\t\t\t\t}\n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,IAAI,KAAK,MAAO,MAAM,YAAY,MAAM,SAAU,GAAI,IAAI;IAC3E,CAAC;GACF;GAIA,IAAI,EAAE,gBAAgB,OAAO;IAC5B,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAC1C,QACC,aACA,OAAO;KAAE,MAAM;KAAO,UAAU,EAAE,YAAA;IAA6B,CAAC,CACjE,GACA,YAAY,CACb,CAAC;IACD,MAAM,gBAAgB,IAAI,IAAI,OAAO,SAAS,KAAK,UAAU,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC;IAChF,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,SAAS,OAAO,WAAW;KACrC,MAAM,YAAY,OAAO,MAAM,CAAC;KAChC,IAAI,CAAC,WACJ;KAED,MAAM,WAAW,cAAc,IAAI,MAAM,CAAC,KAAK;KAC/C,KAAK,KAAK;MACT;MACA,SAAS,UAAU,EAAE,SAAS;OAAE,WAAW,MAAM;OAAG,QAAQ;OAAU;MAAS,CAAC;KACjF,CAAC;IACF;IACA,OAAO;KAAE;KAAM;KAAQ;IAAK;GAC7B;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK;EACpD;CACD;AACD"}
|
|
@@ -8,6 +8,7 @@ import { DEFAULT_AUTO_CAPTURE } from "../tracker/config.js";
|
|
|
8
8
|
import { DEFAULT_TRACKER_SKIP } from "../tracker/skip.js";
|
|
9
9
|
import { withExclusionPrelude } from "./exclusionPrelude.js";
|
|
10
10
|
import { normalizeMountPath } from "./mountPath.js";
|
|
11
|
+
import { fullSnippetArgs, slotWithoutConsent, snippetModeArgs } from "./withoutConsent.js";
|
|
11
12
|
import { formatAdminURL } from "payload/shared";
|
|
12
13
|
//#region src/capture/trackerConfig.ts
|
|
13
14
|
/**
|
|
@@ -91,6 +92,14 @@ const warnSharedVendor = (payload, args) => {
|
|
|
91
92
|
warnedSharedVendor.add(payload);
|
|
92
93
|
payload.logger?.warn(`analytics: the ${args.slot} slot resolved to "${args.adapterId}", a second ${args.kind} slot beside "${args.first.adapterId}" on the ${args.first.slot} slot. ${args.kind} runs one client per page, so two slots of it would share that client: neither slot's gate could be answered alone and the ${args.slot} slot's events could land in the other slot's project. The ${args.slot} slot is left out of the tracker config; only PostHog runs a second client beside the first. Logged once.`);
|
|
93
94
|
};
|
|
95
|
+
/** The Payload instances that already logged a `capture.withoutConsent` function failing. */
|
|
96
|
+
const warnedWithoutConsent = /* @__PURE__ */ new WeakSet();
|
|
97
|
+
/** A `capture.withoutConsent` function that threw or answered nonsense, logged once per instance. */
|
|
98
|
+
const warnWithoutConsent = (payload, slot, err) => {
|
|
99
|
+
if (!payload || warnedWithoutConsent.has(payload)) return;
|
|
100
|
+
warnedWithoutConsent.add(payload);
|
|
101
|
+
payload.logger?.warn(`analytics: capture.withoutConsent failed for the ${slot} slot, which therefore sends nothing without consent: ${err instanceof Error ? err.message : String(err)}. Logged once.`);
|
|
102
|
+
};
|
|
94
103
|
/**
|
|
95
104
|
* The per-request tracker config, one entry per capturing slot in slot order. Public and anonymous
|
|
96
105
|
* (the visitor's request, no user or cookies), so any failure drops a slot instead of erroring.
|
|
@@ -132,20 +141,34 @@ const resolveTrackerConfig = async (args) => {
|
|
|
132
141
|
adapterId: adapter.id,
|
|
133
142
|
kind
|
|
134
143
|
}, (err) => req.payload?.logger?.warn(`analytics: capture.gate threw for the ${slot} slot, which waits: ${String(err)}`));
|
|
144
|
+
const withoutConsent = gated ? slotWithoutConsent({
|
|
145
|
+
slot,
|
|
146
|
+
adapterId: adapter.id,
|
|
147
|
+
kind,
|
|
148
|
+
capture,
|
|
149
|
+
option: runtime.captureWithoutConsent
|
|
150
|
+
}, (err) => warnWithoutConsent(req.payload, slot, err)) : void 0;
|
|
135
151
|
try {
|
|
152
|
+
const snippetFor = (args) => withExclusionPrelude(capture.snippet({
|
|
153
|
+
path,
|
|
154
|
+
scope,
|
|
155
|
+
...instance ? { instance } : {},
|
|
156
|
+
...args
|
|
157
|
+
}), exclusion?.param);
|
|
158
|
+
const snippet = snippetFor(snippetModeArgs(withoutConsent));
|
|
159
|
+
const fullArgs = fullSnippetArgs(withoutConsent);
|
|
160
|
+
const fullSnippet = fullArgs ? snippetFor(fullArgs) : void 0;
|
|
136
161
|
slots.push({
|
|
137
162
|
slot,
|
|
138
163
|
kind,
|
|
139
164
|
adapterId: adapter.id,
|
|
140
165
|
path,
|
|
141
|
-
snippet
|
|
142
|
-
|
|
143
|
-
scope,
|
|
144
|
-
...instance ? { instance } : {}
|
|
145
|
-
}), exclusion?.param),
|
|
166
|
+
snippet,
|
|
167
|
+
...fullSnippet && JSON.stringify(fullSnippet) !== JSON.stringify(snippet) ? { fullSnippet } : {},
|
|
146
168
|
client: capture.client,
|
|
147
169
|
...instance ? { instance } : {},
|
|
148
|
-
gated
|
|
170
|
+
gated,
|
|
171
|
+
...withoutConsent ? { withoutConsent } : {}
|
|
149
172
|
});
|
|
150
173
|
filled.add(adapter.id);
|
|
151
174
|
} catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trackerConfig.js","names":[],"sources":["../../src/capture/trackerConfig.ts"],"sourcesContent":["import type { Payload, PayloadRequest, SanitizedConfig } from 'payload'\nimport { formatAdminURL } from 'payload/shared'\nimport type { ResolvedGoal } from '../goals/resolver'\nimport { apiPath, appPath } from '../plugin/apiPath'\nimport { analyticsRoutes } from '../plugin/routes'\nimport {\n\ttype AnalyticsRuntime,\n\tresolveCaptureScopeFor,\n\tresolveGoalsDetailedFor,\n} from '../plugin/runtime'\nimport {\n\ttype AdminDigest,\n\ttype CaptureClientKind,\n\ttype CaptureSlot,\n\tDEFAULT_AUTO_CAPTURE,\n\ttype TrackerConfig,\n\ttype TrackerExclusion,\n\ttype TrackerGoal,\n\ttype TrackerSlotConfig,\n} from '../tracker/config'\nimport { DEFAULT_TRACKER_SKIP } from '../tracker/skip'\nimport { captureRequest } from './captureRequest'\nimport { withExclusionPrelude } from './exclusionPrelude'\nimport { exclusionToken, exclusionTokenHash, publicDigest } from './exclusionToken'\nimport { normalizeMountPath } from './mountPath'\nimport { CAPTURE_SLOTS, gateHolds, resolveSlotAdapterFor } from './slots'\n\n/**\n * The admin's address as a page reaches it, behind the Next basePath, as digests: its origin only\n * when `serverURL` puts it on one, its path without a trailing slash.\n */\nconst adminDigest = (config: Partial<SanitizedConfig>): AdminDigest => {\n\tconst address = formatAdminURL({\n\t\tadminRoute: config.routes?.admin ?? '/admin',\n\t\tpath: '',\n\t\tserverURL: config.serverURL,\n\t\tincludeBasePath: true,\n\t})\n\tlet origin: string | undefined\n\tlet path = address\n\tif (/^https?:\\/\\//i.test(address)) {\n\t\ttry {\n\t\t\tconst url = new URL(address)\n\t\t\torigin = url.origin\n\t\t\tpath = url.pathname\n\t\t} catch {\n\t\t\t// A serverURL that does not parse: its digest matches no window, so no page reads as a preview.\n\t\t}\n\t}\n\treturn {\n\t\t...(origin === undefined ? {} : { origin: publicDigest(origin) }),\n\t\tpath: publicDigest(path.replace(/\\/+$/, '') || '/'),\n\t}\n}\n\n/** What the config says about skipping: the install's choice when not the default, and the admin. */\nconst skipFields = (\n\truntime: AnalyticsRuntime,\n\tconfig: Partial<SanitizedConfig>,\n\tdraft: boolean\n): Pick<TrackerConfig, 'skip' | 'draft' | 'admin'> => {\n\tconst skip = runtime.captureSkip ?? DEFAULT_TRACKER_SKIP\n\tconst changed =\n\t\tskip.automation !== DEFAULT_TRACKER_SKIP.automation ||\n\t\tskip.previews !== DEFAULT_TRACKER_SKIP.previews\n\treturn {\n\t\t...(changed ? { skip: { ...skip } } : {}),\n\t\t...(draft ? { draft: true } : {}),\n\t\t...(skip.previews ? { admin: adminDigest(config) } : {}),\n\t}\n}\n\nconst trackerGoals = (goals: ResolvedGoal[]): TrackerGoal[] =>\n\tgoals\n\t\t.filter((entry) => entry.source !== 'builtin')\n\t\t.map(({ goal: { slug, match, value, currency } }) => ({\n\t\t\tslug,\n\t\t\tmatch,\n\t\t\t...(value ? { value } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t}))\n\n/** The visit's scope, or null when the host's resolver has none or throws. */\nconst scopeFor = async (runtime: AnalyticsRuntime, req: PayloadRequest): Promise<string | null> => {\n\ttry {\n\t\treturn await resolveCaptureScopeFor(runtime, req)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: tracker config scope resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n\n/** The scope's merged goals, falling back to the config goals when the merge fails. */\nconst goalsFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<ResolvedGoal[]> => {\n\ttry {\n\t\treturn await resolveGoalsDetailedFor(runtime, req, scope)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(\n\t\t\t`analytics: tracker config goals resolution failed, falling back to config goals: ${String(err)}`\n\t\t)\n\t\treturn (runtime.goals ?? []).map((goal) => ({ goal, source: 'config' as const }))\n\t}\n}\n\n/** The scope's exclusion link as the tracker sees it: the token's hash, never the token. */\nconst exclusionFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): TrackerExclusion | undefined => {\n\tconst secret = req.payload?.secret\n\tif (!runtime.exclusion || typeof secret !== 'string' || secret === '') {\n\t\treturn undefined\n\t}\n\treturn {\n\t\tparam: runtime.exclusion.param,\n\t\ttokenHash: exclusionTokenHash(exclusionToken(secret, scope)),\n\t}\n}\n\n/** The Payload instances that already logged a vendor filling both slots, so a busy site hears it once. */\nconst warnedSharedVendor = new WeakSet<Payload>()\n\n/**\n * The vendors whose browser SDK runs a second client beside the first, each with its own project,\n * gate and storage: a second slot of one of these kinds captures through a client named after it.\n */\nconst NAMED_CLIENT_KINDS: ReadonlySet<CaptureClientKind> = new Set<CaptureClientKind>(['posthog'])\n\n/** Why the second slot of one vendor kind is left out, logged once per instance. */\nconst warnSharedVendor = (\n\tpayload: Payload | undefined,\n\targs: { slot: CaptureSlot; adapterId: string; kind: CaptureClientKind; first: TrackerSlotConfig }\n): void => {\n\tif (!payload || warnedSharedVendor.has(payload)) {\n\t\treturn\n\t}\n\twarnedSharedVendor.add(payload)\n\tpayload.logger?.warn(\n\t\t`analytics: the ${args.slot} slot resolved to \"${args.adapterId}\", a second ${args.kind} slot beside \"${args.first.adapterId}\" on the ${args.first.slot} slot. ${args.kind} runs one client per page, so two slots of it would share that client: neither slot's gate could be answered alone and the ${args.slot} slot's events could land in the other slot's project. The ${args.slot} slot is left out of the tracker config; only PostHog runs a second client beside the first. Logged once.`\n\t)\n}\n\n/**\n * The per-request tracker config, one entry per capturing slot in slot order. Public and anonymous\n * (the visitor's request, no user or cookies), so any failure drops a slot instead of erroring.\n */\nexport const resolveTrackerConfig = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\t/** The page is rendered in draft mode, which `capture.skip.previews` leaves uncounted. */\n\tdraft?: boolean\n}): Promise<TrackerConfig> => {\n\tconst { runtime } = args\n\tconst req = captureRequest(args.req)\n\tconst config = req.payload?.config ?? {}\n\tconst routes = analyticsRoutes(req.payload?.config)\n\t// One scope resolution for the whole config: the slots and the goals must agree on it,\n\t// and the host's resolver can be as expensive as a database read.\n\tconst scope = await scopeFor(runtime, req)\n\tconst exclusion = exclusionFor(runtime, req, scope)\n\tconst slots: TrackerSlotConfig[] = []\n\tconst filled = new Set<string>()\n\tfor (const slot of CAPTURE_SLOTS) {\n\t\tconst adapter = await resolveSlotAdapterFor({ runtime, req, slot, scope })\n\t\tconst capture = adapter?.capture\n\t\t// One adapter fills one slot: two sinks for it would send every event twice.\n\t\tif (!adapter || !capture || filled.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst kind = capture.client.kind\n\t\tconst first = slots.find((entry) => entry.kind === kind)\n\t\tif (first && !NAMED_CLIENT_KINDS.has(kind)) {\n\t\t\twarnSharedVendor(req.payload, { slot, adapterId: adapter.id, kind, first })\n\t\t\tcontinue\n\t\t}\n\t\tconst instance = first ? slot : undefined\n\t\tconst override = runtime.capturePaths?.[slot]\n\t\tconst path = override\n\t\t\t? appPath(normalizeMountPath(override))\n\t\t\t: apiPath(config, `${routes.proxy}/${slot}`)\n\t\tconst gated = gateHolds(runtime, { slot, adapterId: adapter.id, kind }, (err) =>\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture.gate threw for the ${slot} slot, which waits: ${String(err)}`\n\t\t\t)\n\t\t)\n\t\ttry {\n\t\t\tslots.push({\n\t\t\t\tslot,\n\t\t\t\tkind,\n\t\t\t\tadapterId: adapter.id,\n\t\t\t\tpath,\n\t\t\t\tsnippet: withExclusionPrelude(\n\t\t\t\t\tcapture.snippet({ path, scope, ...(instance ? { instance } : {}) }),\n\t\t\t\t\texclusion?.param\n\t\t\t\t),\n\t\t\t\tclient: capture.client,\n\t\t\t\t...(instance ? { instance } : {}),\n\t\t\t\tgated,\n\t\t\t})\n\t\t\tfilled.add(adapter.id)\n\t\t} catch (err) {\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture snippet for \"${adapter.id}\" failed, dropping the ${slot} slot: ${String(err)}`\n\t\t\t)\n\t\t}\n\t}\n\treturn {\n\t\tslots,\n\t\tautoCapture: runtime.autoCapture ?? DEFAULT_AUTO_CAPTURE,\n\t\tgoals: trackerGoals(await goalsFor(runtime, req, scope)),\n\t\tingestPath: apiPath(config, runtime.ingestPath ?? routes.ingest),\n\t\t...(exclusion ? { exclusion } : {}),\n\t\t...skipFields(runtime, config, args.draft === true),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,MAAM,eAAe,WAAkD;CACtE,MAAM,UAAU,eAAe;EAC9B,YAAY,OAAO,QAAQ,SAAS;EACpC,MAAM;EACN,WAAW,OAAO;EAClB,iBAAiB;CAClB,CAAC;CACD,IAAI;CACJ,IAAI,OAAO;CACX,IAAI,gBAAgB,KAAK,OAAO,GAC/B,IAAI;EACH,MAAM,MAAM,IAAI,IAAI,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S,CAAC,mBAAmB,IAAI,IAAI,GAAG;GAC3C,iBAAiB,IAAI,SAAS;IAAE;IAAM,WAAW,QAAQ;IAAI;IAAM;GAAM,CAAC;GAC1E;EACD;EACA,MAAM,WAAW,QAAQ,OAAO,KAAA;EAChC,MAAM,WAAW,QAAQ,eAAe;EACxC,MAAM,OAAO,WACV,QAAQ,mBAAmB,QAAQ,CAAC,IACpC,QAAQ,QAAQ,GAAG,OAAO,MAAM,GAAG,MAAM;EAC5C,MAAM,QAAQ,UAAU,SAAS;GAAE;GAAM,WAAW,QAAQ;GAAI;EAAK,IAAI,QACxE,IAAI,SAAS,QAAQ,KACpB,yCAAyC,KAAK,sBAAsB,OAAO,GAAG,GAC/E,CACD;EACA,IAAI;GACH,MAAM,KAAK;IACV;IACA;IACA,WAAW,QAAQ;IACnB;IACA,SAAS,qBACR,QAAQ,QAAQ;KAAE;KAAM;KAAO,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;IAAG,CAAC,GAClE,WAAW,KACZ;IACA,QAAQ,QAAQ;IAChB,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;IAC/B;GACD,CAAC;GACD,OAAO,IAAI,QAAQ,EAAE;EACtB,SAAS,KAAK;GACb,IAAI,SAAS,QAAQ,KACpB,mCAAmC,QAAQ,GAAG,yBAAyB,KAAK,SAAS,OAAO,GAAG,GAChG;EACD;CACD;CACA,OAAO;EACN;EACA,aAAa,QAAQ,eAAe;EACpC,OAAO,aAAa,MAAM,SAAS,SAAS,KAAK,KAAK,CAAC;EACvD,YAAY,QAAQ,QAAQ,QAAQ,cAAc,OAAO,MAAM;EAC/D,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;EACjC,GAAG,WAAW,SAAS,QAAQ,KAAK,UAAU,IAAI;CACnD;AACD"}
|
|
1
|
+
{"version":3,"file":"trackerConfig.js","names":[],"sources":["../../src/capture/trackerConfig.ts"],"sourcesContent":["import type { Payload, PayloadRequest, SanitizedConfig } from 'payload'\nimport { formatAdminURL } from 'payload/shared'\nimport type { SnippetArgs } from '../core/capture'\nimport type { ResolvedGoal } from '../goals/resolver'\nimport { apiPath, appPath } from '../plugin/apiPath'\nimport { analyticsRoutes } from '../plugin/routes'\nimport {\n\ttype AnalyticsRuntime,\n\tresolveCaptureScopeFor,\n\tresolveGoalsDetailedFor,\n} from '../plugin/runtime'\nimport {\n\ttype AdminDigest,\n\ttype CaptureClientKind,\n\ttype CaptureSlot,\n\ttype CaptureSnippet,\n\tDEFAULT_AUTO_CAPTURE,\n\ttype TrackerConfig,\n\ttype TrackerExclusion,\n\ttype TrackerGoal,\n\ttype TrackerSlotConfig,\n} from '../tracker/config'\nimport { DEFAULT_TRACKER_SKIP } from '../tracker/skip'\nimport { captureRequest } from './captureRequest'\nimport { withExclusionPrelude } from './exclusionPrelude'\nimport { exclusionToken, exclusionTokenHash, publicDigest } from './exclusionToken'\nimport { normalizeMountPath } from './mountPath'\nimport { CAPTURE_SLOTS, gateHolds, resolveSlotAdapterFor } from './slots'\nimport { fullSnippetArgs, slotWithoutConsent, snippetModeArgs } from './withoutConsent'\n\n/**\n * The admin's address as a page reaches it, behind the Next basePath, as digests: its origin only\n * when `serverURL` puts it on one, its path without a trailing slash.\n */\nconst adminDigest = (config: Partial<SanitizedConfig>): AdminDigest => {\n\tconst address = formatAdminURL({\n\t\tadminRoute: config.routes?.admin ?? '/admin',\n\t\tpath: '',\n\t\tserverURL: config.serverURL,\n\t\tincludeBasePath: true,\n\t})\n\tlet origin: string | undefined\n\tlet path = address\n\tif (/^https?:\\/\\//i.test(address)) {\n\t\ttry {\n\t\t\tconst url = new URL(address)\n\t\t\torigin = url.origin\n\t\t\tpath = url.pathname\n\t\t} catch {\n\t\t\t// A serverURL that does not parse: its digest matches no window, so no page reads as a preview.\n\t\t}\n\t}\n\treturn {\n\t\t...(origin === undefined ? {} : { origin: publicDigest(origin) }),\n\t\tpath: publicDigest(path.replace(/\\/+$/, '') || '/'),\n\t}\n}\n\n/** What the config says about skipping: the install's choice when not the default, and the admin. */\nconst skipFields = (\n\truntime: AnalyticsRuntime,\n\tconfig: Partial<SanitizedConfig>,\n\tdraft: boolean\n): Pick<TrackerConfig, 'skip' | 'draft' | 'admin'> => {\n\tconst skip = runtime.captureSkip ?? DEFAULT_TRACKER_SKIP\n\tconst changed =\n\t\tskip.automation !== DEFAULT_TRACKER_SKIP.automation ||\n\t\tskip.previews !== DEFAULT_TRACKER_SKIP.previews\n\treturn {\n\t\t...(changed ? { skip: { ...skip } } : {}),\n\t\t...(draft ? { draft: true } : {}),\n\t\t...(skip.previews ? { admin: adminDigest(config) } : {}),\n\t}\n}\n\nconst trackerGoals = (goals: ResolvedGoal[]): TrackerGoal[] =>\n\tgoals\n\t\t.filter((entry) => entry.source !== 'builtin')\n\t\t.map(({ goal: { slug, match, value, currency } }) => ({\n\t\t\tslug,\n\t\t\tmatch,\n\t\t\t...(value ? { value } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t}))\n\n/** The visit's scope, or null when the host's resolver has none or throws. */\nconst scopeFor = async (runtime: AnalyticsRuntime, req: PayloadRequest): Promise<string | null> => {\n\ttry {\n\t\treturn await resolveCaptureScopeFor(runtime, req)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: tracker config scope resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n\n/** The scope's merged goals, falling back to the config goals when the merge fails. */\nconst goalsFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<ResolvedGoal[]> => {\n\ttry {\n\t\treturn await resolveGoalsDetailedFor(runtime, req, scope)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(\n\t\t\t`analytics: tracker config goals resolution failed, falling back to config goals: ${String(err)}`\n\t\t)\n\t\treturn (runtime.goals ?? []).map((goal) => ({ goal, source: 'config' as const }))\n\t}\n}\n\n/** The scope's exclusion link as the tracker sees it: the token's hash, never the token. */\nconst exclusionFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): TrackerExclusion | undefined => {\n\tconst secret = req.payload?.secret\n\tif (!runtime.exclusion || typeof secret !== 'string' || secret === '') {\n\t\treturn undefined\n\t}\n\treturn {\n\t\tparam: runtime.exclusion.param,\n\t\ttokenHash: exclusionTokenHash(exclusionToken(secret, scope)),\n\t}\n}\n\n/** The Payload instances that already logged a vendor filling both slots, so a busy site hears it once. */\nconst warnedSharedVendor = new WeakSet<Payload>()\n\n/**\n * The vendors whose browser SDK runs a second client beside the first, each with its own project,\n * gate and storage: a second slot of one of these kinds captures through a client named after it.\n */\nconst NAMED_CLIENT_KINDS: ReadonlySet<CaptureClientKind> = new Set<CaptureClientKind>(['posthog'])\n\n/** Why the second slot of one vendor kind is left out, logged once per instance. */\nconst warnSharedVendor = (\n\tpayload: Payload | undefined,\n\targs: { slot: CaptureSlot; adapterId: string; kind: CaptureClientKind; first: TrackerSlotConfig }\n): void => {\n\tif (!payload || warnedSharedVendor.has(payload)) {\n\t\treturn\n\t}\n\twarnedSharedVendor.add(payload)\n\tpayload.logger?.warn(\n\t\t`analytics: the ${args.slot} slot resolved to \"${args.adapterId}\", a second ${args.kind} slot beside \"${args.first.adapterId}\" on the ${args.first.slot} slot. ${args.kind} runs one client per page, so two slots of it would share that client: neither slot's gate could be answered alone and the ${args.slot} slot's events could land in the other slot's project. The ${args.slot} slot is left out of the tracker config; only PostHog runs a second client beside the first. Logged once.`\n\t)\n}\n\n/** The Payload instances that already logged a `capture.withoutConsent` function failing. */\nconst warnedWithoutConsent = new WeakSet<Payload>()\n\n/** A `capture.withoutConsent` function that threw or answered nonsense, logged once per instance. */\nconst warnWithoutConsent = (\n\tpayload: Payload | undefined,\n\tslot: CaptureSlot,\n\terr: unknown\n): void => {\n\tif (!payload || warnedWithoutConsent.has(payload)) {\n\t\treturn\n\t}\n\twarnedWithoutConsent.add(payload)\n\tpayload.logger?.warn(\n\t\t`analytics: capture.withoutConsent failed for the ${slot} slot, which therefore sends nothing without consent: ${err instanceof Error ? err.message : String(err)}. Logged once.`\n\t)\n}\n\n/**\n * The per-request tracker config, one entry per capturing slot in slot order. Public and anonymous\n * (the visitor's request, no user or cookies), so any failure drops a slot instead of erroring.\n */\nexport const resolveTrackerConfig = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\t/** The page is rendered in draft mode, which `capture.skip.previews` leaves uncounted. */\n\tdraft?: boolean\n}): Promise<TrackerConfig> => {\n\tconst { runtime } = args\n\tconst req = captureRequest(args.req)\n\tconst config = req.payload?.config ?? {}\n\tconst routes = analyticsRoutes(req.payload?.config)\n\t// One scope resolution for the whole config: the slots and the goals must agree on it,\n\t// and the host's resolver can be as expensive as a database read.\n\tconst scope = await scopeFor(runtime, req)\n\tconst exclusion = exclusionFor(runtime, req, scope)\n\tconst slots: TrackerSlotConfig[] = []\n\tconst filled = new Set<string>()\n\tfor (const slot of CAPTURE_SLOTS) {\n\t\tconst adapter = await resolveSlotAdapterFor({ runtime, req, slot, scope })\n\t\tconst capture = adapter?.capture\n\t\t// One adapter fills one slot: two sinks for it would send every event twice.\n\t\tif (!adapter || !capture || filled.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst kind = capture.client.kind\n\t\tconst first = slots.find((entry) => entry.kind === kind)\n\t\tif (first && !NAMED_CLIENT_KINDS.has(kind)) {\n\t\t\twarnSharedVendor(req.payload, { slot, adapterId: adapter.id, kind, first })\n\t\t\tcontinue\n\t\t}\n\t\tconst instance = first ? slot : undefined\n\t\tconst override = runtime.capturePaths?.[slot]\n\t\tconst path = override\n\t\t\t? appPath(normalizeMountPath(override))\n\t\t\t: apiPath(config, `${routes.proxy}/${slot}`)\n\t\tconst gated = gateHolds(runtime, { slot, adapterId: adapter.id, kind }, (err) =>\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture.gate threw for the ${slot} slot, which waits: ${String(err)}`\n\t\t\t)\n\t\t)\n\t\t// A slot the gate does not hold runs in full from page load, whatever withoutConsent says.\n\t\tconst withoutConsent = gated\n\t\t\t? slotWithoutConsent(\n\t\t\t\t\t{\n\t\t\t\t\t\tslot,\n\t\t\t\t\t\tadapterId: adapter.id,\n\t\t\t\t\t\tkind,\n\t\t\t\t\t\tcapture,\n\t\t\t\t\t\toption: runtime.captureWithoutConsent,\n\t\t\t\t\t},\n\t\t\t\t\t(err) => warnWithoutConsent(req.payload, slot, err)\n\t\t\t\t)\n\t\t\t: undefined\n\t\ttry {\n\t\t\tconst snippetFor = (args: Pick<SnippetArgs, 'mode' | 'withoutConsent'>): CaptureSnippet =>\n\t\t\t\twithExclusionPrelude(\n\t\t\t\t\tcapture.snippet({ path, scope, ...(instance ? { instance } : {}), ...args }),\n\t\t\t\t\texclusion?.param\n\t\t\t\t)\n\t\t\tconst snippet = snippetFor(snippetModeArgs(withoutConsent))\n\t\t\tconst fullArgs = fullSnippetArgs(withoutConsent)\n\t\t\tconst fullSnippet = fullArgs ? snippetFor(fullArgs) : undefined\n\t\t\tslots.push({\n\t\t\t\tslot,\n\t\t\t\tkind,\n\t\t\t\tadapterId: adapter.id,\n\t\t\t\tpath,\n\t\t\t\tsnippet,\n\t\t\t\t// Only where it differs: a vendor that stores nothing renders one snippet in every mode.\n\t\t\t\t...(fullSnippet && JSON.stringify(fullSnippet) !== JSON.stringify(snippet)\n\t\t\t\t\t? { fullSnippet }\n\t\t\t\t\t: {}),\n\t\t\t\tclient: capture.client,\n\t\t\t\t...(instance ? { instance } : {}),\n\t\t\t\tgated,\n\t\t\t\t...(withoutConsent ? { withoutConsent } : {}),\n\t\t\t})\n\t\t\tfilled.add(adapter.id)\n\t\t} catch (err) {\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture snippet for \"${adapter.id}\" failed, dropping the ${slot} slot: ${String(err)}`\n\t\t\t)\n\t\t}\n\t}\n\treturn {\n\t\tslots,\n\t\tautoCapture: runtime.autoCapture ?? DEFAULT_AUTO_CAPTURE,\n\t\tgoals: trackerGoals(await goalsFor(runtime, req, scope)),\n\t\tingestPath: apiPath(config, runtime.ingestPath ?? routes.ingest),\n\t\t...(exclusion ? { exclusion } : {}),\n\t\t...skipFields(runtime, config, args.draft === true),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkCA,MAAM,eAAe,WAAkD;CACtE,MAAM,UAAU,eAAe;EAC9B,YAAY,OAAO,QAAQ,SAAS;EACpC,MAAM;EACN,WAAW,OAAO;EAClB,iBAAiB;CAClB,CAAC;CACD,IAAI;CACJ,IAAI,OAAO;CACX,IAAI,gBAAgB,KAAK,OAAO,GAC/B,IAAI;EACH,MAAM,MAAM,IAAI,IAAI,OAAO;EAC3B,SAAS,IAAI;EACb,OAAO,IAAI;CACZ,QAAQ,CAER;CAED,OAAO;EACN,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,aAAa,MAAM,EAAE;EAC/D,MAAM,aAAa,KAAK,QAAQ,QAAQ,EAAE,KAAK,GAAG;CACnD;AACD;;AAGA,MAAM,cACL,SACA,QACA,UACqD;CACrD,MAAM,OAAO,QAAQ,eAAe;CAIpC,OAAO;EACN,GAHA,KAAK,eAAe,qBAAqB,cACzC,KAAK,aAAa,qBAAqB,WAEzB,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,IAAI,CAAC;EACvC,GAAI,QAAQ,EAAE,OAAO,KAAK,IAAI,CAAC;EAC/B,GAAI,KAAK,WAAW,EAAE,OAAO,YAAY,MAAM,EAAE,IAAI,CAAC;CACvD;AACD;AAEA,MAAM,gBAAgB,UACrB,MACE,QAAQ,UAAU,MAAM,WAAW,SAAS,EAC5C,KAAK,EAAE,MAAM,EAAE,MAAM,OAAO,OAAO,kBAAkB;CACrD;CACA;CACA,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;CACzB,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAChC,EAAE;;AAGJ,MAAM,WAAW,OAAO,SAA2B,QAAgD;CAClG,IAAI;EACH,OAAO,MAAM,uBAAuB,SAAS,GAAG;C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ACH,IAAI;GACH,MAAM,cAAc,SACnB,qBACC,QAAQ,QAAQ;IAAE;IAAM;IAAO,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;IAAI,GAAG;GAAK,CAAC,GAC3E,WAAW,KACZ;GACD,MAAM,UAAU,WAAW,gBAAgB,cAAc,CAAC;GAC1D,MAAM,WAAW,gBAAgB,cAAc;GAC/C,MAAM,cAAc,WAAW,WAAW,QAAQ,IAAI,KAAA;GACtD,MAAM,KAAK;IACV;IACA;IACA,WAAW,QAAQ;IACnB;IACA;IAEA,GAAI,eAAe,KAAK,UAAU,WAAW,MAAM,KAAK,UAAU,OAAO,IACtE,EAAE,YAAY,IACd,CAAC;IACJ,QAAQ,QAAQ;IAChB,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;IAC/B;IACA,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC;GAC5C,CAAC;GACD,OAAO,IAAI,QAAQ,EAAE;EACtB,SAAS,KAAK;GACb,IAAI,SAAS,QAAQ,KACpB,mCAAmC,QAAQ,GAAG,yBAAyB,KAAK,SAAS,OAAO,GAAG,GAChG;EACD;CACD;CACA,OAAO;EACN;EACA,aAAa,QAAQ,eAAe;EACpC,OAAO,aAAa,MAAM,SAAS,SAAS,KAAK,KAAK,CAAC;EACvD,YAAY,QAAQ,QAAQ,QAAQ,cAAc,OAAO,MAAM;EAC/D,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;EACjC,GAAG,WAAW,SAAS,QAAQ,KAAK,UAAU,IAAI;CACnD;AACD"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { isOneOf, kindOf } from "../core/values.js";
|
|
2
|
+
//#region src/capture/withoutConsent.ts
|
|
3
|
+
const CONSENT_PHASES = ["pending", "refused"];
|
|
4
|
+
const WITHOUT_CONSENT_LEVELS = ["cookieless", "off"];
|
|
5
|
+
/** `capture.withoutConsent` left unset. */
|
|
6
|
+
const DEFAULT_WITHOUT_CONSENT = {
|
|
7
|
+
pending: "cookieless",
|
|
8
|
+
refused: "cookieless"
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* A held slot's mode in one phase: the adapter's own setting, else the host's function, else the
|
|
12
|
+
* install's level, where `'cookieless'` takes the adapter's declared default. A function that
|
|
13
|
+
* throws or answers anything else is `off`, reported to `onError`, failing closed like the gate.
|
|
14
|
+
*/
|
|
15
|
+
const heldSlotMode = (args, onError) => {
|
|
16
|
+
const { capture, option, phase, slot, adapterId, kind } = args;
|
|
17
|
+
const support = capture.cookieless;
|
|
18
|
+
if (!support) return "off";
|
|
19
|
+
if (capture.withoutConsent !== void 0) return capture.withoutConsent;
|
|
20
|
+
if (typeof option === "function") {
|
|
21
|
+
try {
|
|
22
|
+
const answer = option({
|
|
23
|
+
slot,
|
|
24
|
+
adapterId,
|
|
25
|
+
kind,
|
|
26
|
+
phase
|
|
27
|
+
});
|
|
28
|
+
if (isOneOf(WITHOUT_CONSENT_LEVELS, answer)) return answer;
|
|
29
|
+
onError?.(/* @__PURE__ */ new Error(`it answered ${kindOf(answer)}, not 'cookieless' or 'off'`));
|
|
30
|
+
} catch (err) {
|
|
31
|
+
onError?.(err);
|
|
32
|
+
}
|
|
33
|
+
return "off";
|
|
34
|
+
}
|
|
35
|
+
return (option ?? DEFAULT_WITHOUT_CONSENT)[phase] === "off" ? "off" : support.default ?? "cookieless";
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* A held slot's modes without consent, or undefined when both are `off`: such a slot's config is
|
|
39
|
+
* exactly 1.0.0-beta.14's.
|
|
40
|
+
*/
|
|
41
|
+
const slotWithoutConsent = (args, onError) => {
|
|
42
|
+
const pending = heldSlotMode({
|
|
43
|
+
...args,
|
|
44
|
+
phase: "pending"
|
|
45
|
+
}, onError);
|
|
46
|
+
const refused = heldSlotMode({
|
|
47
|
+
...args,
|
|
48
|
+
phase: "refused"
|
|
49
|
+
}, onError);
|
|
50
|
+
return pending === "off" && refused === "off" ? void 0 : {
|
|
51
|
+
pending,
|
|
52
|
+
refused
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* What a slot's snippet is rendered for: a held slot that may count without consent starts
|
|
57
|
+
* cookieless and switches up on consent; every other slot gets 1.0.0-beta.14's snippet.
|
|
58
|
+
*/
|
|
59
|
+
const snippetModeArgs = (withoutConsent) => withoutConsent ? {
|
|
60
|
+
mode: "cookieless",
|
|
61
|
+
withoutConsent: true
|
|
62
|
+
} : {
|
|
63
|
+
mode: "full",
|
|
64
|
+
withoutConsent: false
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* What the full variant of a slot counting without consent is rendered for, which a server-known
|
|
68
|
+
* grant renders; undefined for every other slot, whose one snippet is already full.
|
|
69
|
+
*/
|
|
70
|
+
const fullSnippetArgs = (withoutConsent) => withoutConsent ? {
|
|
71
|
+
mode: "full",
|
|
72
|
+
withoutConsent: true
|
|
73
|
+
} : void 0;
|
|
74
|
+
/**
|
|
75
|
+
* An adapter factory's `withoutConsent` (`at` names it, such as `plausible({ withoutConsent })`),
|
|
76
|
+
* refused at boot unless it is one of `allowed`.
|
|
77
|
+
*/
|
|
78
|
+
const adapterWithoutConsent = (value, at, allowed) => {
|
|
79
|
+
if (value === void 0 || isOneOf(allowed, value)) return value;
|
|
80
|
+
const names = allowed.map((level) => `'${level}'`);
|
|
81
|
+
throw new Error(`analytics: ${at} must be ${names.slice(0, -1).join(", ")} or ${names.at(-1)}, got ${kindOf(value)}`);
|
|
82
|
+
};
|
|
83
|
+
/** The `capture` fields an adapter able to count without consent declares, its own setting included. */
|
|
84
|
+
const cookielessCapture = (cookieless, withoutConsent) => ({
|
|
85
|
+
cookieless,
|
|
86
|
+
...withoutConsent === void 0 ? {} : { withoutConsent }
|
|
87
|
+
});
|
|
88
|
+
//#endregion
|
|
89
|
+
export { CONSENT_PHASES, WITHOUT_CONSENT_LEVELS, adapterWithoutConsent, cookielessCapture, fullSnippetArgs, slotWithoutConsent, snippetModeArgs };
|
|
90
|
+
|
|
91
|
+
//# sourceMappingURL=withoutConsent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"withoutConsent.js","names":[],"sources":["../../src/capture/withoutConsent.ts"],"sourcesContent":["import type { CaptureSupport, CookielessSupport, SnippetArgs } from '../core/capture'\nimport type { CaptureGateArgs, ResolvedWithoutConsent } from '../core/options'\nimport { isOneOf, kindOf } from '../core/values'\nimport type {\n\tConsentPhase,\n\tHeldSlotMode,\n\tSlotWithoutConsent,\n\tWithoutConsentLevel,\n} from '../tracker/config'\n\nexport const CONSENT_PHASES: readonly ConsentPhase[] = ['pending', 'refused']\n\nexport const WITHOUT_CONSENT_LEVELS: readonly WithoutConsentLevel[] = ['cookieless', 'off']\n\n/** `capture.withoutConsent` left unset. */\nexport const DEFAULT_WITHOUT_CONSENT: Record<ConsentPhase, WithoutConsentLevel> = {\n\tpending: 'cookieless',\n\trefused: 'cookieless',\n}\n\nexport interface HeldSlotArgs extends CaptureGateArgs {\n\tcapture: Pick<CaptureSupport, 'cookieless' | 'withoutConsent'>\n\t/** `capture.withoutConsent` resolved; absent means unset. */\n\toption: ResolvedWithoutConsent | undefined\n}\n\n/**\n * A held slot's mode in one phase: the adapter's own setting, else the host's function, else the\n * install's level, where `'cookieless'` takes the adapter's declared default. A function that\n * throws or answers anything else is `off`, reported to `onError`, failing closed like the gate.\n */\nexport const heldSlotMode = (\n\targs: HeldSlotArgs & { phase: ConsentPhase },\n\tonError?: (err: unknown) => void\n): HeldSlotMode => {\n\tconst { capture, option, phase, slot, adapterId, kind } = args\n\tconst support = capture.cookieless\n\tif (!support) {\n\t\treturn 'off'\n\t}\n\tif (capture.withoutConsent !== undefined) {\n\t\treturn capture.withoutConsent\n\t}\n\tif (typeof option === 'function') {\n\t\ttry {\n\t\t\tconst answer: unknown = option({ slot, adapterId, kind, phase })\n\t\t\tif (isOneOf(WITHOUT_CONSENT_LEVELS, answer)) {\n\t\t\t\treturn answer\n\t\t\t}\n\t\t\tonError?.(new Error(`it answered ${kindOf(answer)}, not 'cookieless' or 'off'`))\n\t\t} catch (err) {\n\t\t\tonError?.(err)\n\t\t}\n\t\treturn 'off'\n\t}\n\tconst level = (option ?? DEFAULT_WITHOUT_CONSENT)[phase]\n\treturn level === 'off' ? 'off' : (support.default ?? 'cookieless')\n}\n\n/**\n * A held slot's modes without consent, or undefined when both are `off`: such a slot's config is\n * exactly 1.0.0-beta.14's.\n */\nexport const slotWithoutConsent = (\n\targs: HeldSlotArgs,\n\tonError?: (err: unknown) => void\n): SlotWithoutConsent | undefined => {\n\tconst pending = heldSlotMode({ ...args, phase: 'pending' }, onError)\n\tconst refused = heldSlotMode({ ...args, phase: 'refused' }, onError)\n\treturn pending === 'off' && refused === 'off' ? undefined : { pending, refused }\n}\n\n/**\n * What a slot's snippet is rendered for: a held slot that may count without consent starts\n * cookieless and switches up on consent; every other slot gets 1.0.0-beta.14's snippet.\n */\nexport const snippetModeArgs = (\n\twithoutConsent: SlotWithoutConsent | undefined\n): Pick<SnippetArgs, 'mode' | 'withoutConsent'> =>\n\twithoutConsent\n\t\t? { mode: 'cookieless', withoutConsent: true }\n\t\t: { mode: 'full', withoutConsent: false }\n\n/**\n * What the full variant of a slot counting without consent is rendered for, which a server-known\n * grant renders; undefined for every other slot, whose one snippet is already full.\n */\nexport const fullSnippetArgs = (\n\twithoutConsent: SlotWithoutConsent | undefined\n): Pick<SnippetArgs, 'mode' | 'withoutConsent'> | undefined =>\n\twithoutConsent ? { mode: 'full', withoutConsent: true } : undefined\n\n/**\n * An adapter factory's `withoutConsent` (`at` names it, such as `plausible({ withoutConsent })`),\n * refused at boot unless it is one of `allowed`.\n */\nexport const adapterWithoutConsent = <T extends HeldSlotMode>(\n\tvalue: unknown,\n\tat: string,\n\tallowed: readonly T[]\n): T | undefined => {\n\tif (value === undefined || isOneOf(allowed, value)) {\n\t\treturn value\n\t}\n\tconst names = allowed.map((level) => `'${level}'`)\n\tthrow new Error(\n\t\t`analytics: ${at} must be ${names.slice(0, -1).join(', ')} or ${names.at(-1)}, got ${kindOf(value)}`\n\t)\n}\n\n/** The `capture` fields an adapter able to count without consent declares, its own setting included. */\nexport const cookielessCapture = (\n\tcookieless: CookielessSupport,\n\twithoutConsent: HeldSlotMode | undefined\n): Pick<CaptureSupport, 'cookieless' | 'withoutConsent'> => ({\n\tcookieless,\n\t...(withoutConsent === undefined ? {} : { withoutConsent }),\n})\n"],"mappings":";;AAUA,MAAa,iBAA0C,CAAC,WAAW,SAAS;AAE5E,MAAa,yBAAyD,CAAC,cAAc,KAAK;;AAG1F,MAAa,0BAAqE;CACjF,SAAS;CACT,SAAS;AACV;;;;;;AAaA,MAAa,gBACZ,MACA,YACkB;CAClB,MAAM,EAAE,SAAS,QAAQ,OAAO,MAAM,WAAW,SAAS;CAC1D,MAAM,UAAU,QAAQ;CACxB,IAAI,CAAC,SACJ,OAAO;CAER,IAAI,QAAQ,mBAAmB,KAAA,GAC9B,OAAO,QAAQ;CAEhB,IAAI,OAAO,WAAW,YAAY;EACjC,IAAI;GACH,MAAM,SAAkB,OAAO;IAAE;IAAM;IAAW;IAAM;GAAM,CAAC;GAC/D,IAAI,QAAQ,wBAAwB,MAAM,GACzC,OAAO;GAER,0BAAU,IAAI,MAAM,eAAe,OAAO,MAAM,EAAE,4BAA4B,CAAC;EAChF,SAAS,KAAK;GACb,UAAU,GAAG;EACd;EACA,OAAO;CACR;CAEA,QADe,UAAU,yBAAyB,WACjC,QAAQ,QAAS,QAAQ,WAAW;AACtD;;;;;AAMA,MAAa,sBACZ,MACA,YACoC;CACpC,MAAM,UAAU,aAAa;EAAE,GAAG;EAAM,OAAO;CAAU,GAAG,OAAO;CACnE,MAAM,UAAU,aAAa;EAAE,GAAG;EAAM,OAAO;CAAU,GAAG,OAAO;CACnE,OAAO,YAAY,SAAS,YAAY,QAAQ,KAAA,IAAY;EAAE;EAAS;CAAQ;AAChF;;;;;AAMA,MAAa,mBACZ,mBAEA,iBACG;CAAE,MAAM;CAAc,gBAAgB;AAAK,IAC3C;CAAE,MAAM;CAAQ,gBAAgB;AAAM;;;;;AAM1C,MAAa,mBACZ,mBAEA,iBAAiB;CAAE,MAAM;CAAQ,gBAAgB;AAAK,IAAI,KAAA;;;;;AAM3D,MAAa,yBACZ,OACA,IACA,YACmB;CACnB,IAAI,UAAU,KAAA,KAAa,QAAQ,SAAS,KAAK,GAChD,OAAO;CAER,MAAM,QAAQ,QAAQ,KAAK,UAAU,IAAI,MAAM,EAAE;CACjD,MAAM,IAAI,MACT,cAAc,GAAG,WAAW,MAAM,MAAM,GAAG,EAAE,EAAE,KAAK,IAAI,EAAE,MAAM,MAAM,GAAG,EAAE,EAAE,QAAQ,OAAO,KAAK,GAClG;AACD;;AAGA,MAAa,qBACZ,YACA,oBAC4D;CAC5D;CACA,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe;AAC1D"}
|
package/dist/core/capture.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CaptureSnippet, TrackerSlotConfig } from "../tracker/config.js";
|
|
1
|
+
import { CaptureSnippet, HeldSlotMode, TrackerSlotConfig, WithoutConsentLevel } from "../tracker/config.js";
|
|
2
2
|
import { FetchLike } from "./fetch.js";
|
|
3
3
|
|
|
4
4
|
//#region src/core/capture.d.ts
|
|
@@ -29,24 +29,54 @@ interface ProxyDescriptor {
|
|
|
29
29
|
*/
|
|
30
30
|
fetch?: FetchLike;
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* How a vendor counts without consent. `inherent`: it never stores anything, so one snippet serves
|
|
34
|
+
* every phase. `switched`: its sink switches the vendor's client between cookieless and full.
|
|
35
|
+
* `default` is the level `capture.withoutConsent: 'cookieless'` gives it (GA4: `off`).
|
|
36
|
+
*/
|
|
37
|
+
interface CookielessSupport {
|
|
38
|
+
kind: 'inherent' | 'switched';
|
|
39
|
+
default?: WithoutConsentLevel;
|
|
40
|
+
}
|
|
41
|
+
/** What a snippet starts in: `cookieless` for a held slot counting before an answer, else `full`. */
|
|
42
|
+
type SnippetMode = 'cookieless' | 'full';
|
|
43
|
+
interface SnippetArgs {
|
|
44
|
+
path: string;
|
|
45
|
+
/**
|
|
46
|
+
* The request's resolved scope, which a vendor able to carry it stamps on every event. Null when
|
|
47
|
+
* unscoped or unresolved.
|
|
48
|
+
*/
|
|
49
|
+
scope?: string | null;
|
|
50
|
+
/**
|
|
51
|
+
* The client the snippet initialises, set only for a vendor that runs a second client beside the
|
|
52
|
+
* other slot's (PostHog).
|
|
53
|
+
*/
|
|
54
|
+
instance?: string;
|
|
55
|
+
/** Absent (a caller from before 1.0.0-beta.15) means `full`. */
|
|
56
|
+
mode?: SnippetMode;
|
|
57
|
+
/**
|
|
58
|
+
* True when the slot drops to a cookieless level in some phase without consent, so the snippet
|
|
59
|
+
* boots a client able to switch (PostHog: `cookieless_mode: 'on_reject'`). False keeps the
|
|
60
|
+
* strict boot of 1.0.0-beta.14.
|
|
61
|
+
*/
|
|
62
|
+
withoutConsent?: boolean;
|
|
63
|
+
}
|
|
32
64
|
/**
|
|
33
65
|
* How a vendor's browser tracker is proxied and booted. Carries only what the browser may see,
|
|
34
66
|
* never a secret credential such as PostHog's Query API key.
|
|
35
67
|
*/
|
|
36
68
|
interface CaptureSupport {
|
|
37
69
|
proxy: ProxyDescriptor;
|
|
70
|
+
snippet(args: SnippetArgs): CaptureSnippet;
|
|
71
|
+
client: TrackerSlotConfig['client'];
|
|
72
|
+
/** Absent: the vendor cannot count without consent, so its held slot sends nothing until then. */
|
|
73
|
+
cookieless?: CookielessSupport;
|
|
38
74
|
/**
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
* only for a vendor that runs a second client beside the other slot's (PostHog).
|
|
75
|
+
* The adapter's own `withoutConsent` (factory option or provider document), which beats
|
|
76
|
+
* `capture.withoutConsent` for its slot in both phases. Ignored without `cookieless`.
|
|
42
77
|
*/
|
|
43
|
-
|
|
44
|
-
path: string;
|
|
45
|
-
scope?: string | null;
|
|
46
|
-
instance?: string;
|
|
47
|
-
}): CaptureSnippet;
|
|
48
|
-
client: TrackerSlotConfig['client'];
|
|
78
|
+
withoutConsent?: HeldSlotMode;
|
|
49
79
|
}
|
|
50
80
|
//#endregion
|
|
51
|
-
export { CaptureSupport, ProxyDescriptor, ProxyRoute, ProxyRouteKind };
|
|
81
|
+
export { CaptureSupport, CookielessSupport, ProxyDescriptor, ProxyRoute, ProxyRouteKind, SnippetArgs, SnippetMode };
|
|
52
82
|
//# sourceMappingURL=capture.d.ts.map
|
|
@@ -1,17 +1,19 @@
|
|
|
1
|
-
import { kindOf } from "./values.js";
|
|
1
|
+
import { isOneOf, kindOf } from "./values.js";
|
|
2
2
|
import { siteAddress } from "./siteAddress.js";
|
|
3
3
|
import { isTrustedPlatform } from "../net/platform.js";
|
|
4
4
|
import { DEFAULT_PROXY_MAX_BODY_BYTES, DEFAULT_PROXY_TIMEOUT_MS } from "../capture/relay.js";
|
|
5
5
|
import { resolveAllowedOrigins } from "../capture/requestTrust.js";
|
|
6
|
-
import { isCaptureSlot } from "../capture/slots.js";
|
|
6
|
+
import { CAPTURE_SLOTS, isCaptureSlot } from "../capture/slots.js";
|
|
7
7
|
import { DEFAULT_AUTO_CAPTURE, DEFAULT_ITEM_CAPTURE, NO_ITEM_CAPTURE } from "../tracker/config.js";
|
|
8
8
|
import { DEFAULT_TRACKER_SKIP } from "../tracker/skip.js";
|
|
9
9
|
import { DEFAULT_EXCLUSION_PARAM } from "../tracker/exclusion.js";
|
|
10
|
+
import { CONSENT_PHASES, WITHOUT_CONSENT_LEVELS, slotWithoutConsent } from "../capture/withoutConsent.js";
|
|
10
11
|
import { keysOf, optionalBoolean, optionsObject, positiveWhole } from "./optionChecks.js";
|
|
11
12
|
import { assertNamesAdapter } from "./sourceOptions.js";
|
|
12
13
|
//#region src/core/captureOptions.ts
|
|
13
14
|
const CAPTURE_KEYS = keysOf({
|
|
14
15
|
gate: true,
|
|
16
|
+
withoutConsent: true,
|
|
15
17
|
allowedOrigins: true,
|
|
16
18
|
exclusion: true,
|
|
17
19
|
slots: true,
|
|
@@ -90,6 +92,69 @@ const resolveGate = (option, required) => {
|
|
|
90
92
|
if (typeof option === "function") return (args) => option(args) !== false;
|
|
91
93
|
throw new Error(`analytics: capture.gate must be 'all', 'off', a list of slots or a function, got ${kindOf(option)}`);
|
|
92
94
|
};
|
|
95
|
+
const isLevel = (value) => isOneOf(WITHOUT_CONSENT_LEVELS, value);
|
|
96
|
+
const resolveWithoutConsent = (option) => {
|
|
97
|
+
if (option === void 0 || typeof option === "function") return option;
|
|
98
|
+
if (isLevel(option)) return {
|
|
99
|
+
pending: option,
|
|
100
|
+
refused: option
|
|
101
|
+
};
|
|
102
|
+
const phases = optionsObject(option, {
|
|
103
|
+
path: "capture.withoutConsent",
|
|
104
|
+
known: CONSENT_PHASES,
|
|
105
|
+
example: "'cookieless', 'off', an object such as { refused: 'off' } or a function"
|
|
106
|
+
});
|
|
107
|
+
const level = (phase) => {
|
|
108
|
+
const value = phases[phase];
|
|
109
|
+
if (value === void 0) return "cookieless";
|
|
110
|
+
if (!isLevel(value)) throw new Error(`analytics: capture.withoutConsent.${phase} must be 'cookieless' or 'off', got ${kindOf(value)}`);
|
|
111
|
+
return value;
|
|
112
|
+
};
|
|
113
|
+
return {
|
|
114
|
+
pending: level("pending"),
|
|
115
|
+
refused: level("refused")
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
/** Slots the gate may hold, judged without calling host code: a function may hold either. */
|
|
119
|
+
const heldAtBoot = (gate) => new Set(gate === "off" ? [] : Array.isArray(gate) ? gate : CAPTURE_SLOTS);
|
|
120
|
+
/**
|
|
121
|
+
* Whether a source following `capture.withoutConsent` may count without consent: unless the option
|
|
122
|
+
* is `'off'` in both phases, since a function may answer `'cookieless'`.
|
|
123
|
+
*/
|
|
124
|
+
const followingCountsWithoutConsent = (option) => typeof option === "function" || CONSENT_PHASES.some((phase) => (option?.[phase] ?? "cookieless") !== "off");
|
|
125
|
+
/** Whether a config adapter may fill `slot`, as far as the boot can tell without a request. */
|
|
126
|
+
const fillsAtBoot = (fill, slot, adapterId) => {
|
|
127
|
+
const configured = fill.capture.slots[slot];
|
|
128
|
+
if (configured === false) return false;
|
|
129
|
+
if (slot === "tenant") return fill.scoped && (configured === void 0 || configured === adapterId);
|
|
130
|
+
const only = fill.adapters.length === 1 ? fill.adapters[0]?.id : void 0;
|
|
131
|
+
return (configured || fill.platformAdapter || only) === adapterId;
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* Whether a config adapter may count without consent in a slot the gate holds, judged at boot
|
|
135
|
+
* without calling a host function: a `capture.withoutConsent` function may answer `'cookieless'`.
|
|
136
|
+
*/
|
|
137
|
+
const adapterCountsWithoutConsent = (fill, adapter) => {
|
|
138
|
+
const capture = adapter.capture;
|
|
139
|
+
if (!capture) return false;
|
|
140
|
+
const option = fill.capture.withoutConsent;
|
|
141
|
+
const answered = typeof option === "function" ? () => "cookieless" : option;
|
|
142
|
+
return CAPTURE_SLOTS.some((slot) => fill.capture.heldSlots.has(slot) && fillsAtBoot(fill, slot, adapter.id) && slotWithoutConsent({
|
|
143
|
+
slot,
|
|
144
|
+
adapterId: adapter.id,
|
|
145
|
+
kind: capture.client.kind,
|
|
146
|
+
capture,
|
|
147
|
+
option: answered
|
|
148
|
+
}) !== void 0);
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* Whether a held tenant slot may fall to a runtime provider document's adapter: with providers on,
|
|
152
|
+
* unless the slot names a config adapter.
|
|
153
|
+
*/
|
|
154
|
+
const documentsFillHeldTenant = (fill, providersOn) => {
|
|
155
|
+
const configured = fill.capture.slots.tenant;
|
|
156
|
+
return providersOn && fill.scoped && configured !== false && fill.capture.heldSlots.has("tenant") && !fill.adapters.some((adapter) => adapter.id === configured);
|
|
157
|
+
};
|
|
93
158
|
const resolveItemCapture = (option) => option === false ? { ...NO_ITEM_CAPTURE } : {
|
|
94
159
|
impressions: option?.impressions ?? DEFAULT_ITEM_CAPTURE.impressions,
|
|
95
160
|
clicks: option?.clicks ?? DEFAULT_ITEM_CAPTURE.clicks,
|
|
@@ -212,16 +277,30 @@ const resolveCapture = (options, scoped) => {
|
|
|
212
277
|
assertCaptureShape(option);
|
|
213
278
|
const globalSlot = option?.slots?.global;
|
|
214
279
|
if (typeof globalSlot === "string") assertNamesAdapter(globalSlot, "capture.slots.global", options.adapters ?? []);
|
|
280
|
+
const gate = resolveGate(option?.gate, fillableSlots(options, scoped).length > 0);
|
|
281
|
+
const withoutConsent = resolveWithoutConsent(option?.withoutConsent);
|
|
282
|
+
const fill = {
|
|
283
|
+
adapters: options.adapters ?? [],
|
|
284
|
+
...options.platformAdapter ? { platformAdapter: options.platformAdapter } : {},
|
|
285
|
+
scoped,
|
|
286
|
+
capture: {
|
|
287
|
+
slots: {
|
|
288
|
+
global: globalSlot,
|
|
289
|
+
tenant: option?.slots?.tenant
|
|
290
|
+
},
|
|
291
|
+
heldSlots: heldAtBoot(option?.gate),
|
|
292
|
+
...withoutConsent === void 0 ? {} : { withoutConsent }
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
const providersOn = Boolean(options.providers?.collection) || options.providers?.resolve !== void 0;
|
|
215
296
|
return {
|
|
216
|
-
|
|
217
|
-
global: globalSlot,
|
|
218
|
-
tenant: option?.slots?.tenant
|
|
219
|
-
},
|
|
297
|
+
...fill.capture,
|
|
220
298
|
paths: {
|
|
221
299
|
global: option?.paths?.global,
|
|
222
300
|
tenant: option?.paths?.tenant
|
|
223
301
|
},
|
|
224
|
-
gate
|
|
302
|
+
gate,
|
|
303
|
+
installCountsWithoutConsent: fill.adapters.some((adapter) => adapterCountsWithoutConsent(fill, adapter)) || documentsFillHeldTenant(fill, providersOn) && followingCountsWithoutConsent(withoutConsent),
|
|
225
304
|
autoCapture: resolveAutoCapture(option?.autoCapture),
|
|
226
305
|
proxy: {
|
|
227
306
|
timeoutMs: positiveWhole(option?.proxy?.timeoutMs, "capture.proxy.timeoutMs", DEFAULT_PROXY_TIMEOUT_MS),
|
|
@@ -252,7 +331,17 @@ const untrustedAddressNotice = (resolved, production) => {
|
|
|
252
331
|
if (!production || resolved.trustedProxyHops !== void 0 || resolved.trustedPlatform !== void 0) return null;
|
|
253
332
|
return resolved.providers.collection.enabled || resolved.providers.resolve !== void 0 || resolved.adapters.some((adapter) => adapter.ingest !== void 0 || (adapter.capture?.proxy.routes.length ?? 0) > 0) ? "analytics: visitor IP addresses and countries can be spoofed on this install. Neither trustedProxyHops nor trustedPlatform is set, so the plugin reads them from request headers a visitor can write. Set trustedPlatform to 'vercel' or 'cloudflare' when the app runs behind one, or trustedProxyHops to the number of proxies in front of it." : null;
|
|
254
333
|
};
|
|
334
|
+
/**
|
|
335
|
+
* The boot line for an install leaving `capture.withoutConsent` unset while a held slot may count
|
|
336
|
+
* without consent, naming the default in effect; null otherwise.
|
|
337
|
+
*/
|
|
338
|
+
const withoutConsentUnsetNotice = (resolved) => resolved.capture.withoutConsent === void 0 && resolved.capture.installCountsWithoutConsent ? "analytics: capture.withoutConsent is unset, so held slots measure cookielessly before consent and after a refusal. Set it to 'off' to send nothing without consent." : null;
|
|
339
|
+
/**
|
|
340
|
+
* The production boot warning for a held slot counting without consent while nothing says where
|
|
341
|
+
* the client address comes from, or null: cookieless counting tells visitors apart by its hash.
|
|
342
|
+
*/
|
|
343
|
+
const cookielessTrustNotice = (resolved, production) => production && resolved.capture.installCountsWithoutConsent && resolved.trustedProxyHops === void 0 && resolved.trustedPlatform === void 0 ? "analytics: a held capture slot counts visitors cookielessly, telling them apart by a hash of the client IP address, yet neither trustedProxyHops nor trustedPlatform is set. Behind a proxy, a missing or wrong hop count hashes the proxy's address instead and collapses every visitor into one. Set trustedPlatform to 'vercel' or 'cloudflare', or trustedProxyHops to the number of proxies in front of the app." : null;
|
|
255
344
|
//#endregion
|
|
256
|
-
export { fillableSlots, resolveCapture, resolveTrust, trackerAutoCapture, untrustedAddressNotice };
|
|
345
|
+
export { adapterCountsWithoutConsent, cookielessTrustNotice, documentsFillHeldTenant, fillableSlots, followingCountsWithoutConsent, resolveCapture, resolveTrust, trackerAutoCapture, untrustedAddressNotice, withoutConsentUnsetNotice };
|
|
257
346
|
|
|
258
347
|
//# sourceMappingURL=captureOptions.js.map
|