@delmaredigital/payload-experiments 0.4.0-rc.6 → 0.4.0-rc.9

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 (294) hide show
  1. package/README.md +12 -12
  2. package/dist/admin/blocks/BlockPanel.js +6 -4
  3. package/dist/admin/blocks/inject.js +1 -0
  4. package/dist/admin/blocks/model.d.ts +3 -2
  5. package/dist/admin/blocks/model.js +9 -5
  6. package/dist/admin/copy/blocks.d.ts +3 -2
  7. package/dist/admin/copy/blocks.js +8 -7
  8. package/dist/admin/surface/ResultsRoute.js +18 -11
  9. package/dist/admin/surface/TestsHome.d.ts +2 -1
  10. package/dist/admin/surface/TestsHome.js +131 -44
  11. package/dist/admin/surface/TestsSurface.js +3 -0
  12. package/dist/admin/surface/home.model.d.ts +2 -0
  13. package/dist/admin/surface/newTest/PageWizard.js +9 -2
  14. package/dist/admin/surface/newTest/newTest.css +1 -1
  15. package/dist/admin/surface/results/ResultsHeader.js +11 -6
  16. package/dist/admin/surface/test/TestPage.js +3 -3
  17. package/dist/admin/views/TestsSurfaceClient.d.ts +3 -0
  18. package/dist/admin/views/TestsSurfaceClient.js +11 -0
  19. package/dist/admin/views/buildSurfaceProps.js +10 -3
  20. package/dist/blocks/bindings.js +3 -2
  21. package/dist/blocks/formState.js +1 -1
  22. package/dist/blocks/placementLanguages.d.ts +7 -0
  23. package/dist/blocks/placementLanguages.js +27 -0
  24. package/dist/blocks/placementLocale.d.ts +21 -7
  25. package/dist/blocks/placementLocale.js +218 -67
  26. package/dist/collections/experiments/config.js +8 -3
  27. package/dist/collections/experiments/deleteGuard.js +2 -2
  28. package/dist/collections/experiments/lockHook.js +21 -2
  29. package/dist/collections/experiments/pickSlug.js +2 -0
  30. package/dist/collections/metricsGuards.js +2 -0
  31. package/dist/collections/serialize.js +5 -4
  32. package/dist/constants.d.ts +1 -0
  33. package/dist/constants.js +1 -0
  34. package/dist/db/adapter.d.ts +9 -1
  35. package/dist/db/adapter.js +77 -1
  36. package/dist/db/appends.d.ts +13 -0
  37. package/dist/db/appends.js +49 -0
  38. package/dist/db/bulkPlacementRemoval.js +8 -4
  39. package/dist/db/delete.d.ts +1 -1
  40. package/dist/db/delete.js +2 -4
  41. package/dist/db/events.d.ts +9 -0
  42. package/dist/db/events.js +42 -8
  43. package/dist/db/executor.d.ts +7 -1
  44. package/dist/db/executor.js +7 -3
  45. package/dist/db/results.d.ts +5 -1
  46. package/dist/db/results.js +21 -5
  47. package/dist/db/snapshots.d.ts +1 -0
  48. package/dist/endpoints/contentLocale.d.ts +6 -0
  49. package/dist/endpoints/contentLocale.js +15 -0
  50. package/dist/endpoints/deleteImpact.d.ts +6 -0
  51. package/dist/endpoints/deleteImpact.js +207 -0
  52. package/dist/endpoints/events.js +103 -39
  53. package/dist/endpoints/index.js +9 -8
  54. package/dist/endpoints/pages.js +7 -3
  55. package/dist/endpoints/placementStatus.js +13 -5
  56. package/dist/endpoints/preflight.d.ts +1 -1
  57. package/dist/endpoints/preflight.js +17 -2
  58. package/dist/endpoints/results.d.ts +1 -1
  59. package/dist/endpoints/results.js +6 -2
  60. package/dist/endpoints/routeId.d.ts +2 -2
  61. package/dist/endpoints/routeId.js +11 -5
  62. package/dist/endpoints/summary.js +46 -12
  63. package/dist/endpoints/transitions.js +37 -24
  64. package/dist/errors.d.ts +4 -0
  65. package/dist/errors.js +6 -0
  66. package/dist/events/request.d.ts +6 -2
  67. package/dist/events/request.js +35 -8
  68. package/dist/events/rows.d.ts +1 -1
  69. package/dist/events/rows.js +24 -8
  70. package/dist/events/writable.d.ts +9 -0
  71. package/dist/events/writable.js +13 -0
  72. package/dist/exports/adminClient.d.ts +1 -1
  73. package/dist/exports/adminClient.js +1 -1
  74. package/dist/exports/index.d.ts +1 -1
  75. package/dist/exports/rsc.d.ts +1 -0
  76. package/dist/exports/rsc.js +1 -0
  77. package/dist/goals/fairness.js +38 -31
  78. package/dist/hooks/blockRemovalRule.d.ts +2 -2
  79. package/dist/hooks/blockRemovalRule.js +16 -14
  80. package/dist/hooks/hostHook.js +6 -2
  81. package/dist/hooks/pageGuard.d.ts +3 -0
  82. package/dist/hooks/pageGuard.js +37 -23
  83. package/dist/hooks/puckNestedTests.d.ts +8 -0
  84. package/dist/hooks/puckNestedTests.js +36 -0
  85. package/dist/lib/fetchAllDocs.d.ts +1 -1
  86. package/dist/lib/placementPages.d.ts +2 -1
  87. package/dist/lib/placementPages.js +10 -2
  88. package/dist/manifest/compile.d.ts +2 -1
  89. package/dist/manifest/compile.js +13 -6
  90. package/dist/onInit.js +14 -0
  91. package/dist/options.js +5 -0
  92. package/dist/proxy/pageNavigation.d.ts +4 -0
  93. package/dist/proxy/pageNavigation.js +28 -0
  94. package/dist/proxy/resolve.js +52 -25
  95. package/dist/puck/ExperimentPicker.js +40 -37
  96. package/dist/puck/editor/ConfigureTestDrawer.d.ts +8 -4
  97. package/dist/puck/editor/ConfigureTestDrawer.js +5 -2
  98. package/dist/puck/editor/ExperimentSlotEditor.js +313 -158
  99. package/dist/puck/editor/LeftoverVersions.d.ts +1 -1
  100. package/dist/puck/editor/LeftoverVersions.js +40 -43
  101. package/dist/puck/editor/QuickTestActions.d.ts +5 -2
  102. package/dist/puck/editor/QuickTestActions.js +16 -4
  103. package/dist/puck/editor/ResultsReadout.d.ts +2 -1
  104. package/dist/puck/editor/ResultsReadout.js +2 -1
  105. package/dist/puck/editor/VersionBuilder.d.ts +31 -3
  106. package/dist/puck/editor/VersionBuilder.js +336 -74
  107. package/dist/puck/editor/armWrites.js +1 -1
  108. package/dist/puck/editor/armsCache.js +1 -3
  109. package/dist/puck/editor/blockClipboard.d.ts +16 -0
  110. package/dist/puck/editor/blockClipboard.js +20 -0
  111. package/dist/puck/editor/copy.d.ts +12 -2
  112. package/dist/puck/editor/copy.js +13 -2
  113. package/dist/puck/editor/editor.chrome.css +118 -3
  114. package/dist/puck/editor/editor.css +131 -8
  115. package/dist/puck/editor/editor.model.d.ts +3 -1
  116. package/dist/puck/editor/editor.model.js +2 -2
  117. package/dist/puck/editor/localPlacements.d.ts +1 -0
  118. package/dist/puck/editor/localPlacements.js +12 -0
  119. package/dist/puck/editor/placementsCache.d.ts +22 -12
  120. package/dist/puck/editor/placementsCache.js +62 -49
  121. package/dist/puck/editor/usePageSaveReadiness.d.ts +9 -0
  122. package/dist/puck/editor/usePageSaveReadiness.js +34 -0
  123. package/dist/puck/editor/usePlacementNotice.d.ts +2 -2
  124. package/dist/puck/editor/usePlacementNotice.js +6 -4
  125. package/dist/puck/experimentSlug.d.ts +2 -0
  126. package/dist/puck/experimentSlug.js +3 -0
  127. package/dist/puck/nestedTestCopy.d.ts +8 -0
  128. package/dist/puck/nestedTestCopy.js +22 -0
  129. package/dist/puck/nestedTests.d.ts +17 -0
  130. package/dist/puck/nestedTests.js +30 -0
  131. package/dist/puck/slotConfig.d.ts +1 -1
  132. package/dist/puck/slotConfig.js +17 -4
  133. package/dist/puck/visibility.d.ts +2 -3
  134. package/dist/puck/visibility.js +11 -7
  135. package/dist/results/aggregate.d.ts +6 -3
  136. package/dist/results/aggregate.js +9 -9
  137. package/dist/results/health.d.ts +8 -0
  138. package/dist/results/health.js +28 -0
  139. package/dist/results/identityCredit.d.ts +1 -0
  140. package/dist/results/identityCredit.js +4 -1
  141. package/dist/results/verdict.js +2 -1
  142. package/dist/runtime/cookie.d.ts +10 -2
  143. package/dist/runtime/cookie.js +38 -6
  144. package/dist/runtime/cookieOptions.d.ts +6 -0
  145. package/dist/runtime/cookieOptions.js +14 -0
  146. package/dist/runtime/proxyRuntime.d.ts +1 -0
  147. package/dist/runtime/proxyRuntime.js +18 -8
  148. package/dist/runtime/signing.d.ts +1 -0
  149. package/dist/runtime/signing.js +5 -0
  150. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  151. package/dist/sanitizeReadinessDetail.js +20 -2
  152. package/dist/server/getAssignments.js +11 -10
  153. package/dist/server/recordContentChange.d.ts +1 -1
  154. package/dist/server/recordContentChange.js +45 -21
  155. package/dist/server/resolveExperimentBlocks.js +2 -4
  156. package/dist/server/resolveExperimentData.js +4 -7
  157. package/dist/server/runResults.js +52 -14
  158. package/dist/server/startExperiment.d.ts +20 -0
  159. package/dist/server/startExperiment.js +70 -0
  160. package/dist/server/trackConversion.js +10 -13
  161. package/dist/testSurface/PreviewLinks.js +6 -2
  162. package/dist/testSurface/actions/DecideDialog.d.ts +4 -1
  163. package/dist/testSurface/actions/DecideDialog.js +32 -14
  164. package/dist/testSurface/actions/MakeContentResult.d.ts +4 -3
  165. package/dist/testSurface/actions/MakeContentResult.js +9 -1
  166. package/dist/testSurface/api.d.ts +11 -8
  167. package/dist/testSurface/api.js +27 -11
  168. package/dist/testSurface/contentLocaleURL.d.ts +2 -0
  169. package/dist/testSurface/contentLocaleURL.js +3 -0
  170. package/dist/testSurface/copy/actions.d.ts +1 -0
  171. package/dist/testSurface/copy/actions.js +1 -0
  172. package/dist/testSurface/copy/common.d.ts +6 -0
  173. package/dist/testSurface/copy/common.js +11 -5
  174. package/dist/testSurface/copy/languages.d.ts +12 -0
  175. package/dist/testSurface/copy/languages.js +8 -0
  176. package/dist/testSurface/copy/metrics.d.ts +1 -0
  177. package/dist/testSurface/copy/metrics.js +1 -0
  178. package/dist/testSurface/copy/readiness.d.ts +13 -2
  179. package/dist/testSurface/copy/readiness.js +19 -2
  180. package/dist/testSurface/copy/results.d.ts +5 -2
  181. package/dist/testSurface/copy/results.js +5 -2
  182. package/dist/testSurface/copy/testPage.d.ts +40 -1
  183. package/dist/testSurface/copy/testPage.js +53 -1
  184. package/dist/testSurface/placementLabel.d.ts +8 -0
  185. package/dist/testSurface/placementLabel.js +24 -0
  186. package/dist/testSurface/placements/placementLabels.d.ts +2 -0
  187. package/dist/testSurface/placements/placementLabels.js +2 -1
  188. package/dist/testSurface/readPreflight.d.ts +5 -0
  189. package/dist/testSurface/readPreflight.js +7 -0
  190. package/dist/testSurface/readinessRead.d.ts +3 -0
  191. package/dist/testSurface/readinessRead.js +4 -0
  192. package/dist/testSurface/results/VerdictHero.d.ts +2 -1
  193. package/dist/testSurface/results/VerdictHero.js +5 -1
  194. package/dist/testSurface/results/results.css +1 -1
  195. package/dist/testSurface/results/results.model.d.ts +1 -1
  196. package/dist/testSurface/results/results.model.js +6 -2
  197. package/dist/testSurface/surface/contracts.d.ts +10 -1
  198. package/dist/testSurface/surface/editorPlacement.d.ts +7 -2
  199. package/dist/testSurface/surface/editorPlacement.js +19 -1
  200. package/dist/testSurface/surface/pageBlock/pageBlock.model.js +4 -3
  201. package/dist/testSurface/surface/pageBlock/parts.js +24 -6
  202. package/dist/testSurface/surface/pagePicker/PageCombobox.js +20 -6
  203. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +4 -2
  204. package/dist/testSurface/surface/readiness/ActionDialogs.js +39 -34
  205. package/dist/testSurface/surface/readiness/Banner.js +23 -12
  206. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +4 -3
  207. package/dist/testSurface/surface/readiness/SaveStatus.js +15 -15
  208. package/dist/testSurface/surface/readiness/readiness.model.d.ts +6 -1
  209. package/dist/testSurface/surface/readiness/readiness.model.js +116 -12
  210. package/dist/testSurface/surface/readiness/useTransition.d.ts +4 -4
  211. package/dist/testSurface/surface/readiness/useTransition.js +12 -10
  212. package/dist/testSurface/surface/results/ReleasePages.d.ts +4 -2
  213. package/dist/testSurface/surface/results/ReleasePages.js +5 -4
  214. package/dist/testSurface/surface/results/ResultsBody.d.ts +4 -2
  215. package/dist/testSurface/surface/results/ResultsBody.js +86 -43
  216. package/dist/testSurface/surface/results/useResults.d.ts +11 -7
  217. package/dist/testSurface/surface/results/useResults.js +3 -2
  218. package/dist/testSurface/surface/setting/parts.js +58 -18
  219. package/dist/testSurface/surface/test/AdvancedSection.js +1 -0
  220. package/dist/testSurface/surface/test/DeleteTest.d.ts +19 -0
  221. package/dist/testSurface/surface/test/DeleteTest.js +262 -0
  222. package/dist/testSurface/surface/test/GoalSection.js +7 -3
  223. package/dist/testSurface/surface/test/LengthSection.js +3 -0
  224. package/dist/testSurface/surface/test/PageHoldout.js +4 -1
  225. package/dist/testSurface/surface/test/ReadinessBar.js +1 -1
  226. package/dist/testSurface/surface/test/TargetingSection.js +77 -12
  227. package/dist/testSurface/surface/test/TestSurface.js +97 -15
  228. package/dist/testSurface/surface/test/VersionsSection.js +56 -29
  229. package/dist/testSurface/surface/test/fields.d.ts +29 -4
  230. package/dist/testSurface/surface/test/fields.js +159 -39
  231. package/dist/testSurface/surface/test/pageParts.js +14 -5
  232. package/dist/testSurface/surface/test/testPage.model.d.ts +1 -0
  233. package/dist/testSurface/surface/test/testPage.model.js +6 -0
  234. package/dist/testSurface/surface/testDocument.model.d.ts +3 -0
  235. package/dist/testSurface/surface/testDocument.model.js +4 -1
  236. package/dist/testSurface/surface/useTestDocument.d.ts +23 -4
  237. package/dist/testSurface/surface/useTestDocument.js +425 -162
  238. package/dist/testSurface/useApi.d.ts +9 -6
  239. package/dist/testSurface/useOnTestReturn.d.ts +2 -0
  240. package/dist/testSurface/useOnTestReturn.js +27 -0
  241. package/dist/testSurface/useReadinessPolling.js +3 -1
  242. package/dist/transitions/addMetric.d.ts +1 -4
  243. package/dist/transitions/allocate.d.ts +2 -2
  244. package/dist/transitions/allocate.js +3 -1
  245. package/dist/transitions/archive.d.ts +1 -1
  246. package/dist/transitions/archive.js +3 -2
  247. package/dist/transitions/checkStart.d.ts +5 -1
  248. package/dist/transitions/checkStart.js +130 -16
  249. package/dist/transitions/contentFields.js +9 -5
  250. package/dist/transitions/decide.d.ts +1 -1
  251. package/dist/transitions/decide.js +5 -3
  252. package/dist/transitions/deleteExperiment.d.ts +2 -2
  253. package/dist/transitions/deleteExperiment.js +17 -7
  254. package/dist/transitions/kernel.d.ts +2 -0
  255. package/dist/transitions/kernel.js +9 -4
  256. package/dist/transitions/makeContent.d.ts +2 -1
  257. package/dist/transitions/makeContent.js +17 -12
  258. package/dist/transitions/nestedPlacementNames.d.ts +5 -0
  259. package/dist/transitions/nestedPlacementNames.js +32 -0
  260. package/dist/transitions/pageVersions.js +3 -1
  261. package/dist/transitions/phaseRecord.d.ts +2 -0
  262. package/dist/transitions/phaseRecord.js +5 -0
  263. package/dist/transitions/placementInteractions.d.ts +3 -3
  264. package/dist/transitions/placementInteractions.js +15 -11
  265. package/dist/transitions/placements.d.ts +28 -1
  266. package/dist/transitions/placements.js +223 -60
  267. package/dist/transitions/preflightData.d.ts +5 -3
  268. package/dist/transitions/preflightData.js +126 -37
  269. package/dist/transitions/releaseHoldout.d.ts +2 -1
  270. package/dist/transitions/releaseHoldout.js +3 -1
  271. package/dist/transitions/releasePages.d.ts +2 -1
  272. package/dist/transitions/releasePages.js +3 -1
  273. package/dist/transitions/resolveCaps.d.ts +2 -4
  274. package/dist/transitions/start.d.ts +6 -8
  275. package/dist/transitions/start.js +70 -34
  276. package/dist/transitions/startReads.d.ts +7 -0
  277. package/dist/transitions/startReads.js +28 -0
  278. package/dist/transitions/stop.d.ts +2 -1
  279. package/dist/transitions/stop.js +3 -2
  280. package/dist/types/contracts.d.ts +6 -3
  281. package/dist/types/endpoints.d.ts +86 -9
  282. package/dist/types/endpoints.js +1 -1
  283. package/dist/types/runtime.d.ts +15 -9
  284. package/dist/types/snapshot.d.ts +2 -0
  285. package/dist/types/surface.d.ts +2 -0
  286. package/dist/ui/Button.js +2 -2
  287. package/dist/ui/ChipsInput.d.ts +8 -1
  288. package/dist/ui/ChipsInput.js +17 -4
  289. package/dist/ui/Inputs.d.ts +4 -3
  290. package/dist/ui/Inputs.js +9 -9
  291. package/dist/ui/SelectControl.d.ts +33 -0
  292. package/dist/ui/SelectControl.js +504 -0
  293. package/dist/ui/ui.css +13 -5
  294. package/package.json +3 -2
