@delmaredigital/payload-experiments 0.4.1 → 0.5.1

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 (310) hide show
  1. package/README.md +9 -5
  2. package/dist/admin/blocks/model.js +2 -0
  3. package/dist/admin/copy/blocks.d.ts +1 -0
  4. package/dist/admin/copy/blocks.js +1 -0
  5. package/dist/admin/copy/status.d.ts +3 -0
  6. package/dist/admin/copy/status.js +3 -0
  7. package/dist/admin/placementStatus.model.js +3 -0
  8. package/dist/admin/status.model.d.ts +3 -2
  9. package/dist/admin/status.model.js +9 -3
  10. package/dist/admin/surface/ResultsRoute.js +2 -1
  11. package/dist/admin/surface/TestsHome.d.ts +2 -1
  12. package/dist/admin/surface/TestsHome.js +31 -11
  13. package/dist/admin/surface/TestsSurface.js +4 -0
  14. package/dist/admin/surface/home.model.d.ts +11 -6
  15. package/dist/admin/surface/home.model.js +19 -8
  16. package/dist/admin/surface/newTest/PageWizard.js +13 -3
  17. package/dist/admin/surface/results/ResultsHeader.js +43 -9
  18. package/dist/admin/surface/test/TestPage.js +11 -1
  19. package/dist/admin/useLayerUsage.d.ts +1 -1
  20. package/dist/admin/views/buildSurfaceProps.js +3 -0
  21. package/dist/blocks/placementLocale.d.ts +14 -0
  22. package/dist/blocks/placementLocale.js +80 -13
  23. package/dist/blocks/placementPublication.d.ts +14 -0
  24. package/dist/blocks/placementPublication.js +24 -0
  25. package/dist/cohorts/build.d.ts +35 -0
  26. package/dist/cohorts/build.js +134 -0
  27. package/dist/cohorts/key.d.ts +12 -0
  28. package/dist/cohorts/key.js +15 -0
  29. package/dist/cohorts/maintenance.d.ts +10 -0
  30. package/dist/cohorts/maintenance.js +70 -0
  31. package/dist/cohorts/readiness.d.ts +30 -0
  32. package/dist/cohorts/readiness.js +54 -0
  33. package/dist/cohorts/readinessData.d.ts +29 -0
  34. package/dist/cohorts/readinessData.js +123 -0
  35. package/dist/cohorts/rule.d.ts +33 -0
  36. package/dist/cohorts/rule.js +50 -0
  37. package/dist/collections/cohortMembers.d.ts +4 -0
  38. package/dist/collections/cohortMembers.js +95 -0
  39. package/dist/collections/experiments/config.js +157 -7
  40. package/dist/collections/experiments/editability.js +10 -6
  41. package/dist/collections/experiments/lockHook.js +39 -20
  42. package/dist/collections/index.js +4 -1
  43. package/dist/collections/phases.js +4 -1
  44. package/dist/constants.d.ts +2 -0
  45. package/dist/constants.js +2 -0
  46. package/dist/db/adapter.d.ts +2 -1
  47. package/dist/db/adapter.js +17 -4
  48. package/dist/db/appends.d.ts +2 -1
  49. package/dist/db/appends.js +3 -2
  50. package/dist/db/bulkPlacementRemoval.d.ts +5 -0
  51. package/dist/db/bulkPlacementRemoval.js +7 -2
  52. package/dist/db/cohortMembership.d.ts +11 -0
  53. package/dist/db/cohortMembership.js +31 -0
  54. package/dist/db/cohortPool.d.ts +9 -0
  55. package/dist/db/cohortPool.js +53 -0
  56. package/dist/db/cohortTransactions.d.ts +3 -0
  57. package/dist/db/cohortTransactions.js +52 -0
  58. package/dist/db/cohorts.d.ts +72 -0
  59. package/dist/db/cohorts.js +280 -0
  60. package/dist/db/erase.d.ts +2 -0
  61. package/dist/db/erase.js +21 -2
  62. package/dist/db/events.d.ts +2 -0
  63. package/dist/db/events.js +8 -0
  64. package/dist/db/executor.d.ts +2 -0
  65. package/dist/db/executor.js +8 -0
  66. package/dist/db/locks.d.ts +7 -0
  67. package/dist/db/locks.js +13 -1
  68. package/dist/db/names.d.ts +95 -1
  69. package/dist/db/names.js +95 -1
  70. package/dist/db/occupancy.d.ts +21 -0
  71. package/dist/db/occupancy.js +46 -0
  72. package/dist/db/pageBindings.d.ts +2 -2
  73. package/dist/db/pageBindings.js +3 -3
  74. package/dist/db/pageOccupancy.d.ts +4 -4
  75. package/dist/db/pageOccupancy.js +13 -10
  76. package/dist/db/pgExecutor.d.ts +4 -0
  77. package/dist/db/pgExecutor.js +1 -1
  78. package/dist/db/placements.d.ts +6 -1
  79. package/dist/db/placements.js +27 -1
  80. package/dist/db/results.d.ts +5 -2
  81. package/dist/db/results.js +32 -5
  82. package/dist/db/slices.d.ts +9 -2
  83. package/dist/db/slices.js +15 -8
  84. package/dist/db/snapshots.d.ts +16 -1
  85. package/dist/db/snapshots.js +27 -2
  86. package/dist/db/sql.d.ts +2 -2
  87. package/dist/db/sql.js +1 -2
  88. package/dist/endpoints/cohortSources.d.ts +16 -0
  89. package/dist/endpoints/cohortSources.js +335 -0
  90. package/dist/endpoints/contentLocale.d.ts +1 -1
  91. package/dist/endpoints/duplicateOriginal.d.ts +1 -0
  92. package/dist/endpoints/events.js +82 -18
  93. package/dist/endpoints/index.js +45 -1
  94. package/dist/endpoints/pausedBy.d.ts +14 -0
  95. package/dist/endpoints/pausedBy.js +94 -0
  96. package/dist/endpoints/preflight.js +4 -1
  97. package/dist/endpoints/previewToken.js +2 -0
  98. package/dist/endpoints/results.d.ts +2 -2
  99. package/dist/endpoints/results.js +111 -3
  100. package/dist/endpoints/routeId.d.ts +2 -1
  101. package/dist/endpoints/routeId.js +6 -2
  102. package/dist/endpoints/summary.js +24 -1
  103. package/dist/endpoints/transitions.d.ts +7 -0
  104. package/dist/endpoints/transitions.js +50 -1
  105. package/dist/events/rows.d.ts +1 -1
  106. package/dist/events/rows.js +5 -3
  107. package/dist/exports/index.d.ts +2 -0
  108. package/dist/exports/index.js +1 -0
  109. package/dist/exports/runtimeProxy.d.ts +1 -0
  110. package/dist/exports/runtimeProxy.js +1 -0
  111. package/dist/hooks/blockRemovalRule.d.ts +1 -1
  112. package/dist/hooks/blockRemovalRule.js +12 -8
  113. package/dist/hooks/pageGuard.d.ts +7 -1
  114. package/dist/hooks/pageGuard.js +177 -4
  115. package/dist/hooks/puckNestedTests.d.ts +1 -1
  116. package/dist/hooks/puckNestedTests.js +3 -1
  117. package/dist/labels/status.d.ts +15 -0
  118. package/dist/labels/status.js +12 -0
  119. package/dist/manifest/compile.d.ts +15 -4
  120. package/dist/manifest/compile.js +91 -3
  121. package/dist/onInit.js +4 -6
  122. package/dist/options.d.ts +1 -0
  123. package/dist/options.js +10 -0
  124. package/dist/proxy/consentFallback.d.ts +1 -1
  125. package/dist/proxy/consentFallback.js +4 -4
  126. package/dist/proxy/control.d.ts +1 -1
  127. package/dist/proxy/control.js +2 -2
  128. package/dist/proxy/pageRewrite.d.ts +1 -1
  129. package/dist/proxy/pageRewrite.js +3 -2
  130. package/dist/proxy/resolve.js +76 -17
  131. package/dist/puck/ExperimentPicker.js +2 -1
  132. package/dist/puck/copy.d.ts +6 -5
  133. package/dist/puck/copy.js +3 -7
  134. package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
  135. package/dist/puck/editor/QuickTestActions.js +7 -1
  136. package/dist/puck/editor/armWrites.js +6 -1
  137. package/dist/puck/editor/copy.d.ts +3 -0
  138. package/dist/puck/editor/copy.js +3 -0
  139. package/dist/puck/editor/editor.css +2 -1
  140. package/dist/puck/editor/editor.model.d.ts +2 -1
  141. package/dist/puck/editor/editor.model.js +2 -0
  142. package/dist/puck/editor/placementsCache.d.ts +1 -1
  143. package/dist/puck/editor/placementsCache.js +6 -3
  144. package/dist/results/analyse.d.ts +3 -1
  145. package/dist/results/analyse.js +20 -3
  146. package/dist/results/health.d.ts +11 -0
  147. package/dist/results/health.js +38 -0
  148. package/dist/results/power.d.ts +1 -1
  149. package/dist/results/power.js +1 -1
  150. package/dist/results/snapshot.d.ts +8 -2
  151. package/dist/results/snapshot.js +23 -1
  152. package/dist/results/unitValues.d.ts +48 -0
  153. package/dist/results/unitValues.js +166 -0
  154. package/dist/runtime/assign.d.ts +7 -3
  155. package/dist/runtime/assign.js +12 -4
  156. package/dist/runtime/cohortCookie.d.ts +15 -0
  157. package/dist/runtime/cohortCookie.js +72 -0
  158. package/dist/runtime/cohortLookup.d.ts +9 -0
  159. package/dist/runtime/cohortLookup.js +25 -0
  160. package/dist/runtime/eligibility.d.ts +11 -5
  161. package/dist/runtime/eligibility.js +33 -7
  162. package/dist/runtime/header.d.ts +1 -0
  163. package/dist/runtime/header.js +1 -1
  164. package/dist/runtime/proxyRuntime.js +5 -1
  165. package/dist/runtime/targeting.d.ts +3 -2
  166. package/dist/runtime/targeting.js +2 -1
  167. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  168. package/dist/sanitizeReadinessDetail.js +41 -4
  169. package/dist/schedule/activeTime.d.ts +28 -0
  170. package/dist/schedule/activeTime.js +322 -0
  171. package/dist/schedule/ranges.d.ts +13 -0
  172. package/dist/schedule/ranges.js +11 -0
  173. package/dist/schedule/roundTime.d.ts +10 -0
  174. package/dist/schedule/roundTime.js +45 -0
  175. package/dist/schedule/types.d.ts +29 -0
  176. package/dist/schedule/types.js +1 -0
  177. package/dist/server/cohortLookup.d.ts +3 -0
  178. package/dist/server/cohortLookup.js +7 -0
  179. package/dist/server/eraseUser.d.ts +1 -0
  180. package/dist/server/getAssignments.js +63 -40
  181. package/dist/server/previewDraft.d.ts +1 -1
  182. package/dist/server/previewDraft.js +3 -2
  183. package/dist/server/recordContentChange.d.ts +1 -1
  184. package/dist/server/recordContentChange.js +42 -20
  185. package/dist/server/recordExposures.js +4 -2
  186. package/dist/server/runResults.js +97 -150
  187. package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
  188. package/dist/testSurface/actions/LifecycleAction.js +15 -5
  189. package/dist/testSurface/actions/actions.model.d.ts +13 -2
  190. package/dist/testSurface/actions/actions.model.js +38 -5
  191. package/dist/testSurface/api.d.ts +13 -1
  192. package/dist/testSurface/api.js +19 -0
  193. package/dist/testSurface/copy/actions.d.ts +13 -0
  194. package/dist/testSurface/copy/actions.js +13 -0
  195. package/dist/testSurface/copy/cohorts.d.ts +68 -0
  196. package/dist/testSurface/copy/cohorts.js +81 -0
  197. package/dist/testSurface/copy/common.d.ts +2 -3
  198. package/dist/testSurface/copy/common.js +4 -4
  199. package/dist/testSurface/copy/inputs.d.ts +3 -0
  200. package/dist/testSurface/copy/inputs.js +3 -0
  201. package/dist/testSurface/copy/readiness.d.ts +20 -6
  202. package/dist/testSurface/copy/readiness.js +42 -9
  203. package/dist/testSurface/copy/results.d.ts +1 -0
  204. package/dist/testSurface/copy/results.js +1 -0
  205. package/dist/testSurface/copy/schedule.d.ts +58 -0
  206. package/dist/testSurface/copy/schedule.js +150 -0
  207. package/dist/testSurface/copy/surface.d.ts +2 -0
  208. package/dist/testSurface/copy/surface.js +2 -0
  209. package/dist/testSurface/copy/testPage.d.ts +12 -2
  210. package/dist/testSurface/copy/testPage.js +17 -2
  211. package/dist/testSurface/format/roundProgress.d.ts +13 -1
  212. package/dist/testSurface/format/roundProgress.js +34 -5
  213. package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
  214. package/dist/testSurface/format/scheduleStatus.js +93 -0
  215. package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
  216. package/dist/testSurface/format/useScheduleClock.js +20 -0
  217. package/dist/testSurface/labels.d.ts +4 -9
  218. package/dist/testSurface/labels.js +2 -7
  219. package/dist/testSurface/lockedNotice.model.d.ts +2 -2
  220. package/dist/testSurface/lockedNotice.model.js +16 -3
  221. package/dist/testSurface/readPreflight.d.ts +3 -0
  222. package/dist/testSurface/readPreflight.js +14 -0
  223. package/dist/testSurface/readinessRead.d.ts +2 -2
  224. package/dist/testSurface/results/DataQualityPanel.js +7 -7
  225. package/dist/testSurface/results/results.model.d.ts +1 -1
  226. package/dist/testSurface/results/results.model.js +34 -6
  227. package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
  228. package/dist/testSurface/review/cohortEstimate.js +32 -0
  229. package/dist/testSurface/surface/contracts.d.ts +2 -1
  230. package/dist/testSurface/surface/contracts.js +1 -0
  231. package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
  232. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
  233. package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
  234. package/dist/testSurface/surface/readiness/Banner.js +29 -11
  235. package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
  236. package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
  237. package/dist/testSurface/surface/readiness/useTransition.js +17 -5
  238. package/dist/testSurface/surface/results/ResultsBody.js +44 -8
  239. package/dist/testSurface/surface/results/useResults.d.ts +16 -1
  240. package/dist/testSurface/surface/results/useResults.js +17 -6
  241. package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
  242. package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
  243. package/dist/testSurface/surface/test/LengthSection.js +26 -6
  244. package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
  245. package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
  246. package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
  247. package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
  248. package/dist/testSurface/surface/test/Section.js +1 -1
  249. package/dist/testSurface/surface/test/TargetingSection.js +306 -182
  250. package/dist/testSurface/surface/test/TestSurface.js +9 -0
  251. package/dist/testSurface/surface/test/fields.d.ts +2 -1
  252. package/dist/testSurface/surface/test/fields.js +3 -3
  253. package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
  254. package/dist/testSurface/surface/test/jumpToSection.js +4 -4
  255. package/dist/testSurface/surface/test/testPage.css +26 -0
  256. package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
  257. package/dist/testSurface/surface/testDocument.model.js +2 -1
  258. package/dist/testSurface/surface/useTestDocument.js +11 -4
  259. package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
  260. package/dist/testSurface/targeting/targeting.model.js +1 -1
  261. package/dist/testSurface/useApi.d.ts +12 -0
  262. package/dist/transitions/addMetric.js +5 -2
  263. package/dist/transitions/allocate.js +6 -1
  264. package/dist/transitions/assertNoOverlap.d.ts +9 -0
  265. package/dist/transitions/assertNoOverlap.js +24 -0
  266. package/dist/transitions/buildCohorts.d.ts +10 -0
  267. package/dist/transitions/buildCohorts.js +68 -0
  268. package/dist/transitions/cancelSchedule.d.ts +4 -0
  269. package/dist/transitions/cancelSchedule.js +42 -0
  270. package/dist/transitions/checkStart.d.ts +17 -3
  271. package/dist/transitions/checkStart.js +20 -7
  272. package/dist/transitions/decide.js +40 -13
  273. package/dist/transitions/kernel.d.ts +3 -1
  274. package/dist/transitions/kernel.js +5 -2
  275. package/dist/transitions/pause.d.ts +4 -0
  276. package/dist/transitions/pause.js +35 -0
  277. package/dist/transitions/phaseRecord.d.ts +19 -2
  278. package/dist/transitions/phaseRecord.js +50 -11
  279. package/dist/transitions/placementInteractions.d.ts +7 -2
  280. package/dist/transitions/placementInteractions.js +9 -7
  281. package/dist/transitions/placements.d.ts +4 -3
  282. package/dist/transitions/placements.js +28 -14
  283. package/dist/transitions/preflightData.d.ts +11 -3
  284. package/dist/transitions/preflightData.js +134 -81
  285. package/dist/transitions/reschedule.d.ts +4 -0
  286. package/dist/transitions/reschedule.js +58 -0
  287. package/dist/transitions/resume.d.ts +4 -0
  288. package/dist/transitions/resume.js +32 -0
  289. package/dist/transitions/scheduledRound.d.ts +18 -0
  290. package/dist/transitions/scheduledRound.js +42 -0
  291. package/dist/transitions/start.d.ts +4 -0
  292. package/dist/transitions/start.js +139 -56
  293. package/dist/transitions/startReads.d.ts +14 -0
  294. package/dist/transitions/startReads.js +27 -0
  295. package/dist/transitions/stop.d.ts +10 -0
  296. package/dist/transitions/stop.js +35 -22
  297. package/dist/types/admin.d.ts +1 -1
  298. package/dist/types/contracts.d.ts +7 -1
  299. package/dist/types/endpoints.d.ts +72 -3
  300. package/dist/types/manifest.d.ts +9 -0
  301. package/dist/types/runtime.d.ts +5 -0
  302. package/dist/types/snapshot.d.ts +10 -0
  303. package/dist/types/status.d.ts +1 -0
  304. package/dist/types/status.js +1 -0
  305. package/dist/types/surface.d.ts +1 -0
  306. package/dist/ui/Feedback.d.ts +9 -6
  307. package/dist/ui/Feedback.js +10 -9
  308. package/dist/ui/SelectControl.js +1 -1
  309. package/dist/ui/ui.css +2 -1
  310. package/package.json +2 -2
