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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +21 -21
  3. package/README.md +5 -1
  4. package/dist/adapters/ga4/ga4.js +13 -0
  5. package/dist/adapters/ga4/ga4.js.map +1 -1
  6. package/dist/adapters/http/fetchJson.js +1 -1
  7. package/dist/adapters/plausible/plausible.d.ts +10 -0
  8. package/dist/adapters/plausible/plausible.js +51 -0
  9. package/dist/adapters/plausible/plausible.js.map +1 -1
  10. package/dist/adapters/posthog/posthog.d.ts +10 -1
  11. package/dist/adapters/posthog/posthog.js +84 -3
  12. package/dist/adapters/posthog/posthog.js.map +1 -1
  13. package/dist/adapters/series.js +11 -1
  14. package/dist/adapters/series.js.map +1 -1
  15. package/dist/adapters/umami/umami.d.ts +5 -1
  16. package/dist/adapters/umami/umami.js +28 -0
  17. package/dist/adapters/umami/umami.js.map +1 -1
  18. package/dist/capture/getTrackerConfig.d.ts +20 -0
  19. package/dist/capture/getTrackerConfig.js +31 -0
  20. package/dist/capture/getTrackerConfig.js.map +1 -0
  21. package/dist/capture/mountPath.js +14 -0
  22. package/dist/capture/mountPath.js.map +1 -0
  23. package/dist/capture/proxyEndpoint.js +123 -0
  24. package/dist/capture/proxyEndpoint.js.map +1 -0
  25. package/dist/capture/proxyRoutes.js +108 -0
  26. package/dist/capture/proxyRoutes.js.map +1 -0
  27. package/dist/capture/requestBody.js +68 -0
  28. package/dist/capture/requestBody.js.map +1 -0
  29. package/dist/capture/slots.d.ts +8 -0
  30. package/dist/capture/slots.js +43 -0
  31. package/dist/capture/slots.js.map +1 -0
  32. package/dist/capture/trackerConfig.d.ts +32 -0
  33. package/dist/capture/trackerConfig.js +70 -0
  34. package/dist/capture/trackerConfig.js.map +1 -0
  35. package/dist/capture/trackerEndpoint.js +35 -0
  36. package/dist/capture/trackerEndpoint.js.map +1 -0
  37. package/dist/core/capabilities.d.ts +5 -1
  38. package/dist/core/capabilities.js +4 -0
  39. package/dist/core/capabilities.js.map +1 -1
  40. package/dist/core/capture.d.ts +49 -0
  41. package/dist/core/contract.d.ts +33 -4
  42. package/dist/core/contract.js.map +1 -1
  43. package/dist/core/options.d.ts +97 -2
  44. package/dist/core/options.js +63 -2
  45. package/dist/core/options.js.map +1 -1
  46. package/dist/core/registry.d.ts +1 -0
  47. package/dist/core/scopeList.js +32 -0
  48. package/dist/core/scopeList.js.map +1 -0
  49. package/dist/core/scopedRead.js +13 -6
  50. package/dist/core/scopedRead.js.map +1 -1
  51. package/dist/exports/next.d.ts +2 -1
  52. package/dist/exports/next.js +2 -1
  53. package/dist/exports/react.d.ts +4 -0
  54. package/dist/exports/react.js +5 -0
  55. package/dist/exports/rsc.d.ts +5 -2
  56. package/dist/exports/rsc.js +3 -1
  57. package/dist/exports/tracker.d.ts +18 -0
  58. package/dist/exports/tracker.js +12 -0
  59. package/dist/exports/types.d.ts +6 -3
  60. package/dist/fields/AnalyticsPanelClient.js +1 -1
  61. package/dist/fields/config/narrow.js +2 -0
  62. package/dist/fields/config/narrow.js.map +1 -1
  63. package/dist/fields/readForDocument.js +1 -1
  64. package/dist/goals/match.js +64 -0
  65. package/dist/goals/match.js.map +1 -0
  66. package/dist/goals/types.d.ts +33 -0
  67. package/dist/goals/types.js +7 -0
  68. package/dist/goals/types.js.map +1 -0
  69. package/dist/index.d.ts +4 -3
  70. package/dist/index.js +39 -10
  71. package/dist/index.js.map +1 -1
  72. package/dist/native/collections/events.js +21 -1
  73. package/dist/native/collections/events.js.map +1 -1
  74. package/dist/native/collections/rollups.js +39 -3
  75. package/dist/native/collections/rollups.js.map +1 -1
  76. package/dist/native/geo/maxmindResolver.js +2 -4
  77. package/dist/native/geo/maxmindResolver.js.map +1 -1
  78. package/dist/native/ingest/clientIp.js +15 -0
  79. package/dist/native/ingest/clientIp.js.map +1 -0
  80. package/dist/native/ingest/endpoint.js +40 -4
  81. package/dist/native/ingest/endpoint.js.map +1 -1
  82. package/dist/native/ingest/flushBatch.js +4 -13
  83. package/dist/native/ingest/flushBatch.js.map +1 -1
  84. package/dist/native/ingest/normalizeEvent.js +76 -9
  85. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  86. package/dist/native/nativeAdapter.js +100 -5
  87. package/dist/native/nativeAdapter.js.map +1 -1
  88. package/dist/native/query/eventAgg.js +161 -0
  89. package/dist/native/query/eventAgg.js.map +1 -0
  90. package/dist/native/rollupAcc.js +12 -1
  91. package/dist/native/rollupAcc.js.map +1 -1
  92. package/dist/native/rollups/applyDistinctDeltas.js +1 -1
  93. package/dist/native/rollups/applyDistinctDeltas.js.map +1 -1
  94. package/dist/native/rollups/bumpRollup.js +7 -2
  95. package/dist/native/rollups/bumpRollup.js.map +1 -1
  96. package/dist/native/rollups/deltas.js +70 -11
  97. package/dist/native/rollups/deltas.js.map +1 -1
  98. package/dist/next/captureRewrites.d.ts +41 -0
  99. package/dist/next/captureRewrites.js +56 -0
  100. package/dist/next/captureRewrites.js.map +1 -0
  101. package/dist/next/posthogProxyRewrites.d.ts +5 -0
  102. package/dist/next/posthogProxyRewrites.js +16 -21
  103. package/dist/next/posthogProxyRewrites.js.map +1 -1
  104. package/dist/plugin/documentEndpoint.js +1 -1
  105. package/dist/plugin/paths.js +11 -1
  106. package/dist/plugin/paths.js.map +1 -1
  107. package/dist/plugin/runtime.d.ts +1 -0
  108. package/dist/plugin/runtime.js.map +1 -1
  109. package/dist/plugin/sourcesEndpoint.js +16 -4
  110. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  111. package/dist/plugin/warmTask.js +0 -0
  112. package/dist/plugin/warmTask.js.map +1 -1
  113. package/dist/providers/collection.js +56 -16
  114. package/dist/providers/collection.js.map +1 -1
  115. package/dist/providers/factory.js +8 -2
  116. package/dist/providers/factory.js.map +1 -1
  117. package/dist/react/AnalyticsProvider.d.ts +43 -0
  118. package/dist/react/AnalyticsProvider.js +66 -0
  119. package/dist/react/AnalyticsProvider.js.map +1 -0
  120. package/dist/react/TrackerBoot.d.ts +22 -0
  121. package/dist/react/TrackerBoot.js +30 -0
  122. package/dist/react/TrackerBoot.js.map +1 -0
  123. package/dist/react/useAnalytics.d.ts +17 -0
  124. package/dist/react/useAnalytics.js +36 -0
  125. package/dist/react/useAnalytics.js.map +1 -0
  126. package/dist/rsc/AnalyticsScripts.d.ts +30 -0
  127. package/dist/rsc/AnalyticsScripts.js +41 -0
  128. package/dist/rsc/AnalyticsScripts.js.map +1 -0
  129. package/dist/surfacing/cacheStore.d.ts +1 -0
  130. package/dist/surfacing/cacheStore.js +18 -2
  131. package/dist/surfacing/cacheStore.js.map +1 -1
  132. package/dist/surfacing/engine.d.ts +1 -0
  133. package/dist/surfacing/engine.js +44 -4
  134. package/dist/surfacing/engine.js.map +1 -1
  135. package/dist/surfacing/queue.js +22 -6
  136. package/dist/surfacing/queue.js.map +1 -1
  137. package/dist/surfacing/rateLimiter.js +130 -0
  138. package/dist/surfacing/rateLimiter.js.map +1 -0
  139. package/dist/surfacing/retryPolicy.js +15 -0
  140. package/dist/surfacing/retryPolicy.js.map +1 -0
  141. package/dist/sync/collection.js +23 -7
  142. package/dist/sync/collection.js.map +1 -1
  143. package/dist/sync/syncTask.js +68 -33
  144. package/dist/sync/syncTask.js.map +1 -1
  145. package/dist/testing/memoryAdapter.d.ts +2 -0
  146. package/dist/testing/memoryAdapter.js +17 -0
  147. package/dist/testing/memoryAdapter.js.map +1 -1
  148. package/dist/tracker/autoCapture.d.ts +48 -0
  149. package/dist/tracker/autoCapture.js +129 -0
  150. package/dist/tracker/autoCapture.js.map +1 -0
  151. package/dist/tracker/consent.d.ts +24 -0
  152. package/dist/tracker/consent.js +48 -0
  153. package/dist/tracker/consent.js.map +1 -0
  154. package/dist/tracker/createTracker.d.ts +18 -0
  155. package/dist/tracker/createTracker.js +163 -0
  156. package/dist/tracker/createTracker.js.map +1 -0
  157. package/dist/tracker/initTracker.d.ts +22 -0
  158. package/dist/tracker/initTracker.js +33 -0
  159. package/dist/tracker/initTracker.js.map +1 -0
  160. package/dist/tracker/loadScript.d.ts +14 -0
  161. package/dist/tracker/loadScript.js +41 -0
  162. package/dist/tracker/loadScript.js.map +1 -0
  163. package/dist/tracker/pageTracking.d.ts +17 -0
  164. package/dist/tracker/pageTracking.js +38 -0
  165. package/dist/tracker/pageTracking.js.map +1 -0
  166. package/dist/tracker/registry.d.ts +27 -0
  167. package/dist/tracker/registry.js +73 -0
  168. package/dist/tracker/registry.js.map +1 -0
  169. package/dist/tracker/sinks/native.d.ts +22 -0
  170. package/dist/tracker/sinks/native.js +56 -0
  171. package/dist/tracker/sinks/native.js.map +1 -0
  172. package/dist/tracker/sinks/plausible.d.ts +14 -0
  173. package/dist/tracker/sinks/plausible.js +25 -0
  174. package/dist/tracker/sinks/plausible.js.map +1 -0
  175. package/dist/tracker/sinks/posthog.d.ts +14 -0
  176. package/dist/tracker/sinks/posthog.js +18 -0
  177. package/dist/tracker/sinks/posthog.js.map +1 -0
  178. package/dist/tracker/sinks/umami.d.ts +13 -0
  179. package/dist/tracker/sinks/umami.js +17 -0
  180. package/dist/tracker/sinks/umami.js.map +1 -0
  181. package/dist/tracker/sinks/vendor.d.ts +14 -0
  182. package/dist/tracker/sinks/vendor.js +66 -0
  183. package/dist/tracker/sinks/vendor.js.map +1 -0
  184. package/dist/tracker/transport.js +28 -0
  185. package/dist/tracker/transport.js.map +1 -0
  186. package/dist/tracker/types.d.ts +66 -0
  187. package/dist/translations/ar.js +83 -0
  188. package/dist/translations/ar.js.map +1 -0
  189. package/dist/translations/de.js +6 -0
  190. package/dist/translations/de.js.map +1 -1
  191. package/dist/translations/en.js +6 -0
  192. package/dist/translations/en.js.map +1 -1
  193. package/dist/translations/es.js +83 -0
  194. package/dist/translations/es.js.map +1 -0
  195. package/dist/translations/fr.js +83 -0
  196. package/dist/translations/fr.js.map +1 -0
  197. package/dist/translations/id.js +83 -0
  198. package/dist/translations/id.js.map +1 -0
  199. package/dist/translations/index.d.ts +10 -1
  200. package/dist/translations/index.js +19 -1
  201. package/dist/translations/index.js.map +1 -1
  202. package/dist/translations/keys.d.ts +6 -0
  203. package/dist/translations/keys.js +6 -0
  204. package/dist/translations/keys.js.map +1 -1
  205. package/dist/translations/ko.js +83 -0
  206. package/dist/translations/ko.js.map +1 -0
  207. package/dist/translations/pt.js +83 -0
  208. package/dist/translations/pt.js.map +1 -0
  209. package/dist/translations/ru.js +83 -0
  210. package/dist/translations/ru.js.map +1 -0
  211. package/dist/translations/uk.js +83 -0
  212. package/dist/translations/uk.js.map +1 -0
  213. package/dist/translations/zh.js +83 -0
  214. package/dist/translations/zh.js.map +1 -0
  215. package/dist/widgets/breakdownTypes.js +5 -0
  216. package/dist/widgets/breakdownTypes.js.map +1 -1
  217. package/dist/widgets/readForWidget.d.ts +2 -1
  218. package/dist/widgets/readForWidget.js +32 -14
  219. package/dist/widgets/readForWidget.js.map +1 -1
  220. package/dist/widgets/readForWidgetBreakdown.d.ts +2 -1
  221. package/dist/widgets/readForWidgetBreakdown.js +29 -15
  222. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  223. package/dist/widgets/readForWidgetRealtime.js +1 -1
  224. package/dist/widgets/readForWidgetSeries.d.ts +2 -1
  225. package/dist/widgets/readForWidgetSeries.js +34 -16
  226. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  227. package/dist/widgets/registerWidgets.js +10 -4
  228. package/dist/widgets/registerWidgets.js.map +1 -1
  229. package/dist/widgets/types.js +4 -1
  230. package/dist/widgets/types.js.map +1 -1
  231. package/package.json +20 -5