@@ -44,16 +44,21 @@ export function experimentsCollection(options) {
44
44
  },
45
45
  access: {
46
46
  ...managedAccess(options),
47
- delete: async ({ req })=>await options.access.manage({
47
+ delete: async ({ req, id })=>{
48
+ if (await options.access.manage({
48
49
  req
49
- }) === true ? {
50
+ }) !== true) return false;
51
+ // Single deletes report status through the locked beforeDelete guard.
52
+ // Payload catches per-document hook failures in bulk deletes, so keep their status filter in access.
53
+ return id != null ? true : {
50
54
  status: {
51
55
  in: [
52
56
  'draft',
53
57
  'archived'
54
58
  ]
55
59
  }
56
- } : false
60
+ };
61
+ }
57
62
  },
58
63
  admin: {
59
64
  group: SURFACE_COPY.title,
@@ -3,8 +3,8 @@ import { xpOptionsFromReq } from '../../options/fromReq.js';
3
3
  export const deleteGuard = async ({ req, id })=>{
4
4
  await deleteExperiment(req, id);
5
5
  };
6
- export const deleteGuardAfter = async ({ req, id, doc })=>{
7
- await deleteExperimentAfter(req, id);
6
+ export const deleteGuardAfter = async ({ req, doc })=>{
7
+ await deleteExperimentAfter(req);
8
8
  return doc;
9
9
  };
10
10
  export const deleteGuardBeforeOperation = async ({ operation, args, req })=>{
@@ -1,3 +1,4 @@
1
+ import { withSlotsFor } from '../../arms/model.js';
1
2
  import { XpLockedFieldError, XpRefusal } from '../../errors.js';
2
3
  import { XP_IF_UPDATED_AT_HEADER } from '../../constants.js';
3
4
  import { txExecutor } from '../../db/executor.js';
@@ -64,6 +65,24 @@ const dates = new Set([
64
65
  }
65
66
  const same = (a, b, path)=>JSON.stringify(normalize(a, path)) === JSON.stringify(normalize(b, path));
66
67
  export const lockHook = async ({ data, originalDoc, operation, req })=>{
68
+ const kind = operation === 'create' ? data.kind : originalDoc.kind;
69
+ const storedArms = operation === 'update' ? originalDoc.arms : undefined;
70
+ const canonicalSlots = (value)=>{
71
+ if (kind !== 'block' || !Array.isArray(value) || value.some((row)=>!isObject(row))) return value;
72
+ return withSlotsFor(value, 'block');
73
+ };
74
+ const canonicalArms = canonicalSlots(storedArms);
75
+ // Payload runs collection beforeChange before field validation on Create,
76
+ // Update and Restore. Derive slots here so the arms validator sees them.
77
+ const arms = data.arms === undefined ? storedArms : data.arms;
78
+ const repaired = arms === storedArms ? canonicalArms : canonicalSlots(arms);
79
+ if (repaired !== arms) {
80
+ if (operation === 'create') data = {
81
+ ...data,
82
+ arms: repaired
83
+ };
84
+ else data.arms = repaired;
85
+ }
67
86
  if (req.context.xpTransition === true) return data;
68
87
  const baseline = req.headers.get(XP_IF_UPDATED_AT_HEADER);
69
88
  if (operation === 'update' && baseline !== null) {
@@ -71,7 +90,7 @@ export const lockHook = async ({ data, originalDoc, operation, req })=>{
71
90
  // so a competing save observes the preceding save's committed timestamp.
72
91
  const stored = await lockExperimentUpdatedAt(txExecutor(req), originalDoc.id);
73
92
  if (stored === null || new Date(baseline).getTime() !== new Date(stored).getTime()) {
74
- throw new XpRefusal('stale-edit', 'Someone else changed this test. Reload to see their changes.', undefined, 409);
93
+ throw new XpRefusal('stale-edit', 'This test changed. Read the latest settings and try again.', undefined, 409);
75
94
  }
76
95
  }
77
96
  const admin = async ()=>{
@@ -139,7 +158,7 @@ export const lockHook = async ({ data, originalDoc, operation, req })=>{
139
158
  ].includes(field) && isObject(value)) {
140
159
  for (const [key, nested] of Object.entries(value))await check(`${field}.${key}`, nested, originalDoc[field]?.[key]);
141
160
  } else {
142
- await check(field, value, originalDoc[field]);
161
+ await check(field, value, field === 'arms' ? canonicalArms : originalDoc[field]);
143
162
  // Replacing the group also changes its method, including clearing it.
144
163
  if (field === 'analysis' && !same(value, originalDoc.analysis, field) && originalDoc.analysis?.method != null && !await admin()) throw new XpLockedFieldError('analysis.method', status);
145
164
  }
@@ -1,8 +1,10 @@
1
+ import { assertReadCommitted } from '../../db/adapter.js';
1
2
  import { pickSlug } from '../../db/slugs.js';
2
3
  import { pooledExecutor, txExecutor } from '../../db/executor.js';
3
4
  export const pickExperimentSlug = async ({ req, data, operation })=>{
4
5
  if (operation !== 'create' || typeof data.slug !== 'string' || !data.slug) return data;
5
6
  const transactional = await req.transactionID != null;
7
+ if (transactional) await assertReadCommitted(req);
6
8
  data.slug = await pickSlug(transactional ? txExecutor(req) : pooledExecutor(req.payload), data.slug, transactional);
7
9
  return data;
8
10
  };
@@ -1,3 +1,4 @@
1
+ import { assertReadCommitted } from '../db/adapter.js';
1
2
  import { pooledExecutor, txExecutor } from '../db/executor.js';
2
3
  import { findMetricUsage, lockMetricRow } from '../db/metricUsage.js';
3
4
  /** Payload's REST formatter preserves public plugin errors and their 4xx status. */ export class XpGoalInUseError extends Error {
@@ -8,6 +9,7 @@ import { findMetricUsage, lockMetricRow } from '../db/metricUsage.js';
8
9
  async function executor(req, id, mode) {
9
10
  const transactionID = await req.transactionID;
10
11
  if (transactionID != null) {
12
+ await assertReadCommitted(req);
11
13
  const exec = txExecutor(req);
12
14
  await lockMetricRow(exec, id, mode);
13
15
  return exec;
@@ -1,3 +1,4 @@
1
+ import { browserWritableMetric } from '../events/writable.js';
1
2
  export function serializeFlagPoints(options) {
2
3
  return (options.flagPoints ?? []).map(({ id, label, description, params, defaultParams })=>({
3
4
  id,
@@ -19,19 +20,19 @@ export function serializeMetricSources(options) {
19
20
  keyedBy: 'visitor',
20
21
  clientWritable: true
21
22
  },
22
- ...(options.metricSources ?? []).map(({ id, label, kind, keyedBy, clientWritable })=>({
23
+ ...(options.metricSources ?? []).map(({ id, label, kind, keyedBy })=>({
23
24
  id,
24
25
  label,
25
26
  kind,
26
27
  keyedBy,
27
- clientWritable: clientWritable === true
28
+ clientWritable: browserWritableMetric(id, options)
28
29
  })),
29
- ...(options.eventSources ?? []).map(({ name, clientWritable })=>({
30
+ ...(options.eventSources ?? []).map(({ name })=>({
30
31
  id: `events:${name}`,
31
32
  label: name,
32
33
  kind: 'binomial',
33
34
  keyedBy: 'visitor',
34
- clientWritable
35
+ clientWritable: browserWritableMetric(`events:${name}`, options)
35
36
  }))
36
37
  ];
37
38
  }
@@ -7,3 +7,4 @@ export declare const XP_PREVIEW_PARAM = "xp_preview";
7
7
  export declare const XP_MANIFEST_KEY_HEADER = "x-xp-manifest-key";
8
8
  export declare const XP_REQUEST_HEADER = "x-xp-request";
9
9
  export declare const XP_IF_UPDATED_AT_HEADER = "x-xp-if-updated-at";
10
+ export declare const USER_BROWSER_CONVERSION_PREFIX = "conversion:cu:";
package/dist/constants.js CHANGED
@@ -7,3 +7,4 @@ export const XP_PREVIEW_PARAM = 'xp_preview';
7
7
  export const XP_MANIFEST_KEY_HEADER = 'x-xp-manifest-key';
8
8
  export const XP_REQUEST_HEADER = 'x-xp-request';
9
9
  export const XP_IF_UPDATED_AT_HEADER = 'x-xp-if-updated-at';
10
+ export const USER_BROWSER_CONVERSION_PREFIX = 'conversion:cu:';
@@ -1,3 +1,11 @@
1
- import type { Payload } from 'payload';
1
+ import { APIError, type Payload, type PayloadRequest } from 'payload';
2
+ export declare class XpTransactionIsolationError extends APIError {
3
+ constructor();
4
+ }
5
+ /** Payload's initTransaction cannot pass options to the adapter. Like that
6
+ * helper, publish the pending transaction on the request before awaiting it.
7
+ */
8
+ export declare function initTransitionTransaction(req: PayloadRequest): Promise<boolean>;
9
+ export declare function assertReadCommitted(req: PayloadRequest): Promise<void>;
2
10
  export declare function assertPostgresAdapter(payload: Payload): void;
3
11
  export declare function probeTransactions(payload: Payload): Promise<void>;
@@ -1,3 +1,72 @@
1
+ import { APIError } from 'payload';
2
+ import { XpNoTransactionError } from '../errors.js';
3
+ import { API_MESSAGES } from '../testSurface/copy/common.js';
4
+ import { transactionSession, txExecutor } from './executor.js';
5
+ const transitionIsolation = 'read committed';
6
+ const isolationMessage = 'Experiments requires PostgreSQL READ COMMITTED so it can see changes committed while waiting for locks. Set the Postgres adapter\'s transactionOptions.isolationLevel to "read committed" or remove the override.';
7
+ const checkedSessions = new WeakMap();
8
+ export class XpTransactionIsolationError extends APIError {
9
+ constructor(){
10
+ super(API_MESSAGES.transactionIsolation, 500, null, true);
11
+ }
12
+ }
13
+ /** Payload's initTransaction cannot pass options to the adapter. Like that
14
+ * helper, publish the pending transaction on the request before awaiting it.
15
+ */ export async function initTransitionTransaction(req) {
16
+ if (req.transactionID != null) {
17
+ await req.transactionID;
18
+ return false;
19
+ }
20
+ const db = req.payload.db;
21
+ const pending = db.beginTransaction({
22
+ ...db.transactionOptions || {},
23
+ isolationLevel: transitionIsolation
24
+ }).then((id)=>{
25
+ if (id == null) throw new XpNoTransactionError();
26
+ const session = db.sessions?.[id];
27
+ if (session) checkedSessions.set(session, Promise.resolve());
28
+ req.transactionID = id;
29
+ return id;
30
+ });
31
+ req.transactionID = pending;
32
+ try {
33
+ await pending;
34
+ return true;
35
+ } catch (error) {
36
+ if (req.transactionID === pending) delete req.transactionID;
37
+ throw error;
38
+ }
39
+ }
40
+ /** A borrowed transaction may already have taken its snapshot. Check the
41
+ * effective isolation on that session before relying on a post-lock read.
42
+ */ async function isReadCommitted(exec) {
43
+ const { rows } = await exec.query('SHOW transaction_isolation');
44
+ const level = rows[0]?.transaction_isolation;
45
+ // PostgreSQL implements READ UNCOMMITTED as READ COMMITTED (docs §13.2).
46
+ return level === transitionIsolation || level === 'read uncommitted';
47
+ }
48
+ export async function assertReadCommitted(req) {
49
+ const transaction = {
50
+ payload: req.payload,
51
+ transactionID: await req.transactionID
52
+ };
53
+ // The adapter resolves the ID to a unique session object until commit or
54
+ // rollback. Cache the pending check so concurrent hooks share the same query.
55
+ const session = await transactionSession(transaction);
56
+ let checked = checkedSessions.get(session);
57
+ if (!checked) {
58
+ checked = isReadCommitted(txExecutor(transaction)).then((valid)=>{
59
+ if (!valid) {
60
+ try {
61
+ console.error('Experiments requires PostgreSQL READ COMMITTED so it can see changes committed while waiting for locks. Set the Postgres adapter\'s transactionOptions.isolationLevel to "read committed" or remove the override.');
62
+ } catch {}
63
+ throw new XpTransactionIsolationError();
64
+ }
65
+ });
66
+ checkedSessions.set(session, checked);
67
+ }
68
+ await checked;
69
+ }
1
70
  export function assertPostgresAdapter(payload) {
2
71
  // @payloadcms/db-postgres/dist/index.js:133 declares this package marker.
3
72
  if (payload.db.packageName !== '@payloadcms/db-postgres') throw new Error('Experiments requires @payloadcms/db-postgres');
@@ -5,5 +74,12 @@ export function assertPostgresAdapter(payload) {
5
74
  export async function probeTransactions(payload) {
6
75
  const id = await payload.db.beginTransaction();
7
76
  if (id == null) throw new Error('Experiments transactions are disabled');
8
- await payload.db.rollbackTransaction(id);
77
+ try {
78
+ if (!await isReadCommitted(txExecutor({
79
+ payload,
80
+ transactionID: id
81
+ }))) throw new Error(isolationMessage);
82
+ } finally{
83
+ await payload.db.rollbackTransaction(id);
84
+ }
9
85
  }
@@ -24,6 +24,19 @@ type AppendArgs<T> = {
24
24
  * before the audit savepoint can recover.
25
25
  */
26
26
  export declare function storedContent(req: PayloadRequest, collection: string, id: DocId): Promise<Record<string, unknown> | undefined>;
27
+ export interface PlacementSavePath {
28
+ versionId?: DocId;
29
+ bulk?: boolean;
30
+ draft?: boolean;
31
+ trashing?: boolean;
32
+ publishSpecificLocale?: string;
33
+ }
34
+ /** Payload 3.90.2: updateByID starts from the latest version; update (bulk)
35
+ * starts from main rows except draft/trash saves. utilities/update then replaces
36
+ * unselected locales with the latest published version (publishSpecificLocale).
37
+ * Localized publication status is refused at init. Restore uses the selected version. */
38
+ export declare function placementMergeBase(path: PlacementSavePath): 'restore' | 'main' | 'published' | 'latest';
39
+ export declare function placementWriteContent(req: PayloadRequest, collection: string, id: DocId, main: Record<string, unknown> | undefined, path?: PlacementSavePath): Promise<Record<string, unknown> | undefined>;
27
40
  /** Read the main collection row BEFORE the host write. Draft version retention
28
41
  * and unpublishing cannot remove this baseline.
29
42
  */
@@ -18,6 +18,55 @@ import { qualifiedTable, quoteIdentifier as quote } from './sql.js';
18
18
  });
19
19
  return doc ?? undefined;
20
20
  }
21
+ /** Payload 3.90.2: updateByID starts from the latest version; update (bulk)
22
+ * starts from main rows except draft/trash saves. utilities/update then replaces
23
+ * unselected locales with the latest published version (publishSpecificLocale).
24
+ * Localized publication status is refused at init. Restore uses the selected version. */ export function placementMergeBase(path) {
25
+ if (path.versionId != null) return 'restore';
26
+ if (path.publishSpecificLocale) return 'published';
27
+ return path.bulk && !path.draft && !path.trashing ? 'main' : 'latest';
28
+ }
29
+ export async function placementWriteContent(req, collection, id, main, path = {}) {
30
+ const config = req.payload.config.collections?.find((entry)=>entry.slug === collection);
31
+ if (!config?.versions || !config.versions.drafts) return main;
32
+ const base = placementMergeBase(path);
33
+ if (base === 'main') return main;
34
+ // Adapter read on the guarded write's transaction; no Local API hook recursion.
35
+ const latest = await req.payload.db.findVersions({
36
+ collection,
37
+ req,
38
+ limit: 1,
39
+ pagination: false,
40
+ sort: '-updatedAt',
41
+ where: base === 'restore' ? {
42
+ id: {
43
+ equals: path.versionId
44
+ }
45
+ } : {
46
+ and: [
47
+ {
48
+ parent: {
49
+ equals: id
50
+ }
51
+ },
52
+ base === 'published' ? {
53
+ 'version._status': {
54
+ equals: 'published'
55
+ }
56
+ } : {
57
+ latest: {
58
+ equals: true
59
+ }
60
+ }
61
+ ]
62
+ },
63
+ overrideAccess: false
64
+ });
65
+ return latest.docs[0] ? {
66
+ ...latest.docs[0].version,
67
+ id
68
+ } : base === 'published' ? undefined : main;
69
+ }
21
70
  /** Read the main collection row BEFORE the host write. Draft version retention
22
71
  * and unpublishing cannot remove this baseline.
23
72
  */ export async function previousPublishedContent(req, collection, id) {
@@ -1,4 +1,4 @@
1
- import { removedPlacementViews, placementDocumentKey } from '../blocks/placementLocale.js';
1
+ import { placementLocaleContent, mergedPlacementLocales, removedPlacementViews, placementDocumentKey } from '../blocks/placementLocale.js';
2
2
  // Payload starts/ends a transaction per bulk document with this adapter option.
3
3
  export function usesBulkDocumentTransactions(req) {
4
4
  return req.payload.db.bulkOperationsSingleTransaction === true;
@@ -98,10 +98,14 @@ const operationRequestState = Symbol('xpPlacementRequestState');
98
98
  collection,
99
99
  String(doc.id)
100
100
  ]))) return false;
101
- const after = {
102
- ...doc,
101
+ // locale=all data and the adapter row share the same all-language shape.
102
+ // A single-locale write instead merges its flattened values once.
103
+ const input = req.locale === 'all' ? 'all-locales' : 'localized';
104
+ const pending = {
105
+ ...input === 'all-locales' ? doc : placementLocaleContent(req, collection, doc, 'all-locales'),
103
106
  ...change.data
104
107
  };
105
- const views = removedPlacementViews(req, collection, doc, after, change.deleting || after.deletedAt != null || after._status === 'draft');
108
+ const after = input === 'all-locales' ? pending : mergedPlacementLocales(req, collection, doc, pending);
109
+ const views = removedPlacementViews(req, collection, doc, after, change.deleting || after.deletedAt != null || after._status === 'draft', 'all-locales');
106
110
  return (views.get(slug) ?? []).some((removed)=>placementDocumentKey(collection, doc.id, removed) === placementDocumentKey(collection, doc.id, view));
107
111
  }
@@ -1,6 +1,6 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { DocId } from '../types/contracts.js';
3
- import type { Executor } from './executor.js';
3
+ import { type Executor } from './executor.js';
4
4
  interface DeleteState {
5
5
  tail: Promise<void>;
6
6
  retiredSlugs: Set<string>;
package/dist/db/delete.js CHANGED
@@ -1,4 +1,4 @@
1
- import { XpNoTransactionError } from '../errors.js';
1
+ import { transactionSession } from './executor.js';
2
2
  import { COLUMNS, TABLES } from './names.js';
3
3
  import { qualifiedTable, quoteIdentifier as quote } from './sql.js';
4
4
  // Key by the actual session: borrowed requests in one transaction share a queue,
@@ -9,9 +9,7 @@ const transactions = new WeakMap();
9
9
  * Successful beforeDelete bodies retain exclusions until the transaction ends:
10
10
  * another row can be between hooks with its children gone but its row present.
11
11
  */ export async function serializeDelete(req, fn) {
12
- const id = await req.transactionID;
13
- const session = id == null ? undefined : req.payload.db.sessions?.[id];
14
- if (!session) throw new XpNoTransactionError();
12
+ const session = await transactionSession(req);
15
13
  let state = transactions.get(session);
16
14
  if (!state) {
17
15
  state = {
@@ -17,5 +17,14 @@ export interface EventRow {
17
17
  attributes?: Record<string, unknown>;
18
18
  dedupeKey: string;
19
19
  }
20
+ type ServerConversion = Pick<EventRow, 'unitId' | 'unitType' | 'userId' | 'ts'> & {
21
+ eventName: string;
22
+ value: number;
23
+ idempotencyKey: string;
24
+ };
25
+ /** A retained legacy row suppresses retries for its event name. The scoped key's
26
+ * unique index handles concurrent writes after the old writers have been drained. */
27
+ export declare function insertServerConversion(exec: Executor, event: ServerConversion, log: (message: string) => void): Promise<void>;
20
28
  /** Pooled/autocommit executor required: an FK failure must not poison a caller's transaction. */
21
29
  export declare function insertEvents(exec: Executor, rows: EventRow[], log?: (message: string) => void): Promise<number>;
30
+ export {};
package/dist/db/events.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { exposureDimensions } from '../events/dimensions.js';
2
3
  import { COLUMNS, TABLES } from './names.js';
3
4
  import { qualifiedTable, quoteIdentifier } from './sql.js';
@@ -6,7 +7,7 @@ import { qualifiedTable, quoteIdentifier } from './sql.js';
6
7
  experimentId
7
8
  ]);
8
9
  }
9
- const quote = (name)=>`"${name.replaceAll('"', '""')}"`;
10
+ const quote = quoteIdentifier;
10
11
  const c = COLUMNS.events;
11
12
  function foreignKeyViolation(error) {
12
13
  const seen = new Set();
@@ -28,15 +29,48 @@ function foreignKeyViolation(error) {
28
29
  return null;
29
30
  }
30
31
  }
32
+ function hasFiniteValue(value, log) {
33
+ if (value === undefined || Number.isFinite(value)) return true;
34
+ log('Experiments: dropped event with non-finite value');
35
+ return false;
36
+ }
37
+ /** A retained legacy row suppresses retries for its event name. The scoped key's
38
+ * unique index handles concurrent writes after the old writers have been drained. */ export async function insertServerConversion(exec, event, log) {
39
+ if (!hasFiniteValue(event.value, log)) return;
40
+ const table = qualifiedTable(exec, TABLES.events);
41
+ const digest = createHash('sha256').update(JSON.stringify([
42
+ event.eventName,
43
+ event.idempotencyKey
44
+ ])).digest('hex');
45
+ await exec.query(`INSERT INTO ${table} (${[
46
+ c.type,
47
+ c.unitId,
48
+ c.unitType,
49
+ c.userId,
50
+ c.eventName,
51
+ c.value,
52
+ c.ts,
53
+ c.dedupeKey,
54
+ c.createdAt,
55
+ c.updatedAt
56
+ ].map(quote).join(', ')})
57
+ SELECT 'conversion', $1, $2, $3, $4, $5, $6, $7, now(), now()
58
+ WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE ${quote(c.dedupeKey)} = $8 AND ${quote(c.eventName)} = $4)
59
+ ON CONFLICT (${quote(c.dedupeKey)}) DO NOTHING`, [
60
+ event.unitId,
61
+ event.unitType,
62
+ event.userId ?? null,
63
+ event.eventName,
64
+ event.value,
65
+ event.ts,
66
+ `conversion:s2:${digest}`,
67
+ `conversion:s:${event.idempotencyKey}`
68
+ ]);
69
+ }
31
70
  /** Pooled/autocommit executor required: an FK failure must not poison a caller's transaction. */ export async function insertEvents(exec, rows, log = console.error) {
32
- const valid = rows.filter((row)=>{
33
- if (row.value === undefined || Number.isFinite(row.value)) return true;
34
- log('Experiments: dropped event with non-finite value');
35
- return false;
36
- });
71
+ const valid = rows.filter((row)=>hasFiniteValue(row.value, log));
37
72
  if (!valid.length) return 0;
38
- const schema = exec.schemaName;
39
- const table = `${schema ? `${quote(schema)}.` : ''}${quote(TABLES.events)}`;
73
+ const table = qualifiedTable(exec, TABLES.events);
40
74
  async function insert(batch) {
41
75
  const params = [];
42
76
  const values = batch.map((row)=>{
@@ -2,7 +2,13 @@ import type { Payload, PayloadRequest } from 'payload';
2
2
  import type { Executor } from './pgExecutor.js';
3
3
  export type { Executor } from './pgExecutor.js';
4
4
  export { pgPoolExecutor, ownConnection, withStatementTimeout, raceDeadline, ResultsBudgetError, RESULTS_TIMEOUT_MARGIN_MS } from './pgExecutor.js';
5
- export declare function txExecutor(req: PayloadRequest): Executor & {
5
+ type TransactionRequest = Pick<PayloadRequest, 'payload' | 'transactionID'>;
6
+ export declare function transactionSession(req: TransactionRequest): Promise<{
7
+ db: unknown;
8
+ reject: () => Promise<void>;
9
+ resolve: () => Promise<void>;
10
+ }>;
11
+ export declare function txExecutor(req: TransactionRequest): Executor & {
6
12
  schemaName?: string;
7
13
  };
8
14
  export declare function pooledExecutor(payload: Payload): Executor & {
@@ -14,14 +14,18 @@ export { pgPoolExecutor, ownConnection, withStatementTimeout, raceDeadline, Resu
14
14
  chunks.push(sql.raw(text.slice(start)));
15
15
  return sql.join(chunks, sql.raw(''));
16
16
  }
17
+ export async function transactionSession(req) {
18
+ const id = await req.transactionID;
19
+ const session = id == null ? undefined : req.payload.db.sessions?.[id];
20
+ if (!session) throw new XpNoTransactionError();
21
+ return session;
22
+ }
17
23
  export function txExecutor(req) {
18
24
  const db = req.payload.db;
19
25
  return {
20
26
  schemaName: db.schemaName,
21
27
  async query (text, params = []) {
22
- const id = await req.transactionID;
23
- const session = id == null ? undefined : db.sessions?.[id];
24
- if (!session) throw new XpNoTransactionError();
28
+ const session = await transactionSession(req);
25
29
  return normalise(await session.db.execute(bind(text, params)));
26
30
  }
27
31
  };
@@ -5,6 +5,7 @@ export interface PhaseExposureRow {
5
5
  unitId: string;
6
6
  arm: string;
7
7
  ts: number;
8
+ unitAgeMs?: number;
8
9
  }
9
10
  export interface RolloutExposureRow {
10
11
  unitId: string;
@@ -16,6 +17,7 @@ export interface MetricEventRow {
16
17
  userId: string | null;
17
18
  value: number;
18
19
  ts: number;
20
+ unitAgeMs?: number;
19
21
  }
20
22
  export interface IdentityRow {
21
23
  anonymousId: string;
@@ -41,12 +43,14 @@ export declare function rolloutExposureRows(exec: Executor, { experimentId, resp
41
43
  * or userIds for stored user_id (user units and visitor identity credit). Each distinct
42
44
  * ID occurs in one ANY array of at most 10,000, so batching cannot duplicate rows.
43
45
  */
44
- export declare function metricEventRows(exec: Executor, { eventName, unitIds, userIds, from, to }: {
46
+ export declare function metricEventRows(exec: Executor, { eventName, unitIds, userIds, from, to, readAge, forVisitors }: {
45
47
  eventName: string;
46
48
  unitIds?: readonly string[];
47
49
  userIds?: readonly string[];
48
50
  from: Timestamp;
49
51
  to: Timestamp;
52
+ readAge?: boolean;
53
+ forVisitors?: boolean;
50
54
  }): Promise<MetricEventRow[]>;
51
55
  /** Linked visitors for creditUserEvents; disjoint ANY batches of ≤ 10,000 IDs. */
52
56
  export declare function identityRows(exec: Executor, { anonymousIds }: {
@@ -1,11 +1,22 @@
1
1
  import { timestampMs } from '../results/aggregate.js';
2
2
  import { COLUMNS, TABLES } from './names.js';
3
+ import { USER_BROWSER_CONVERSION_PREFIX } from '../constants.js';
3
4
  import { qualifiedTable, quoteIdentifier as q } from './sql.js';
4
5
  const c = COLUMNS.events;
5
6
  const batchSize = 10_000;
6
7
  const iso = (ts)=>new Date(timestampMs(ts)).toISOString();
7
8
  // round()::bigint keeps exact milliseconds on servers where extract() returns a float (PG ≤ 13).
8
9
  const epochMs = `round(extract(epoch from ${q(c.ts)}) * 1000)::bigint`;
10
+ const signedAge = `${q(c.attributes)}->'_xp'->'unitAgeMs' AS "unitAgeMs"`;
11
+ function knownAge(unitAgeMs) {
12
+ // A reissued legacy ID counts as known and older than the rapid activity window.
13
+ if (unitAgeMs === 'legacy') return {
14
+ unitAgeMs: Infinity
15
+ };
16
+ return typeof unitAgeMs === 'number' && Number.isSafeInteger(unitAgeMs) && unitAgeMs >= 0 ? {
17
+ unitAgeMs
18
+ } : {};
19
+ }
9
20
  function phaseFilter({ experimentId, phase, endedAt }, type) {
10
21
  const params = [
11
22
  experimentId,
@@ -24,11 +35,12 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
24
35
  }
25
36
  /** All phase exposures, including multi-arm rows for firstExposures to exclude. */ export async function phaseExposureRows(exec, opts) {
26
37
  const filter = phaseFilter(opts, 'exposure');
27
- const { rows } = await exec.query(`SELECT ${q(c.unitId)} AS "unitId", ${q(c.arm)} AS "arm", ${epochMs} AS "ts" FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${filter.text} ORDER BY ${q(c.ts)}, ${q(c.unitId)}`, filter.params);
38
+ const { rows } = await exec.query(`SELECT ${q(c.unitId)} AS "unitId", ${q(c.arm)} AS "arm", ${epochMs} AS "ts", ${signedAge} FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${filter.text} ORDER BY ${q(c.ts)}, ${q(c.unitId)}`, filter.params);
28
39
  return rows.map((row)=>({
29
40
  unitId: row.unitId,
30
41
  arm: row.arm,
31
- ts: Number(row.ts)
42
+ ts: Number(row.ts),
43
+ ...knownAge(row.unitAgeMs)
32
44
  }));
33
45
  }
34
46
  /** Diagnostic distinct units only; this never contributes to multi-arm exclusion. */ export async function armMismatchCount(exec, opts) {
@@ -52,7 +64,7 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
52
64
  /** events:<name> conversion rows in [from, to). Choose unitIds for stored unit_id,
53
65
  * or userIds for stored user_id (user units and visitor identity credit). Each distinct
54
66
  * ID occurs in one ANY array of at most 10,000, so batching cannot duplicate rows.
55
- */ export async function metricEventRows(exec, { eventName, unitIds, userIds, from, to }) {
67
+ */ export async function metricEventRows(exec, { eventName, unitIds, userIds, from, to, readAge = false, forVisitors = false }) {
56
68
  if (unitIds !== undefined && userIds !== undefined) throw new RangeError('Choose unitIds or userIds');
57
69
  const params = [
58
70
  'conversion',
@@ -60,7 +72,10 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
60
72
  iso(from),
61
73
  iso(to)
62
74
  ];
63
- const text = `SELECT ${q(c.unitId)} AS "unitId", ${q(c.userId)} AS "userId", ${q(c.value)} AS "value", ${epochMs} AS "ts" FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${q(c.type)} = $1 AND ${q(c.eventName)} = $2 AND ${q(c.ts)} >= $3 AND ${q(c.ts)} < $4`;
75
+ // A browser conversion without a visitor cookie cannot count for a visitor,
76
+ // even through the separate linked-user lookup.
77
+ const visitorFilter = forVisitors ? ` AND ${q(c.dedupeKey)} NOT LIKE '${USER_BROWSER_CONVERSION_PREFIX}%'` : '';
78
+ const text = `SELECT ${q(c.unitId)} AS "unitId", ${q(c.userId)} AS "userId", ${q(c.value)} AS "value", ${epochMs} AS "ts"${readAge ? `, ${signedAge}` : ''} FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${q(c.type)} = $1 AND ${q(c.eventName)} = $2 AND ${q(c.ts)} >= $3 AND ${q(c.ts)} < $4${visitorFilter}`;
64
79
  const filterIds = userIds ?? unitIds;
65
80
  const column = userIds === undefined ? c.unitId : c.userId;
66
81
  const ids = filterIds === undefined ? undefined : [
@@ -77,7 +92,8 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
77
92
  unitId: row.unitId,
78
93
  userId: row.userId == null ? null : String(row.userId),
79
94
  value: Number(row.value),
80
- ts: Number(row.ts)
95
+ ts: Number(row.ts),
96
+ ...knownAge(row.unitAgeMs)
81
97
  });
82
98
  }
83
99
  if (ids === undefined) break;
@@ -13,6 +13,7 @@ export interface ResultsPhase extends AnalysisPhase {
13
13
  addedAt?: string;
14
14
  keyedBy?: UnitType;
15
15
  capNotice?: 'no-history';
16
+ browserWritable?: boolean;
16
17
  }>;
17
18
  }
18
19
  export interface ResultsCandidate {
@@ -0,0 +1,6 @@
1
+ import { type PayloadRequest } from 'payload';
2
+ /** Validate advisory-read metadata language; placement discovery still scans all languages. */
3
+ export declare function contentLocale(req: PayloadRequest): {
4
+ locale: string | null | undefined;
5
+ fallbackLocale: false | "none" | "false" | "null" | ({} & string) | ({} & string)[] | null | undefined;
6
+ };
@@ -0,0 +1,15 @@
1
+ import { sanitizeFallbackLocale } from 'payload';
2
+ /** Validate advisory-read metadata language; placement discovery still scans all languages. */ export function contentLocale(req) {
3
+ const localization = req.payload.config.localization;
4
+ const requested = new URL(req.url ?? 'http://xp.invalid').searchParams.get('locale') ?? req.locale;
5
+ const locale = localization ? localization.localeCodes.includes(requested ?? '') ? requested : localization.defaultLocale : undefined;
6
+ const fallbackLocale = localization ? sanitizeFallbackLocale({
7
+ fallbackLocale: req.fallbackLocale ?? null,
8
+ locale: locale,
9
+ localization
10
+ }) : req.fallbackLocale;
11
+ return {
12
+ locale,
13
+ fallbackLocale
14
+ };
15
+ }