@@ -5,6 +5,8 @@ import { TEST_PAGE as C } from '../../../testSurface/copy/testPage.js';
5
5
  import { formatAdminURL } from '../../../testSurface/format/adminURL.js';
6
6
  import { surfaceUrls } from '../../../testSurface/surfaceUrls.js';
7
7
  import { Button } from '../../../ui/Button.js';
8
+ import { useScheduleClock } from '../../../testSurface/format/useScheduleClock.js';
9
+ import { scheduleStatus } from '../../../testSurface/format/scheduleStatus.js';
8
10
  import { StatusChip } from '../../../ui/StatusChip.js';
9
11
  import { useXpStepNav } from '../useXpStepNav.js';
10
12
  import { SurfaceShell } from '../SurfaceShell.js';
@@ -22,6 +24,10 @@ export function TestPage({ id, surface, onTitleChange }) {
22
24
  }
23
25
  function TestPageFrame({ test, surface, children }) {
24
26
  const doc = test.doc;
27
+ const now = useScheduleClock(doc ? [
28
+ doc
29
+ ] : [], surface.timeZone);
30
+ const schedule = doc ? scheduleStatus(doc, now, test.preflight?.timing, surface.timeZone, test.preflight?.pauseAttribution) : undefined;
25
31
  const crumbs = [
26
32
  {
27
33
  label: C.tests,
@@ -47,10 +53,14 @@ function TestPageFrame({ test, surface, children }) {
47
53
  children: C.kinds[doc.kind]
48
54
  }),
49
55
  !test.statusReadPending ? /*#__PURE__*/ _jsx(StatusChip, {
50
- status: doc.status
56
+ status: schedule?.status ?? doc.status
51
57
  }) : null
52
58
  ]
53
59
  }) : undefined,
