@10x-media/analytics 0.1.0-beta.5 → 1.0.0-beta.6

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.
Files changed (70) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -21
  3. package/dist/adapters/ga4/ga4.js +13 -0
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/plausible/plausible.js +11 -0
  6. package/dist/adapters/plausible/plausible.js.map +1 -1
  7. package/dist/adapters/posthog/posthog.js +37 -3
  8. package/dist/adapters/posthog/posthog.js.map +1 -1
  9. package/dist/adapters/series.js +11 -1
  10. package/dist/adapters/series.js.map +1 -1
  11. package/dist/adapters/umami/umami.js +2 -0
  12. package/dist/adapters/umami/umami.js.map +1 -1
  13. package/dist/core/capabilities.d.ts +5 -1
  14. package/dist/core/capabilities.js +4 -0
  15. package/dist/core/capabilities.js.map +1 -1
  16. package/dist/core/contract.d.ts +7 -2
  17. package/dist/core/contract.js.map +1 -1
  18. package/dist/exports/rsc.d.ts +2 -2
  19. package/dist/exports/types.d.ts +2 -2
  20. package/dist/index.js +6 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/native/collections/rollups.js +15 -3
  23. package/dist/native/collections/rollups.js.map +1 -1
  24. package/dist/native/nativeAdapter.js +81 -2
  25. package/dist/native/nativeAdapter.js.map +1 -1
  26. package/dist/native/query/eventAgg.js +135 -0
  27. package/dist/native/query/eventAgg.js.map +1 -0
  28. package/dist/native/rollups/applyDistinctDeltas.js +1 -1
  29. package/dist/native/rollups/applyDistinctDeltas.js.map +1 -1
  30. package/dist/native/rollups/bumpRollup.js +2 -1
  31. package/dist/native/rollups/bumpRollup.js.map +1 -1
  32. package/dist/native/rollups/deltas.js +45 -8
  33. package/dist/native/rollups/deltas.js.map +1 -1
  34. package/dist/sync/collection.js +23 -7
  35. package/dist/sync/collection.js.map +1 -1
  36. package/dist/sync/syncTask.js +12 -4
  37. package/dist/sync/syncTask.js.map +1 -1
  38. package/dist/testing/memoryAdapter.js +7 -0
  39. package/dist/testing/memoryAdapter.js.map +1 -1
  40. package/dist/translations/ar.js +77 -0
  41. package/dist/translations/ar.js.map +1 -0
  42. package/dist/translations/es.js +77 -0
  43. package/dist/translations/es.js.map +1 -0
  44. package/dist/translations/fr.js +77 -0
  45. package/dist/translations/fr.js.map +1 -0
  46. package/dist/translations/id.js +77 -0
  47. package/dist/translations/id.js.map +1 -0
  48. package/dist/translations/index.d.ts +10 -1
  49. package/dist/translations/index.js +19 -1
  50. package/dist/translations/index.js.map +1 -1
  51. package/dist/translations/ko.js +77 -0
  52. package/dist/translations/ko.js.map +1 -0
  53. package/dist/translations/pt.js +77 -0
  54. package/dist/translations/pt.js.map +1 -0
  55. package/dist/translations/ru.js +77 -0
  56. package/dist/translations/ru.js.map +1 -0
  57. package/dist/translations/uk.js +77 -0
  58. package/dist/translations/uk.js.map +1 -0
  59. package/dist/translations/zh.js +77 -0
  60. package/dist/translations/zh.js.map +1 -0
  61. package/dist/widgets/readForWidget.d.ts +2 -1
  62. package/dist/widgets/readForWidget.js +10 -2
  63. package/dist/widgets/readForWidget.js.map +1 -1
  64. package/dist/widgets/readForWidgetBreakdown.d.ts +2 -1
  65. package/dist/widgets/readForWidgetBreakdown.js +7 -2
  66. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  67. package/dist/widgets/readForWidgetSeries.d.ts +2 -1
  68. package/dist/widgets/readForWidgetSeries.js +10 -2
  69. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  70. package/package.json +6 -6
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @10x-media/analytics
2
2
 
3
+ ## 1.0.0-beta.6
4
+
5
+ ### Minor Changes
6
+
7
+ - More built-in locales for the `analytics:` strings.
8
+
9
+ - Added: `es`, `fr`, `id`, `pt`, `ru`, `zh`, `uk`, `ar`, `ko`. Every key is covered in each.
10
+
11
+ - **Breaking:** the query contract grows real filters and finer granularity, and two schemas change. `AnalyticsCapabilities` now requires `filters` and `filterOperators` declarations (custom adapters must add them). `AnalyticsQuery.filters` is honored by native (from raw events, retention-bounded, `eq`/`contains`), PostHog (`eq`/`contains`/`matches` via HogQL), Plausible and GA4 (`eq`), and the widget read helpers accept a `filters` option gated by capability. Native gains the `event` name dimension and `hour` granularity (UTC hour buckets from raw events). Native rollups are now keyed by hostname: deltas write both a hostname-less and a per-hostname bucket family, so `binding.hostname` finally filters native reads with exact unique counts; existing installs must run a migration adding the `hostname` column (backfill `''`) and, on Postgres, rebuilding the rollup unique index to include it: until that index is rebuilt, every native rollup write fails outright on migrate-mode Postgres, not just colliding ones (rebuild DDL is in the native docs). Distinct counting resets once within the deploy-day bucket because ledger keys changed shape. The sync collection gains a required `scope` column (backfill `''`, unique key now source+date+scope) and its read access is scope-filtered in scoped installs, closing a would-be cross-tenant read of synced daily metrics. Migrate-mode Postgres installs must rebuild that unique index too, exactly like the rollups index above; both rebuilds are documented in the native docs' upgrade note.
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies:
16
+ - @10x-media/fields@0.1.0-beta.6
17
+
3
18
  ## 0.1.0-beta.5
4
19
 
5
20
  ### Minor Changes
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 10x Media GmbH
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 10x Media GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -45,6 +45,8 @@ function ga4(config) {
45
45
  maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 425,
46
46
  metrics: ga4Metrics,
47
47
  dimensions: ga4Dimensions,
48
+ filters: ga4Dimensions,
49
+ filterOperators: new Set(["eq"]),
48
50
  batchPageReport: true,
49
51
  rateLimit: {
50
52
  maxConcurrent: 10,
@@ -106,6 +108,17 @@ function ga4(config) {
106
108
  value: q.hostname
107
109
  }
108
110
  } });
111
+ for (const filter of q.filters ?? []) {
112
+ const fieldName = DIMENSION_MAP[filter.dimension];
113
+ if (!fieldName || filter.operator !== "eq") continue;
114
+ filterExprs.push({ filter: {
115
+ fieldName,
116
+ stringFilter: {
117
+ matchType: "EXACT",
118
+ value: filter.value
119
+ }
120
+ } });
121
+ }
109
122
  const dimensionFilter = filterExprs.length === 0 ? void 0 : filterExprs.length === 1 ? filterExprs[0] : { andGroup: { expressions: filterExprs } };
