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

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 (391) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +13 -3
  3. package/dist/adapters/ga4/ga4.js +3 -2
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/http/fetchJson.js +1 -1
  6. package/dist/adapters/plausible/plausible.d.ts +10 -0
  7. package/dist/adapters/plausible/plausible.js +42 -1
  8. package/dist/adapters/plausible/plausible.js.map +1 -1
  9. package/dist/adapters/posthog/posthog.d.ts +10 -1
  10. package/dist/adapters/posthog/posthog.js +47 -0
  11. package/dist/adapters/posthog/posthog.js.map +1 -1
  12. package/dist/adapters/umami/umami.d.ts +5 -1
  13. package/dist/adapters/umami/umami.js +26 -0
  14. package/dist/adapters/umami/umami.js.map +1 -1
  15. package/dist/capture/getTrackerConfig.d.ts +20 -0
  16. package/dist/capture/getTrackerConfig.js +31 -0
  17. package/dist/capture/getTrackerConfig.js.map +1 -0
  18. package/dist/capture/mountPath.js +14 -0
  19. package/dist/capture/mountPath.js.map +1 -0
  20. package/dist/capture/proxyEndpoint.js +123 -0
  21. package/dist/capture/proxyEndpoint.js.map +1 -0
  22. package/dist/capture/proxyRoutes.js +108 -0
  23. package/dist/capture/proxyRoutes.js.map +1 -0
  24. package/dist/capture/requestBody.js +68 -0
  25. package/dist/capture/requestBody.js.map +1 -0
  26. package/dist/capture/slots.d.ts +8 -0
  27. package/dist/capture/slots.js +54 -0
  28. package/dist/capture/slots.js.map +1 -0
  29. package/dist/capture/trackerConfig.d.ts +33 -0
  30. package/dist/capture/trackerConfig.js +95 -0
  31. package/dist/capture/trackerConfig.js.map +1 -0
  32. package/dist/capture/trackerEndpoint.js +35 -0
  33. package/dist/capture/trackerEndpoint.js.map +1 -0
  34. package/dist/charts/BarList.d.ts +15 -1
  35. package/dist/charts/BarList.js +34 -18
  36. package/dist/charts/BarList.js.map +1 -1
  37. package/dist/charts/TrendChart.d.ts +16 -3
  38. package/dist/charts/TrendChart.js +172 -106
  39. package/dist/charts/TrendChart.js.map +1 -1
  40. package/dist/charts/bars.d.ts +2 -0
  41. package/dist/charts/bars.js +2 -1
  42. package/dist/charts/bars.js.map +1 -1
  43. package/dist/charts/bucket.js +10 -1
  44. package/dist/charts/bucket.js.map +1 -1
  45. package/dist/charts/spline.js +2 -2
  46. package/dist/charts/spline.js.map +1 -1
  47. package/dist/charts/styles.js +18 -1
  48. package/dist/charts/styles.js.map +1 -1
  49. package/dist/core/cacheKey.js +13 -1
  50. package/dist/core/cacheKey.js.map +1 -1
  51. package/dist/core/capture.d.ts +49 -0
  52. package/dist/core/contract.d.ts +35 -4
  53. package/dist/core/contract.js +29 -1
  54. package/dist/core/contract.js.map +1 -1
  55. package/dist/core/granularity.js +1 -1
  56. package/dist/core/options.d.ts +148 -4
  57. package/dist/core/options.js +121 -3
  58. package/dist/core/options.js.map +1 -1
  59. package/dist/core/registry.d.ts +1 -0
  60. package/dist/core/scopeList.js +32 -0
  61. package/dist/core/scopeList.js.map +1 -0
  62. package/dist/core/scopedRead.js +45 -28
  63. package/dist/core/scopedRead.js.map +1 -1
  64. package/dist/core/serverEvent.d.ts +42 -0
  65. package/dist/core/serverEvent.js +12 -0
  66. package/dist/core/serverEvent.js.map +1 -0
  67. package/dist/exports/client.d.ts +8 -2
  68. package/dist/exports/client.js +6 -1
  69. package/dist/exports/next.d.ts +2 -1
  70. package/dist/exports/next.js +2 -1
  71. package/dist/exports/react.d.ts +4 -0
  72. package/dist/exports/react.js +5 -0
  73. package/dist/exports/rsc.d.ts +8 -1
  74. package/dist/exports/rsc.js +7 -2
  75. package/dist/exports/tracker.d.ts +18 -0
  76. package/dist/exports/tracker.js +12 -0
  77. package/dist/exports/types.d.ts +14 -3
  78. package/dist/exports/types.js +2 -2
  79. package/dist/fields/AnalyticsPanelClient.js +2 -2
  80. package/dist/fields/AnalyticsPanelField.js +1 -1
  81. package/dist/fields/AnalyticsStatField.js +2 -2
  82. package/dist/fields/config/MetricSelectField.js +2 -2
  83. package/dist/fields/config/MetricSelectField.js.map +1 -1
  84. package/dist/fields/config/SourceSelectField.js +2 -2
  85. package/dist/fields/config/SourceSelectField.js.map +1 -1
  86. package/dist/fields/config/fetchSources.d.ts +5 -1
  87. package/dist/fields/config/narrow.js +2 -0
  88. package/dist/fields/config/narrow.js.map +1 -1
  89. package/dist/fields/readForDocument.d.ts +5 -0
  90. package/dist/fields/readForDocument.js +6 -6
  91. package/dist/fields/readForDocument.js.map +1 -1
  92. package/dist/goals/GoalSelectField.d.ts +7 -0
  93. package/dist/goals/GoalSelectField.js +77 -0
  94. package/dist/goals/GoalSelectField.js.map +1 -0
  95. package/dist/goals/collection.js +250 -0
  96. package/dist/goals/collection.js.map +1 -0
  97. package/dist/goals/currency.js +14 -0
  98. package/dist/goals/currency.js.map +1 -0
  99. package/dist/goals/fetchGoals.d.ts +18 -0
  100. package/dist/goals/fetchGoals.js +29 -0
  101. package/dist/goals/fetchGoals.js.map +1 -0
  102. package/dist/goals/goalField.d.ts +31 -0
  103. package/dist/goals/goalField.js +56 -0
  104. package/dist/goals/goalField.js.map +1 -0
  105. package/dist/goals/goalsEndpoint.d.ts +1 -0
  106. package/dist/goals/goalsEndpoint.js +55 -0
  107. package/dist/goals/goalsEndpoint.js.map +1 -0
  108. package/dist/goals/match.js +64 -0
  109. package/dist/goals/match.js.map +1 -0
  110. package/dist/goals/resolver.d.ts +8 -0
  111. package/dist/goals/resolver.js +147 -0
  112. package/dist/goals/resolver.js.map +1 -0
  113. package/dist/goals/trackGoalAction.d.ts +74 -0
  114. package/dist/goals/trackGoalAction.js +139 -0
  115. package/dist/goals/trackGoalAction.js.map +1 -0
  116. package/dist/goals/types.d.ts +33 -0
  117. package/dist/goals/types.js +7 -0
  118. package/dist/goals/types.js.map +1 -0
  119. package/dist/goals/useAnalyticsGoals.d.ts +20 -0
  120. package/dist/goals/useAnalyticsGoals.js +67 -0
  121. package/dist/goals/useAnalyticsGoals.js.map +1 -0
  122. package/dist/index.d.ts +11 -3
  123. package/dist/index.js +104 -17
  124. package/dist/index.js.map +1 -1
  125. package/dist/native/collections/events.js +21 -1
  126. package/dist/native/collections/events.js.map +1 -1
  127. package/dist/native/collections/rollups.js +24 -0
  128. package/dist/native/collections/rollups.js.map +1 -1
  129. package/dist/native/geo/maxmindResolver.js +2 -4
  130. package/dist/native/geo/maxmindResolver.js.map +1 -1
  131. package/dist/native/ingest/clientIp.js +15 -0
  132. package/dist/native/ingest/clientIp.js.map +1 -0
  133. package/dist/native/ingest/device.js +11 -3
  134. package/dist/native/ingest/device.js.map +1 -1
  135. package/dist/native/ingest/endpoint.d.ts +1 -0
  136. package/dist/native/ingest/endpoint.js +25 -4
  137. package/dist/native/ingest/endpoint.js.map +1 -1
  138. package/dist/native/ingest/flushBatch.js +4 -13
  139. package/dist/native/ingest/flushBatch.js.map +1 -1
  140. package/dist/native/ingest/normalizeEvent.d.ts +20 -0
  141. package/dist/native/ingest/normalizeEvent.js +78 -10
  142. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  143. package/dist/native/ingest/serverTrack.d.ts +20 -0
  144. package/dist/native/ingest/serverTrack.js +99 -0
  145. package/dist/native/ingest/serverTrack.js.map +1 -0
  146. package/dist/native/ingest/validate.js +27 -0
  147. package/dist/native/ingest/validate.js.map +1 -0
  148. package/dist/native/nativeAdapter.d.ts +1 -1
  149. package/dist/native/nativeAdapter.js +38 -11
  150. package/dist/native/nativeAdapter.js.map +1 -1
  151. package/dist/native/query/eventAgg.js +39 -13
  152. package/dist/native/query/eventAgg.js.map +1 -1
  153. package/dist/native/retention/pruneTask.js +1 -1
  154. package/dist/native/rollupAcc.js +12 -1
  155. package/dist/native/rollupAcc.js.map +1 -1
  156. package/dist/native/rollups/bumpRollup.js +5 -1
  157. package/dist/native/rollups/bumpRollup.js.map +1 -1
  158. package/dist/native/rollups/deltas.js +28 -6
  159. package/dist/native/rollups/deltas.js.map +1 -1
  160. package/dist/native/rollups/insertIfNew.js +36 -2
  161. package/dist/native/rollups/insertIfNew.js.map +1 -1
  162. package/dist/next/captureRewrites.d.ts +41 -0
  163. package/dist/next/captureRewrites.js +56 -0
  164. package/dist/next/captureRewrites.js.map +1 -0
  165. package/dist/next/posthogProxyRewrites.d.ts +5 -0
  166. package/dist/next/posthogProxyRewrites.js +16 -21
  167. package/dist/next/posthogProxyRewrites.js.map +1 -1
  168. package/dist/plugin/documentEndpoint.js +28 -10
  169. package/dist/plugin/documentEndpoint.js.map +1 -1
  170. package/dist/plugin/paths.js +15 -1
  171. package/dist/plugin/paths.js.map +1 -1
  172. package/dist/plugin/queryEndpoint.js +113 -0
  173. package/dist/plugin/queryEndpoint.js.map +1 -0
  174. package/dist/plugin/readContextForRequest.js +71 -0
  175. package/dist/plugin/readContextForRequest.js.map +1 -0
  176. package/dist/plugin/realtimeEndpoint.js +6 -3
  177. package/dist/plugin/realtimeEndpoint.js.map +1 -1
  178. package/dist/plugin/runtime.d.ts +1 -0
  179. package/dist/plugin/runtime.js +31 -1
  180. package/dist/plugin/runtime.js.map +1 -1
  181. package/dist/plugin/scopeFieldBoot.js +22 -0
  182. package/dist/plugin/scopeFieldBoot.js.map +1 -0
  183. package/dist/plugin/sourcesEndpoint.js +13 -39
  184. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  185. package/dist/plugin/warmTask.js +0 -0
  186. package/dist/plugin/warmTask.js.map +1 -1
  187. package/dist/providers/collection.js +71 -25
  188. package/dist/providers/collection.js.map +1 -1
  189. package/dist/providers/factory.js +8 -2
  190. package/dist/providers/factory.js.map +1 -1
  191. package/dist/providers/resolver.js.map +1 -1
  192. package/dist/query/dates.js +64 -0
  193. package/dist/query/dates.js.map +1 -0
  194. package/dist/query/errors.d.ts +17 -0
  195. package/dist/query/errors.js +10 -0
  196. package/dist/query/errors.js.map +1 -0
  197. package/dist/query/fetchQuery.d.ts +59 -0
  198. package/dist/query/fetchQuery.js +110 -0
  199. package/dist/query/fetchQuery.js.map +1 -0
  200. package/dist/query/parse.d.ts +22 -0
  201. package/dist/query/parse.js +168 -0
  202. package/dist/query/parse.js.map +1 -0
  203. package/dist/query/response.d.ts +36 -0
  204. package/dist/react/AnalyticsProvider.d.ts +43 -0
  205. package/dist/react/AnalyticsProvider.js +66 -0
  206. package/dist/react/AnalyticsProvider.js.map +1 -0
  207. package/dist/react/TrackerBoot.d.ts +22 -0
  208. package/dist/react/TrackerBoot.js +30 -0
  209. package/dist/react/TrackerBoot.js.map +1 -0
  210. package/dist/react/useAnalytics.d.ts +17 -0
  211. package/dist/react/useAnalytics.js +36 -0
  212. package/dist/react/useAnalytics.js.map +1 -0
  213. package/dist/rsc/AnalyticsScripts.d.ts +30 -0
  214. package/dist/rsc/AnalyticsScripts.js +41 -0
  215. package/dist/rsc/AnalyticsScripts.js.map +1 -0
  216. package/dist/surfacing/cacheStore.d.ts +1 -0
  217. package/dist/surfacing/cacheStore.js +18 -2
  218. package/dist/surfacing/cacheStore.js.map +1 -1
  219. package/dist/surfacing/engine.d.ts +1 -0
  220. package/dist/surfacing/engine.js +44 -4
  221. package/dist/surfacing/engine.js.map +1 -1
  222. package/dist/surfacing/queue.js +22 -6
  223. package/dist/surfacing/queue.js.map +1 -1
  224. package/dist/surfacing/rateLimiter.js +130 -0
  225. package/dist/surfacing/rateLimiter.js.map +1 -0
  226. package/dist/surfacing/retryPolicy.js +15 -0
  227. package/dist/surfacing/retryPolicy.js.map +1 -0
  228. package/dist/sync/syncTask.js +60 -33
  229. package/dist/sync/syncTask.js.map +1 -1
  230. package/dist/testing/memoryAdapter.d.ts +2 -0
  231. package/dist/testing/memoryAdapter.js +10 -0
  232. package/dist/testing/memoryAdapter.js.map +1 -1
  233. package/dist/timeframe/tz.js +17 -6
  234. package/dist/timeframe/tz.js.map +1 -1
  235. package/dist/tracker/autoCapture.d.ts +48 -0
  236. package/dist/tracker/autoCapture.js +129 -0
  237. package/dist/tracker/autoCapture.js.map +1 -0
  238. package/dist/tracker/consent.d.ts +24 -0
  239. package/dist/tracker/consent.js +48 -0
  240. package/dist/tracker/consent.js.map +1 -0
  241. package/dist/tracker/createTracker.d.ts +18 -0
  242. package/dist/tracker/createTracker.js +163 -0
  243. package/dist/tracker/createTracker.js.map +1 -0
  244. package/dist/tracker/initTracker.d.ts +22 -0
  245. package/dist/tracker/initTracker.js +33 -0
  246. package/dist/tracker/initTracker.js.map +1 -0
  247. package/dist/tracker/loadScript.d.ts +14 -0
  248. package/dist/tracker/loadScript.js +41 -0
  249. package/dist/tracker/loadScript.js.map +1 -0
  250. package/dist/tracker/pageTracking.d.ts +17 -0
  251. package/dist/tracker/pageTracking.js +38 -0
  252. package/dist/tracker/pageTracking.js.map +1 -0
  253. package/dist/tracker/registry.d.ts +27 -0
  254. package/dist/tracker/registry.js +73 -0
  255. package/dist/tracker/registry.js.map +1 -0
  256. package/dist/tracker/sinks/native.d.ts +22 -0
  257. package/dist/tracker/sinks/native.js +56 -0
  258. package/dist/tracker/sinks/native.js.map +1 -0
  259. package/dist/tracker/sinks/plausible.d.ts +14 -0
  260. package/dist/tracker/sinks/plausible.js +25 -0
  261. package/dist/tracker/sinks/plausible.js.map +1 -0
  262. package/dist/tracker/sinks/posthog.d.ts +14 -0
  263. package/dist/tracker/sinks/posthog.js +18 -0
  264. package/dist/tracker/sinks/posthog.js.map +1 -0
  265. package/dist/tracker/sinks/umami.d.ts +13 -0
  266. package/dist/tracker/sinks/umami.js +17 -0
  267. package/dist/tracker/sinks/umami.js.map +1 -0
  268. package/dist/tracker/sinks/vendor.d.ts +14 -0
  269. package/dist/tracker/sinks/vendor.js +66 -0
  270. package/dist/tracker/sinks/vendor.js.map +1 -0
  271. package/dist/tracker/transport.js +28 -0
  272. package/dist/tracker/transport.js.map +1 -0
  273. package/dist/tracker/types.d.ts +66 -0
  274. package/dist/translations/ar.js +104 -1
  275. package/dist/translations/ar.js.map +1 -1
  276. package/dist/translations/de.js +104 -1
  277. package/dist/translations/de.js.map +1 -1
  278. package/dist/translations/en.js +104 -1
  279. package/dist/translations/en.js.map +1 -1
  280. package/dist/translations/es.js +104 -1
  281. package/dist/translations/es.js.map +1 -1
  282. package/dist/translations/fr.js +104 -1
  283. package/dist/translations/fr.js.map +1 -1
  284. package/dist/translations/id.js +104 -1
  285. package/dist/translations/id.js.map +1 -1
  286. package/dist/translations/keys.d.ts +103 -0
  287. package/dist/translations/keys.js +104 -1
  288. package/dist/translations/keys.js.map +1 -1
  289. package/dist/translations/ko.js +104 -1
  290. package/dist/translations/ko.js.map +1 -1
  291. package/dist/translations/metricKeys.js +1 -1
  292. package/dist/translations/metricKeys.js.map +1 -1
  293. package/dist/translations/pt.js +104 -1
  294. package/dist/translations/pt.js.map +1 -1
  295. package/dist/translations/ru.js +104 -1
  296. package/dist/translations/ru.js.map +1 -1
  297. package/dist/translations/uk.js +104 -1
  298. package/dist/translations/uk.js.map +1 -1
  299. package/dist/translations/zh.js +104 -1
  300. package/dist/translations/zh.js.map +1 -1
  301. package/dist/view/AnalyticsNavLink.d.ts +19 -0
  302. package/dist/view/AnalyticsNavLink.js +40 -0
  303. package/dist/view/AnalyticsNavLink.js.map +1 -0
  304. package/dist/view/AnalyticsView.d.ts +23 -0
  305. package/dist/view/AnalyticsView.js +45 -0
  306. package/dist/view/AnalyticsView.js.map +1 -0
  307. package/dist/view/AnalyticsViewClient.d.ts +15 -0
  308. package/dist/view/AnalyticsViewClient.js +189 -0
  309. package/dist/view/AnalyticsViewClient.js.map +1 -0
  310. package/dist/view/authRedirect.js +32 -0
  311. package/dist/view/authRedirect.js.map +1 -0
  312. package/dist/view/conversionRate.js +18 -0
  313. package/dist/view/conversionRate.js.map +1 -0
  314. package/dist/view/dayRange.js +68 -0
  315. package/dist/view/dayRange.js.map +1 -0
  316. package/dist/view/gating.d.ts +1 -0
  317. package/dist/view/gating.js +105 -0
  318. package/dist/view/gating.js.map +1 -0
  319. package/dist/view/labels.js +44 -0
  320. package/dist/view/labels.js.map +1 -0
  321. package/dist/view/registerView.js +48 -0
  322. package/dist/view/registerView.js.map +1 -0
  323. package/dist/view/sections/Breakdowns.js +157 -0
  324. package/dist/view/sections/Breakdowns.js.map +1 -0
  325. package/dist/view/sections/EmptyStates.js +92 -0
  326. package/dist/view/sections/EmptyStates.js.map +1 -0
  327. package/dist/view/sections/FilterChips.js +41 -0
  328. package/dist/view/sections/FilterChips.js.map +1 -0
  329. package/dist/view/sections/GoalsPanel.js +81 -0
  330. package/dist/view/sections/GoalsPanel.js.map +1 -0
  331. package/dist/view/sections/OverviewCards.js +65 -0
  332. package/dist/view/sections/OverviewCards.js.map +1 -0
  333. package/dist/view/sections/RealtimeStrip.js +77 -0
  334. package/dist/view/sections/RealtimeStrip.js.map +1 -0
  335. package/dist/view/sections/Toolbar.js +179 -0
  336. package/dist/view/sections/Toolbar.js.map +1 -0
  337. package/dist/view/sections/Trend.js +119 -0
  338. package/dist/view/sections/Trend.js.map +1 -0
  339. package/dist/view/sections/styles.js +74 -0
  340. package/dist/view/sections/styles.js.map +1 -0
  341. package/dist/view/state.js +206 -0
  342. package/dist/view/state.js.map +1 -0
  343. package/dist/view/useViewQueries.js +150 -0
  344. package/dist/view/useViewQueries.js.map +1 -0
  345. package/dist/view/viewProps.d.ts +40 -0
  346. package/dist/view/viewProps.js +90 -0
  347. package/dist/view/viewProps.js.map +1 -0
  348. package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
  349. package/dist/widgets/AnalyticsBreakdownWidget.js +22 -4
  350. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  351. package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
  352. package/dist/widgets/AnalyticsGoalsWidget.js +188 -0
  353. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
  354. package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
  355. package/dist/widgets/AnalyticsMetricWidget.js +35 -12
  356. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  357. package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
  358. package/dist/widgets/AnalyticsRealtimeWidget.js +42 -22
  359. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  360. package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
  361. package/dist/widgets/AnalyticsTrendWidget.js +51 -15
  362. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  363. package/dist/widgets/WidgetViewLink.js +17 -0
  364. package/dist/widgets/WidgetViewLink.js.map +1 -0
  365. package/dist/widgets/breakdownTypes.js +32 -0
  366. package/dist/widgets/breakdownTypes.js.map +1 -1
  367. package/dist/widgets/cardChrome.js +31 -7
  368. package/dist/widgets/cardChrome.js.map +1 -1
  369. package/dist/widgets/range.js +43 -12
  370. package/dist/widgets/range.js.map +1 -1
  371. package/dist/widgets/readForWidget.d.ts +12 -0
  372. package/dist/widgets/readForWidget.js +30 -19
  373. package/dist/widgets/readForWidget.js.map +1 -1
  374. package/dist/widgets/readForWidgetBreakdown.d.ts +15 -0
  375. package/dist/widgets/readForWidgetBreakdown.js +32 -20
  376. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  377. package/dist/widgets/readForWidgetGoals.d.ts +57 -0
  378. package/dist/widgets/readForWidgetGoals.js +126 -0
  379. package/dist/widgets/readForWidgetGoals.js.map +1 -0
  380. package/dist/widgets/readForWidgetRealtime.js +1 -1
  381. package/dist/widgets/readForWidgetSeries.d.ts +13 -0
  382. package/dist/widgets/readForWidgetSeries.js +56 -28
  383. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  384. package/dist/widgets/registerWidgets.js +58 -9
  385. package/dist/widgets/registerWidgets.js.map +1 -1
  386. package/dist/widgets/types.js +16 -2
  387. package/dist/widgets/types.js.map +1 -1
  388. package/dist/widgets/viewLink.d.ts +22 -0
  389. package/dist/widgets/viewLink.js +83 -0
  390. package/dist/widgets/viewLink.js.map +1 -0
  391. package/package.json +25 -5