60
+ subtitle: !test.statusReadPending && schedule?.line ? /*#__PURE__*/ _jsx("p", {
61
+ role: "status",
62
+ children: schedule.line
63
+ }) : undefined,
54
64
  actions: doc && !test.statusReadPending && surface.canReadResults && doc.status !== 'draft' ? /*#__PURE__*/ _jsx(Button, {
55
65
  variant: "secondary",
56
66
  href: formatAdminURL({
@@ -4,7 +4,7 @@ export declare function useLayerExperiments(layerId: DocId | null): {
4
4
  free: number;
5
5
  rows: {
6
6
  name: string;
7
- status: import("../types/contracts.js").Status;
7
+ status: import("../types/status.js").Status;
8
8
  slices: number;
9
9
  }[];
10
10
  } | null;
@@ -67,6 +67,9 @@ export async function buildSurfaceProps({ req, route, id, searchParams }) {
67
67
  },
68
68
  adminRoute,
69
69
  apiRoute: req.payload.config.routes.api,
70
+ ...options.timeZone ? {
71
+ timeZone: options.timeZone
72
+ } : {},
70
73
  ...req.payload.config.localization ? {
71
74
  contentLanguageLabels: placementLanguageNames(req, req.payload.config.localization.localeCodes)
72
75
  } : {},
@@ -1,5 +1,6 @@
1
1
  import { type PayloadRequest } from 'payload';
2
2
  import type { DocId, ResolvedOptions } from '../types/contracts.js';
3
+ import { type PublicationStatus } from './placementPublication.js';
3
4
  export type PlacementInput = 'all-locales' | 'localized';
4
5
  export declare function placementLocaleContent(req: PayloadRequest, collection: string, doc: Record<string, unknown> | undefined, input: PlacementInput): Record<string, unknown> | undefined;
5
6
  /** The single document → locale view → editor/placements boundary. Compiled schemas are shared per sanitized config.
@@ -8,6 +9,7 @@ export declare function placementLocaleContent(req: PayloadRequest, collection:
8
9
  export declare function placementReader(req: PayloadRequest, collection: string, options?: Pick<ResolvedOptions, "puck" | "blocks">): {
9
10
  views: PlacementLocaleView[];
10
11
  documentViews: PlacementLocaleView[];
12
+ isPublished(doc: Record<string, unknown> | null | undefined, view: PlacementLocaleView): boolean;
11
13
  read(doc: Record<string, unknown> | null | undefined, input: PlacementInput, view?: PlacementLocaleView): {
12
14
  view: PlacementLocaleView;
13
15
  readonly doc: Record<string, unknown> | undefined;
@@ -32,6 +34,18 @@ export declare function placementLocaleViews(req: PayloadRequest, collection: st
32
34
  export declare function removedPlacementViews(req: PayloadRequest, collection: string, before: Record<string, unknown> | undefined, after: Record<string, unknown>, removingPage: boolean, input?: PlacementInput): RemovedPlacementViews;
33
35
  /** Rebuild unchanged locale maps around a flattened hook write before reading each view. */
34
36
  export declare function mergedPlacementLocales(req: PayloadRequest, collection: string, before: Record<string, unknown> | undefined, after: Record<string, unknown>): Record<string, unknown>;
37
+ export declare function selectPlacementLocales(req: PayloadRequest, collection: string, doc: Record<string, unknown>, keep: ReadonlySet<string>): Record<string, unknown>;
38
+ /** Predict the main row Payload will write, keeping the stored status map
39
+ * separate from the locale-hoisted hook data and its validation locale.
40
+ */
41
+ export declare function localizedPlacementAfter(req: PayloadRequest, collection: string, main: Record<string, unknown> | undefined, base: Record<string, unknown> | undefined, data: Record<string, unknown>, { status, all, restore, }: {
42
+ status: unknown;
43
+ all?: {
44
+ status: PublicationStatus;
45
+ locales: string[];
46
+ };
47
+ restore?: boolean;
48
+ }): Record<string, unknown>;
35
49
  /** Project host document adapters before they run. Callers own path normalization
36
50
  * and use sortLockKeys for the existing experiment → page-path lock ordering. */
37
51
  export declare function placementDocumentPaths(req: PayloadRequest, collection: string, docs: Array<Record<string, unknown> | undefined>, input: PlacementInput, pathOf: (doc: Record<string, unknown>) => string | null): string[];
@@ -4,6 +4,8 @@ import { documentEditor, puckCollections } from '../options.js';
4
4
  import { placementSlugs } from './bindings.js';
5
5
  import { contentBlocks, hasLocalizedFields } from '../transitions/contentFields.js';
6
6
  import { isObject } from './model.js';
7
+ import { isPublicationStatus, payloadPublishesAllByDefault, publicationStatusInLocale, publishedInLocale, usesLocalizedPublication } from './placementPublication.js';
8
+ import { usesRelationalBlocks } from '../db/adapter.js';
7
9
  const identity = (data)=>data;
8
10
  // Sanitized schemas are immutable. Weak ownership keeps separate Payload configs
9
11
  // (and test harnesses) isolated; locale transforms survive individual readers/saves.
@@ -33,7 +35,7 @@ const localeTransforms = new WeakMap();
33
35
  const cached = compiled.get(fields);
34
36
  if (cached) return cached;
35
37
  let project;
36
- const transform = (data, write, previous)=>project(data, write, previous);
38
+ const transform = (data, write, previous, options)=>project(data, write, previous, options);
37
39
  compiled.set(fields, transform);
38
40
  const steps = flattenTopLevelFields(fields).flatMap((field)=>{
39
41
  if (!('name' in field) || !field.name) return [];
@@ -62,15 +64,31 @@ const localeTransforms = new WeakMap();
62
64
  })) : undefined;
63
65
  if (!localized && !children && !variants) return [];
64
66
  return [
65
- (data, write, previous)=>{
67
+ (data, write, previous, options)=>{
66
68
  if (!(name in data)) return data;
67
69
  let value = data[name];
68
70
  const prior = previous?.[name];
69
- if (localized && write) value = {
70
- ...isObject(prior) ? prior : {},
71
- [locale]: value
72
- };
73
- else {
71
+ const keep = options?.keep;
72
+ if (localized && keep) {
73
+ if (isObject(value)) value = Object.fromEntries(Object.entries(value).filter(([code])=>keep.has(code)));
74
+ } else if (localized && write) {
75
+ const existing = isObject(prior) ? prior : {};
76
+ // Relational blocks have no stored locale value when there are no
77
+ // rows. The visitor will see fallback content in that locale.
78
+ const storedValue = (input)=>options?.omitEmptyBlocks && field.type === 'blocks' && Array.isArray(input) && input.length === 0 ? undefined : input;
79
+ if (locale !== 'all') value = {
80
+ ...existing,
81
+ [locale]: storedValue(value)
82
+ };
83
+ else if (payloadPublishesAllByDefault) value = {
84
+ ...existing,
85
+ ...Object.fromEntries(Object.entries(isObject(value) ? value : {}).map(([code, input])=>[
86
+ code,
87
+ storedValue(input)
88
+ ]))
89
+ };
90
+ else if (Object.keys(existing).length) value = existing;
91
+ } else {
74
92
  if (localized) {
75
93
  const values = isObject(value) ? value : {};
76
94
  value = values[locale];
@@ -89,7 +107,7 @@ const localeTransforms = new WeakMap();
89
107
  const visit = (row, old)=>{
90
108
  if (!isObject(row)) return row;
91
109
  const transform = children ?? (variants && typeof row.blockType === 'string' ? variants.get(row.blockType) : undefined);
92
- return transform ? transform(row, write, isObject(old) ? old : undefined) : row;
110
+ return transform ? transform(row, write, isObject(old) ? old : undefined, options) : row;
93
111
  };
94
112
  if (children || variants) {
95
113
  if (Array.isArray(value)) {
@@ -105,7 +123,7 @@ const localeTransforms = new WeakMap();
105
123
  }
106
124
  ];
107
125
  });
108
- project = (data, write = false, previous)=>steps.reduce((result, step)=>step(result, write, previous), data);
126
+ project = (data, write = false, previous, options)=>steps.reduce((result, step)=>step(result, write, previous, options), data);
109
127
  return transform;
110
128
  }
111
129
  const transform = hasLocalizedFields(config.fields ?? [], payloadConfig) ? compile(config.fields ?? []) : identity;
@@ -120,9 +138,13 @@ export function placementLocaleContent(req, collection, doc, input) {
120
138
  */ export function placementReader(req, collection, options = req.payload.config.custom?.xp) {
121
139
  const views = placementLocaleViews(req, collection, options);
122
140
  const transforms = new Map();
141
+ const localizedStatus = usesLocalizedPublication(req, collection);
123
142
  return {
124
143
  views,
125
144
  documentViews: schemaLocaleViews(req, collection),
145
+ isPublished (doc, view) {
146
+ return !localizedStatus || publishedInLocale(doc, view.locale);
147
+ },
126
148
  read (doc, input, view) {
127
149
  const requested = view ?? {
128
150
  locale: req.locale ?? '',
@@ -153,6 +175,11 @@ export function placementLocaleContent(req, collection, doc, input) {
153
175
  transforms.set(key, transform);
154
176
  }
155
177
  content = transform(doc);
178
+ // Content can fall back to another locale. Publication status cannot.
179
+ if (localizedStatus) content = {
180
+ ...content,
181
+ _status: publicationStatusInLocale(doc, locale)
182
+ };
156
183
  }
157
184
  return content;
158
185
  };
@@ -175,7 +202,7 @@ export function placementLocaleContent(req, collection, doc, input) {
175
202
  export function allPlacementSlugs(req, collection, doc, input) {
176
203
  const reader = placementReader(req, collection);
177
204
  return [
178
- ...new Set(reader.views.flatMap((view)=>reader.read(doc, input, view).slugs))
205
+ ...new Set(reader.views.flatMap((view)=>reader.isPublished(doc, view) ? reader.read(doc, input, view).slugs : []))
179
206
  ];
180
207
  }
181
208
  export const placementDocumentKey = (collection, id, view)=>JSON.stringify([
@@ -198,7 +225,7 @@ export function localeRequest(req, view) {
198
225
  /** Audits may contain localized arm-select tags outside registered editors. */ function schemaLocaleViews(req, collection) {
199
226
  const localization = req.payload.config.localization;
200
227
  const config = req.payload.config.collections?.find((entry)=>entry.slug === collection);
201
- return localization && hasLocalizedFields(config?.fields ?? [], req.payload.config) ? (localization.localeCodes ?? localization.locales.map((entry)=>typeof entry === 'string' ? entry : entry.code)).map((locale)=>({
228
+ return localization && (usesLocalizedPublication(req, collection, config) || hasLocalizedFields(config?.fields ?? [], req.payload.config)) ? (localization.localeCodes ?? localization.locales.map((entry)=>typeof entry === 'string' ? entry : entry.code)).map((locale)=>({
202
229
  locale,
203
230
  fallbackLocale: sanitizeFallbackLocale({
204
231
  fallbackLocale: null,
@@ -220,7 +247,7 @@ export function localeRequest(req, view) {
220
247
  ...(options.blocks?.collections ?? []).filter((entry)=>entry.slug === collection).map((entry)=>entry.field)
221
248
  ]);
222
249
  const localized = config && hasLocalizedFields(config.fields ?? [], req.payload.config) && (Boolean(options.blocks?.collections.some((entry)=>entry.slug === collection && entry.appliesTo)) || flattenTopLevelFields(config.fields ?? []).some((field)=>'name' in field && names.has(field.name) && ('localized' in field && field.localized || 'fields' in field && hasLocalizedFields(field.fields, req.payload.config) || field.type === 'blocks' && hasLocalizedFields(contentBlocks(field, req.payload.config.blocks).flatMap((block)=>block.fields), req.payload.config))));
223
- return localization && localized ? (localization.localeCodes ?? localization.locales.map((entry)=>typeof entry === 'string' ? entry : entry.code)).map((locale)=>({
250
+ return localization && (localized || usesLocalizedPublication(req, collection, config)) ? (localization.localeCodes ?? localization.locales.map((entry)=>typeof entry === 'string' ? entry : entry.code)).map((locale)=>({
224
251
  locale,
225
252
  fallbackLocale: sanitizeFallbackLocale({
226
253
  fallbackLocale: null,
@@ -243,8 +270,9 @@ export function localeRequest(req, view) {
243
270
  const reader = placementReader(req, collection);
244
271
  const rawAfter = input === 'all-locales' ? after : mergedPlacementLocales(req, collection, before, after);
245
272
  for (const view of reader.views){
273
+ if (!reader.isPublished(before, view)) continue;
246
274
  const previous = reader.read(before, 'all-locales', view).slugs;
247
- const next = removingPage ? [] : reader.read(rawAfter, 'all-locales', view).slugs;
275
+ const next = removingPage || !reader.isPublished(rawAfter, view) ? [] : reader.read(rawAfter, 'all-locales', view).slugs;
248
276
  for (const slug of previous.filter((slug)=>!next.includes(slug)))result.set(slug, [
249
277
  ...result.get(slug) ?? [],
250
278
  view
@@ -257,10 +285,49 @@ export function localeRequest(req, view) {
257
285
  if (!localization || req.locale === 'all') return after;
258
286
  return localeTransform(req.payload.config, collection, req.locale || localization.defaultLocale, false)(after, true, before);
259
287
  }
288
+ export function selectPlacementLocales(req, collection, doc, keep) {
289
+ return localeTransform(req.payload.config, collection, '', false)(doc, false, undefined, {
290
+ keep
291
+ });
292
+ }
293
+ /** Predict the main row Payload will write, keeping the stored status map
294
+ * separate from the locale-hoisted hook data and its validation locale.
295
+ */ export function localizedPlacementAfter(req, collection, main, base, data, { status, all, restore }) {
296
+ const localization = req.payload.config.localization;
297
+ if (!localization) return data;
298
+ const locale = req.locale || localization.defaultLocale;
299
+ const selected = isObject(status) ? status[locale] : status;
300
+ // V3 merges every single-locale live update with main. V4 does that on
301
+ // publish, while unpublish uses the unmerged result of beforeChange.
302
+ const isolatedPublish = !restore && !all && payloadPublishesAllByDefault && selected === 'published' && locale !== 'all';
303
+ let source = !restore && !all && main && (!payloadPublishesAllByDefault || isolatedPublish) ? main : base;
304
+ const before = isObject(source?._status) ? source._status : {};
305
+ const statuses = {
306
+ ...before
307
+ };
308
+ if (isolatedPublish && main) {
309
+ source = selectPlacementLocales(req, collection, main, new Set(Object.keys(before).filter((code)=>before[code] === 'published')));
310
+ }
311
+ if (all) for (const code of all.locales)statuses[code] = all.status;
312
+ else if (locale !== 'all' && isPublicationStatus(selected)) statuses[locale] = selected;
313
+ else if (locale === 'all' && isObject(status) && (payloadPublishesAllByDefault || !main)) Object.assign(statuses, status);
314
+ else if (locale === 'all' && payloadPublishesAllByDefault && isPublicationStatus(status) && !Object.keys(before).length) {
315
+ for (const code of localization.localeCodes)statuses[code] = status;
316
+ }
317
+ const merged = localeTransform(req.payload.config, collection, locale, false)(data, true, source, {
318
+ omitEmptyBlocks: usesRelationalBlocks(req.payload)
319
+ });
320
+ return {
321
+ ...source,
322
+ ...merged,
323
+ _status: statuses
324
+ };
325
+ }
260
326
  /** Project host document adapters before they run. Callers own path normalization
261
327
  * and use sortLockKeys for the existing experiment → page-path lock ordering. */ export function placementDocumentPaths(req, collection, docs, input, pathOf) {
262
328
  const reader = placementReader(req, collection);
263
329
  return docs.flatMap((raw)=>reader.documentViews.flatMap((view)=>{
330
+ if (!reader.isPublished(raw, view)) return [];
264
331
  const doc = reader.read(raw, input, view).doc;
265
332
  const path = doc ? pathOf(doc) : null;
266
333
  return path === null ? [] : [
@@ -0,0 +1,14 @@
1
+ import type { PayloadRequest, SanitizedCollectionConfig } from 'payload';
2
+ export declare const payloadPublishesAllByDefault: boolean;
3
+ export declare function usesLocalizedPublication(req: PayloadRequest, collection: string, config?: SanitizedCollectionConfig): boolean;
4
+ export type PublicationStatus = 'published' | 'draft';
5
+ export type PublicationFlags = {
6
+ draft?: boolean;
7
+ restore?: boolean;
8
+ publishAllLocales?: boolean;
9
+ unpublishAllLocales?: boolean;
10
+ };
11
+ export declare function isPublicationStatus(value: unknown): value is PublicationStatus;
12
+ export declare function allLocalesStatus(req: PayloadRequest, flags: PublicationFlags | undefined, status: unknown, operation: 'create' | 'update'): PublicationStatus | undefined;
13
+ export declare function publicationStatusInLocale(doc: Record<string, unknown> | null | undefined, locale: string): PublicationStatus | undefined;
14
+ export declare function publishedInLocale(doc: Record<string, unknown> | null | undefined, locale: string): boolean;
@@ -0,0 +1,24 @@
1
+ import * as payloadCore from 'payload';
2
+ import { isObject } from './model.js';
3
+ // Payload 4 dropped createLocalReq and made a non-draft locale=all save an
4
+ // all-locale publish by default. Payload 3 requires the explicit flag.
5
+ export const payloadPublishesAllByDefault = !('createLocalReq' in payloadCore);
6
+ export function usesLocalizedPublication(req, collection, config) {
7
+ const versions = (config ?? req.payload.config.collections?.find((entry)=>entry.slug === collection))?.versions;
8
+ return Boolean(req.payload.config.localization && versions && versions.drafts && versions.drafts.localizeStatus);
9
+ }
10
+ export function isPublicationStatus(value) {
11
+ return value === 'published' || value === 'draft';
12
+ }
13
+ export function allLocalesStatus(req, flags, status, operation) {
14
+ if (flags?.unpublishAllLocales && status === 'draft') return 'draft';
15
+ const publishAll = flags?.publishAllLocales ?? (operation === 'update' && payloadPublishesAllByDefault && req.locale === 'all');
16
+ if (!flags?.draft && publishAll && status === 'published') return 'published';
17
+ }
18
+ export function publicationStatusInLocale(doc, locale) {
19
+ const status = isObject(doc?._status) ? doc._status[locale] : undefined;
20
+ return isPublicationStatus(status) ? status : undefined;
21
+ }
22
+ export function publishedInLocale(doc, locale) {
23
+ return publicationStatusInLocale(doc, locale) === 'published';
24
+ }
@@ -0,0 +1,35 @@
1
+ import type { FrozenCohortRule } from './rule.js';
2
+ import type { ResolvedOptions } from '../types/contracts.js';
3
+ import { type ResultsPhase } from '../db/snapshots.js';
4
+ import { type CohortSource } from '../db/cohorts.js';
5
+ import { type Executor } from '../db/executor.js';
6
+ import { XpRefusal } from '../errors.js';
7
+ export declare function cohortClosed(phase: ResultsPhase, now: Date): boolean;
8
+ export declare function cohortExposureQuery(phase: ResultsPhase, now: Date): {
9
+ experiment: import("../types/contracts.js").DocId;
10
+ phase: number;
11
+ from: Date;
12
+ to: Date;
13
+ inactive: {
14
+ from: Date;
15
+ to: Date;
16
+ }[];
17
+ };
18
+ type BuildOptions = {
19
+ budgetMs: number;
20
+ now: Date;
21
+ options: Pick<ResolvedOptions, 'eventSources' | 'metricSources'>;
22
+ readExec: Executor;
23
+ source?: CohortSource;
24
+ };
25
+ export declare function deriveCohort(exec: Executor, rule: FrozenCohortRule, { now, options, readExec, source }: Omit<BuildOptions, 'budgetMs'>, deadline: number): Promise<{
26
+ members: number;
27
+ }>;
28
+ export declare function cohortBuildTimeout(cohortKeys: string[]): XpRefusal;
29
+ /** Build and mark the audience ready on the caller's transaction. */
30
+ export declare function buildCohort(exec: Executor, rule: FrozenCohortRule, opts: BuildOptions): Promise<{
31
+ members: number;
32
+ }>;
33
+ /** Hold every key from the first build through the transition's commit. */
34
+ export declare function buildStartCohorts(exec: Executor, rules: FrozenCohortRule[], sources: Map<string, CohortSource>, opts: BuildOptions): Promise<void>;
35
+ export {};
@@ -0,0 +1,134 @@
1
+ import { roundActiveSpec } from '../schedule/roundTime.js';
2
+ import { inactiveIntervals } from '../schedule/activeTime.js';
3
+ import { timestampMs } from '../results/aggregate.js';
4
+ import { metricUnitValues, readUnitMetricEvents, unitValueContext } from '../results/unitValues.js';
5
+ import { LATE_BEACON_GRACE_MS } from '../db/snapshots.js';
6
+ import { cohortExposureUnits, isCohortTimeout, readCohort, readCohortSource, replaceExposureCohort, replaceGoalCohort, withCohortTimeout, writeCohort } from '../db/cohorts.js';
7
+ import { ResultsBudgetError } from '../db/executor.js';
8
+ import { lockCohortErasure, lockCohorts, sortLockKeys } from '../db/locks.js';
9
+ import { XpRefusal } from '../errors.js';
10
+ import { COHORT_COPY } from '../testSurface/copy/cohorts.js';
11
+ export function cohortClosed(phase, now) {
12
+ return phase.endedAt != null && +now >= timestampMs(phase.endedAt) + LATE_BEACON_GRACE_MS;
13
+ }
14
+ export function cohortExposureQuery(phase, now) {
15
+ const from = new Date(timestampMs(phase.startedAt));
16
+ const spec = roundActiveSpec(phase);
17
+ const to = new Date(Math.min(+now, phase.endedAt == null ? Infinity : timestampMs(phase.endedAt), spec.to ? timestampMs(spec.to) : Infinity));
18
+ const inactive = inactiveIntervals(spec, phase.pauses ?? [], {
19
+ from,
20
+ to
21
+ });
22
+ return {
23
+ experiment: phase.experiment,
24
+ phase: phase.phase,
25
+ from,
26
+ to,
27
+ inactive
28
+ };
29
+ }
30
+ export async function deriveCohort(exec, rule, { now, options, readExec, source }, deadline) {
31
+ source ??= await readCohortSource(readExec, rule.experiment, rule.phase);
32
+ if (!source) throw new XpRefusal('cohort-source-invalid', COHORT_COPY.invalid, {
33
+ reason: 'round'
34
+ }, 422);
35
+ const { phase, unitType } = source;
36
+ const closed = cohortClosed(phase, now);
37
+ const query = cohortExposureQuery(phase, now);
38
+ let members;
39
+ if (!rule.goal) {
40
+ // The write statement reads committed exposure rows on the transaction and
41
+ // materializes them in SQL without transferring ids to the application.
42
+ members = await replaceExposureCohort(exec, rule.key, now, query, rule.arms);
43
+ } else {
44
+ if (!rule.goal.completed && !closed) throw new XpRefusal('cohort-source-open', COHORT_COPY.open, undefined, 422);
45
+ const definition = phase.metricDefinitions?.find((metric)=>String(metric.metricId) === rule.goal.metricId);
46
+ if (!definition) throw new XpRefusal('cohort-source-invalid', COHORT_COPY.invalid, {
47
+ reason: 'goal'
48
+ }, 422);
49
+ const exposed = await cohortExposureUnits(readExec, query);
50
+ const units = new Map(exposed.map((unit)=>[
51
+ unit.unitId,
52
+ {
53
+ arm: unit.arm,
54
+ firstTs: new Date(unit.firstTs)
55
+ }
56
+ ]));
57
+ const context = await unitValueContext(readExec, unitType, units);
58
+ const metric = await readUnitMetricEvents(readExec, {
59
+ phase,
60
+ unitType,
61
+ units,
62
+ context,
63
+ definition,
64
+ options,
65
+ to: query.to,
66
+ deadline
67
+ });
68
+ const { values } = metricUnitValues(units, definition, metric, query.to);
69
+ const arms = new Set(rule.arms);
70
+ const desired = [
71
+ ...units.keys()
72
+ ].filter((id)=>arms.has(units.get(id).arm) && (rule.goal.completed ? values.get(id) > 0 : values.get(id) === 0));
73
+ members = await replaceGoalCohort(exec, rule.key, now, desired);
74
+ }
75
+ await writeCohort(exec, rule, {
76
+ closed,
77
+ members,
78
+ now
79
+ });
80
+ return {
81
+ members
82
+ };
83
+ }
84
+ export function cohortBuildTimeout(cohortKeys) {
85
+ return new XpRefusal('cohort-build-timeout', COHORT_COPY.timeout, {
86
+ cohortKeys
87
+ }, 409);
88
+ }
89
+ /** Build and mark the audience ready on the caller's transaction. */ export async function buildCohort(exec, rule, opts) {
90
+ const deadline = Date.now() + opts.budgetMs;
91
+ try {
92
+ return await withCohortTimeout(exec, deadline, async (timed)=>{
93
+ await lockCohortErasure(timed);
94
+ await lockCohorts(timed, [
95
+ rule.key
96
+ ]);
97
+ const existing = await readCohort(timed, rule.key);
98
+ if (existing?.closed) return {
99
+ members: existing.members
100
+ };
101
+ return deriveCohort(timed, rule, opts, deadline);
102
+ });
103
+ } catch (error) {
104
+ if (isCohortTimeout(error)) throw cohortBuildTimeout([
105
+ rule.key
106
+ ]);
107
+ throw error;
108
+ }
109
+ }
110
+ /** Hold every key from the first build through the transition's commit. */ export async function buildStartCohorts(exec, rules, sources, opts) {
111
+ const keys = sortLockKeys(rules.map((rule)=>rule.key));
112
+ if (!keys.length) return;
113
+ const deadline = Date.now() + opts.budgetMs;
114
+ try {
115
+ await withCohortTimeout(exec, deadline, async (timed)=>{
116
+ await lockCohortErasure(timed);
117
+ await lockCohorts(timed, keys);
118
+ for (const key of keys){
119
+ if (Date.now() >= deadline) throw new ResultsBudgetError();
120
+ const rule = rules.find((rule)=>rule.key === key);
121
+ const existing = await readCohort(timed, key);
122
+ if (existing && (existing.closed || rule.goal)) continue;
123
+ await deriveCohort(timed, rule, {
124
+ ...opts,
125
+ now: new Date(),
126
+ source: sources.get(key)
127
+ }, deadline);
128
+ }
129
+ });
130
+ } catch (error) {
131
+ if (isCohortTimeout(error)) throw cohortBuildTimeout(keys);
132
+ throw error;
133
+ }
134
+ }
@@ -0,0 +1,12 @@
1
+ import type { CohortRule } from './rule.js';
2
+ type KeyRule = Omit<CohortRule, 'phase' | 'experiment' | 'goal'> & {
3
+ phase: number;
4
+ experiment: string | number;
5
+ goal?: {
6
+ metricId: string | number;
7
+ completed: boolean;
8
+ };
9
+ };
10
+ /** Server-only key. Object fields are emitted in lexical order at both levels. */
11
+ export declare function cohortKey(rule: KeyRule): string;
12
+ export {};
@@ -0,0 +1,15 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** Server-only key. Object fields are emitted in lexical order at both levels. */ export function cohortKey(rule) {
3
+ const canonical = JSON.stringify({
4
+ arms: [
5
+ ...rule.arms
6
+ ].sort(),
7
+ experiment: String(rule.experiment),
8
+ goal: rule.goal ? {
9
+ completed: rule.goal.completed,
10
+ metricId: String(rule.goal.metricId)
11
+ } : null,
12
+ phase: rule.phase
13
+ });
14
+ return createHash('sha256').update('xp:cohort:' + canonical).digest('hex').slice(0, 16);
15
+ }
@@ -0,0 +1,10 @@
1
+ import type { Payload } from 'payload';
2
+ export declare function refreshCohorts(payload: Payload, { budgetMs, now }: {
3
+ budgetMs: number;
4
+ now?: Date;
5
+ }): Promise<void>;
6
+ export declare function sweepCohorts(payload: Payload, { now, retentionDays, deadline }: {
7
+ now: Date;
8
+ retentionDays: number;
9
+ deadline: number;
10
+ }): Promise<void>;
@@ -0,0 +1,70 @@
1
+ import { inCohortTransaction } from '../db/cohortTransactions.js';
2
+ import { cohortIsReferenced, isCohortTimeout, readCohort, readCohortSource, refreshableCohortKeys, sweepableCohortKeys, sweepCohortKey, withCohortTimeout } from '../db/cohorts.js';
3
+ import { lockCohortErasure, lockCohorts } from '../db/locks.js';
4
+ import { LATE_BEACON_GRACE_MS, resultsExecutor } from '../db/snapshots.js';
5
+ import { safeError } from '../log.js';
6
+ import { XpRefusal } from '../errors.js';
7
+ import { deriveCohort } from './build.js';
8
+ import { DAY_MS } from '../schedule/roundTime.js';
9
+ export async function refreshCohorts(payload, { budgetMs, now = new Date() }) {
10
+ const deadline = Date.now() + budgetMs;
11
+ const options = payload.config.custom?.xp;
12
+ if (budgetMs <= 0) return;
13
+ const readExec = resultsExecutor(payload, ()=>deadline - Date.now());
14
+ try {
15
+ for (const key of (await refreshableCohortKeys(readExec))){
16
+ if (Date.now() >= deadline) break;
17
+ try {
18
+ await inCohortTransaction(payload, deadline, (exec)=>withCohortTimeout(exec, deadline, async (timed)=>{
19
+ await lockCohortErasure(timed);
20
+ await lockCohorts(timed, [
21
+ key
22
+ ]);
23
+ const current = await readCohort(timed, key);
24
+ if (!current || current.closed || +new Date(current.builtAt) >= +now || !await cohortIsReferenced(timed, key)) return;
25
+ const source = await readCohortSource(timed, current.rule.experiment, current.rule.phase);
26
+ if (!source || source.phase.endedAt != null && +new Date(source.phase.endedAt) < +now - (options.events?.retentionDays ?? 180) * DAY_MS) return;
27
+ await deriveCohort(timed, {
28
+ ...current.rule,
29
+ include: true
30
+ }, {
31
+ now,
32
+ options,
33
+ readExec,
34
+ source
35
+ }, deadline);
36
+ }));
37
+ } catch (error) {
38
+ if (isCohortTimeout(error) || error instanceof XpRefusal && error.code === 'cohort-build-timeout') break;
39
+ payload.logger.warn({
40
+ err: safeError(error)
41
+ }, 'Experiment audience refresh failed');
42
+ }
43
+ }
44
+ } catch (error) {
45
+ if (!isCohortTimeout(error)) payload.logger.warn({
46
+ err: safeError(error)
47
+ }, 'Experiment audience refresh could not be scheduled');
48
+ }
49
+ }
50
+ export async function sweepCohorts(payload, { now, retentionDays, deadline }) {
51
+ const readExec = resultsExecutor(payload, ()=>deadline - Date.now());
52
+ const stale = new Date(+now - LATE_BEACON_GRACE_MS);
53
+ const cutoff = new Date(+now - retentionDays * DAY_MS);
54
+ try {
55
+ for (const key of (await sweepableCohortKeys(readExec, stale, cutoff))){
56
+ if (Date.now() >= deadline) return;
57
+ await inCohortTransaction(payload, deadline, (exec)=>withCohortTimeout(exec, deadline, async (timed)=>{
58
+ await lockCohortErasure(timed);
59
+ await lockCohorts(timed, [
60
+ key
61
+ ]);
62
+ await sweepCohortKey(timed, key, stale, cutoff);
63
+ }));
64
+ }
65
+ } catch (error) {
66
+ if (!isCohortTimeout(error)) payload.logger.warn({
67
+ err: safeError(error)
68
+ }, 'Experiment audience retention sweep failed');
69
+ }
70
+ }
@@ -0,0 +1,30 @@
1
+ import type { CohortSource } from '../db/cohorts.js';
2
+ import type { DocId, TargetingRule } from '../types/contracts.js';
3
+ import { type CohortRule } from './rule.js';
4
+ export type CohortReadinessCode = 'cohort-source-invalid' | 'cohort-cycle' | 'cohort-source-open' | 'cohort-lookup-missing';
5
+ export declare const isCohortReadiness: (code: string) => code is CohortReadinessCode;
6
+ export type CohortSourceIssue = 'source' | 'self' | 'round' | 'arms' | 'goal' | 'no-exposure' | 'retention' | 'invalid-rule';
7
+ type CohortFact = {
8
+ source?: CohortSource;
9
+ sourceName?: string;
10
+ hasExposure?: boolean;
11
+ cycle?: boolean;
12
+ };
13
+ export type CohortFacts = {
14
+ proxyLookup: boolean;
15
+ now: Date;
16
+ cutoff: Date;
17
+ rules: Map<number, CohortFact>;
18
+ };
19
+ export declare function checkCohorts(experiment: {
20
+ id: DocId;
21
+ targeting?: Array<TargetingRule | CohortRule> | null;
22
+ }, facts?: CohortFacts): {
23
+ code: CohortReadinessCode;
24
+ ok: boolean;
25
+ detail?: {
26
+ rule: number;
27
+ reason?: CohortSourceIssue;
28
+ };
29
+ }[];
30
+ export {};