@@ -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"}
@@ -7,7 +7,11 @@ interface UmamiConfig {
7
7
  apiKey?: string;
8
8
  /** Self-hosted bearer token (from POST /api/auth/login). */
9
9
  token?: string;
10
- /** API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is e.g. https://site/api. */
10
+ /**
11
+ * API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is
12
+ * e.g. https://site/api. Capture derives the app origin from this (a trailing `/api`
13
+ * is stripped), so one `host` value serves both the Stats API and the tracker.
14
+ */
11
15
  host?: string;
12
16
  /** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */
13
17
  maxLookbackDays?: number | null;
@@ -2,6 +2,31 @@ import { dayIso } from "../series.js";
2
2
  import { fetchJson } from "../http/fetchJson.js";
3
3
  //#region src/adapters/umami/umami.ts
4
4
  const CLOUD_BASE = "https://api.umami.is/v1";
5
+ const CLOUD_SCRIPT = "https://cloud.umami.is/script.js";
6
+ const CLOUD_SEND = "https://gateway.umami.is/api/send";
7
+ function buildCapture(config) {
8
+ const origin = config.host ? config.host.replace(/\/api\/?$/, "").replace(/\/+$/, "") : null;
9
+ const scriptUpstream = origin ? `${origin}/script.js` : CLOUD_SCRIPT;
10
+ const sendUpstream = origin ? `${origin}/api/send` : CLOUD_SEND;
11
+ return {
12
+ proxy: { routes: [{
13
+ source: "/script.js",
14
+ upstream: scriptUpstream
15
+ }, {
16
+ source: "/api/send",
17
+ upstream: sendUpstream
18
+ }] },
19
+ snippet: ({ path }) => ({ scripts: [{
20
+ src: `${path}/script.js`,
21
+ defer: true,
22
+ attrs: {
23
+ "data-website-id": config.websiteId,
24
+ "data-host-url": path
25
+ }
26
+ }] }),
27
+ client: { kind: "umami" }
28
+ };
29
+ }
5
30
  const umamiMetrics = new Set([
6
31
  "pageviews",
7
32
  "visitors",
@@ -21,6 +46,8 @@ function umami(config) {
21
46
  maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730,
22
47
  metrics: umamiMetrics,
23
48
  dimensions: umamiDimensions,
49
+ filters: /* @__PURE__ */ new Set(),
50
+ filterOperators: new Set(["eq"]),
24
51
  batchPageReport: true,
25
52
  rateLimit: null,
26
53
  recommendedTtl: {
@@ -41,6 +68,7 @@ function umami(config) {
41
68
  id: "umami",
42
69
  label: "Umami",
43
70
  capabilities,
71
+ capture: buildCapture(config),
44
72
  isConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),
45
73
  async query(q, ctx) {
46
74
  const fetchedAt = q.dateRange.end.toISOString();
@@ -1 +1 @@
1
- {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface UmamiConfig {\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/** API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is e.g. https://site/api. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst CLOUD_BASE = 'https://api.umami.is/v1'\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>(['page'])\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst base = config.host ?? CLOUD_BASE\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\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;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AAG;MACd,QAAQ;MACR,UAAU;KACX;KACA,MAAM,UAA8C,CAAC;KACrD,KAAK,MAAM,KAAK,EAAE,SACjB,IAAI,IAAI,OAAO,KAAA,GACd,QAAQ,KAAK,IAAI;KAGnB,KAAK,KAAK;MAAE,WAAW;MAAI;KAAQ,CAAC;IACrC;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAS;KAAU;IAAE;GAC/D;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAS;IAAU;GAAE;EACtF;CACD;AACD"}
1
+ {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface UmamiConfig {\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is\n\t * e.g. https://site/api. Capture derives the app origin from this (a trailing `/api`\n\t * is stripped), so one `host` value serves both the Stats API and the tracker.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst CLOUD_BASE = 'https://api.umami.is/v1'\nconst CLOUD_SCRIPT = 'https://cloud.umami.is/script.js'\nconst CLOUD_SEND = 'https://gateway.umami.is/api/send'\n\nfunction buildCapture(config: UmamiConfig): CaptureSupport {\n\tconst origin = config.host ? config.host.replace(/\\/api\\/?$/, '').replace(/\\/+$/, '') : null\n\tconst scriptUpstream = origin ? `${origin}/script.js` : CLOUD_SCRIPT\n\tconst sendUpstream = origin ? `${origin}/api/send` : CLOUD_SEND\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: scriptUpstream },\n\t\t\t\t{ source: '/api/send', upstream: sendUpstream },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>(['page'])\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst base = config.host ?? CLOUD_BASE\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tfilters: new Set(),\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\t// NOTE: the cloud header name and the per-URL `path` filter (set in params(), also\n\t// sent to /metrics) match the documented v2 shape but are unvalidated against a live\n\t// instance; confirm both before relying on per-URL provider data in production.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\tconst params = (q: AnalyticsQuery): URLSearchParams => {\n\t\tconst p = new URLSearchParams({\n\t\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\t\tendAt: String(q.dateRange.end.getTime()),\n\t\t})\n\t\tif (q.path) {\n\t\t\tp.set('path', q.path)\n\t\t}\n\t\treturn p\n\t}\n\n\treturn {\n\t\tid: 'umami',\n\t\tlabel: 'Umami',\n\t\tcapabilities,\n\t\tcapture: buildCapture(config),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst headers = authHeaders()\n\t\t\tconst wantsPageBreakdown = (q.dimensions ?? []).includes('page')\n\n\t\t\tif (wantsPageBreakdown) {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('type', 'url')\n\t\t\t\tconst data = await fetchJson<Array<{ x: string; y: number }>>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/metrics?${p.toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst metric: MetricKey = q.metrics.includes('pageviews') ? 'pageviews' : 'visitors'\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { page: row.x },\n\t\t\t\t\tmetrics: { [metric]: row.y } as Partial<Record<MetricKey, number>>,\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst stats = await fetchJson<UmamiStats>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/stats?${params(q).toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios are omitted (not zeroed) when there are no visits, so the\n\t\t\t\t\t// display layer shows a \"no data\" state instead of a misleading 0.\n\t\t\t\t\tbounceRate:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : undefined,\n\t\t\t\t\tavgDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : undefined,\n\t\t\t\t}\n\t\t\t\tconst totals: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\ttotals[m] = all[m]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn totals\n\t\t\t}\n\n\t\t\t// Umami's only time-series endpoint reports pageviews and sessions per interval;\n\t\t\t// visitors/bounceRate/avgDuration have no per-day source, so a trend on those\n\t\t\t// metrics keeps a correct headline (from /stats) but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('unit', 'day')\n\t\t\t\tp.set('timezone', q.timezone ?? 'UTC')\n\t\t\t\tconst fetchSeries = () =>\n\t\t\t\t\tfetchJson<{\n\t\t\t\t\t\tpageviews: Array<{ x: string; y: number }>\n\t\t\t\t\t\tsessions: Array<{ x: string; y: number }>\n\t\t\t\t\t}>(`${base}/websites/${config.websiteId}/pageviews?${p.toString()}`, {\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\t})\n\t\t\t\tconst [series, totals] = await Promise.all([fetchSeries(), fetchTotals()])\n\t\t\t\tconst sessionsByX = new Map(series.sessions.map((s) => [s.x, s.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const pv of series.pageviews) {\n\t\t\t\t\tconst ts = dayIso(pv.x)\n\t\t\t\t\tif (!ts) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst dayMetrics = sessionsByX.get(pv.x) ?? 0\n\t\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\t\tpageviews: pv.y,\n\t\t\t\t\t\tvisits: dayMetrics,\n\t\t\t\t\t\tsessions: dayMetrics,\n\t\t\t\t\t}\n\t\t\t\t\tconst metrics: Partial<Record<MetricKey, number>> = {}\n\t\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\t\tmetrics[m] = all[m]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trows.push({ timestamp: ts, metrics })\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'umami', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AA8BA,MAAM,aAAa;AACnB,MAAM,eAAe;AACrB,MAAM,aAAa;AAEnB,SAAS,aAAa,QAAqC;CAC1D,MAAM,SAAS,OAAO,OAAO,OAAO,KAAK,QAAQ,aAAa,EAAE,EAAE,QAAQ,QAAQ,EAAE,IAAI;CACxF,MAAM,iBAAiB,SAAS,GAAG,OAAO,cAAc;CACxD,MAAM,eAAe,SAAS,GAAG,OAAO,aAAa;CACrD,OAAO;EACN,OAAO,EACN,QAAQ,CACP;GAAE,QAAQ;GAAc,UAAU;EAAe,G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K;IACnB,EAAE,IAAI,YAAY,EAAE,YAAY,KAAK;IACrC,MAAM,oBACL,UAGG,GAAG,KAAK,YAAY,OAAO,UAAU,aAAa,EAAE,SAAS,KAAK;KACpE;KACA,QAAQ,IAAI;KACZ,UAAU;IACX,CAAC;IACF,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC,CAAC;IACzE,MAAM,cAAc,IAAI,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAClE,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,MAAM,OAAO,WAAW;KAClC,MAAM,KAAK,OAAO,GAAG,CAAC;KACtB,IAAI,CAAC,IACJ;KAED,MAAM,aAAa,YAAY,IAAI,GAAG,CAAC,KAAK;KAC5C,MAAM,MAA0C;MAC/C,WAAW,GAAG;MACd,QAAQ;MACR,UAAU;KACX;KACA,MAAM,UAA8C,CAAC;KACrD,KAAK,MAAM,KAAK,EAAE,SACjB,IAAI,IAAI,OAAO,KAAA,GACd,QAAQ,KAAK,IAAI;KAGnB,KAAK,KAAK;MAAE,WAAW;MAAI;KAAQ,CAAC;IACrC;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAS;KAAU;IAAE;GAC/D;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAS;IAAU;GAAE;EACtF;CACD;AACD"}
@@ -0,0 +1,20 @@
1
+ import { TrackerConfig } from "./trackerConfig.js";
2
+ import { Payload } from "payload";
3
+
4
+ //#region src/capture/getTrackerConfig.d.ts
5
+ /**
6
+ * Server-side twin of the tracker endpoint, for a Next app that renders `AnalyticsScripts`
7
+ * itself: pass the incoming request's `headers()` and the host's `scopeResolver` sees the
8
+ * same request it would over HTTP. `host` is lifted onto the request because Payload
9
+ * derives `req.host` from the URL rather than the header, and hostname-derived scoping is
10
+ * the common case.
11
+ *
12
+ * A fresh request object is built on every call: `createLocalReq` mutates the one it is
13
+ * given, so a shared literal would accumulate another caller's locale, user, and loader.
14
+ */
15
+ declare const getTrackerConfig: (payload: Payload, args?: {
16
+ headers?: Headers;
17
+ }) => Promise<TrackerConfig>;
18
+ //#endregion
19
+ export { getTrackerConfig };
20
+ //# sourceMappingURL=getTrackerConfig.d.ts.map
@@ -0,0 +1,31 @@
1
+ import { getRuntime } from "../plugin/runtime.js";
2
+ import { emptyTrackerConfig, resolveTrackerConfig } from "./trackerConfig.js";
3
+ import { createLocalReq } from "payload";
4
+ //#region src/capture/getTrackerConfig.ts
5
+ /**
6
+ * Server-side twin of the tracker endpoint, for a Next app that renders `AnalyticsScripts`
7
+ * itself: pass the incoming request's `headers()` and the host's `scopeResolver` sees the
8
+ * same request it would over HTTP. `host` is lifted onto the request because Payload
9
+ * derives `req.host` from the URL rather than the header, and hostname-derived scoping is
10
+ * the common case.
11
+ *
12
+ * A fresh request object is built on every call: `createLocalReq` mutates the one it is
13
+ * given, so a shared literal would accumulate another caller's locale, user, and loader.
14
+ */
15
+ const getTrackerConfig = async (payload, args) => {
16
+ const headers = args?.headers ?? new Headers();
17
+ const host = headers.get("host");
18
+ const req = await createLocalReq({ req: {
19
+ headers,
20
+ ...host ? { host } : {}
21
+ } }, payload);
22
+ const runtime = getRuntime(payload);
23
+ return runtime ? resolveTrackerConfig({
24
+ runtime,
25
+ req
26
+ }) : emptyTrackerConfig(req);
27
+ };
28
+ //#endregion
29
+ export { getTrackerConfig };
30
+
31
+ //# sourceMappingURL=getTrackerConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getTrackerConfig.js","names":[],"sources":["../../src/capture/getTrackerConfig.ts"],"sourcesContent":["import { createLocalReq, type Payload, type PayloadRequest } from 'payload'\nimport { getRuntime } from '../plugin/runtime'\nimport { emptyTrackerConfig, resolveTrackerConfig, type TrackerConfig } from './trackerConfig'\n\n/**\n * Server-side twin of the tracker endpoint, for a Next app that renders `AnalyticsScripts`\n * itself: pass the incoming request's `headers()` and the host's `scopeResolver` sees the\n * same request it would over HTTP. `host` is lifted onto the request because Payload\n * derives `req.host` from the URL rather than the header, and hostname-derived scoping is\n * the common case.\n *\n * A fresh request object is built on every call: `createLocalReq` mutates the one it is\n * given, so a shared literal would accumulate another caller's locale, user, and loader.\n */\nexport const getTrackerConfig = async (\n\tpayload: Payload,\n\targs?: { headers?: Headers }\n): Promise<TrackerConfig> => {\n\tconst headers = args?.headers ?? new Headers()\n\tconst host = headers.get('host')\n\tconst req = await createLocalReq(\n\t\t{ req: { headers, ...(host ? { host } : {}) } as Partial<PayloadRequest> },\n\t\tpayload\n\t)\n\tconst runtime = getRuntime(payload)\n\treturn runtime ? resolveTrackerConfig({ runtime, req }) : emptyTrackerConfig(req)\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,mBAAmB,OAC/B,SACA,SAC4B;CAC5B,MAAM,UAAU,MAAM,WAAW,IAAI,QAAQ;CAC7C,MAAM,OAAO,QAAQ,IAAI,MAAM;CAC/B,MAAM,MAAM,MAAM,eACjB,EAAE,KAAK;EAAE;EAAS,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;CAAG,EAA6B,GACzE,OACD;CACA,MAAM,UAAU,WAAW,OAAO;CAClC,OAAO,UAAU,qBAAqB;EAAE;EAAS;CAAI,CAAC,IAAI,mBAAmB,GAAG;AACjF"}
@@ -0,0 +1,14 @@
1
+ //#region src/capture/mountPath.ts
2
+ /**
3
+ * One mount path, canonical: a leading slash, no trailing one, `/` for what reduces to
4
+ * the site root. Shared by the Next rewrites helper and the tracker config resolver so a
5
+ * `capture.paths` override and the rewrite it was mounted at cannot disagree over a slash.
6
+ */
7
+ const normalizeMountPath = (path) => {
8
+ const trimmed = (path.startsWith("/") ? path : `/${path}`).replace(/\/+$/, "");
9
+ return trimmed === "" ? "/" : trimmed;
10
+ };
11
+ //#endregion
12
+ export { normalizeMountPath };
13
+
14
+ //# sourceMappingURL=mountPath.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mountPath.js","names":[],"sources":["../../src/capture/mountPath.ts"],"sourcesContent":["/**\n * One mount path, canonical: a leading slash, no trailing one, `/` for what reduces to\n * the site root. Shared by the Next rewrites helper and the tracker config resolver so a\n * `capture.paths` override and the rewrite it was mounted at cannot disagree over a slash.\n */\nexport const normalizeMountPath = (path: string): string => {\n\tconst withLeading = path.startsWith('/') ? path : `/${path}`\n\tconst trimmed = withLeading.replace(/\\/+$/, '')\n\treturn trimmed === '' ? '/' : trimmed\n}\n"],"mappings":";;;;;;AAKA,MAAa,sBAAsB,SAAyB;CAE3D,MAAM,WADc,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,QAC1B,QAAQ,QAAQ,EAAE;CAC9C,OAAO,YAAY,KAAK,MAAM;AAC/B"}
@@ -0,0 +1,123 @@
1
+ import { clientIpFromHeaders } from "../native/ingest/clientIp.js";
2
+ import { PROXY_PATH } from "../plugin/paths.js";
3
+ import { getRuntime } from "../plugin/runtime.js";
4
+ import { buildDownstreamHeaders, buildUpstreamHeaders, matchProxyRoute } from "./proxyRoutes.js";
5
+ import { readCappedBody } from "./requestBody.js";
6
+ import { isCaptureSlot, resolveSlotAdapter } from "./slots.js";
7
+ //#region src/capture/proxyEndpoint.ts
8
+ /** Deadline for the upstream response headers, not for the body download. */
9
+ const DEFAULT_PROXY_TIMEOUT_MS = 1e4;
10
+ /** PostHog batches carrying session-replay data routinely exceed 64 KB. */
11
+ const DEFAULT_PROXY_MAX_BODY_BYTES = 1024 * 1024;
12
+ /** The path pattern the proxy is registered at, one entry per method. */
13
+ const PROXY_ENDPOINT_PATH = `${PROXY_PATH}/:slot/:path*`;
14
+ /**
15
+ * Payload matches an endpoint by exact method, and `@payloadcms/next` only routes these
16
+ * six, so the handler is registered for all of them: the three it serves, and the three
17
+ * it must answer 405 for rather than leaving to Payload's generic 404.
18
+ */
19
+ const PROXY_METHODS = [
20
+ "get",
21
+ "post",
22
+ "options",
23
+ "put",
24
+ "patch",
25
+ "delete"
26
+ ];
27
+ const ALLOWED_METHODS = "GET, POST, OPTIONS";
28
+ const SERVED_METHODS = new Set([
29
+ "GET",
30
+ "POST",
31
+ "OPTIONS"
32
+ ]);
33
+ const empty = (status, headers) => new Response(null, {
34
+ status,
35
+ headers
36
+ });
37
+ /**
38
+ * The request path relative to the slot mount, still percent-encoded: path-to-regexp
39
+ * decodes it per segment, so re-encoding here would turn legal path characters
40
+ * (`,=+:@`) into escapes the vendor never sent.
41
+ */
42
+ const subPath = (req, slot) => {
43
+ const pathname = req.pathname ?? (req.url ? new URL(req.url).pathname : "");
44
+ const mount = `${PROXY_PATH}/${slot}`;
45
+ const start = pathname.indexOf(mount);
46
+ if (start === -1) return "/";
47
+ return pathname.slice(start + mount.length) || "/";
48
+ };
49
+ const proxyLimits = (runtime) => ({
50
+ timeoutMs: runtime.captureProxy?.timeoutMs ?? 1e4,
51
+ maxBodyBytes: runtime.captureProxy?.maxBodyBytes ?? 1048576
52
+ });
53
+ /**
54
+ * Public first-party proxy for a slot's vendor tracker: `${PROXY_PATH}/:slot/:path*`,
55
+ * registered for every method Payload routes.
56
+ *
57
+ * The only URLs it ever fetches are compiled from the slot adapter's own
58
+ * `capture.proxy.routes` templates, so an unfilled slot, an adapter without capture, or
59
+ * a path outside the declared routes is a 404 and nothing leaves the server. Credentials
60
+ * (`cookie`, `authorization`) never go upstream and `set-cookie` never comes back; a
61
+ * body over `capture.proxy.maxBodyBytes` is refused with 413 and one that dies in
62
+ * transit with 400, both before anything is forwarded; upstream failures answer 502
63
+ * without echoing the URL or the error.
64
+ */
65
+ const makeProxyHandler = () => async (req) => {
66
+ const method = (req.method ?? "get").toUpperCase();
67
+ if (!SERVED_METHODS.has(method)) return empty(405, { allow: ALLOWED_METHODS });
68
+ if (method === "OPTIONS") return empty(204, { allow: ALLOWED_METHODS });
69
+ const runtime = getRuntime(req.payload);
70
+ const slot = req.routeParams?.slot;
71
+ if (!runtime || typeof slot !== "string" || !isCaptureSlot(slot)) return empty(404);
72
+ const adapter = await resolveSlotAdapter(runtime, req, slot);
73
+ const descriptor = adapter?.capture?.proxy;
74
+ if (!descriptor || descriptor.routes.length === 0) return empty(404);
75
+ const matched = matchProxyRoute(descriptor.routes, subPath(req, slot), { trailingSlashes: descriptor.trailingSlashes });
76
+ if (!matched) return empty(404);
77
+ const { upstreamUrl } = matched;
78
+ const search = req.search ?? (req.url ? new URL(req.url).search : "");
79
+ if (search && search !== "?") {
80
+ const incoming = search.startsWith("?") ? search.slice(1) : search;
81
+ upstreamUrl.search = upstreamUrl.search ? `${upstreamUrl.search}&${incoming}` : `?${incoming}`;
82
+ }
83
+ const limits = proxyLimits(runtime);
84
+ let body;
85
+ if (method === "POST") {
86
+ const read = await readCappedBody(req, limits.maxBodyBytes);
87
+ if (!read.ok) return empty(read.reason === "too-large" ? 413 : 400);
88
+ body = read.body;
89
+ }
90
+ const controller = new AbortController();
91
+ const timer = setTimeout(() => controller.abort(), limits.timeoutMs);
92
+ try {
93
+ const upstream = await fetch(upstreamUrl, {
94
+ method,
95
+ headers: buildUpstreamHeaders(req.headers, clientIpFromHeaders(req.headers), descriptor.forwardHeaders ?? []),
96
+ body,
97
+ redirect: "manual",
98
+ signal: controller.signal
99
+ });
100
+ return new Response(upstream.body, {
101
+ status: upstream.status,
102
+ headers: buildDownstreamHeaders(upstream.headers)
103
+ });
104
+ } catch (err) {
105
+ req.payload?.logger?.warn(`analytics: capture proxy upstream failed for "${adapter?.id}": ${String(err)}`);
106
+ return empty(502);
107
+ } finally {
108
+ clearTimeout(timer);
109
+ }
110
+ };
111
+ /** The six endpoint entries the plugin registers, all sharing one handler. */
112
+ const proxyEndpoints = () => {
113
+ const handler = makeProxyHandler();
114
+ return PROXY_METHODS.map((method) => ({
115
+ method,
116
+ path: PROXY_ENDPOINT_PATH,
117
+ handler
118
+ }));
119
+ };
120
+ //#endregion
121
+ export { DEFAULT_PROXY_MAX_BODY_BYTES, DEFAULT_PROXY_TIMEOUT_MS, proxyEndpoints };
122
+
123
+ //# sourceMappingURL=proxyEndpoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxyEndpoint.js","names":[],"sources":["../../src/capture/proxyEndpoint.ts"],"sourcesContent":["import type { Endpoint, PayloadHandler, PayloadRequest } from 'payload'\nimport { clientIpFromHeaders } from '../native/ingest/clientIp'\nimport { PROXY_PATH } from '../plugin/paths'\nimport { type AnalyticsRuntime, getRuntime } from '../plugin/runtime'\nimport { buildDownstreamHeaders, buildUpstreamHeaders, matchProxyRoute } from './proxyRoutes'\nimport { readCappedBody } from './requestBody'\nimport { type CaptureSlot, isCaptureSlot, resolveSlotAdapter } from './slots'\n\nexport { PROXY_PATH }\n\n/** Deadline for the upstream response headers, not for the body download. */\nexport const DEFAULT_PROXY_TIMEOUT_MS = 10_000\n\n/** PostHog batches carrying session-replay data routinely exceed 64 KB. */\nexport const DEFAULT_PROXY_MAX_BODY_BYTES = 1024 * 1024\n\n/** The path pattern the proxy is registered at, one entry per method. */\nexport const PROXY_ENDPOINT_PATH = `${PROXY_PATH}/:slot/:path*`\n\n/**\n * Payload matches an endpoint by exact method, and `@payloadcms/next` only routes these\n * six, so the handler is registered for all of them: the three it serves, and the three\n * it must answer 405 for rather than leaving to Payload's generic 404.\n */\nexport const PROXY_METHODS: ReadonlyArray<Endpoint['method']> = [\n\t'get',\n\t'post',\n\t'options',\n\t'put',\n\t'patch',\n\t'delete',\n]\n\nconst ALLOWED_METHODS = 'GET, POST, OPTIONS'\nconst SERVED_METHODS = new Set(['GET', 'POST', 'OPTIONS'])\n\nconst empty = (status: number, headers?: HeadersInit) => new Response(null, { status, headers })\n\n/**\n * The request path relative to the slot mount, still percent-encoded: path-to-regexp\n * decodes it per segment, so re-encoding here would turn legal path characters\n * (`,=+:@`) into escapes the vendor never sent.\n */\nconst subPath = (req: PayloadRequest, slot: CaptureSlot): string => {\n\tconst pathname = req.pathname ?? (req.url ? new URL(req.url).pathname : '')\n\tconst mount = `${PROXY_PATH}/${slot}`\n\tconst start = pathname.indexOf(mount)\n\tif (start === -1) {\n\t\treturn '/'\n\t}\n\treturn pathname.slice(start + mount.length) || '/'\n}\n\nconst proxyLimits = (runtime: AnalyticsRuntime) => ({\n\ttimeoutMs: runtime.captureProxy?.timeoutMs ?? DEFAULT_PROXY_TIMEOUT_MS,\n\tmaxBodyBytes: runtime.captureProxy?.maxBodyBytes ?? DEFAULT_PROXY_MAX_BODY_BYTES,\n})\n\n/**\n * Public first-party proxy for a slot's vendor tracker: `${PROXY_PATH}/:slot/:path*`,\n * registered for every method Payload routes.\n *\n * The only URLs it ever fetches are compiled from the slot adapter's own\n * `capture.proxy.routes` templates, so an unfilled slot, an adapter without capture, or\n * a path outside the declared routes is a 404 and nothing leaves the server. Credentials\n * (`cookie`, `authorization`) never go upstream and `set-cookie` never comes back; a\n * body over `capture.proxy.maxBodyBytes` is refused with 413 and one that dies in\n * transit with 400, both before anything is forwarded; upstream failures answer 502\n * without echoing the URL or the error.\n */\nexport const makeProxyHandler = (): PayloadHandler => async (req) => {\n\tconst method = (req.method ?? 'get').toUpperCase()\n\tif (!SERVED_METHODS.has(method)) {\n\t\treturn empty(405, { allow: ALLOWED_METHODS })\n\t}\n\t// The tracker is same-origin, so a preflight never reaches a real deployment. Answering\n\t// locally beats forwarding one and stripping the CORS headers that made it meaningful.\n\tif (method === 'OPTIONS') {\n\t\treturn empty(204, { allow: ALLOWED_METHODS })\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tconst slot = (req.routeParams as { slot?: unknown } | undefined)?.slot\n\tif (!runtime || typeof slot !== 'string' || !isCaptureSlot(slot)) {\n\t\treturn empty(404)\n\t}\n\tconst adapter = await resolveSlotAdapter(runtime, req, slot)\n\tconst descriptor = adapter?.capture?.proxy\n\tif (!descriptor || descriptor.routes.length === 0) {\n\t\treturn empty(404)\n\t}\n\tconst matched = matchProxyRoute(descriptor.routes, subPath(req, slot), {\n\t\ttrailingSlashes: descriptor.trailingSlashes,\n\t})\n\tif (!matched) {\n\t\treturn empty(404)\n\t}\n\tconst { upstreamUrl } = matched\n\tconst search = req.search ?? (req.url ? new URL(req.url).search : '')\n\tif (search && search !== '?') {\n\t\tconst incoming = search.startsWith('?') ? search.slice(1) : search\n\t\tupstreamUrl.search = upstreamUrl.search ? `${upstreamUrl.search}&${incoming}` : `?${incoming}`\n\t}\n\tconst limits = proxyLimits(runtime)\n\t// Buffered rather than streamed: a duplex request stream fails as a hung upstream\n\t// connection, and the cap has to be enforced before any of it is forwarded anyway.\n\tlet body: ArrayBuffer | undefined\n\tif (method === 'POST') {\n\t\tconst read = await readCappedBody(req, limits.maxBodyBytes)\n\t\tif (!read.ok) {\n\t\t\treturn empty(read.reason === 'too-large' ? 413 : 400)\n\t\t}\n\t\tbody = read.body\n\t}\n\t// The deadline covers time-to-headers only. AbortSignal.timeout would keep running\n\t// against the body stream and truncate a slow but healthy download.\n\tconst controller = new AbortController()\n\tconst timer = setTimeout(() => controller.abort(), limits.timeoutMs)\n\ttry {\n\t\tconst upstream = await fetch(upstreamUrl, {\n\t\t\tmethod,\n\t\t\theaders: buildUpstreamHeaders(\n\t\t\t\treq.headers,\n\t\t\t\tclientIpFromHeaders(req.headers),\n\t\t\t\tdescriptor.forwardHeaders ?? []\n\t\t\t),\n\t\t\tbody,\n\t\t\tredirect: 'manual',\n\t\t\tsignal: controller.signal,\n\t\t})\n\t\treturn new Response(upstream.body, {\n\t\t\tstatus: upstream.status,\n\t\t\theaders: buildDownstreamHeaders(upstream.headers),\n\t\t})\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(\n\t\t\t`analytics: capture proxy upstream failed for \"${adapter?.id}\": ${String(err)}`\n\t\t)\n\t\treturn empty(502)\n\t} finally {\n\t\tclearTimeout(timer)\n\t}\n}\n\n/** The six endpoint entries the plugin registers, all sharing one handler. */\nexport const proxyEndpoints = (): Endpoint[] => {\n\tconst handler = makeProxyHandler()\n\treturn PROXY_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AGA,MAAa,uBAAmC;CAC/C,MAAM,UAAU,iBAAiB;CACjC,OAAO,cAAc,KAAK,YAAY;EAAE;EAAQ,MAAM;EAAqB;CAAQ,EAAE;AACtF"}
@@ -0,0 +1,108 @@
1
+ import { compile, match } from "path-to-regexp";
2
+ //#region src/capture/proxyRoutes.ts
3
+ /** Request headers every vendor proxy forwards upstream. */
4
+ const FORWARDED_REQUEST_HEADERS = [
5
+ "content-type",
6
+ "accept",
7
+ "accept-encoding",
8
+ "accept-language",
9
+ "user-agent",
10
+ "origin",
11
+ "referer",
12
+ "if-none-match",
13
+ "if-modified-since"
14
+ ];
15
+ /**
16
+ * Never forwarded, whatever a descriptor's `forwardHeaders` asks for: credentials
17
+ * the vendor has no business seeing, and the forwarding chain the proxy sets itself.
18
+ */
19
+ const NEVER_FORWARDED_REQUEST_HEADERS = new Set([
20
+ "cookie",
21
+ "authorization",
22
+ "proxy-authorization",
23
+ "host",
24
+ "forwarded",
25
+ "x-forwarded-for",
26
+ "x-forwarded-host",
27
+ "x-forwarded-proto",
28
+ "x-real-ip"
29
+ ]);
30
+ /**
31
+ * The only upstream response headers passed back. `content-encoding` and
32
+ * `content-length` are deliberately absent: fetch decodes the body but leaves both
33
+ * describing the compressed bytes, so forwarding either corrupts the response.
34
+ */
35
+ const FORWARDED_RESPONSE_HEADERS = [
36
+ "content-type",
37
+ "cache-control",
38
+ "etag",
39
+ "last-modified",
40
+ "vary"
41
+ ];
42
+ const isSafeUpstream = (url) => url.protocol === "https:" || url.protocol === "http:";
43
+ const PATH_SAFE_ESCAPES = /%(24|26|2B|2C|3A|3D|40)/gi;
44
+ const encodeSegment = (segment) => encodeURIComponent(segment).replace(PATH_SAFE_ESCAPES, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
45
+ const paramSegments = (value) => Array.isArray(value) ? value.map(String) : typeof value === "string" ? [value] : [];
46
+ /** A dot segment would collapse when assigned to `URL.pathname`, escaping the route prefix. */
47
+ const hasDotSegment = (params) => Object.values(params).flatMap(paramSegments).some((segment) => segment === "." || segment === "..");
48
+ /**
49
+ * First declared route whose `source` matches `path` (percent-encoded, relative to the
50
+ * slot mount), compiled into its absolute upstream URL. Null when no route matches, so
51
+ * the caller answers 404: an upstream URL only ever comes from a descriptor template,
52
+ * never from the request.
53
+ */
54
+ const matchProxyRoute = (routes, path, options = {}) => {
55
+ for (const route of routes) {
56
+ let template;
57
+ try {
58
+ template = new URL(route.upstream);
59
+ } catch {
60
+ continue;
61
+ }
62
+ if (!isSafeUpstream(template)) continue;
63
+ const matched = match(route.source, { decode: decodeURIComponent })(path);
64
+ if (!matched) continue;
65
+ const params = matched.params;
66
+ if (hasDotSegment(params)) return null;
67
+ let compiled;
68
+ try {
69
+ compiled = compile(template.pathname, { encode: encodeSegment })(params);
70
+ } catch {
71
+ continue;
72
+ }
73
+ const keepSlash = options.trailingSlashes === true && path.endsWith("/") && !compiled.endsWith("/");
74
+ const upstreamUrl = new URL(template.href);
75
+ upstreamUrl.pathname = compiled === "" ? "/" : `${compiled}${keepSlash ? "/" : ""}`;
76
+ return { upstreamUrl };
77
+ }
78
+ return null;
79
+ };
80
+ /**
81
+ * The headers the upstream request carries: the allowlist plus a descriptor's own
82
+ * extras, and `X-Forwarded-For` from the resolved client IP so vendor geo stays
83
+ * correct. An absent IP sends no header rather than a fabricated one.
84
+ */
85
+ const buildUpstreamHeaders = (incoming, clientIp, extra = []) => {
86
+ const out = new Headers();
87
+ const names = [...FORWARDED_REQUEST_HEADERS, ...extra.map((name) => name.toLowerCase())];
88
+ for (const name of names) {
89
+ if (NEVER_FORWARDED_REQUEST_HEADERS.has(name)) continue;
90
+ const value = incoming.get(name);
91
+ if (value !== null) out.set(name, value);
92
+ }
93
+ if (clientIp) out.set("x-forwarded-for", clientIp);
94
+ return out;
95
+ };
96
+ /** The headers the client sees: the response allowlist, so `set-cookie` can never pass. */
97
+ const buildDownstreamHeaders = (upstream) => {
98
+ const out = new Headers();
99
+ for (const name of FORWARDED_RESPONSE_HEADERS) {
100
+ const value = upstream.get(name);
101
+ if (value !== null) out.set(name, value);
102
+ }
103
+ return out;
104
+ };
105
+ //#endregion
106
+ export { buildDownstreamHeaders, buildUpstreamHeaders, matchProxyRoute };
107
+
108
+ //# sourceMappingURL=proxyRoutes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxyRoutes.js","names":[],"sources":["../../src/capture/proxyRoutes.ts"],"sourcesContent":["import { compile, match } from 'path-to-regexp'\nimport type { ProxyRoute } from '../core/capture'\n\n/** Request headers every vendor proxy forwards upstream. */\nexport const FORWARDED_REQUEST_HEADERS = [\n\t'content-type',\n\t'accept',\n\t'accept-encoding',\n\t'accept-language',\n\t'user-agent',\n\t'origin',\n\t'referer',\n\t'if-none-match',\n\t'if-modified-since',\n]\n\n/**\n * Never forwarded, whatever a descriptor's `forwardHeaders` asks for: credentials\n * the vendor has no business seeing, and the forwarding chain the proxy sets itself.\n */\nconst NEVER_FORWARDED_REQUEST_HEADERS = new Set([\n\t'cookie',\n\t'authorization',\n\t'proxy-authorization',\n\t'host',\n\t'forwarded',\n\t'x-forwarded-for',\n\t'x-forwarded-host',\n\t'x-forwarded-proto',\n\t'x-real-ip',\n])\n\n/**\n * The only upstream response headers passed back. `content-encoding` and\n * `content-length` are deliberately absent: fetch decodes the body but leaves both\n * describing the compressed bytes, so forwarding either corrupts the response.\n */\nexport const FORWARDED_RESPONSE_HEADERS = [\n\t'content-type',\n\t'cache-control',\n\t'etag',\n\t'last-modified',\n\t'vary',\n]\n\nexport interface ProxyMatch {\n\tupstreamUrl: URL\n}\n\nexport interface MatchProxyRouteOptions {\n\t/** `ProxyDescriptor.trailingSlashes`: keep a request's trailing slash upstream. */\n\ttrailingSlashes?: boolean\n}\n\nconst isSafeUpstream = (url: URL): boolean => url.protocol === 'https:' || url.protocol === 'http:'\n\n// encodeURIComponent escapes every RFC 3986 sub-delim plus ':' and '@', all of which are\n// legal inside a path segment, so a vendor URL would not round-trip byte for byte. Restore\n// exactly those; '/', '?' and '#' stay escaped because they would change the URL's shape,\n// and ';' because some upstreams read it as a matrix-param separator.\nconst PATH_SAFE_ESCAPES = /%(24|26|2B|2C|3A|3D|40)/gi\n\nconst encodeSegment = (segment: string): string =>\n\tencodeURIComponent(segment).replace(PATH_SAFE_ESCAPES, (_, hex: string) =>\n\t\tString.fromCharCode(Number.parseInt(hex, 16))\n\t)\n\nconst paramSegments = (value: unknown): string[] =>\n\tArray.isArray(value) ? value.map(String) : typeof value === 'string' ? [value] : []\n\n/** A dot segment would collapse when assigned to `URL.pathname`, escaping the route prefix. */\nconst hasDotSegment = (params: Record<string, unknown>): boolean =>\n\tObject.values(params)\n\t\t.flatMap(paramSegments)\n\t\t.some((segment) => segment === '.' || segment === '..')\n\n/**\n * First declared route whose `source` matches `path` (percent-encoded, relative to the\n * slot mount), compiled into its absolute upstream URL. Null when no route matches, so\n * the caller answers 404: an upstream URL only ever comes from a descriptor template,\n * never from the request.\n */\nexport const matchProxyRoute = (\n\troutes: ProxyRoute[],\n\tpath: string,\n\toptions: MatchProxyRouteOptions = {}\n): ProxyMatch | null => {\n\tfor (const route of routes) {\n\t\tlet template: URL\n\t\ttry {\n\t\t\ttemplate = new URL(route.upstream)\n\t\t} catch {\n\t\t\tcontinue\n\t\t}\n\t\tif (!isSafeUpstream(template)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst matched = match(route.source, { decode: decodeURIComponent })(path)\n\t\tif (!matched) {\n\t\t\tcontinue\n\t\t}\n\t\tconst params = matched.params as Record<string, unknown>\n\t\tif (hasDotSegment(params)) {\n\t\t\treturn null\n\t\t}\n\t\tlet compiled: string\n\t\ttry {\n\t\t\tcompiled = compile(template.pathname, { encode: encodeSegment })(params)\n\t\t} catch {\n\t\t\t// A template naming a param its source never produces is a broken descriptor,\n\t\t\t// not a request the client can fix: skip it rather than throwing a public 500.\n\t\t\tcontinue\n\t\t}\n\t\t// path-to-regexp drops the trailing slash a wildcard consumed. Only a descriptor\n\t\t// that asks for it gets it back, because only PostHog's capture endpoints need it.\n\t\tconst keepSlash =\n\t\t\toptions.trailingSlashes === true && path.endsWith('/') && !compiled.endsWith('/')\n\t\tconst upstreamUrl = new URL(template.href)\n\t\tupstreamUrl.pathname = compiled === '' ? '/' : `${compiled}${keepSlash ? '/' : ''}`\n\t\treturn { upstreamUrl }\n\t}\n\treturn null\n}\n\n/**\n * The headers the upstream request carries: the allowlist plus a descriptor's own\n * extras, and `X-Forwarded-For` from the resolved client IP so vendor geo stays\n * correct. An absent IP sends no header rather than a fabricated one.\n */\nexport const buildUpstreamHeaders = (\n\tincoming: Headers,\n\tclientIp: string | null,\n\textra: string[] = []\n): Headers => {\n\tconst out = new Headers()\n\tconst names = [...FORWARDED_REQUEST_HEADERS, ...extra.map((name) => name.toLowerCase())]\n\tfor (const name of names) {\n\t\tif (NEVER_FORWARDED_REQUEST_HEADERS.has(name)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst value = incoming.get(name)\n\t\tif (value !== null) {\n\t\t\tout.set(name, value)\n\t\t}\n\t}\n\tif (clientIp) {\n\t\tout.set('x-forwarded-for', clientIp)\n\t}\n\treturn out\n}\n\n/** The headers the client sees: the response allowlist, so `set-cookie` can never pass. */\nexport const buildDownstreamHeaders = (upstream: Headers): Headers => {\n\tconst out = new Headers()\n\tfor (const name of FORWARDED_RESPONSE_HEADERS) {\n\t\tconst value = upstream.get(name)\n\t\tif (value !== null) {\n\t\t\tout.set(name, value)\n\t\t}\n\t}\n\treturn out\n}\n"],"mappings":";;;AAIA,MAAa,4BAA4B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;AAMA,MAAM,kCAAkC,IAAI,IAAI;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;AAOD,MAAa,6BAA6B;CACzC;CACA;CACA;CACA;CACA;AACD;AAWA,MAAM,kBAAkB,QAAsB,IAAI,aAAa,YAAY,IAAI,aAAa;AAM5F,MAAM,oBAAoB;AAE1B,M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C;CACvF,KAAK,MAAM,QAAQ,OAAO;EACzB,IAAI,gCAAgC,IAAI,IAAI,GAC3C;EAED,MAAM,QAAQ,SAAS,IAAI,IAAI;EAC/B,IAAI,UAAU,MACb,IAAI,IAAI,MAAM,KAAK;CAErB;CACA,IAAI,UACH,IAAI,IAAI,mBAAmB,QAAQ;CAEpC,OAAO;AACR;;AAGA,MAAa,0BAA0B,aAA+B;CACrE,MAAM,MAAM,IAAI,QAAQ;CACxB,KAAK,MAAM,QAAQ,4BAA4B;EAC9C,MAAM,QAAQ,SAAS,IAAI,IAAI;EAC/B,IAAI,UAAU,MACb,IAAI,IAAI,MAAM,KAAK;CAErB;CACA,OAAO;AACR"}
@@ -0,0 +1,68 @@
1
+ //#region src/capture/requestBody.ts
2
+ const tooLarge = {
3
+ ok: false,
4
+ reason: "too-large"
5
+ };
6
+ const unreadable = {
7
+ ok: false,
8
+ reason: "unreadable"
9
+ };
10
+ const concat = (chunks, total) => {
11
+ const out = new Uint8Array(total);
12
+ let offset = 0;
13
+ for (const chunk of chunks) {
14
+ out.set(chunk, offset);
15
+ offset += chunk.byteLength;
16
+ }
17
+ return out.buffer;
18
+ };
19
+ /**
20
+ * Buffers a request body, refusing anything over `maxBytes`. A declared `content-length`
21
+ * short-circuits before a byte is read; a chunked body declares no length at all, so the
22
+ * running total is checked per chunk and the read is cancelled the moment it passes the
23
+ * cap. A stream that errors mid-read (a beacon from a tab that is already unloading is
24
+ * routine, not exceptional) resolves as `unreadable` rather than throwing, which would
25
+ * escape the handler into Payload's routeError as a 500.
26
+ */
27
+ const readCappedBody = async (req, maxBytes) => {
28
+ const declared = req.headers.get("content-length");
29
+ if (declared !== null) {
30
+ const length = Number(declared);
31
+ if (Number.isFinite(length) && length > maxBytes) return tooLarge;
32
+ }
33
+ const stream = req.body;
34
+ if (!stream) try {
35
+ const buffered = await req.arrayBuffer?.() ?? /* @__PURE__ */ new ArrayBuffer(0);
36
+ return buffered.byteLength > maxBytes ? tooLarge : {
37
+ ok: true,
38
+ body: buffered
39
+ };
40
+ } catch {
41
+ return unreadable;
42
+ }
43
+ const reader = stream.getReader();
44
+ const chunks = [];
45
+ let total = 0;
46
+ try {
47
+ while (true) {
48
+ const { done, value } = await reader.read();
49
+ if (done) break;
50
+ total += value.byteLength;
51
+ if (total > maxBytes) {
52
+ await reader.cancel();
53
+ return tooLarge;
54
+ }
55
+ chunks.push(value);
56
+ }
57
+ } catch {
58
+ return unreadable;
59
+ }
60
+ return {
61
+ ok: true,
62
+ body: concat(chunks, total)
63
+ };
64
+ };
65
+ //#endregion
66
+ export { readCappedBody };
67
+
68
+ //# sourceMappingURL=requestBody.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestBody.js","names":[],"sources":["../../src/capture/requestBody.ts"],"sourcesContent":["/** The subset of a Request the capped reader needs, so a PayloadRequest satisfies it. */\nexport interface CappedBodySource {\n\theaders: Headers\n\tbody?: ReadableStream<Uint8Array> | null\n\tarrayBuffer?: () => Promise<ArrayBuffer>\n}\n\n/**\n * `too-large` is the caller's 413; `unreadable` is its 400. They are distinct because a\n * body that died in transit is the client's problem to retry, not a limit it exceeded.\n */\nexport type CappedBodyResult =\n\t| { ok: true; body: ArrayBuffer }\n\t| { ok: false; reason: 'too-large' | 'unreadable' }\n\nconst tooLarge = { ok: false, reason: 'too-large' } as const\nconst unreadable = { ok: false, reason: 'unreadable' } as const\n\nconst concat = (chunks: Uint8Array[], total: number): ArrayBuffer => {\n\tconst out = new Uint8Array(total)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tout.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn out.buffer\n}\n\n/**\n * Buffers a request body, refusing anything over `maxBytes`. A declared `content-length`\n * short-circuits before a byte is read; a chunked body declares no length at all, so the\n * running total is checked per chunk and the read is cancelled the moment it passes the\n * cap. A stream that errors mid-read (a beacon from a tab that is already unloading is\n * routine, not exceptional) resolves as `unreadable` rather than throwing, which would\n * escape the handler into Payload's routeError as a 500.\n */\nexport const readCappedBody = async (\n\treq: CappedBodySource,\n\tmaxBytes: number\n): Promise<CappedBodyResult> => {\n\tconst declared = req.headers.get('content-length')\n\tif (declared !== null) {\n\t\tconst length = Number(declared)\n\t\tif (Number.isFinite(length) && length > maxBytes) {\n\t\t\treturn tooLarge\n\t\t}\n\t}\n\tconst stream = req.body\n\tif (!stream) {\n\t\ttry {\n\t\t\tconst buffered = (await req.arrayBuffer?.()) ?? new ArrayBuffer(0)\n\t\t\treturn buffered.byteLength > maxBytes ? tooLarge : { ok: true, body: buffered }\n\t\t} catch {\n\t\t\treturn unreadable\n\t\t}\n\t}\n\tconst reader = stream.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet total = 0\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (done) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttotal += value.byteLength\n\t\t\tif (total > maxBytes) {\n\t\t\t\tawait reader.cancel()\n\t\t\t\treturn tooLarge\n\t\t\t}\n\t\t\tchunks.push(value)\n\t\t}\n\t} catch {\n\t\treturn unreadable\n\t}\n\treturn { ok: true, body: concat(chunks, total) }\n}\n"],"mappings":";AAeA,MAAM,WAAW;CAAE,IAAI;CAAO,QAAQ;AAAY;AAClD,MAAM,aAAa;CAAE,IAAI;CAAO,QAAQ;AAAa;AAErD,MAAM,UAAU,QAAsB,UAA+B;CACpE,MAAM,MAAM,IAAI,WAAW,KAAK;CAChC,IAAI,SAAS;CACb,KAAK,MAAM,SAAS,QAAQ;EAC3B,IAAI,IAAI,OAAO,MAAM;EACrB,UAAU,MAAM;CACjB;CACA,OAAO,IAAI;AACZ;;;;;;;;;AAUA,MAAa,iBAAiB,OAC7B,KACA,aAC+B;CAC/B,MAAM,WAAW,IAAI,QAAQ,IAAI,gBAAgB;CACjD,IAAI,aAAa,MAAM;EACtB,MAAM,SAAS,OAAO,QAAQ;EAC9B,IAAI,OAAO,SAAS,MAAM,KAAK,SAAS,UACvC,OAAO;CAET;CACA,MAAM,SAAS,IAAI;CACnB,IAAI,CAAC,QACJ,IAAI;EACH,MAAM,WAAY,MAAM,IAAI,cAAc,qBAAM,IAAI,YAAY,CAAC;EACjE,OAAO,SAAS,aAAa,WAAW,WAAW;GAAE,IAAI;GAAM,MAAM;EAAS;CAC/E,QAAQ;EACP,OAAO;CACR;CAED,MAAM,SAAS,OAAO,UAAU;CAChC,MAAM,SAAuB,CAAC;CAC9B,IAAI,QAAQ;CACZ,IAAI;EACH,OAAO,MAAM;GACZ,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;GAC1C,IAAI,MACH;GAED,SAAS,MAAM;GACf,IAAI,QAAQ,UAAU;IACrB,MAAM,OAAO,OAAO;IACpB,OAAO;GACR;GACA,OAAO,KAAK,KAAK;EAClB;CACD,QAAQ;EACP,OAAO;CACR;CACA,OAAO;EAAE,IAAI;EAAM,MAAM,OAAO,QAAQ,KAAK;CAAE;AAChD"}
@@ -0,0 +1,8 @@
1
+ import { PayloadRequest } from "payload";
2
+
3
+ //#region src/capture/slots.d.ts
4
+ /** The two capture slots an install can fill: the platform's own and the tenant's. */
5
+ type CaptureSlot = 'global' | 'tenant';
6
+ //#endregion
7
+ export { CaptureSlot };
8
+ //# sourceMappingURL=slots.d.ts.map
@@ -0,0 +1,43 @@
1
+ import { resolveRegistryFor, resolveScopeFor } from "../plugin/runtime.js";
2
+ //#region src/capture/slots.ts
3
+ const CAPTURE_SLOTS = ["global", "tenant"];
4
+ const isCaptureSlot = (value) => CAPTURE_SLOTS.includes(value);
5
+ /**
6
+ * The adapter filling one capture slot for this request, or null when the slot is
7
+ * unfilled. `global` is install-wide, so it resolves out of the config registry only:
8
+ * the `capture.slots.global` override, else the designated `platformAdapter`, else the
9
+ * single config adapter when there is exactly one. `tenant` resolves out of the
10
+ * request's own per-scope registry (which includes that scope's runtime providers) and
11
+ * is null whenever no scope resolves. Any resolution failure degrades to null, so the
12
+ * proxy 404s instead of throwing.
13
+ *
14
+ * A slot configured `false` is null before any of that runs: an explicit disable outranks
15
+ * every default, and nothing happens on its behalf, not even a scope lookup.
16
+ */
17
+ const resolveSlotAdapter = async (runtime, req, slot) => {
18
+ const configured = runtime.captureSlots?.[slot];
19
+ if (configured === false) return null;
20
+ try {
21
+ if (slot === "global") {
22
+ if (configured) return runtime.registry.get(configured);
23
+ if (runtime.platformAdapterId) return runtime.registry.get(runtime.platformAdapterId);
24
+ const all = runtime.registry.all();
25
+ return all.length === 1 ? all[0] : null;
26
+ }
27
+ const scope = await resolveScopeFor(runtime, req);
28
+ if (scope === null) return null;
29
+ const registry = await resolveRegistryFor(runtime, {
30
+ payload: req.payload,
31
+ req,
32
+ scope
33
+ });
34
+ return configured ? registry.get(configured) : registry.default();
35
+ } catch (err) {
36
+ req.payload?.logger?.warn(`analytics: capture slot "${slot}" resolution failed: ${String(err)}`);
37
+ return null;
38
+ }
39
+ };
40
+ //#endregion
41
+ export { CAPTURE_SLOTS, isCaptureSlot, resolveSlotAdapter };
42
+
43
+ //# sourceMappingURL=slots.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slots.js","names":[],"sources":["../../src/capture/slots.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport { type AnalyticsRuntime, resolveRegistryFor, resolveScopeFor } from '../plugin/runtime'\n\n/** The two capture slots an install can fill: the platform's own and the tenant's. */\nexport type CaptureSlot = 'global' | 'tenant'\n\nexport const CAPTURE_SLOTS: readonly CaptureSlot[] = ['global', 'tenant']\n\nexport const isCaptureSlot = (value: string): value is CaptureSlot =>\n\t(CAPTURE_SLOTS as readonly string[]).includes(value)\n\n/**\n * The adapter filling one capture slot for this request, or null when the slot is\n * unfilled. `global` is install-wide, so it resolves out of the config registry only:\n * the `capture.slots.global` override, else the designated `platformAdapter`, else the\n * single config adapter when there is exactly one. `tenant` resolves out of the\n * request's own per-scope registry (which includes that scope's runtime providers) and\n * is null whenever no scope resolves. Any resolution failure degrades to null, so the\n * proxy 404s instead of throwing.\n *\n * A slot configured `false` is null before any of that runs: an explicit disable outranks\n * every default, and nothing happens on its behalf, not even a scope lookup.\n */\nexport const resolveSlotAdapter = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tslot: CaptureSlot\n): Promise<AnalyticsAdapter | null> => {\n\tconst configured = runtime.captureSlots?.[slot]\n\tif (configured === false) {\n\t\treturn null\n\t}\n\ttry {\n\t\tif (slot === 'global') {\n\t\t\tif (configured) {\n\t\t\t\treturn runtime.registry.get(configured)\n\t\t\t}\n\t\t\tif (runtime.platformAdapterId) {\n\t\t\t\treturn runtime.registry.get(runtime.platformAdapterId)\n\t\t\t}\n\t\t\tconst all = runtime.registry.all()\n\t\t\treturn all.length === 1 ? (all[0] as AnalyticsAdapter) : null\n\t\t}\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\tif (scope === null) {\n\t\t\treturn null\n\t\t}\n\t\tconst registry = await resolveRegistryFor(runtime, { payload: req.payload, req, scope })\n\t\treturn configured ? registry.get(configured) : registry.default()\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: capture slot \"${slot}\" resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n"],"mappings":";;AAOA,MAAa,gBAAwC,CAAC,UAAU,QAAQ;AAExE,MAAa,iBAAiB,UAC5B,cAAoC,SAAS,KAAK;;;;;;;;;;;;;AAcpD,MAAa,qBAAqB,OACjC,SACA,KACA,SACsC;CACtC,MAAM,aAAa,QAAQ,eAAe;CAC1C,IAAI,eAAe,OAClB,OAAO;CAER,IAAI;EACH,IAAI,SAAS,UAAU;GACtB,IAAI,YACH,OAAO,QAAQ,SAAS,IAAI,UAAU;GAEvC,IAAI,QAAQ,mBACX,OAAO,QAAQ,SAAS,IAAI,QAAQ,iBAAiB;GAEtD,MAAM,MAAM,QAAQ,SAAS,IAAI;GACjC,OAAO,IAAI,WAAW,IAAK,IAAI,KAA0B;EAC1D;EACA,MAAM,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EAChD,IAAI,UAAU,MACb,OAAO;EAER,MAAM,WAAW,MAAM,mBAAmB,SAAS;GAAE,SAAS,IAAI;GAAS;GAAK;EAAM,CAAC;EACvF,OAAO,aAAa,SAAS,IAAI,UAAU,IAAI,SAAS,QAAQ;CACjE,SAAS,KAAK;EACb,IAAI,SAAS,QAAQ,KAAK,4BAA4B,KAAK,uBAAuB,OAAO,GAAG,GAAG;EAC/F,OAAO;CACR;AACD"}