110
123
  const baseRequest = {
111
124
  property: `properties/${config.propertyId}`,
@@ -1 +1 @@
1
- {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { dayIso } from '../series'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n}\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\n\t\t\tconst readRow = (\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName: 'pagePath', stringFilter: { matchType: 'EXACT', value: q.path } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: {\n\t\t\t\t\t\tfieldName: 'hostName',\n\t\t\t\t\t\tstringFilter: { matchType: 'EXACT', value: q.hostname },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst dimensionFilter =\n\t\t\t\tfilterExprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: filterExprs.length === 1\n\t\t\t\t\t\t? filterExprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: filterExprs } }\n\n\t\t\tconst baseRequest: protos.google.analytics.data.v1beta.IRunReportRequest = {\n\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\tdateRanges: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstartDate: q.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\tendDate: q.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmetrics: providerMetrics.map((name) => ({ name })),\n\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [response] = await client.runReport({\n\t\t\t\t\t...baseRequest,\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of response.rows ?? []) {\n\t\t\t\t\tconst ymd = row.dimensionValues?.[0]?.value ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst totalsRow = response.totals?.[0]\n\t\t\t\tconst totals = totalsRow ? readRow(totalsRow) : {}\n\t\t\t\treturn { rows, totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst [response] = await client.runReport({\n\t\t\t\t...baseRequest,\n\t\t\t\t...(providerDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {}),\n\t\t\t\t...(q.limit ? { limit: q.limit } : {}),\n\t\t\t})\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst row = response.rows?.[0]\n\t\t\t\tconst totals = row ? readRow(row) : {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = (response.rows ?? []).map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tdimValues[d] = row.dimensionValues?.[idx]?.value ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'ga4', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;AAwBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,WAAW;CACX,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,UAAU;CACV,OAAO;AACR;AA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E;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAO;IAAU;GAAE;EACxE;CACD;AACD"}
1
+ {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { dayIso } from '../series'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n}\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tfilters: ga4Dimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\n\t\t\tconst readRow = (\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName: 'pagePath', stringFilter: { matchType: 'EXACT', value: q.path } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: {\n\t\t\t\t\t\tfieldName: 'hostName',\n\t\t\t\t\t\tstringFilter: { matchType: 'EXACT', value: q.hostname },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst fieldName = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!fieldName || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName, stringFilter: { matchType: 'EXACT', value: filter.value } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst dimensionFilter =\n\t\t\t\tfilterExprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: filterExprs.length === 1\n\t\t\t\t\t\t? filterExprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: filterExprs } }\n\n\t\t\tconst baseRequest: protos.google.analytics.data.v1beta.IRunReportRequest = {\n\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\tdateRanges: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstartDate: q.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\tendDate: q.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmetrics: providerMetrics.map((name) => ({ name })),\n\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [response] = await client.runReport({\n\t\t\t\t\t...baseRequest,\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of response.rows ?? []) {\n\t\t\t\t\tconst ymd = row.dimensionValues?.[0]?.value ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst totalsRow = response.totals?.[0]\n\t\t\t\tconst totals = totalsRow ? readRow(totalsRow) : {}\n\t\t\t\treturn { rows, totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst [response] = await client.runReport({\n\t\t\t\t...baseRequest,\n\t\t\t\t...(providerDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {}),\n\t\t\t\t...(q.limit ? { limit: q.limit } : {}),\n\t\t\t})\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst row = response.rows?.[0]\n\t\t\t\tconst totals = row ? readRow(row) : {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = (response.rows ?? []).map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tdimValues[d] = row.dimensionValues?.[idx]?.value ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'ga4', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;AAwBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,WAAW;CAC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AQ,GAAG,IAAI,CAAC;IACrC,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM;MAAE,UAAU;MAAO;KAAU;IAAE;GACpF;GAUA,OAAO;IAAE,OARqB,SAAS,QAAQ,CAAC,GAAG,KAAK,QAAQ;KAC/D,MAAM,YAAmD,CAAC;KAC1D,KAAK,MAAM,KAAK,MAAM;MACrB,MAAM,MAAM,aAAa,QAAQ,cAAc,EAAY;MAC3D,UAAU,KAAK,IAAI,kBAAkB,MAAM,SAAS;KACrD;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAO;IAAU;GAAE;EACxE;CACD;AACD"}
@@ -42,6 +42,8 @@ function plausible(config) {
42
42
  maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730,
43
43
  metrics: plausibleMetrics,
44
44
  dimensions: plausibleDimensions,
45
+ filters: plausibleDimensions,
46
+ filterOperators: new Set(["eq"]),
45
47
  batchPageReport: true,
46
48
  rateLimit: { requestsPerHour: 600 },
47
49
  recommendedTtl: {
@@ -66,6 +68,15 @@ function plausible(config) {
66
68
  "event:hostname",
67
69
  [q.hostname]
68
70
  ]);
71
+ for (const filter of q.filters ?? []) {
72
+ const mapped = DIMENSION_MAP[filter.dimension];
73
+ if (!mapped || filter.operator !== "eq") continue;
74
+ filters.push([
75
+ "is",
76
+ mapped,
77
+ [filter.value]
78
+ ]);
79
+ }
69
80
  const readRow = (row) => {
70
81
  const out = {};
71
82
  for (const m of wanted) {
@@ -1 +1 @@
1
- {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tq.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\t\tq.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAsBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,WAAW;CACX,WAAW;CACX,aAAa;AACd;AAEA,MAAM,mBAA2C,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AAC/F,MAAM,sBAAiD,IAAI,IAC1D,OAAO,KAAK,aAAa,CAC1B;AAOA,MAAM,mBAAmB,QAAmB,QAC3C,WAAW,gBAAgB,KAAK,MAAM,MAAM,GAAI,IAAI;AAErD,SAAgB,UAAU,QAA2C;CACpE,MAAM,OAAO,OAAO,QAAQ;CAgB5B,OAAO;EACN,IAAI;EACJ,OAAO;EACP,cAAA;GAfA,cAAc;GACd,UAAU;GACV,YAAY;GACZ,gBAAgB;GAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;GAQvF,SAAS;GACT,YAAY;GACZ,iBAAiB;GACjB,WAAW,EAAE,iBAAiB,IAAI;GAClC,gBAAgB;IAAE,UAAU;IAAK,WAAW;GAAK;EAMtC;EACX,oBAAoB,QAAQ,OAAO,UAAU,OAAO,MAAM;EAC1D,MAAM,MAAM,GAAmB,KAA+C;GAC7E,MAAM,YAAY,EAAE,UAAU,IAAI,YAAY;GAC9C,MAAM,SAAS,EAAE,QAAQ,QAAQ,MAAM,WAAW,E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AAU,EAAE,CAAC,GACtC,YAAY,CACb,CAAC;IACD,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,OAAO,WAAW,SAAS;KACrC,MAAM,KAAK,OAAO,IAAI,WAAW,MAAM,EAAE;KACzC,IAAI,IACH,KAAK,KAAK;MAAE,WAAW;MAAI,SAAS,QAAQ,GAAG;KAAE,CAAC;IAEpD;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAa;KAAU;IAAE;GACnE;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,SAAS,MAAM,YAAY;IACjC,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM;MAAE,UAAU;MAAa;KAAU;IAAE;GAC1F;GAaA,OAAO;IAAE,OAVoB,MADV,UAAU,EAAE,YAAY,KAAK,KAAK,MAAM,cAAc,EAAY,EAAE,CAAC,GACtD,QAAQ,KAAK,QAAQ;KACtD,MAAM,YAAmD,CAAC;KAC1D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;MACrC,MAAM,IAAI,KAAK;MACf,IAAI,MAAM,KAAA,GACT,UAAU,KAAK,IAAI,WAAW,MAAM;KAEtC;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
1
+ {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tq.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\t\tq.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAsBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,WAAW;CACX,WAAW;CACX,aAAa;AACd;AAEA,MAAM,mBAA2C,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AAC/F,MAAM,sBAAiD,IAAI,IAC1D,OAAO,KAAK,aAAa,CAC1B;AAOA,MAAM,mBAAmB,QAAmB,QAC3C,WAAW,gBAAgB,KAAK,MAAM,MAAM,GAAI,IAAI;AAErD,SAAgB,UAAU,QAA2C;CACpE,MAAM,OAAO,OAAO,QAAQ;CAkB5B,OAAO;EACN,IAAI;EACJ,OAAO;EACP,cAAA;GAjBA,cAAc;GACd,UAAU;GACV,YAAY;GACZ,gBAAgB;GAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;GAQvF,SAAS;GACT,YAAY;GACZ,SAAS;GACT,iBAAiB,IAAI,IAAI,CAAC,IAAI,CAAC;GAC/B,iBAAiB;GACj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,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
@@ -1,4 +1,4 @@
1
- import { dayIso } from "../series.js";
1
+ import { dayIso, hourIso } from "../series.js";
2
2
  import { fetchJson } from "../http/fetchJson.js";
3
3
  //#region src/adapters/posthog/posthog.ts
4
4
  const US_CLOUD = "https://us.posthog.com";
@@ -22,6 +22,7 @@ const DIMENSION_SQL = {
22
22
  const posthogMetrics = new Set(Object.keys(METRIC_SQL_ALL));
23
23
  const posthogDimensions = new Set(Object.keys(DIMENSION_SQL));
24
24
  const sqlString = (value) => `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
25
+ const escapeLikeValue = (value) => value.replace(/[\\%_]/g, (c) => `\\${c}`);
25
26
  const sqlDateTimeLiteral = (d) => sqlString(d.toISOString().slice(0, 19).replace("T", " "));
26
27
  function posthog(config) {
27
28
  const host = config.host ?? US_CLOUD;
@@ -32,10 +33,16 @@ function posthog(config) {
32
33
  perPageQuery: true,
33
34
  realtime: false,
34
35
  comparison: false,
35
- minGranularity: "day",
36
+ minGranularity: "hour",
36
37
  maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730,
37
38
  metrics: posthogMetrics,
38
39
  dimensions: posthogDimensions,
40
+ filters: posthogDimensions,
41
+ filterOperators: new Set([
42
+ "eq",
43
+ "contains",
44
+ "matches"
45
+ ]),
39
46
  batchPageReport: true,
40
47
  rateLimit: {
41
48
  requestsPerMinute: 240,
@@ -51,7 +58,7 @@ function posthog(config) {
51
58
  async query(q, ctx) {
52
59
  const fetchedAt = q.dateRange.end.toISOString();
53
60
  const breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d]);
54
- const scanAllEvents = q.metrics.includes("events") || breakdownDim === "event";
61
+ const scanAllEvents = q.metrics.includes("events") || breakdownDim === "event" || (q.filters ?? []).some((f) => f.dimension === "event" && DIMENSION_SQL[f.dimension]);
55
62
  const metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW;
56
63
  const wanted = q.metrics.filter((m) => metricSql[m]);
57
64
  const exprs = [...new Set(wanted.map((m) => metricSql[m]))];
@@ -60,6 +67,13 @@ function posthog(config) {
60
67
  if (q.path) where.push(`properties.$pathname = ${sqlString(q.path)}`);
61
68
  if (q.hostname) where.push(`properties.$host = ${sqlString(q.hostname)}`);
62
69
  if (config.scopeProperty && q.scope !== void 0) where.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`);
70
+ for (const filter of q.filters ?? []) {
71
+ const expr = DIMENSION_SQL[filter.dimension];
72
+ if (!expr) continue;
73
+ if (filter.operator === "eq") where.push(`${expr} = ${sqlString(filter.value)}`);
74
+ else if (filter.operator === "contains") where.push(`${expr} ILIKE ${sqlString(`%${escapeLikeValue(filter.value)}%`)}`);
75
+ else if (filter.operator === "matches") where.push(`match(${expr}, ${sqlString(filter.value)})`);
76
+ }
63
77
  const selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`);
64
78
  const runSql = (sql) => fetchJson(`${host}/api/projects/${config.projectId}/query/`, {
65
79
  method: "POST",
@@ -103,6 +117,26 @@ function posthog(config) {
103
117
  }
104
118
  };
105
119
  }
120
+ if (q.granularity === "hour" && !breakdownDim) {
121
+ const seriesSql = `SELECT ${`toStartOfHour(timestamp, ${sqlString(q.timezone ?? "UTC")})`} AS hour, ${selectMetrics.join(", ")} FROM events WHERE ${where.join(" AND ")} GROUP BY hour ORDER BY hour`;
122
+ const [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()]);
123
+ const rows = [];
124
+ for (const row of seriesData.results) {
125
+ const ts = hourIso(String(row[0] ?? ""));
126
+ if (ts) rows.push({
127
+ timestamp: ts,
128
+ metrics: readRow(row, 1)
129
+ });
130
+ }
131
+ return {
132
+ rows,
133
+ totals,
134
+ meta: {
135
+ provider: "posthog",
136
+ fetchedAt
137
+ }
138
+ };
139
+ }
106
140
  if (breakdownDim) return {
107
141
  rows: (await runSql(`SELECT ${DIMENSION_SQL[breakdownDim]} AS dim, ${selectMetrics.join(", ")} FROM events WHERE ${where.join(" AND ")} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`)).results.map((row) => ({
108
142
  dimensions: { [breakdownDim]: String(row[0] ?? "") },
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PosthogConfig {\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). */\n\tapiKey: string\n\t/** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a query's scope (e.g. 'tenant'). Enables scoped queries:\n\t * one platform project captures every scope with this property set, and a scoped\n\t * read filters on it. Both the property name and value are escaped literals.\n\t */\n\tscopeProperty?: string\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\n// Pageview-scoped expressions, used when the read filters the WHERE to `$pageview`.\n// visits and sessions share the distinct-session expression and are deduped before the\n// SELECT, then read back by the expression's position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, used when `events` (total captured events, matching PostHog's own\n// Events definition) or an `event`-name breakdown is requested. The WHERE is not filtered to\n// `$pageview`, so the pageview-family metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tevent: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_SQL_ALL) as MetricKey[])\nconst posthogDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_SQL) as DimensionKey[]\n)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\nconst sqlDateTimeLiteral = (d: Date): string =>\n\tsqlString(d.toISOString().slice(0, 19).replace('T', ' '))\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = config.host ?? US_CLOUD\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\tlabel: 'PostHog',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d])\n\t\t\t// A total-events metric or an event-name breakdown must scan every event, not\n\t\t\t// just pageviews; those reads switch to conditional aggregation.\n\t\t\tconst scanAllEvents = q.metrics.includes('events') || breakdownDim === 'event'\n\t\t\tconst metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW\n\t\t\tconst wanted = q.metrics.filter((m) => metricSql[m])\n\t\t\tconst exprs = [...new Set(wanted.map((m) => metricSql[m] as string))]\n\n\t\t\tconst where = [\n\t\t\t\t`timestamp >= toDateTime(${sqlDateTimeLiteral(q.dateRange.start)})`,\n\t\t\t\t`timestamp <= toDateTime(${sqlDateTimeLiteral(q.dateRange.end)})`,\n\t\t\t]\n\t\t\tif (!scanAllEvents) {\n\t\t\t\twhere.unshift(\"event = '$pageview'\")\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\tconst selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`)\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tfetchJson<PosthogQueryResponse>(`${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t})\n\n\t\t\tconst readRow = (row: unknown[], offset: number): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = exprs.indexOf(metricSql[m] as string)\n\t\t\t\t\tout[m] = Number(row[offset + idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')}`\n\t\t\t\t)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !breakdownDim) {\n\t\t\t\t// HogQL buckets in the timezone argument when given; without it PostHog falls back\n\t\t\t\t// to the project's own timezone, so the resolved reporting timezone (UTC included)\n\t\t\t\t// is always passed to keep day buckets deterministic across projects. The window\n\t\t\t\t// literals stay UTC instants (already aligned to the reporting-timezone day\n\t\t\t\t// boundary by the caller).\n\t\t\t\tconst dayExpr = `toStartOfDay(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${dayExpr} AS day, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY day ORDER BY day`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (breakdownDim) {\n\t\t\t\tconst dimSql = DIMENSION_SQL[breakdownDim] as string\n\t\t\t\tconst sql = `SELECT ${dimSql} AS dim, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\tconst data = await runSql(sql)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdownDim]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AA8BA,MAAM,WAAW;AAKjB,MAAM,sBAA0D;CAC/D,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;AACX;AAKA,MAAM,iBAAqD;CAC1D,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,QAAQ;AACT;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,OAAO;AACR;AAEA,MAAM,iBAAyC,IAAI,IAAI,OAAO,KAAK,cAAc,CAAgB;AACjG,MAAM,oBAA+C,IAAI,IACxD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,aAAa,UAClB,IAAI,MAAM,QAAQ,OAAO,MAAM,EAAE,QAAQ,MAAM,KAAK,EAAE;AAEvD,MAAM,sBAAsB,MAC3B,UAAU,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,EAAE,QAAQ,KAAK,GAAG,CAAC;AAQzD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UAAU;MAAW;KAAU;IAAE;GACjE;GAEA,IAAI,cAQH,OAAO;IAAE,OAJoB,MADV,OAAO,UAFX,cAAc,cACA,WAAW,cAAc,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,OAAO,EAAE,uCAAuC,EAAE,SAAS,KAC/H,GACK,QAAQ,KAAK,SAAS;KACvD,YAAY,GAAG,eAAe,OAAO,IAAI,MAAM,EAAE,EAAE;KACnD,SAAS,QAAQ,KAAK,CAAC;IACxB,EACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;GAG5E,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;EACxF;CACD;AACD"}
1
+ {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso, hourIso } from '../series'\n\nexport interface PosthogConfig {\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). */\n\tapiKey: string\n\t/** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a query's scope (e.g. 'tenant'). Enables scoped queries:\n\t * one platform project captures every scope with this property set, and a scoped\n\t * read filters on it. Both the property name and value are escaped literals.\n\t */\n\tscopeProperty?: string\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\n// Pageview-scoped expressions, used when the read filters the WHERE to `$pageview`.\n// visits and sessions share the distinct-session expression and are deduped before the\n// SELECT, then read back by the expression's position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, used when `events` (total captured events, matching PostHog's own\n// Events definition) or an `event`-name breakdown is requested. The WHERE is not filtered to\n// `$pageview`, so the pageview-family metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tevent: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_SQL_ALL) as MetricKey[])\nconst posthogDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_SQL) as DimensionKey[]\n)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE treats % and _ as wildcards and backslash as its own escape char; backslash-escape\n// backslash first (so a raw \\ in the value doesn't get read as escaping the next char),\n// then % and _, before the whole thing is wrapped in % ... % and quoted.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\nconst sqlDateTimeLiteral = (d: Date): string =>\n\tsqlString(d.toISOString().slice(0, 19).replace('T', ' '))\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = config.host ?? US_CLOUD\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogDimensions,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\tlabel: 'PostHog',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d])\n\t\t\t// A total-events metric, an event-name breakdown, or a filter on the event\n\t\t\t// dimension must scan every event, not just pageviews (a `$pageview` WHERE\n\t\t\t// clause combined with an `event = 'x'` filter would be self-contradictory and\n\t\t\t// zero every metric); those reads switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tbreakdownDim === 'event' ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event' && DIMENSION_SQL[f.dimension])\n\t\t\tconst metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW\n\t\t\tconst wanted = q.metrics.filter((m) => metricSql[m])\n\t\t\tconst exprs = [...new Set(wanted.map((m) => metricSql[m] as string))]\n\n\t\t\tconst where = [\n\t\t\t\t`timestamp >= toDateTime(${sqlDateTimeLiteral(q.dateRange.start)})`,\n\t\t\t\t`timestamp <= toDateTime(${sqlDateTimeLiteral(q.dateRange.end)})`,\n\t\t\t]\n\t\t\tif (!scanAllEvents) {\n\t\t\t\twhere.unshift(\"event = '$pageview'\")\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension is dropped here as the safety net so it never throws.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst expr = DIMENSION_SQL[filter.dimension]\n\t\t\t\tif (!expr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (filter.operator === 'eq') {\n\t\t\t\t\twhere.push(`${expr} = ${sqlString(filter.value)}`)\n\t\t\t\t} else if (filter.operator === 'contains') {\n\t\t\t\t\twhere.push(`${expr} ILIKE ${sqlString(`%${escapeLikeValue(filter.value)}%`)}`)\n\t\t\t\t} else if (filter.operator === 'matches') {\n\t\t\t\t\twhere.push(`match(${expr}, ${sqlString(filter.value)})`)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`)\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tfetchJson<PosthogQueryResponse>(`${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t})\n\n\t\t\tconst readRow = (row: unknown[], offset: number): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = exprs.indexOf(metricSql[m] as string)\n\t\t\t\t\tout[m] = Number(row[offset + idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')}`\n\t\t\t\t)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !breakdownDim) {\n\t\t\t\t// HogQL buckets in the timezone argument when given; without it PostHog falls back\n\t\t\t\t// to the project's own timezone, so the resolved reporting timezone (UTC included)\n\t\t\t\t// is always passed to keep day buckets deterministic across projects. The window\n\t\t\t\t// literals stay UTC instants (already aligned to the reporting-timezone day\n\t\t\t\t// boundary by the caller).\n\t\t\t\tconst dayExpr = `toStartOfDay(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${dayExpr} AS day, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY day ORDER BY day`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (q.granularity === 'hour' && !breakdownDim) {\n\t\t\t\t// Same timezone-bucketing rationale as the day branch above, at hour resolution.\n\t\t\t\tconst hourExpr = `toStartOfHour(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${hourExpr} AS hour, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY hour ORDER BY hour`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = hourIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (breakdownDim) {\n\t\t\t\tconst dimSql = DIMENSION_SQL[breakdownDim] as string\n\t\t\t\tconst sql = `SELECT ${dimSql} AS dim, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\tconst data = await runSql(sql)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdownDim]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AA8BA,MAAM,WAAW;AAKjB,M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E,YAAY,KAAK,EAAE,GACvC,YAAY,cAAc,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,OAAO,EAAE;IACnH,MAAM,CAAC,YAAY,UAAU,MAAM,QAAQ,IAAI,CAAC,OAAO,SAAS,GAAG,YAAY,CAAC,CAAC;IACjF,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,OAAO,WAAW,SAAS;KACrC,MAAM,KAAK,QAAQ,OAAO,IAAI,MAAM,EAAE,CAAC;KACvC,IAAI,IACH,KAAK,KAAK;MAAE,WAAW;MAAI,SAAS,QAAQ,KAAK,CAAC;KAAE,CAAC;IAEvD;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAW;KAAU;IAAE;GACjE;GAEA,IAAI,cAQH,OAAO;IAAE,OAJoB,MADV,OAAO,UAFX,cAAc,cACA,WAAW,cAAc,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,OAAO,EAAE,uCAAuC,EAAE,SAAS,KAC/H,GACK,QAAQ,KAAK,SAAS;KACvD,YAAY,GAAG,eAAe,OAAO,IAAI,MAAM,EAAE,EAAE;KACnD,SAAS,QAAQ,KAAK,CAAC;IACxB,EACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;GAG5E,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;EACxF;CACD;AACD"}
@@ -11,7 +11,17 @@ const dayIso = (value) => {
11
11
  const t = Date.parse(`${date}T00:00:00.000Z`);
12
12
  return Number.isNaN(t) ? null : new Date(t).toISOString();
13
13
  };
14
+ /**
15
+ * Normalize a provider's hour label to a UTC ISO string. Takes a datetime like
16
+ * `2026-06-23 14:00:00` (space- or T-separated). Returns null for an unparseable or
17
+ * truncated value so the caller can skip that one row rather than emit a broken timestamp.
18
+ */
19
+ const hourIso = (value) => {
20
+ if (value.length < 19) return null;
21
+ const t = Date.parse(`${value.slice(0, 10)}T${value.slice(11, 19)}.000Z`);
22
+ return Number.isNaN(t) ? null : new Date(t).toISOString();
23
+ };
14
24
  //#endregion
15
- export { dayIso };
25
+ export { dayIso, hourIso };
16
26
 
17
27
  //# sourceMappingURL=series.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"series.js","names":[],"sources":["../../src/adapters/series.ts"],"sourcesContent":["/**\n * Normalize a provider's day label to a UTC-day ISO string. Takes any value whose first\n * 10 chars are `YYYY-MM-DD` (a bare date, or a datetime like `2026-06-23 14:00:00`).\n * Returns null for an unparseable value so the caller can skip that one row rather than\n * emit a broken timestamp.\n */\nexport const dayIso = (value: string): string | null => {\n\tconst date = value.slice(0, 10)\n\t// V8's Date.parse leniently accepts year-only and year-month strings, so require a\n\t// full YYYY-MM-DD before parsing or a short value would resolve to Jan 1, not null.\n\tif (date.length !== 10) {\n\t\treturn null\n\t}\n\tconst t = Date.parse(`${date}T00:00:00.000Z`)\n\treturn Number.isNaN(t) ? null : new Date(t).toISOString()\n}\n"],"mappings":";;;;;;;AAMA,MAAa,UAAU,UAAiC;CACvD,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE;CAG9B,IAAI,KAAK,WAAW,IACnB,OAAO;CAER,MAAM,IAAI,KAAK,MAAM,GAAG,KAAK,eAAe;CAC5C,OAAO,OAAO,MAAM,CAAC,IAAI,OAAO,IAAI,KAAK,CAAC,EAAE,YAAY;AACzD"}
1
+ {"version":3,"file":"series.js","names":[],"sources":["../../src/adapters/series.ts"],"sourcesContent":["/**\n * Normalize a provider's day label to a UTC-day ISO string. Takes any value whose first\n * 10 chars are `YYYY-MM-DD` (a bare date, or a datetime like `2026-06-23 14:00:00`).\n * Returns null for an unparseable value so the caller can skip that one row rather than\n * emit a broken timestamp.\n */\nexport const dayIso = (value: string): string | null => {\n\tconst date = value.slice(0, 10)\n\t// V8's Date.parse leniently accepts year-only and year-month strings, so require a\n\t// full YYYY-MM-DD before parsing or a short value would resolve to Jan 1, not null.\n\tif (date.length !== 10) {\n\t\treturn null\n\t}\n\tconst t = Date.parse(`${date}T00:00:00.000Z`)\n\treturn Number.isNaN(t) ? null : new Date(t).toISOString()\n}\n\n/**\n * Normalize a provider's hour label to a UTC ISO string. Takes a datetime like\n * `2026-06-23 14:00:00` (space- or T-separated). Returns null for an unparseable or\n * truncated value so the caller can skip that one row rather than emit a broken timestamp.\n */\nexport const hourIso = (value: string): string | null => {\n\tif (value.length < 19) {\n\t\treturn null\n\t}\n\tconst t = Date.parse(`${value.slice(0, 10)}T${value.slice(11, 19)}.000Z`)\n\treturn Number.isNaN(t) ? null : new Date(t).toISOString()\n}\n"],"mappings":";;;;;;;AAMA,MAAa,UAAU,UAAiC;CACvD,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE;CAG9B,IAAI,KAAK,WAAW,IACnB,OAAO;CAER,MAAM,IAAI,KAAK,MAAM,GAAG,KAAK,eAAe;CAC5C,OAAO,OAAO,MAAM,CAAC,IAAI,OAAO,IAAI,KAAK,CAAC,EAAE,YAAY;AACzD;;;;;;AAOA,MAAa,WAAW,UAAiC;CACxD,IAAI,MAAM,SAAS,IAClB,OAAO;CAER,MAAM,IAAI,KAAK,MAAM,GAAG,MAAM,MAAM,GAAG,EAAE,EAAE,GAAG,MAAM,MAAM,IAAI,EAAE,EAAE,MAAM;CACxE,OAAO,OAAO,MAAM,CAAC,IAAI,OAAO,IAAI,KAAK,CAAC,EAAE,YAAY;AACzD"}
@@ -21,6 +21,8 @@ function umami(config) {
21
21
  maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730,
22
22
  metrics: umamiMetrics,
23
23
  dimensions: umamiDimensions,
24
+ filters: /* @__PURE__ */ new Set(),
25
+ filterOperators: new Set(["eq"]),
24
26
  batchPageReport: true,
25
27
  rateLimit: null,
26
28
  recommendedTtl: {
@@ -1 +1 @@
1
- {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface UmamiConfig {\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/** API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is e.g. https://site/api. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst CLOUD_BASE = 'https://api.umami.is/v1'\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>(['page'])\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst base = config.host ?? CLOUD_BASE\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tbatchPageReport: true,\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\t// NOTE: the cloud header name and the per-URL `path` filter (set in params(), also\n\t// sent to /metrics) match the documented v2 shape but are unvalidated against a live\n\t// instance; confirm both before relying on per-URL provider data in production.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\tconst params = (q: AnalyticsQuery): URLSearchParams => {\n\t\tconst p = new URLSearchParams({\n\t\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\t\tendAt: String(q.dateRange.end.getTime()),\n\t\t})\n\t\tif (q.path) {\n\t\t\tp.set('path', q.path)\n\t\t}\n\t\treturn p\n\t}\n\n\treturn {\n\t\tid: 'umami',\n\t\tlabel: 'Umami',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst headers = authHeaders()\n\t\t\tconst wantsPageBreakdown = (q.dimensions ?? []).includes('page')\n\n\t\t\tif (wantsPageBreakdown) {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('type', 'url')\n\t\t\t\tconst data = await fetchJson<Array<{ x: string; y: number }>>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/metrics?${p.toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst metric: MetricKey = q.metrics.includes('pageviews') ? 'pageviews' : 'visitors'\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { page: row.x },\n\t\t\t\t\tmetrics: { [metric]: row.y } as Partial<Record<MetricKey, number>>,\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst stats = await fetchJson<UmamiStats>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/stats?${params(q).toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios are omitted (not zeroed) when there are no visits, so the\n\t\t\t\t\t// display layer shows a \"no data\" state instead of a misleading 0.\n\t\t\t\t\tbounceRate:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : undefined,\n\t\t\t\t\tavgDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : undefined,\n\t\t\t\t}\n\t\t\t\tconst totals: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\ttotals[m] = all[m]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn totals\n\t\t\t}\n\n\t\t\t// Umami's only time-series endpoint reports pageviews and sessions per interval;\n\t\t\t// visitors/bounceRate/avgDuration have no per-day source, so a trend on those\n\t\t\t// metrics keeps a correct headline (from /stats) but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('unit', 'day')\n\t\t\t\tp.set('timezone', q.timezone ?? 'UTC')\n\t\t\t\tconst fetchSeries = () =>\n\t\t\t\t\tfetchJson<{\n\t\t\t\t\t\tpageviews: Array<{ x: string; y: number }>\n\t\t\t\t\t\tsessions: Array<{ x: string; y: number }>\n\t\t\t\t\t}>(`${base}/websites/${config.websiteId}/pageviews?${p.toString()}`, {\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\t})\n\t\t\t\tconst [series, totals] = await Promise.all([fetchSeries(), fetchTotals()])\n\t\t\t\tconst sessionsByX = new Map(series.sessions.map((s) => [s.x, s.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const pv of series.pageviews) {\n\t\t\t\t\tconst ts = dayIso(pv.x)\n\t\t\t\t\tif (!ts) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst dayMetrics = sessionsByX.get(pv.x) ?? 0\n\t\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\t\tpageviews: pv.y,\n\t\t\t\t\t\tvisits: dayMetrics,\n\t\t\t\t\t\tsessions: dayMetrics,\n\t\t\t\t\t}\n\t\t\t\t\tconst metrics: Partial<Record<MetricKey, number>> = {}\n\t\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\t\tmetrics[m] = all[m]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trows.push({ timestamp: ts, metrics })\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'umami', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAyBA,MAAM,aAAa;AAEnB,MAAM,eAAuC,IAAI,IAAe;CAC/D;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,kBAA6C,IAAI,IAAkB,CAAC,MAAM,CAAC;AAUjF,SAAgB,MAAM,QAAuC;CAC5D,MAAM,OAAO,OAAO,QAAQ;CAG5B,MAAM,eAAsC;EAC3C,cAAc;EACd,UAAU;EACV,YAAY;EACZ,gBAAgB;EAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;EAQvF,SAAS;EACT,YAAY;EACZ,iBAAiB;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d,QAAQ,KAAK,IAAI;KAGnB,KAAK,KAAK;MAAE,WAAW;MAAI;KAAQ,CAAC;IACrC;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAS;KAAU;IAAE;GAC/D;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAS;IAAU;GAAE;EACtF;CACD;AACD"}
1
+ {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface UmamiConfig {\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/** API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is e.g. https://site/api. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst CLOUD_BASE = 'https://api.umami.is/v1'\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>(['page'])\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst base = config.host ?? CLOUD_BASE\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tfilters: new Set(),\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\t// NOTE: the cloud header name and the per-URL `path` filter (set in params(), also\n\t// sent to /metrics) match the documented v2 shape but are unvalidated against a live\n\t// instance; confirm both before relying on per-URL provider data in production.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\tconst params = (q: AnalyticsQuery): URLSearchParams => {\n\t\tconst p = new URLSearchParams({\n\t\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\t\tendAt: String(q.dateRange.end.getTime()),\n\t\t})\n\t\tif (q.path) {\n\t\t\tp.set('path', q.path)\n\t\t}\n\t\treturn p\n\t}\n\n\treturn {\n\t\tid: 'umami',\n\t\tlabel: 'Umami',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst headers = authHeaders()\n\t\t\tconst wantsPageBreakdown = (q.dimensions ?? []).includes('page')\n\n\t\t\tif (wantsPageBreakdown) {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('type', 'url')\n\t\t\t\tconst data = await fetchJson<Array<{ x: string; y: number }>>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/metrics?${p.toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst metric: MetricKey = q.metrics.includes('pageviews') ? 'pageviews' : 'visitors'\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { page: row.x },\n\t\t\t\t\tmetrics: { [metric]: row.y } as Partial<Record<MetricKey, number>>,\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst stats = await fetchJson<UmamiStats>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/stats?${params(q).toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios are omitted (not zeroed) when there are no visits, so the\n\t\t\t\t\t// display layer shows a \"no data\" state instead of a misleading 0.\n\t\t\t\t\tbounceRate:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : undefined,\n\t\t\t\t\tavgDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : undefined,\n\t\t\t\t}\n\t\t\t\tconst totals: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\ttotals[m] = all[m]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn totals\n\t\t\t}\n\n\t\t\t// Umami's only time-series endpoint reports pageviews and sessions per interval;\n\t\t\t// visitors/bounceRate/avgDuration have no per-day source, so a trend on those\n\t\t\t// metrics keeps a correct headline (from /stats) but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('unit', 'day')\n\t\t\t\tp.set('timezone', q.timezone ?? 'UTC')\n\t\t\t\tconst fetchSeries = () =>\n\t\t\t\t\tfetchJson<{\n\t\t\t\t\t\tpageviews: Array<{ x: string; y: number }>\n\t\t\t\t\t\tsessions: Array<{ x: string; y: number }>\n\t\t\t\t\t}>(`${base}/websites/${config.websiteId}/pageviews?${p.toString()}`, {\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\t})\n\t\t\t\tconst [series, totals] = await Promise.all([fetchSeries(), fetchTotals()])\n\t\t\t\tconst sessionsByX = new Map(series.sessions.map((s) => [s.x, s.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const pv of series.pageviews) {\n\t\t\t\t\tconst ts = dayIso(pv.x)\n\t\t\t\t\tif (!ts) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst dayMetrics = sessionsByX.get(pv.x) ?? 0\n\t\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\t\tpageviews: pv.y,\n\t\t\t\t\t\tvisits: dayMetrics,\n\t\t\t\t\t\tsessions: dayMetrics,\n\t\t\t\t\t}\n\t\t\t\t\tconst metrics: Partial<Record<MetricKey, number>> = {}\n\t\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\t\tmetrics[m] = all[m]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trows.push({ timestamp: ts, metrics })\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'umami', fetchedAt } }\n\t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AQ,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC,CAAC;IACzE,MAAM,cAAc,IAAI,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAClE,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,MAAM,OAAO,WAAW;KAClC,MAAM,KAAK,OAAO,GAAG,CAAC;KACtB,IAAI,CAAC,IACJ;KAED,MAAM,aAAa,YAAY,IAAI,GAAG,CAAC,KAAK;KAC5C,MAAM,MAA0C;MAC/C,WAAW,GAAG;MACd,QAAQ;MACR,UAAU;KACX;KACA,MAAM,UAA8C,CAAC;KACrD,KAAK,MAAM,KAAK,EAAE,SACjB,IAAI,IAAI,OAAO,KAAA,GACd,QAAQ,KAAK,IAAI;KAGnB,KAAK,KAAK;MAAE,WAAW;MAAI;KAAQ,CAAC;IACrC;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAS;KAAU;IAAE;GAC/D;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAS;IAAU;GAAE;EACtF;CACD;AACD"}
@@ -1,9 +1,11 @@
1
- import { DimensionKey, Granularity, MetricKey } from "./contract.js";
1
+ import { DimensionKey, FilterOperator, Granularity, MetricKey } from "./contract.js";
2
2
 
3
3
  //#region src/core/capabilities.d.ts
4
4
  interface CapabilityRequirement {
5
5
  metrics?: MetricKey[];
6
6
  dimensions?: DimensionKey[];
7
+ filters?: DimensionKey[];
8
+ filterOperators?: FilterOperator[];
7
9
  realtime?: boolean;
8
10
  perPageQuery?: boolean;
9
11
  }
@@ -11,6 +13,8 @@ interface CapabilityRequirement {
11
13
  type SerializedCapabilities = {
12
14
  metrics: MetricKey[];
13
15
  dimensions: DimensionKey[];
16
+ filters: DimensionKey[];
17
+ filterOperators: FilterOperator[];
14
18
  realtime: boolean;
15
19
  realtimeWindowMinutes?: number;
16
20
  perPageQuery: boolean;
@@ -4,11 +4,15 @@ function satisfiesCapabilities(caps, req) {
4
4
  if (req.perPageQuery && !caps.perPageQuery) return false;
5
5
  if (req.metrics?.some((m) => !caps.metrics.has(m))) return false;
6
6
  if (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false;
7
+ if (req.filters?.some((d) => !caps.filters.has(d))) return false;
8
+ if (req.filterOperators?.some((op) => !caps.filterOperators.has(op))) return false;
7
9
  return true;
8
10
  }
9
11
  const serializeCapabilities = (caps) => ({
10
12
  metrics: [...caps.metrics],
11
13
  dimensions: [...caps.dimensions],
14
+ filters: [...caps.filters],
15
+ filterOperators: [...caps.filterOperators],
12
16
  realtime: caps.realtime,
13
17
  ...caps.realtimeWindowMinutes !== void 0 ? { realtimeWindowMinutes: caps.realtimeWindowMinutes } : {},
14
18
  perPageQuery: caps.perPageQuery,
@@ -1 +1 @@
1
- {"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["import type { AnalyticsCapabilities, DimensionKey, Granularity, MetricKey } from './contract'\n\nexport interface CapabilityRequirement {\n\tmetrics?: MetricKey[]\n\tdimensions?: DimensionKey[]\n\trealtime?: boolean\n\tperPageQuery?: boolean\n}\n\nexport function satisfiesCapabilities(\n\tcaps: AnalyticsCapabilities,\n\treq: CapabilityRequirement\n): boolean {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.has(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false\n\treturn true\n}\n\n/** Wire form of AnalyticsCapabilities for client pickers: a deliberate allowlist, so adapter internals (rate limits, TTLs) never become client contract by accident. */\nexport type SerializedCapabilities = {\n\tmetrics: MetricKey[]\n\tdimensions: DimensionKey[]\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\tperPageQuery: boolean\n\tcomparison: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n}\n\nexport const serializeCapabilities = (caps: AnalyticsCapabilities): SerializedCapabilities => ({\n\tmetrics: [...caps.metrics],\n\tdimensions: [...caps.dimensions],\n\trealtime: caps.realtime,\n\t...(caps.realtimeWindowMinutes !== undefined\n\t\t? { realtimeWindowMinutes: caps.realtimeWindowMinutes }\n\t\t: {}),\n\tperPageQuery: caps.perPageQuery,\n\tcomparison: caps.comparison,\n\tminGranularity: caps.minGranularity,\n\tmaxLookbackDays: caps.maxLookbackDays,\n})\n"],"mappings":";AASA,SAAgB,sBACf,MACA,KACU;CACV,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;CACjE,OAAO;AACR;AAcA,MAAa,yBAAyB,UAAyD;CAC9F,SAAS,CAAC,GAAG,KAAK,OAAO;CACzB,YAAY,CAAC,GAAG,KAAK,UAAU;CAC/B,UAAU,KAAK;CACf,GAAI,KAAK,0BAA0B,KAAA,IAChC,EAAE,uBAAuB,KAAK,sBAAsB,IACpD,CAAC;CACJ,cAAc,KAAK;CACnB,YAAY,KAAK;CACjB,gBAAgB,KAAK;CACrB,iBAAiB,KAAK;AACvB"}
1
+ {"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["import type {\n\tAnalyticsCapabilities,\n\tDimensionKey,\n\tFilterOperator,\n\tGranularity,\n\tMetricKey,\n} from './contract'\n\nexport interface CapabilityRequirement {\n\tmetrics?: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tfilters?: DimensionKey[]\n\tfilterOperators?: FilterOperator[]\n\trealtime?: boolean\n\tperPageQuery?: boolean\n}\n\nexport function satisfiesCapabilities(\n\tcaps: AnalyticsCapabilities,\n\treq: CapabilityRequirement\n): boolean {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.has(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false\n\tif (req.filters?.some((d) => !caps.filters.has(d))) return false\n\tif (req.filterOperators?.some((op) => !caps.filterOperators.has(op))) return false\n\treturn true\n}\n\n/** Wire form of AnalyticsCapabilities for client pickers: a deliberate allowlist, so adapter internals (rate limits, TTLs) never become client contract by accident. */\nexport type SerializedCapabilities = {\n\tmetrics: MetricKey[]\n\tdimensions: DimensionKey[]\n\tfilters: DimensionKey[]\n\tfilterOperators: FilterOperator[]\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\tperPageQuery: boolean\n\tcomparison: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n}\n\nexport const serializeCapabilities = (caps: AnalyticsCapabilities): SerializedCapabilities => ({\n\tmetrics: [...caps.metrics],\n\tdimensions: [...caps.dimensions],\n\tfilters: [...caps.filters],\n\tfilterOperators: [...caps.filterOperators],\n\trealtime: caps.realtime,\n\t...(caps.realtimeWindowMinutes !== undefined\n\t\t? { realtimeWindowMinutes: caps.realtimeWindowMinutes }\n\t\t: {}),\n\tperPageQuery: caps.perPageQuery,\n\tcomparison: caps.comparison,\n\tminGranularity: caps.minGranularity,\n\tmaxLookbackDays: caps.maxLookbackDays,\n})\n"],"mappings":";AAiBA,SAAgB,sBACf,MACA,KACU;CACV,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;CACjE,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,iBAAiB,MAAM,OAAO,CAAC,KAAK,gBAAgB,IAAI,EAAE,CAAC,GAAG,OAAO;CAC7E,OAAO;AACR;AAgBA,MAAa,yBAAyB,UAAyD;CAC9F,SAAS,CAAC,GAAG,KAAK,OAAO;CACzB,YAAY,CAAC,GAAG,KAAK,UAAU;CAC/B,SAAS,CAAC,GAAG,KAAK,OAAO;CACzB,iBAAiB,CAAC,GAAG,KAAK,eAAe;CACzC,UAAU,KAAK;CACf,GAAI,KAAK,0BAA0B,KAAA,IAChC,EAAE,uBAAuB,KAAK,sBAAsB,IACpD,CAAC;CACJ,cAAc,KAAK;CACnB,YAAY,KAAK;CACjB,gBAAgB,KAAK;CACrB,iBAAiB,KAAK;AACvB"}
@@ -13,9 +13,10 @@ interface DateRange {
13
13
  start: Date;
14
14
  end: Date;
15
15
  }
16
+ type FilterOperator = 'eq' | 'contains' | 'matches';
16
17
  interface AnalyticsFilter {
17
18
  dimension: DimensionKey;
18
- operator: 'eq' | 'contains' | 'matches';
19
+ operator: FilterOperator;
19
20
  value: string;
20
21
  }
21
22
  interface AnalyticsQuery {
@@ -76,6 +77,10 @@ interface AnalyticsCapabilities {
76
77
  maxLookbackDays: number | null;
77
78
  metrics: ReadonlySet<MetricKey>;
78
79
  dimensions: ReadonlySet<DimensionKey>;
80
+ /** Dimensions the adapter can apply AnalyticsQuery.filters on; empty = filters unsupported. */
81
+ filters: ReadonlySet<DimensionKey>;
82
+ /** Operators the adapter honors in filters; adapters ignore filters whose operator they lack. */
83
+ filterOperators: ReadonlySet<FilterOperator>;
79
84
  batchPageReport: boolean;
80
85
  rateLimit: RateLimitDescriptor | null;
81
86
  recommendedTtl: {
@@ -116,5 +121,5 @@ interface AnalyticsAdapter {
116
121
  }
117
122
  type AnalyticsAdapterFactory<Config> = (config: Config) => AnalyticsAdapter;
118
123
  //#endregion
119
- export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DateRange, DimensionKey, Granularity, MetricKey, PLATFORM_SCOPE, RateLimitDescriptor };
124
+ export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DateRange, DimensionKey, FilterOperator, Granularity, MetricKey, PLATFORM_SCOPE, RateLimitDescriptor };
120
125
  //# sourceMappingURL=contract.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"contract.js","names":[],"sources":["../../src/core/contract.ts"],"sourcesContent":["import type { Config, PayloadRequest } from 'payload'\n\n/**\n * Explicit cross-scope read marker: pass as a read's `scope` to aggregate over every\n * scope. Gated by `access.platformRead`; the query reaches the adapter unscoped.\n */\nexport const PLATFORM_SCOPE = '*'\n\nexport type MetricKey =\n\t| 'pageviews'\n\t| 'visitors'\n\t| 'visits'\n\t| 'sessions'\n\t| 'bounceRate'\n\t| 'avgDuration'\n\t| 'scrollDepth'\n\t| 'events'\n\t| 'conversions'\n\t| 'revenue'\n\nexport type DimensionKey =\n\t| 'page'\n\t| 'referrer'\n\t| 'source'\n\t| 'medium'\n\t| 'campaign'\n\t| 'utmSource'\n\t| 'utmMedium'\n\t| 'utmCampaign'\n\t| 'utmContent'\n\t| 'utmTerm'\n\t| 'device'\n\t| 'browser'\n\t| 'os'\n\t| 'country'\n\t| 'region'\n\t| 'city'\n\t| 'language'\n\t| 'event'\n\nexport type Granularity = 'minute' | 'hour' | 'day' | 'week' | 'month'\n\nexport interface DateRange {\n\tstart: Date\n\tend: Date\n}\n\nexport interface AnalyticsFilter {\n\tdimension: DimensionKey\n\toperator: 'eq' | 'contains' | 'matches'\n\tvalue: string\n}\n\nexport interface AnalyticsQuery {\n\tpath?: string\n\thostname?: string\n\tmetrics: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tdateRange: DateRange\n\tgranularity?: Granularity\n\tfilters?: AnalyticsFilter[]\n\tlimit?: number\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n\t/**\n\t * Analytics boundary this read belongs to (tenant id, site key). Undefined means\n\t * install-wide (the default). Adapters that can filter by scope apply it; others\n\t * ignore it. Always part of the surfacing cache key, so per-scope adapter\n\t * instances sharing an id never share cached results.\n\t */\n\tscope?: string\n\t/**\n\t * IANA reporting timezone the read's day boundaries are aligned to. Undefined\n\t * means UTC. Adapters that can bucket in a timezone apply it (PostHog, Umami);\n\t * others report in their own account timezone. Part of the cache key when set.\n\t */\n\ttimezone?: string\n}\n\nexport interface AnalyticsRow {\n\tdimensions?: Partial<Record<DimensionKey, string>>\n\tmetrics: Partial<Record<MetricKey, number>>\n\ttimestamp?: string\n}\n\nexport interface AnalyticsResult {\n\trows: AnalyticsRow[]\n\ttotals?: Partial<Record<MetricKey, number>>\n\tmeta: { provider: string; sampled?: boolean; clamped?: boolean; fetchedAt: string }\n}\n\nexport interface RateLimitDescriptor {\n\trequestsPerMinute?: number\n\trequestsPerHour?: number\n\tmaxConcurrent?: number\n\tquotaModel?: 'requests' | 'tokens'\n\treadsCountAsUsage?: boolean\n}\n\nexport interface AnalyticsCapabilities {\n\tperPageQuery: boolean\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\tcomparison: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n\tmetrics: ReadonlySet<MetricKey>\n\tdimensions: ReadonlySet<DimensionKey>\n\tbatchPageReport: boolean\n\trateLimit: RateLimitDescriptor | null\n\trecommendedTtl: { realtime: number; aggregate: number }\n\t/**\n\t * The adapter applies `AnalyticsQuery.scope` as a provider-native filter (native\n\t * scope column, PostHog `scopeProperty`, ...). Without it, a scoped read through\n\t * a shared platform adapter would expose cross-scope data, so such reads are\n\t * gated by `access.platformRead`.\n\t */\n\tscopedQueries?: boolean\n}\n\nexport interface AdapterContext {\n\tsignal?: AbortSignal\n}\n\n/** Extra context the plugin hands adapters when they register config surface. */\nexport interface AdapterRegisterContext {\n\t/** True when the plugin has a scopeResolver configured. */\n\tscoped: boolean\n\t/** The plugin's scopeResolver bound for adapter use (e.g. ingest stamping). */\n\tresolveScope: (req: PayloadRequest) => Promise<string | null>\n\t/**\n\t * The plugin's reportingTimezone bound for adapter use (e.g. bucketing native\n\t * rollups at ingest). Resolves to `'UTC'` when no reportingTimezone is set.\n\t */\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n}\n\nexport interface AnalyticsAdapter {\n\treadonly id: string\n\treadonly label: string\n\treadonly capabilities: AnalyticsCapabilities\n\tisConfigured(): boolean\n\tquery(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\trealtime?(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\tregister?(config: Config, context?: AdapterRegisterContext): void\n}\n\nexport type AnalyticsAdapterFactory<Config> = (config: Config) => AnalyticsAdapter\n"],"mappings":";;;;;AAMA,MAAa,iBAAiB"}
1
+ {"version":3,"file":"contract.js","names":[],"sources":["../../src/core/contract.ts"],"sourcesContent":["import type { Config, PayloadRequest } from 'payload'\n\n/**\n * Explicit cross-scope read marker: pass as a read's `scope` to aggregate over every\n * scope. Gated by `access.platformRead`; the query reaches the adapter unscoped.\n */\nexport const PLATFORM_SCOPE = '*'\n\nexport type MetricKey =\n\t| 'pageviews'\n\t| 'visitors'\n\t| 'visits'\n\t| 'sessions'\n\t| 'bounceRate'\n\t| 'avgDuration'\n\t| 'scrollDepth'\n\t| 'events'\n\t| 'conversions'\n\t| 'revenue'\n\nexport type DimensionKey =\n\t| 'page'\n\t| 'referrer'\n\t| 'source'\n\t| 'medium'\n\t| 'campaign'\n\t| 'utmSource'\n\t| 'utmMedium'\n\t| 'utmCampaign'\n\t| 'utmContent'\n\t| 'utmTerm'\n\t| 'device'\n\t| 'browser'\n\t| 'os'\n\t| 'country'\n\t| 'region'\n\t| 'city'\n\t| 'language'\n\t| 'event'\n\nexport type Granularity = 'minute' | 'hour' | 'day' | 'week' | 'month'\n\nexport interface DateRange {\n\tstart: Date\n\tend: Date\n}\n\nexport type FilterOperator = 'eq' | 'contains' | 'matches'\n\nexport interface AnalyticsFilter {\n\tdimension: DimensionKey\n\toperator: FilterOperator\n\tvalue: string\n}\n\nexport interface AnalyticsQuery {\n\tpath?: string\n\thostname?: string\n\tmetrics: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tdateRange: DateRange\n\tgranularity?: Granularity\n\tfilters?: AnalyticsFilter[]\n\tlimit?: number\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n\t/**\n\t * Analytics boundary this read belongs to (tenant id, site key). Undefined means\n\t * install-wide (the default). Adapters that can filter by scope apply it; others\n\t * ignore it. Always part of the surfacing cache key, so per-scope adapter\n\t * instances sharing an id never share cached results.\n\t */\n\tscope?: string\n\t/**\n\t * IANA reporting timezone the read's day boundaries are aligned to. Undefined\n\t * means UTC. Adapters that can bucket in a timezone apply it (PostHog, Umami);\n\t * others report in their own account timezone. Part of the cache key when set.\n\t */\n\ttimezone?: string\n}\n\nexport interface AnalyticsRow {\n\tdimensions?: Partial<Record<DimensionKey, string>>\n\tmetrics: Partial<Record<MetricKey, number>>\n\ttimestamp?: string\n}\n\nexport interface AnalyticsResult {\n\trows: AnalyticsRow[]\n\ttotals?: Partial<Record<MetricKey, number>>\n\tmeta: { provider: string; sampled?: boolean; clamped?: boolean; fetchedAt: string }\n}\n\nexport interface RateLimitDescriptor {\n\trequestsPerMinute?: number\n\trequestsPerHour?: number\n\tmaxConcurrent?: number\n\tquotaModel?: 'requests' | 'tokens'\n\treadsCountAsUsage?: boolean\n}\n\nexport interface AnalyticsCapabilities {\n\tperPageQuery: boolean\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\tcomparison: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n\tmetrics: ReadonlySet<MetricKey>\n\tdimensions: ReadonlySet<DimensionKey>\n\t/** Dimensions the adapter can apply AnalyticsQuery.filters on; empty = filters unsupported. */\n\tfilters: ReadonlySet<DimensionKey>\n\t/** Operators the adapter honors in filters; adapters ignore filters whose operator they lack. */\n\tfilterOperators: ReadonlySet<FilterOperator>\n\tbatchPageReport: boolean\n\trateLimit: RateLimitDescriptor | null\n\trecommendedTtl: { realtime: number; aggregate: number }\n\t/**\n\t * The adapter applies `AnalyticsQuery.scope` as a provider-native filter (native\n\t * scope column, PostHog `scopeProperty`, ...). Without it, a scoped read through\n\t * a shared platform adapter would expose cross-scope data, so such reads are\n\t * gated by `access.platformRead`.\n\t */\n\tscopedQueries?: boolean\n}\n\nexport interface AdapterContext {\n\tsignal?: AbortSignal\n}\n\n/** Extra context the plugin hands adapters when they register config surface. */\nexport interface AdapterRegisterContext {\n\t/** True when the plugin has a scopeResolver configured. */\n\tscoped: boolean\n\t/** The plugin's scopeResolver bound for adapter use (e.g. ingest stamping). */\n\tresolveScope: (req: PayloadRequest) => Promise<string | null>\n\t/**\n\t * The plugin's reportingTimezone bound for adapter use (e.g. bucketing native\n\t * rollups at ingest). Resolves to `'UTC'` when no reportingTimezone is set.\n\t */\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n}\n\nexport interface AnalyticsAdapter {\n\treadonly id: string\n\treadonly label: string\n\treadonly capabilities: AnalyticsCapabilities\n\tisConfigured(): boolean\n\tquery(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\trealtime?(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\tregister?(config: Config, context?: AdapterRegisterContext): void\n}\n\nexport type AnalyticsAdapterFactory<Config> = (config: Config) => AnalyticsAdapter\n"],"mappings":";;;;;AAMA,MAAa,iBAAiB"}
@@ -1,4 +1,4 @@
1
- import { DateRange, DimensionKey, MetricKey } from "../core/contract.js";
1
+ import { AnalyticsFilter, DateRange, DimensionKey, MetricKey } from "../core/contract.js";
2
2
  import { CapabilityRequirement } from "../core/capabilities.js";
3
3
  import { ReadForWidgetRealtimeArgs, RealtimePoint, WidgetRealtimeResult, WidgetRealtimeStatus, readForWidgetRealtime } from "../widgets/readForWidgetRealtime.js";
4
4
  import { AnalyticsStatField } from "../fields/AnalyticsStatField.js";
@@ -13,4 +13,4 @@ import { AnalyticsRealtimeWidget } from "../widgets/AnalyticsRealtimeWidget.js";
13
13
  import { AnalyticsTrendWidget } from "../widgets/AnalyticsTrendWidget.js";
14
14
  import { cardStyle, labelStyle } from "../widgets/cardChrome.js";
15
15
  import { BreakdownRow, ReadForWidgetBreakdownArgs, WidgetBreakdownResult, readForWidgetBreakdown } from "../widgets/readForWidgetBreakdown.js";
16
- export { AnalyticsBreakdownWidget, AnalyticsMetricWidget, AnalyticsPanelField, AnalyticsRealtimeWidget, AnalyticsStatField, AnalyticsTrendWidget, type BreakdownRow, type CapabilityRequirement, type DateRange, type DimensionKey, type FieldReadResult, type FieldReadStatus, type MetricKey, type ReadForFieldArgs, type ReadForWidgetArgs, type ReadForWidgetBreakdownArgs, type ReadForWidgetRealtimeArgs, type ReadForWidgetSeriesArgs, type RealtimePoint, type SeriesPoint, type WidgetBreakdownResult, type WidgetReadResult, type WidgetReadStatus, type WidgetRealtimeResult, type WidgetRealtimeStatus, type WidgetSeriesResult, formatMetricValue, readForField, readForWidget, readForWidgetBreakdown, readForWidgetRealtime, readForWidgetSeries, cardStyle as widgetCardStyle, labelStyle as widgetLabelStyle };
16
+ export { AnalyticsBreakdownWidget, type AnalyticsFilter, AnalyticsMetricWidget, AnalyticsPanelField, AnalyticsRealtimeWidget, AnalyticsStatField, AnalyticsTrendWidget, type BreakdownRow, type CapabilityRequirement, type DateRange, type DimensionKey, type FieldReadResult, type FieldReadStatus, type MetricKey, type ReadForFieldArgs, type ReadForWidgetArgs, type ReadForWidgetBreakdownArgs, type ReadForWidgetRealtimeArgs, type ReadForWidgetSeriesArgs, type RealtimePoint, type SeriesPoint, type WidgetBreakdownResult, type WidgetReadResult, type WidgetReadStatus, type WidgetRealtimeResult, type WidgetRealtimeStatus, type WidgetSeriesResult, formatMetricValue, readForField, readForWidget, readForWidgetBreakdown, readForWidgetRealtime, readForWidgetSeries, cardStyle as widgetCardStyle, labelStyle as widgetLabelStyle };
@@ -1,7 +1,7 @@
1
- import { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DateRange, DimensionKey, Granularity, MetricKey, PLATFORM_SCOPE, RateLimitDescriptor } from "../core/contract.js";
1
+ import { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DateRange, DimensionKey, FilterOperator, Granularity, MetricKey, PLATFORM_SCOPE, RateLimitDescriptor } from "../core/contract.js";
2
2
  import { SerializedCapabilities } from "../core/capabilities.js";
3
3
  import { AnalyticsBinding, BindingContext, HostnameResolver, PathResolver } from "../binding/types.js";
4
4
  import { TimeframePreset } from "../timeframe/presets.js";
5
5
  import { AnalyticsFieldsOptions, AnalyticsMetricLabel, AnalyticsMetricLabels, AnalyticsStatOptions, AnalyticsStatRowOptions, AnalyticsTabOptions } from "../fields/factories.js";
6
6
  import { AnalyticsPluginOptions } from "../core/options.js";
7
- export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, DateRange, DimensionKey, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, RateLimitDescriptor, type SerializedCapabilities, type TimeframePreset };
7
+ export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, DateRange, DimensionKey, FilterOperator, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, RateLimitDescriptor, type SerializedCapabilities, type TimeframePreset };