@@ -0,0 +1,77 @@
1
+ "use client";
2
+ import { keys } from "../translations/keys.js";
3
+ import { useTranslation as useTranslation$1 } from "../translations/useTranslation.js";
4
+ import { useAnalyticsGoals } from "./useAnalyticsGoals.js";
5
+ import { useMemo } from "react";
6
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
+ import { FieldDescription, SelectInput, useConfig, useField, withCondition } from "@payloadcms/ui";
8
+ import { mergeFieldStyles } from "@payloadcms/ui/shared";
9
+ //#region src/goals/GoalSelectField.tsx
10
+ /** Admin placeholders are a plain string or a locale map; SelectInput wants one string. */
11
+ const resolvePlaceholder = (placeholder, locale) => typeof placeholder === "string" ? placeholder : placeholder?.[locale] ?? placeholder?.en;
12
+ /**
13
+ * Goal picker for a {@link goalField}: lists the config goals merged with the goals
14
+ * collection for the caller's scope and stores the picked goal's slug. While the fetch is
15
+ * in flight the picker renders with no options rather than a notice, so a slow answer
16
+ * never reads as "this install has no goals". Once it settles, an empty scope and a failed
17
+ * fetch each say so below the input, next to the field's own description rather than in
18
+ * place of it, and the picker stays editable either way so a stored slug can still be
19
+ * cleared.
20
+ */
21
+ const GoalSelectFieldComponent = (props) => {
22
+ const { field, path: pathFromProps, readOnly } = props;
23
+ const { i18n, t } = useTranslation$1();
24
+ const { collection, error, goals } = useAnalyticsGoals();
25
+ const { customComponents: { AfterInput, BeforeInput, Description, Error: ErrorComponent, Label } = {}, disabled, path, setValue, showError, value } = useField({ potentiallyStalePath: pathFromProps });
26
+ const { config: { routes: { admin: adminRoute } } } = useConfig();
27
+ const options = useMemo(() => (goals ?? []).map((goal) => ({
28
+ label: goal.name,
29
+ value: goal.slug
30
+ })), [goals]);
31
+ const style = useMemo(() => mergeFieldStyles(field), [field]);
32
+ const empty = goals !== null && goals.length === 0;
33
+ const manageHref = collection ? `${adminRoute}/collections/${collection.slug}` : null;
34
+ const notice = empty ? /* @__PURE__ */ jsxs("div", {
35
+ className: "field-description",
36
+ children: [t(keys.fieldGoalEmpty), manageHref ? /* @__PURE__ */ jsxs(Fragment, { children: [" ", /* @__PURE__ */ jsx("a", {
37
+ href: manageHref,
38
+ children: t(keys.fieldGoalManage)
39
+ })] }) : null]
40
+ }) : error ? /* @__PURE__ */ jsx("div", {
41
+ className: "field-description",
42
+ children: t(keys.fieldGoalError)
43
+ }) : null;
44
+ return /* @__PURE__ */ jsx(SelectInput, {
45
+ AfterInput,
46
+ BeforeInput,
47
+ className: field.admin?.className,
48
+ Description: notice ? /* @__PURE__ */ jsxs(Fragment, { children: [Description ?? /* @__PURE__ */ jsx(FieldDescription, {
49
+ description: field.admin?.description,
50
+ path
51
+ }), notice] }) : Description,
52
+ description: field.admin?.description,
53
+ Error: ErrorComponent,
54
+ isClearable: !field.required,
55
+ Label,
56
+ label: field.label,
57
+ localized: field.localized,
58
+ name: field.name,
59
+ onChange: (selected) => {
60
+ const option = Array.isArray(selected) ? selected[0] : selected;
61
+ setValue(option?.value ? String(option.value) : null);
62
+ },
63
+ options,
64
+ path,
65
+ placeholder: resolvePlaceholder(field.admin?.placeholder, i18n.language),
66
+ readOnly: readOnly || disabled || field.admin?.readOnly,
67
+ required: field.required,
68
+ showError,
69
+ style,
70
+ value
71
+ });
72
+ };
73
+ const GoalSelectField = withCondition(GoalSelectFieldComponent);
74
+ //#endregion
75
+ export { GoalSelectField };
76
+
77
+ //# sourceMappingURL=GoalSelectField.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GoalSelectField.js","names":["useTranslation"],"sources":["../../src/goals/GoalSelectField.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tFieldDescription,\n\ttype ReactSelectOption,\n\tSelectInput,\n\tuseConfig,\n\tuseField,\n\twithCondition,\n} from '@payloadcms/ui'\nimport { mergeFieldStyles } from '@payloadcms/ui/shared'\nimport type { TextFieldClientProps } from 'payload'\nimport { useMemo } from 'react'\nimport { keys } from '../translations/keys'\nimport { useTranslation } from '../translations/useTranslation'\nimport { useAnalyticsGoals } from './useAnalyticsGoals'\n\n/** Admin placeholders are a plain string or a locale map; SelectInput wants one string. */\nconst resolvePlaceholder = (\n\tplaceholder: Record<string, string> | string | undefined,\n\tlocale: string\n): string | undefined =>\n\ttypeof placeholder === 'string' ? placeholder : (placeholder?.[locale] ?? placeholder?.en)\n\n/**\n * Goal picker for a {@link goalField}: lists the config goals merged with the goals\n * collection for the caller's scope and stores the picked goal's slug. While the fetch is\n * in flight the picker renders with no options rather than a notice, so a slow answer\n * never reads as \"this install has no goals\". Once it settles, an empty scope and a failed\n * fetch each say so below the input, next to the field's own description rather than in\n * place of it, and the picker stays editable either way so a stored slug can still be\n * cleared.\n */\nconst GoalSelectFieldComponent = (props: TextFieldClientProps) => {\n\tconst { field, path: pathFromProps, readOnly } = props\n\tconst { i18n, t } = useTranslation()\n\tconst { collection, error, goals } = useAnalyticsGoals()\n\tconst {\n\t\tcustomComponents: { AfterInput, BeforeInput, Description, Error: ErrorComponent, Label } = {},\n\t\tdisabled,\n\t\tpath,\n\t\tsetValue,\n\t\tshowError,\n\t\tvalue,\n\t} = useField<string>({ potentiallyStalePath: pathFromProps })\n\tconst {\n\t\tconfig: {\n\t\t\troutes: { admin: adminRoute },\n\t\t},\n\t} = useConfig()\n\n\tconst options = useMemo(\n\t\t() => (goals ?? []).map((goal) => ({ label: goal.name, value: goal.slug })),\n\t\t[goals]\n\t)\n\tconst style = useMemo(() => mergeFieldStyles(field), [field])\n\n\tconst empty = goals !== null && goals.length === 0\n\tconst manageHref = collection ? `${adminRoute}/collections/${collection.slug}` : null\n\tconst notice = empty ? (\n\t\t<div className=\"field-description\">\n\t\t\t{t(keys.fieldGoalEmpty)}\n\t\t\t{manageHref ? (\n\t\t\t\t<>\n\t\t\t\t\t{' '}\n\t\t\t\t\t<a href={manageHref}>{t(keys.fieldGoalManage)}</a>\n\t\t\t\t</>\n\t\t\t) : null}\n\t\t</div>\n\t) : error ? (\n\t\t<div className=\"field-description\">{t(keys.fieldGoalError)}</div>\n\t) : null\n\n\treturn (\n\t\t<SelectInput\n\t\t\tAfterInput={AfterInput}\n\t\t\tBeforeInput={BeforeInput}\n\t\t\tclassName={field.admin?.className}\n\t\t\tDescription={\n\t\t\t\tnotice ? (\n\t\t\t\t\t<>\n\t\t\t\t\t\t{Description ?? <FieldDescription description={field.admin?.description} path={path} />}\n\t\t\t\t\t\t{notice}\n\t\t\t\t\t</>\n\t\t\t\t) : (\n\t\t\t\t\tDescription\n\t\t\t\t)\n\t\t\t}\n\t\t\tdescription={field.admin?.description}\n\t\t\tError={ErrorComponent}\n\t\t\tisClearable={!field.required}\n\t\t\tLabel={Label}\n\t\t\tlabel={field.label}\n\t\t\tlocalized={field.localized}\n\t\t\tname={field.name}\n\t\t\tonChange={(selected: ReactSelectOption | ReactSelectOption[]) => {\n\t\t\t\tconst option = Array.isArray(selected) ? selected[0] : selected\n\t\t\t\tsetValue(option?.value ? String(option.value) : null)\n\t\t\t}}\n\t\t\toptions={options}\n\t\t\tpath={path}\n\t\t\tplaceholder={resolvePlaceholder(field.admin?.placeholder, i18n.language)}\n\t\t\treadOnly={readOnly || disabled || field.admin?.readOnly}\n\t\t\trequired={field.required}\n\t\t\tshowError={showError}\n\t\t\tstyle={style}\n\t\t\tvalue={value}\n\t\t/>\n\t)\n}\n\nexport const GoalSelectField = withCondition(GoalSelectFieldComponent)\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,sBACL,aACA,WAEA,OAAO,gBAAgB,WAAW,cAAe,cAAc,WAAW,aAAa;;;;;;;;;;AAWxF,MAAM,4BAA4B,UAAgC;CACjE,MAAM,EAAE,OAAO,MAAM,eAAe,aAAa;CACjD,MAAM,EAAE,MAAM,MAAMA,iBAAe;CACnC,MAAM,EAAE,YAAY,OAAO,UAAU,kBAAkB;CACvD,MAAM,EACL,kBAAkB,EAAE,YAAY,aAAa,aAAa,OAAO,gBAAgB,UAAU,CAAC,GAC5F,UACA,MACA,UACA,WACA,UACG,SAAiB,EAAE,sBAAsB,cAAc,CAAC;CAC5D,MAAM,EACL,QAAQ,EACP,QAAQ,EAAE,OAAO,mBAEf,UAAU;CAEd,MA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import { providerCreateAccess, providerRowAccess } from "../providers/access.js";
2
+ import { stampScope } from "../providers/stampScope.js";
3
+ import { keys } from "../translations/keys.js";
4
+ import { asTranslate, labelForKey } from "../translations/server.js";
5
+ import { validateCurrency } from "./currency.js";
6
+ import { GOAL_SLUG_PATTERN } from "./types.js";
7
+ import { goalScopeWhere } from "./resolver.js";
8
+ import { ValidationError } from "payload";
9
+ //#region src/goals/collection.ts
10
+ const GOALS_SLUG = "analytics-goals";
11
+ const validateSlug = (value, { req }) => typeof value === "string" && GOAL_SLUG_PATTERN.test(value) ? true : asTranslate(req.t)(keys.goalErrorSlug);
12
+ const asScope = (value) => value === null || value === void 0 || value === "" ? null : String(value);
13
+ /**
14
+ * The scope the stamp will land the write in, resolved with stampScope's precedence. Only a
15
+ * platform admin's declared scope is honoured: taking an ordinary tenant's body scope on
16
+ * trust would turn "slug taken" into an oracle for what another tenant owns, since the stamp
17
+ * refuses the write either way.
18
+ */
19
+ const writeScope = async (args, write) => {
20
+ const { data, originalDoc, req } = write;
21
+ try {
22
+ if (await args.platformRead({ req })) return asScope(data?.[args.scopeField]) ?? asScope(originalDoc?.[args.scopeField]);
23
+ return asScope(await args.resolveScope(req));
24
+ } catch {
25
+ return null;
26
+ }
27
+ };
28
+ /**
29
+ * Slugs stay editable, so uniqueness is checked on every write: the same slug may exist once
30
+ * per scope, and the tracker and the rollups key on it. The compound index backs this up
31
+ * where it can, but it cannot cover install-wide rows on Postgres or a host-owned scope field.
32
+ */
33
+ const uniqueSlug = (args) => {
34
+ return async ({ data, originalDoc, req }) => {
35
+ const slug = data?.slug;
36
+ if (typeof slug !== "string" || slug === "") return data;
37
+ const where = [{ slug: { equals: slug } }];
38
+ if (args.scoped) where.push(goalScopeWhere(args.scopeField, await writeScope(args, {
39
+ data,
40
+ originalDoc,
41
+ req
42
+ })));
43
+ const id = originalDoc?.id;
44
+ if (id !== void 0 && id !== null) where.push({ id: { not_equals: id } });
45
+ const { docs } = await req.payload.find({
46
+ collection: args.slug,
47
+ where: { and: where },
48
+ limit: 1,
49
+ pagination: false,
50
+ depth: 0,
51
+ overrideAccess: true,
52
+ req
53
+ });
54
+ if (docs.length > 0) throw new ValidationError({
55
+ collection: args.slug,
56
+ errors: [{
57
+ label: labelForKey(keys.goalFieldSlug),
58
+ message: asTranslate(req.t)(keys.goalErrorSlugTaken),
59
+ path: "slug"
60
+ }]
61
+ });
62
+ return data;
63
+ };
64
+ };
65
+ /**
66
+ * Database-level backstop for the hook, and only where the plugin owns the scope field: a
67
+ * host-owned one (a tenant plugin's relationship) is not ours to index. Postgres treats a
68
+ * NULL scope as distinct from every other, so install-wide rows stay hook-guarded.
69
+ */
70
+ const uniqueSlugIndex = (args) => {
71
+ if (!args.scoped) return {
72
+ fields: ["slug"],
73
+ unique: true
74
+ };
75
+ return args.scopeField === "scope" ? {
76
+ fields: ["slug", "scope"],
77
+ unique: true
78
+ } : void 0;
79
+ };
80
+ /**
81
+ * The plugin's own scope field, and only when `scopeField` still names it: a host-owned
82
+ * field (a tenant plugin's relationship) is the host's to register, and shadowing it with a
83
+ * hidden text field of another name would store the scope twice.
84
+ */
85
+ const scopeField = (args) => args.scopeField === "scope" ? [{
86
+ name: "scope",
87
+ type: "text",
88
+ index: true,
89
+ label: labelForKey(keys.providerFieldScope),
90
+ admin: { hidden: true }
91
+ }] : [];
92
+ const matchField = () => ({
93
+ name: "match",
94
+ type: "group",
95
+ label: labelForKey(keys.goalFieldMatch),
96
+ fields: [
97
+ {
98
+ name: "kind",
99
+ type: "select",
100
+ required: true,
101
+ defaultValue: "goal",
102
+ label: labelForKey(keys.goalFieldMatchKind),
103
+ options: [
104
+ {
105
+ label: labelForKey(keys.goalKindGoal),
106
+ value: "goal"
107
+ },
108
+ {
109
+ label: labelForKey(keys.goalKindEvent),
110
+ value: "event"
111
+ },
112
+ {
113
+ label: labelForKey(keys.goalKindPath),
114
+ value: "path"
115
+ }
116
+ ]
117
+ },
118
+ {
119
+ name: "name",
120
+ type: "text",
121
+ label: labelForKey(keys.goalFieldMatchEventName),
122
+ admin: { condition: (_data, siblingData) => siblingData?.kind === "event" }
123
+ },
124
+ {
125
+ name: "pattern",
126
+ type: "text",
127
+ label: labelForKey(keys.goalFieldMatchPathPattern),
128
+ admin: {
129
+ condition: (_data, siblingData) => siblingData?.kind === "path",
130
+ description: labelForKey(keys.goalFieldMatchPathPatternHelp)
131
+ }
132
+ }
133
+ ]
134
+ });
135
+ const valueField = () => ({
136
+ name: "value",
137
+ type: "group",
138
+ label: labelForKey(keys.goalFieldValue),
139
+ fields: [{
140
+ type: "row",
141
+ fields: [{
142
+ name: "fixed",
143
+ type: "number",
144
+ min: 0,
145
+ label: labelForKey(keys.goalFieldValueFixed),
146
+ admin: { width: "50%" }
147
+ }, {
148
+ name: "prop",
149
+ type: "text",
150
+ label: labelForKey(keys.goalFieldValueProp),
151
+ admin: {
152
+ width: "50%",
153
+ description: labelForKey(keys.goalFieldValuePropHelp)
154
+ }
155
+ }]
156
+ }]
157
+ });
158
+ /**
159
+ * The editor-managed goals collection: one document per goal (and per scope in scoped
160
+ * installs), merged over the config goals by the resolver. Admin-only by default; `access`
161
+ * entries override individual operations and `overrides` reshapes the whole config last,
162
+ * so slugs, labels, fields, and access all stay overridable.
163
+ */
164
+ const buildGoalsCollection = (args) => {
165
+ const unique = uniqueSlugIndex(args);
166
+ const collection = {
167
+ slug: args.slug,
168
+ ...unique ? { indexes: [unique] } : {},
169
+ labels: {
170
+ singular: labelForKey(keys.goalsCollectionSingular),
171
+ plural: labelForKey(keys.goalsCollectionPlural)
172
+ },
173
+ disableDuplicate: true,
174
+ admin: {
175
+ useAsTitle: "name",
176
+ defaultColumns: [
177
+ "name",
178
+ "slug",
179
+ "match.kind",
180
+ "enabled"
181
+ ],
182
+ group: "Analytics"
183
+ },
184
+ access: {
185
+ read: providerRowAccess(args),
186
+ create: providerCreateAccess(args),
187
+ update: providerRowAccess(args),
188
+ delete: providerRowAccess(args),
189
+ ...args.access
190
+ },
191
+ hooks: {
192
+ beforeValidate: [uniqueSlug(args)],
193
+ beforeChange: [stampScope(args)],
194
+ afterChange: [({ doc }) => {
195
+ args.onChange();
196
+ return doc;
197
+ }],
198
+ afterDelete: [({ doc }) => {
199
+ args.onChange();
200
+ return doc;
201
+ }]
202
+ },
203
+ fields: [
204
+ {
205
+ name: "name",
206
+ type: "text",
207
+ required: true,
208
+ label: labelForKey(keys.goalFieldName)
209
+ },
210
+ {
211
+ type: "row",
212
+ fields: [{
213
+ name: "slug",
214
+ type: "text",
215
+ required: true,
216
+ index: unique === void 0,
217
+ label: labelForKey(keys.goalFieldSlug),
218
+ validate: validateSlug,
219
+ admin: {
220
+ width: "50%",
221
+ description: labelForKey(keys.goalFieldSlugHelp)
222
+ }
223
+ }, {
224
+ name: "enabled",
225
+ type: "checkbox",
226
+ defaultValue: true,
227
+ label: labelForKey(keys.goalFieldEnabled),
228
+ admin: {
229
+ width: "50%",
230
+ style: { alignSelf: "flex-end" }
231
+ }
232
+ }]
233
+ },
234
+ matchField(),
235
+ valueField(),
236
+ {
237
+ name: "currency",
238
+ type: "text",
239
+ label: labelForKey(keys.goalFieldCurrency),
240
+ validate: validateCurrency
241
+ },
242
+ ...scopeField(args)
243
+ ]
244
+ };
245
+ return args.overrides ? args.overrides(collection) : collection;
246
+ };
247
+ //#endregion
248
+ export { GOALS_SLUG, buildGoalsCollection };
249
+
250
+ //# sourceMappingURL=collection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collection.js","names":[],"sources":["../../src/goals/collection.ts"],"sourcesContent":["import type {\n\tCollectionBeforeValidateHook,\n\tCollectionConfig,\n\tCompoundIndex,\n\tField,\n\tPayloadRequest,\n\tTextFieldSingleValidation,\n\tWhere,\n} from 'payload'\nimport { ValidationError } from 'payload'\nimport type { ProviderAccessArgs } from '../providers/access'\nimport { providerCreateAccess, providerRowAccess } from '../providers/access'\nimport { stampScope } from '../providers/stampScope'\nimport { keys } from '../translations/keys'\nimport { asTranslate, labelForKey } from '../translations/server'\nimport { validateCurrency } from './currency'\nimport { goalScopeWhere } from './resolver'\nimport { GOAL_SLUG_PATTERN } from './types'\n\nexport const GOALS_SLUG = 'analytics-goals'\n\nexport interface BuildGoalsCollectionArgs extends ProviderAccessArgs {\n\tslug: string\n\taccess?: Partial<CollectionConfig['access']>\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t/** Called after any change or delete so the merged resolver drops its cached goals. */\n\tonChange: () => void\n}\n\nconst validateSlug: TextFieldSingleValidation = (value, { req }) =>\n\ttypeof value === 'string' && GOAL_SLUG_PATTERN.test(value)\n\t\t? true\n\t\t: asTranslate(req.t)(keys.goalErrorSlug)\n\nconst asScope = (value: unknown): string | null =>\n\tvalue === null || value === undefined || value === '' ? null : String(value)\n\n/**\n * The scope the stamp will land the write in, resolved with stampScope's precedence. Only a\n * platform admin's declared scope is honoured: taking an ordinary tenant's body scope on\n * trust would turn \"slug taken\" into an oracle for what another tenant owns, since the stamp\n * refuses the write either way.\n */\nconst writeScope = async (\n\targs: BuildGoalsCollectionArgs,\n\twrite: {\n\t\tdata?: Record<string, unknown>\n\t\toriginalDoc?: Record<string, unknown>\n\t\treq: PayloadRequest\n\t}\n): Promise<string | null> => {\n\tconst { data, originalDoc, req } = write\n\ttry {\n\t\tif (await args.platformRead({ req })) {\n\t\t\t// No declared scope means an install-wide goal, not one in whatever scope the\n\t\t\t// admin's own request happens to resolve to.\n\t\t\treturn asScope(data?.[args.scopeField]) ?? asScope(originalDoc?.[args.scopeField])\n\t\t}\n\t\treturn asScope(await args.resolveScope(req))\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/**\n * Slugs stay editable, so uniqueness is checked on every write: the same slug may exist once\n * per scope, and the tracker and the rollups key on it. The compound index backs this up\n * where it can, but it cannot cover install-wide rows on Postgres or a host-owned scope field.\n */\nconst uniqueSlug = (args: BuildGoalsCollectionArgs): CollectionBeforeValidateHook => {\n\treturn async ({ data, originalDoc, req }) => {\n\t\tconst slug = data?.slug\n\t\tif (typeof slug !== 'string' || slug === '') {\n\t\t\treturn data\n\t\t}\n\t\tconst where: Where[] = [{ slug: { equals: slug } }]\n\t\tif (args.scoped) {\n\t\t\twhere.push(\n\t\t\t\tgoalScopeWhere(args.scopeField, await writeScope(args, { data, originalDoc, req }))\n\t\t\t)\n\t\t}\n\t\tconst id = originalDoc?.id\n\t\tif (id !== undefined && id !== null) {\n\t\t\twhere.push({ id: { not_equals: id } })\n\t\t}\n\t\t// pagination:false is load-bearing: a paginated read fires its count and its find in\n\t\t// parallel on one Mongo session, which the write's open transaction refuses.\n\t\tconst { docs } = await req.payload.find({\n\t\t\tcollection: args.slug as never,\n\t\t\twhere: { and: where },\n\t\t\tlimit: 1,\n\t\t\tpagination: false,\n\t\t\tdepth: 0,\n\t\t\toverrideAccess: true,\n\t\t\treq,\n\t\t})\n\t\tif (docs.length > 0) {\n\t\t\tthrow new ValidationError({\n\t\t\t\tcollection: args.slug,\n\t\t\t\terrors: [\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel: labelForKey(keys.goalFieldSlug),\n\t\t\t\t\t\tmessage: asTranslate(req.t)(keys.goalErrorSlugTaken),\n\t\t\t\t\t\tpath: 'slug',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\t\treturn data\n\t}\n}\n\n/**\n * Database-level backstop for the hook, and only where the plugin owns the scope field: a\n * host-owned one (a tenant plugin's relationship) is not ours to index. Postgres treats a\n * NULL scope as distinct from every other, so install-wide rows stay hook-guarded.\n */\nconst uniqueSlugIndex = (args: BuildGoalsCollectionArgs): CompoundIndex | undefined => {\n\tif (!args.scoped) {\n\t\treturn { fields: ['slug'], unique: true }\n\t}\n\treturn args.scopeField === 'scope' ? { fields: ['slug', 'scope'], unique: true } : undefined\n}\n\n/**\n * The plugin's own scope field, and only when `scopeField` still names it: a host-owned\n * field (a tenant plugin's relationship) is the host's to register, and shadowing it with a\n * hidden text field of another name would store the scope twice.\n */\nconst scopeField = (args: BuildGoalsCollectionArgs): Field[] =>\n\targs.scopeField === 'scope'\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\t// Written by scoped setups; hidden because single-site installs never touch it.\n\t\t\t\t\tname: 'scope',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tindex: true,\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldScope),\n\t\t\t\t\tadmin: { hidden: true },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\nconst matchField = (): Field => ({\n\tname: 'match',\n\ttype: 'group',\n\tlabel: labelForKey(keys.goalFieldMatch),\n\tfields: [\n\t\t{\n\t\t\tname: 'kind',\n\t\t\ttype: 'select',\n\t\t\trequired: true,\n\t\t\tdefaultValue: 'goal',\n\t\t\tlabel: labelForKey(keys.goalFieldMatchKind),\n\t\t\toptions: [\n\t\t\t\t{ label: labelForKey(keys.goalKindGoal), value: 'goal' },\n\t\t\t\t{ label: labelForKey(keys.goalKindEvent), value: 'event' },\n\t\t\t\t{ label: labelForKey(keys.goalKindPath), value: 'path' },\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tname: 'name',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.goalFieldMatchEventName),\n\t\t\tadmin: { condition: (_data, siblingData) => siblingData?.kind === 'event' },\n\t\t},\n\t\t{\n\t\t\tname: 'pattern',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.goalFieldMatchPathPattern),\n\t\t\tadmin: {\n\t\t\t\tcondition: (_data, siblingData) => siblingData?.kind === 'path',\n\t\t\t\tdescription: labelForKey(keys.goalFieldMatchPathPatternHelp),\n\t\t\t},\n\t\t},\n\t],\n})\n\nconst valueField = (): Field => ({\n\tname: 'value',\n\ttype: 'group',\n\tlabel: labelForKey(keys.goalFieldValue),\n\tfields: [\n\t\t{\n\t\t\ttype: 'row',\n\t\t\tfields: [\n\t\t\t\t{\n\t\t\t\t\tname: 'fixed',\n\t\t\t\t\ttype: 'number',\n\t\t\t\t\tmin: 0,\n\t\t\t\t\tlabel: labelForKey(keys.goalFieldValueFixed),\n\t\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: 'prop',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tlabel: labelForKey(keys.goalFieldValueProp),\n\t\t\t\t\tadmin: {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\tdescription: labelForKey(keys.goalFieldValuePropHelp),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t],\n})\n\n/**\n * The editor-managed goals collection: one document per goal (and per scope in scoped\n * installs), merged over the config goals by the resolver. Admin-only by default; `access`\n * entries override individual operations and `overrides` reshapes the whole config last,\n * so slugs, labels, fields, and access all stay overridable.\n */\nexport const buildGoalsCollection = (args: BuildGoalsCollectionArgs): CollectionConfig => {\n\tconst unique = uniqueSlugIndex(args)\n\tconst collection: CollectionConfig = {\n\t\tslug: args.slug,\n\t\t...(unique ? { indexes: [unique] } : {}),\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.goalsCollectionSingular),\n\t\t\tplural: labelForKey(keys.goalsCollectionPlural),\n\t\t},\n\t\t// A duplicate would carry the slug over, which the uniqueness hook refuses anyway.\n\t\tdisableDuplicate: true,\n\t\tadmin: {\n\t\t\tuseAsTitle: 'name',\n\t\t\tdefaultColumns: ['name', 'slug', 'match.kind', 'enabled'],\n\t\t\tgroup: 'Analytics',\n\t\t},\n\t\taccess: {\n\t\t\tread: providerRowAccess(args),\n\t\t\tcreate: providerCreateAccess(args),\n\t\t\tupdate: providerRowAccess(args),\n\t\t\tdelete: providerRowAccess(args),\n\t\t\t...args.access,\n\t\t},\n\t\thooks: {\n\t\t\tbeforeValidate: [uniqueSlug(args)],\n\t\t\tbeforeChange: [stampScope(args)],\n\t\t\tafterChange: [\n\t\t\t\t({ doc }) => {\n\t\t\t\t\targs.onChange()\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t\tafterDelete: [\n\t\t\t\t({ doc }) => {\n\t\t\t\t\targs.onChange()\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'name',\n\t\t\t\ttype: 'text',\n\t\t\t\trequired: true,\n\t\t\t\tlabel: labelForKey(keys.goalFieldName),\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'slug',\n\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\t// Mongoose refuses a field index and a compound index that share a key\n\t\t\t\t\t\t// spec, and the compound one already covers a lookup by slug.\n\t\t\t\t\t\tindex: unique === undefined,\n\t\t\t\t\t\tlabel: labelForKey(keys.goalFieldSlug),\n\t\t\t\t\t\tvalidate: validateSlug,\n\t\t\t\t\t\tadmin: {\n\t\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\t\tdescription: labelForKey(keys.goalFieldSlugHelp),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'enabled',\n\t\t\t\t\t\ttype: 'checkbox',\n\t\t\t\t\t\tdefaultValue: true,\n\t\t\t\t\t\tlabel: labelForKey(keys.goalFieldEnabled),\n\t\t\t\t\t\tadmin: { width: '50%', style: { alignSelf: 'flex-end' } },\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\tmatchField(),\n\t\t\tvalueField(),\n\t\t\t{\n\t\t\t\tname: 'currency',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelForKey(keys.goalFieldCurrency),\n\t\t\t\tvalidate: validateCurrency,\n\t\t\t},\n\t\t\t...scopeField(args),\n\t\t],\n\t}\n\treturn args.overrides ? args.overrides(collection) : collection\n}\n"],"mappings":";;;;;;;;;AAmBA,MAAa,aAAa;AAU1B,MAAM,gBAA2C,OAAO,EAAE,UACzD,OAAO,UAAU,YAAY,kBAAkB,KAAK,K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YAAY,KAAK,gBAAgB;KACxC,OAAO;MAAE,OAAO;MAAO,OAAO,EAAE,WAAW,WAAW;KAAE;IACzD,CACD;GACD;GACA,WAAW;GACX,WAAW;GACX;IACC,MAAM;IACN,MAAM;IACN,OAAO,YAAY,KAAK,iBAAiB;IACzC,UAAU;GACX;GACA,GAAG,WAAW,IAAI;EACnB;CACD;CACA,OAAO,KAAK,YAAY,KAAK,UAAU,UAAU,IAAI;AACtD"}
@@ -0,0 +1,14 @@
1
+ import { keys } from "../translations/keys.js";
2
+ import { asTranslate } from "../translations/server.js";
3
+ //#region src/goals/currency.ts
4
+ /** ISO 4217: three uppercase letters. */
5
+ const CURRENCY_PATTERN = /^[A-Z]{3}$/;
6
+ /**
7
+ * Shared by the goals collection and the form-builder goal action so a currency authored in
8
+ * either place is accepted on the same terms. Empty is allowed: the currency is optional.
9
+ */
10
+ const validateCurrency = (value, { req }) => !value || CURRENCY_PATTERN.test(value) ? true : asTranslate(req.t)(keys.goalErrorCurrency);
11
+ //#endregion
12
+ export { validateCurrency };
13
+
14
+ //# sourceMappingURL=currency.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"currency.js","names":[],"sources":["../../src/goals/currency.ts"],"sourcesContent":["import type { TextFieldSingleValidation } from 'payload'\nimport { keys } from '../translations/keys'\nimport { asTranslate } from '../translations/server'\n\n/** ISO 4217: three uppercase letters. */\nexport const CURRENCY_PATTERN = /^[A-Z]{3}$/\n\n/**\n * Shared by the goals collection and the form-builder goal action so a currency authored in\n * either place is accepted on the same terms. Empty is allowed: the currency is optional.\n */\nexport const validateCurrency: TextFieldSingleValidation = (value, { req }) =>\n\t!value || CURRENCY_PATTERN.test(value) ? true : asTranslate(req.t)(keys.goalErrorCurrency)\n"],"mappings":";;;;AAKA,MAAa,mBAAmB;;;;;AAMhC,MAAa,oBAA+C,OAAO,EAAE,UACpE,CAAC,SAAS,iBAAiB,KAAK,KAAK,IAAI,OAAO,YAAY,IAAI,CAAC,EAAE,KAAK,iBAAiB"}
@@ -0,0 +1,18 @@
1
+ import { GoalSource } from "./resolver.js";
2
+
3
+ //#region src/goals/fetchGoals.d.ts
4
+ interface WireGoal {
5
+ slug: string;
6
+ name: string;
7
+ source: GoalSource;
8
+ }
9
+ interface GoalsResponse {
10
+ goals: WireGoal[];
11
+ /** The goals collection, when the install enabled it, so a picker can link to it. */
12
+ collection: {
13
+ slug: string;
14
+ } | null;
15
+ }
16
+ //#endregion
17
+ export { GoalsResponse, WireGoal };
18
+ //# sourceMappingURL=fetchGoals.d.ts.map
@@ -0,0 +1,29 @@
1
+ import { GOALS_PATH } from "../plugin/paths.js";
2
+ //#region src/goals/fetchGoals.ts
3
+ const cache = /* @__PURE__ */ new Map();
4
+ /**
5
+ * Fetch the caller-scope goal list once per user per admin session and share it between
6
+ * every picker on the page (a document can carry several goal fields). A failed fetch
7
+ * clears its cache entry so a later mount retries instead of pinning the error, and the
8
+ * user id in the key keeps a soft-navigation logout/login from serving the previous
9
+ * user's goals.
10
+ */
11
+ const fetchGoals = (serverURL, apiRoute, userKey) => {
12
+ const url = `${serverURL}${apiRoute}${GOALS_PATH}`;
13
+ const key = `${userKey}:${url}`;
14
+ const hit = cache.get(key);
15
+ if (hit) return hit;
16
+ const pending = fetch(url, { credentials: "include" }).then((res) => {
17
+ if (!res.ok) throw new Error(`goals ${res.status}`);
18
+ return res.json();
19
+ }).catch((err) => {
20
+ cache.delete(key);
21
+ throw err;
22
+ });
23
+ cache.set(key, pending);
24
+ return pending;
25
+ };
26
+ //#endregion
27
+ export { fetchGoals };
28
+
29
+ //# sourceMappingURL=fetchGoals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchGoals.js","names":[],"sources":["../../src/goals/fetchGoals.ts"],"sourcesContent":["import { GOALS_PATH } from '../plugin/paths'\nimport type { GoalSource } from './resolver'\n\nexport interface WireGoal {\n\tslug: string\n\tname: string\n\tsource: GoalSource\n}\n\nexport interface GoalsResponse {\n\tgoals: WireGoal[]\n\t/** The goals collection, when the install enabled it, so a picker can link to it. */\n\tcollection: { slug: string } | null\n}\n\nconst cache = new Map<string, Promise<GoalsResponse>>()\n\n/**\n * Fetch the caller-scope goal list once per user per admin session and share it between\n * every picker on the page (a document can carry several goal fields). A failed fetch\n * clears its cache entry so a later mount retries instead of pinning the error, and the\n * user id in the key keeps a soft-navigation logout/login from serving the previous\n * user's goals.\n */\nexport const fetchGoals = (\n\tserverURL: string,\n\tapiRoute: string,\n\tuserKey: string\n): Promise<GoalsResponse> => {\n\tconst url = `${serverURL}${apiRoute}${GOALS_PATH}`\n\tconst key = `${userKey}:${url}`\n\tconst hit = cache.get(key)\n\tif (hit) return hit\n\tconst pending = fetch(url, { credentials: 'include' })\n\t\t.then((res) => {\n\t\t\tif (!res.ok) throw new Error(`goals ${res.status}`)\n\t\t\treturn res.json() as Promise<GoalsResponse>\n\t\t})\n\t\t.catch((err) => {\n\t\t\tcache.delete(key)\n\t\t\tthrow err\n\t\t})\n\tcache.set(key, pending)\n\treturn pending\n}\n"],"mappings":";;AAeA,MAAM,wBAAQ,IAAI,IAAoC;;;;;;;;AAStD,MAAa,cACZ,WACA,UACA,YAC4B;CAC5B,MAAM,MAAM,GAAG,YAAY,WAAW;CACtC,MAAM,MAAM,GAAG,QAAQ,GAAG;CAC1B,MAAM,MAAM,MAAM,IAAI,GAAG;CACzB,IAAI,KAAK,OAAO;CAChB,MAAM,UAAU,MAAM,KAAK,EAAE,aAAa,UAAU,CAAC,EACnD,MAAM,QAAQ;EACd,IAAI,CAAC,IAAI,IAAI,MAAM,IAAI,MAAM,SAAS,IAAI,QAAQ;EAClD,OAAO,IAAI,KAAK;CACjB,CAAC,EACA,OAAO,QAAQ;EACf,MAAM,OAAO,GAAG;EAChB,MAAM;CACP,CAAC;CACF,MAAM,IAAI,KAAK,OAAO;CACtB,OAAO;AACR"}
@@ -0,0 +1,31 @@
1
+ import { LabelFunction, StaticLabel, TextField } from "payload";
2
+
3
+ //#region src/goals/goalField.d.ts
4
+ interface GoalFieldOptions {
5
+ /** Field name, and therefore the property the slug is stored under. Default `'goal'`. */
6
+ name?: string;
7
+ /** Default: the translated "Goal". */
8
+ label?: LabelFunction | StaticLabel;
9
+ required?: boolean;
10
+ /** Merged over the factory's own admin config; the Field component is not replaceable here. */
11
+ admin?: TextField['admin'];
12
+ /** Last word on the built field. Spread the field, never deep-merge it. */
13
+ overrides?: (args: {
14
+ field: TextField;
15
+ }) => TextField;
16
+ }
17
+ /**
18
+ * A goal picker for any collection or global: a text field storing the goal slug, rendered
19
+ * by the client picker that lists the config goals merged with the goals collection for the
20
+ * requesting scope. Pair it with {@link goalSlug} wherever the stored value is read back.
21
+ */
22
+ declare const goalField: (options?: GoalFieldOptions) => TextField;
23
+ /**
24
+ * The slug out of a stored goal value, for renderers that read a {@link goalField} back.
25
+ * Accepts the stored string and the `{ slug }` shape a populated document carries; anything
26
+ * else is not a goal reference and resolves to null rather than a guess.
27
+ */
28
+ declare const goalSlug: (value: unknown) => string | null;
29
+ //#endregion
30
+ export { GoalFieldOptions, goalField, goalSlug };
31
+ //# sourceMappingURL=goalField.d.ts.map
@@ -0,0 +1,56 @@
1
+ import { keys } from "../translations/keys.js";
2
+ import { asTranslate, labelForKey } from "../translations/server.js";
3
+ import { GOAL_SLUG_PATTERN } from "./types.js";
4
+ //#region src/goals/goalField.ts
5
+ /** importMap path of the picker; the factory never imports the component itself. */
6
+ const GOAL_FIELD_COMPONENT = "@10x-media/analytics/client#GoalSelectField";
7
+ const makeValidate = (required) => (value, { req }) => {
8
+ const slug = typeof value === "string" ? value.trim() : "";
9
+ if (slug === "") return required ? req.t("validation:required") : true;
10
+ return GOAL_SLUG_PATTERN.test(slug) ? true : asTranslate(req.t)(keys.fieldGoalInvalid);
11
+ };
12
+ /**
13
+ * A goal picker for any collection or global: a text field storing the goal slug, rendered
14
+ * by the client picker that lists the config goals merged with the goals collection for the
15
+ * requesting scope. Pair it with {@link goalSlug} wherever the stored value is read back.
16
+ */
17
+ const goalField = (options = {}) => {
18
+ const field = {
19
+ name: options.name ?? "goal",
20
+ type: "text",
21
+ label: options.label ?? labelForKey(keys.fieldGoalLabel),
22
+ ...options.required ? { required: true } : {},
23
+ validate: makeValidate(Boolean(options.required)),
24
+ admin: {
25
+ ...options.admin,
26
+ components: {
27
+ ...options.admin?.components,
28
+ Field: { path: GOAL_FIELD_COMPONENT }
29
+ }
30
+ }
31
+ };
32
+ return options.overrides ? options.overrides({ field }) : field;
33
+ };
34
+ /**
35
+ * The slug out of a stored goal value, for renderers that read a {@link goalField} back.
36
+ * Accepts the stored string and the `{ slug }` shape a populated document carries; anything
37
+ * else is not a goal reference and resolves to null rather than a guess.
38
+ */
39
+ const goalSlug = (value) => {
40
+ if (typeof value === "string") {
41
+ const slug = value.trim();
42
+ return slug === "" ? null : slug;
43
+ }
44
+ if (value && typeof value === "object" && !Array.isArray(value)) {
45
+ const { slug } = value;
46
+ if (typeof slug === "string") {
47
+ const trimmed = slug.trim();
48
+ return trimmed === "" ? null : trimmed;
49
+ }
50
+ }
51
+ return null;
52
+ };
53
+ //#endregion
54
+ export { goalField, goalSlug };
55
+
56
+ //# sourceMappingURL=goalField.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goalField.js","names":[],"sources":["../../src/goals/goalField.ts"],"sourcesContent":["import type { LabelFunction, StaticLabel, TextField, TextFieldSingleValidation } from 'payload'\nimport { keys } from '../translations/keys'\nimport { asTranslate, labelForKey } from '../translations/server'\nimport { GOAL_SLUG_PATTERN } from './types'\n\n/** importMap path of the picker; the factory never imports the component itself. */\nexport const GOAL_FIELD_COMPONENT = '@10x-media/analytics/client#GoalSelectField'\n\nexport interface GoalFieldOptions {\n\t/** Field name, and therefore the property the slug is stored under. Default `'goal'`. */\n\tname?: string\n\t/** Default: the translated \"Goal\". */\n\tlabel?: LabelFunction | StaticLabel\n\trequired?: boolean\n\t/** Merged over the factory's own admin config; the Field component is not replaceable here. */\n\tadmin?: TextField['admin']\n\t/** Last word on the built field. Spread the field, never deep-merge it. */\n\toverrides?: (args: { field: TextField }) => TextField\n}\n\nconst makeValidate =\n\t(required: boolean): TextFieldSingleValidation =>\n\t(value, { req }) => {\n\t\tconst slug = typeof value === 'string' ? value.trim() : ''\n\t\tif (slug === '') {\n\t\t\treturn required ? req.t('validation:required') : true\n\t\t}\n\t\treturn GOAL_SLUG_PATTERN.test(slug) ? true : asTranslate(req.t)(keys.fieldGoalInvalid)\n\t}\n\n/**\n * A goal picker for any collection or global: a text field storing the goal slug, rendered\n * by the client picker that lists the config goals merged with the goals collection for the\n * requesting scope. Pair it with {@link goalSlug} wherever the stored value is read back.\n */\nexport const goalField = (options: GoalFieldOptions = {}): TextField => {\n\tconst field: TextField = {\n\t\tname: options.name ?? 'goal',\n\t\ttype: 'text',\n\t\tlabel: options.label ?? labelForKey(keys.fieldGoalLabel),\n\t\t...(options.required ? { required: true } : {}),\n\t\tvalidate: makeValidate(Boolean(options.required)),\n\t\tadmin: {\n\t\t\t...options.admin,\n\t\t\tcomponents: {\n\t\t\t\t...options.admin?.components,\n\t\t\t\tField: { path: GOAL_FIELD_COMPONENT },\n\t\t\t},\n\t\t},\n\t}\n\treturn options.overrides ? options.overrides({ field }) : field\n}\n\n/**\n * The slug out of a stored goal value, for renderers that read a {@link goalField} back.\n * Accepts the stored string and the `{ slug }` shape a populated document carries; anything\n * else is not a goal reference and resolves to null rather than a guess.\n */\nexport const goalSlug = (value: unknown): string | null => {\n\tif (typeof value === 'string') {\n\t\tconst slug = value.trim()\n\t\treturn slug === '' ? null : slug\n\t}\n\tif (value && typeof value === 'object' && !Array.isArray(value)) {\n\t\tconst { slug } = value as { slug?: unknown }\n\t\tif (typeof slug === 'string') {\n\t\t\tconst trimmed = slug.trim()\n\t\t\treturn trimmed === '' ? null : trimmed\n\t\t}\n\t}\n\treturn null\n}\n"],"mappings":";;;;;AAMA,MAAa,uBAAuB;AAcpC,MAAM,gBACJ,cACA,OAAO,EAAE,UAAU;CACnB,MAAM,OAAO,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;CACxD,IAAI,SAAS,IACZ,OAAO,WAAW,IAAI,EAAE,qBAAqB,IAAI;CAElD,OAAO,kBAAkB,KAAK,IAAI,IAAI,OAAO,YAAY,IAAI,CAAC,EAAE,KAAK,gBAAgB;AACtF;;;;;;AAOD,MAAa,aAAa,UAA4B,CAAC,MAAiB;CACvE,MAAM,QAAmB;EACxB,MAAM,QAAQ,QAAQ;EACtB,MAAM;EACN,OAAO,QAAQ,SAAS,YAAY,KAAK,cAAc;EACvD,GAAI,QAAQ,WAAW,EAAE,UAAU,KAAK,IAAI,CAAC;EAC7C,UAAU,aAAa,QAAQ,QAAQ,QAAQ,CAAC;EAChD,OAAO;GACN,GAAG,QAAQ;GACX,YAAY;IACX,GAAG,QAAQ,OAAO;IAClB,OAAO,EAAE,MAAM,qBAAqB;GACrC;EACD;CACD;CACA,OAAO,QAAQ,YAAY,QAAQ,UAAU,EAAE,MAAM,CAAC,IAAI;AAC3D;;;;;;AAOA,MAAa,YAAY,UAAkC;CAC1D,IAAI,OAAO,UAAU,UAAU;EAC9B,MAAM,OAAO,MAAM,KAAK;EACxB,OAAO,SAAS,KAAK,OAAO;CAC7B;CACA,IAAI,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,GAAG;EAChE,MAAM,EAAE,SAAS;EACjB,IAAI,OAAO,SAAS,UAAU;GAC7B,MAAM,UAAU,KAAK,KAAK;GAC1B,OAAO,YAAY,KAAK,OAAO;EAChC;CACD;CACA,OAAO;AACR"}
@@ -0,0 +1 @@
1
+ import { GoalsResponse, WireGoal } from "./fetchGoals.js";
@@ -0,0 +1,55 @@
1
+ import "../plugin/paths.js";
2
+ import { getRuntime, platformReadFor, readAccessFor, resolveGoalsDetailedFor, resolveScopeFor } from "../plugin/runtime.js";
3
+ //#region src/goals/goalsEndpoint.ts
4
+ /**
5
+ * Authenticated GET listing the goals visible to the requesting scope, gated by
6
+ * `access.read` like every other read endpoint: the config goals
7
+ * merged with the goals collection, each tagged with where it came from. Scope gating
8
+ * mirrors the sources endpoint exactly, because the reasoning is the same: there is no
9
+ * scope parameter, so a tenant can never enumerate another tenant's goals; on a scoped
10
+ * install a request that resolves no scope is ambiguous rather than install-wide and
11
+ * answers empty unless `platformRead` grants it; and a failed resolution on a scoped
12
+ * install is indistinguishable from a forged one, so it answers empty too, while an
13
+ * unscoped install falls back to the static config goals.
14
+ */
15
+ const makeGoalsHandler = () => async (req) => {
16
+ if (!req.user) return Response.json({ error: "unauthorized" }, { status: 401 });
17
+ const runtime = getRuntime(req.payload);
18
+ if (!runtime) return Response.json({
19
+ goals: [],
20
+ collection: null
21
+ });
22
+ if (!await readAccessFor(runtime, req)) return Response.json({ error: "forbidden" }, { status: 403 });
23
+ const collection = runtime.goalsCollectionSlug ? { slug: runtime.goalsCollectionSlug } : null;
24
+ const configGoals = () => (runtime.goals ?? []).map((goal) => ({
25
+ slug: goal.slug,
26
+ name: goal.name,
27
+ source: "config"
28
+ }));
29
+ try {
30
+ const scope = await resolveScopeFor(runtime, req);
31
+ if (runtime.scoped && scope === null && !await platformReadFor(runtime, req)) return Response.json({
32
+ goals: [],
33
+ collection
34
+ });
35
+ const goals = (await resolveGoalsDetailedFor(runtime, req, scope)).map(({ goal, source }) => ({
36
+ slug: goal.slug,
37
+ name: goal.name,
38
+ source
39
+ }));
40
+ return Response.json({
41
+ goals,
42
+ collection
43
+ });
44
+ } catch (err) {
45
+ req.payload.logger?.warn(`analytics: goals listing failed: ${String(err)}`);
46
+ return Response.json({
47
+ goals: runtime.scoped ? [] : configGoals(),
48
+ collection
49
+ });
50
+ }
51
+ };
52
+ //#endregion
53
+ export { makeGoalsHandler };
54
+
55
+ //# sourceMappingURL=goalsEndpoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goalsEndpoint.js","names":[],"sources":["../../src/goals/goalsEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { GOALS_PATH } from '../plugin/paths'\nimport {\n\tgetRuntime,\n\tplatformReadFor,\n\treadAccessFor,\n\tresolveGoalsDetailedFor,\n\tresolveScopeFor,\n} from '../plugin/runtime'\nimport type { GoalsResponse, WireGoal } from './fetchGoals'\n\nexport type { GoalsResponse, WireGoal }\nexport { GOALS_PATH }\n\n/**\n * Authenticated GET listing the goals visible to the requesting scope, gated by\n * `access.read` like every other read endpoint: the config goals\n * merged with the goals collection, each tagged with where it came from. Scope gating\n * mirrors the sources endpoint exactly, because the reasoning is the same: there is no\n * scope parameter, so a tenant can never enumerate another tenant's goals; on a scoped\n * install a request that resolves no scope is ambiguous rather than install-wide and\n * answers empty unless `platformRead` grants it; and a failed resolution on a scoped\n * install is indistinguishable from a forged one, so it answers empty too, while an\n * unscoped install falls back to the static config goals.\n */\nexport const makeGoalsHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn Response.json({ error: 'unauthorized' }, { status: 401 })\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn Response.json({ goals: [], collection: null } satisfies GoalsResponse)\n\t}\n\tif (!(await readAccessFor(runtime, req))) {\n\t\treturn Response.json({ error: 'forbidden' }, { status: 403 })\n\t}\n\tconst collection = runtime.goalsCollectionSlug ? { slug: runtime.goalsCollectionSlug } : null\n\tconst configGoals = (): WireGoal[] =>\n\t\t(runtime.goals ?? []).map((goal) => ({\n\t\t\tslug: goal.slug,\n\t\t\tname: goal.name,\n\t\t\tsource: 'config' as const,\n\t\t}))\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\tif (runtime.scoped && scope === null && !(await platformReadFor(runtime, req))) {\n\t\t\treturn Response.json({ goals: [], collection } satisfies GoalsResponse)\n\t\t}\n\t\tconst resolved = await resolveGoalsDetailedFor(runtime, req, scope)\n\t\tconst goals = resolved.map(({ goal, source }) => ({\n\t\t\tslug: goal.slug,\n\t\t\tname: goal.name,\n\t\t\tsource,\n\t\t}))\n\t\treturn Response.json({ goals, collection } satisfies GoalsResponse)\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: goals listing failed: ${String(err)}`)\n\t\treturn Response.json({\n\t\t\tgoals: runtime.scoped ? [] : configGoals(),\n\t\t\tcollection,\n\t\t} satisfies GoalsResponse)\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,MAAa,yBAAyC,OAAO,QAAQ;CACpE,IAAI,CAAC,IAAI,MACR,OAAO,SAAS,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;CAEhE,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO,SAAS,KAAK;EAAE,OAAO,CAAC;EAAG,YAAY;CAAK,CAAyB;CAE7E,IAAI,CAAE,MAAM,cAAc,SAAS,GAAG,GACrC,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;CAE7D,MAAM,aAAa,QAAQ,sBAAsB,EAAE,MAAM,QAAQ,oBAAoB,IAAI;CACzF,MAAM,qBACJ,QAAQ,SAAS,CAAC,GAAG,KAAK,UAAU;EACpC,MAAM,KAAK;EACX,MAAM,KAAK;EACX,QAAQ;CACT,EAAE;CACH,IAAI;EACH,MAAM,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EAChD,IAAI,QAAQ,UAAU,UAAU,QAAQ,CAAE,MAAM,gBAAgB,SAAS,GAAG,GAC3E,OAAO,SAAS,KAAK;GAAE,OAAO,CAAC;GAAG;EAAW,CAAyB;EAGvE,MAAM,SAAQ,MADS,wBAAwB,SAAS,KAAK,KAAK,GAC3C,KAAK,EAAE,MAAM,cAAc;GACjD,MAAM,KAAK;GACX,MAAM,KAAK;GACX;EACD,EAAE;EACF,OAAO,SAAS,KAAK;GAAE;GAAO;EAAW,CAAyB;CACnE,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,oCAAoC,OAAO,GAAG,GAAG;EAC1E,OAAO,SAAS,KAAK;GACpB,OAAO,QAAQ,SAAS,CAAC,IAA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