@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
@@ -17,7 +17,7 @@ export declare function releaseRemovalClaim(req: PayloadRequest, collection: str
17
17
  export declare function observeUnpublishedRemoval(req: PayloadRequest, collection: string, id: DocId): void;
18
18
  export declare function releaseRestoredRemovalClaims(req: PayloadRequest, collection: string, doc: Record<string, unknown> & {
19
19
  id: DocId;
20
- }, test: PlacementTest): void;
20
+ }, test: PlacementTest, locales?: ReadonlySet<string>): void;
21
21
  export declare const blockRemovalRule: {
22
22
  prepare(req: PayloadRequest, collection: string, before: Record<string, unknown> | undefined, after: Record<string, unknown>, removingPage: boolean, exec?: Executor, tests?: readonly PlacementTest[], input?: PlacementInput): Promise<{
23
23
  views: RemovedPlacementViews;
@@ -32,15 +32,16 @@ export function releaseRemovalClaim(req, collection, id, ownKeys) {
32
32
  if (slug === collection && docId === String(id)) claims.absent.add(`${test}:${key}`);
33
33
  }
34
34
  }
35
- export function releaseRestoredRemovalClaims(req, collection, doc, test) {
35
+ export function releaseRestoredRemovalClaims(req, collection, doc, test, locales) {
36
36
  const claims = req.context.xpPlacementRemovals;
37
37
  if (!claims) return;
38
38
  claims.absent ??= new Set();
39
+ const reader = placementReader(req, collection);
39
40
  for (const key of claims.tests.get(String(test.id)) ?? []){
40
41
  const [slug, id, view] = JSON.parse(key);
41
- if (slug !== collection || id !== String(doc.id)) continue;
42
+ if (slug !== collection || id !== String(doc.id) || locales && !locales.has(view.locale)) continue;
42
43
  const marker = `${test.id}:${key}`;
43
- if (!placementReader(req, collection).read(doc, 'all-locales', view).slugs.includes(test.slug)) claims.absent.add(marker);
44
+ if (locales && doc.deletedAt != null || !reader.isPublished(doc, view) || !reader.read(doc, 'all-locales', view).slugs.includes(test.slug)) claims.absent.add(marker);
44
45
  else if (claims.absent.has(marker) && (claims.counts?.get(String(test.id))?.get(key) ?? 1) === 1) {
45
46
  claims.tests.get(String(test.id)).delete(`${key}`);
46
47
  claims.counts?.get(String(test.id))?.delete(`${key}`);
@@ -87,7 +88,8 @@ export const blockRemovalRule = {
87
88
  if (tests) return tests.filter((test)=>test.kind === 'block' && [
88
89
  'draft',
89
90
  'stopped',
90
- 'running'
91
+ 'running',
92
+ 'paused'
91
93
  ].includes(test.status) && removed.includes(test.slug));
92
94
  return (await removableBlockTests(exec, removed)).map((test)=>({
93
95
  ...test,
@@ -136,7 +138,8 @@ export const blockRemovalRule = {
136
138
  ]));
137
139
  try {
138
140
  for (const test of affected){
139
- if (!current.some((row)=>String(row.id) === String(test.id) && row.kind === 'block' && row.status === 'running')) continue;
141
+ const live = current.find((row)=>String(row.id) === String(test.id) && row.kind === 'block');
142
+ if (!live || live.status !== 'running' && live.status !== 'paused') continue;
140
143
  const documents = claims?.tests.get(String(test.id));
141
144
  let excludedSibling = false;
142
145
  if (await hasOtherPublishedBlockPlacement(req, req.payload.config.custom.xp, test.slug, (slug, docId, view, doc)=>{
@@ -147,12 +150,13 @@ export const blockRemovalRule = {
147
150
  return true;
148
151
  }
149
152
  return false;
150
- })) continue;
153
+ }, bulk)) continue;
151
154
  if (transaction == null) throw new XpNoTransactionError('Save this page with transactions on.');
152
155
  // Bulk selection is immutable through every sibling's decision, including
153
156
  // earlier rule refusals. afterOperation explains unrelated failed writes.
154
- const message = excludedSibling ? bulk ? bulkBlockRemovalCopy(test.name) : pendingBlockRemovalCopy(test.name) : hidden?.has(test.slug) ? hiddenBlockPlacementCopy(test.name) : lastBlockPlacementCopy(test.name, removingPage);
155
- if (bulk && excludedSibling) bulk.refusals.set(message, pendingBlockRemovalCopy(test.name));
157
+ const pending = pendingBlockRemovalCopy(live.name, live.status);
158
+ const message = excludedSibling ? bulk ? bulkBlockRemovalCopy(live.name, live.status) : pending : hidden?.has(test.slug) ? hiddenBlockPlacementCopy(live.name, live.status) : lastBlockPlacementCopy(live.name, removingPage, live.status);
159
+ if (bulk && excludedSibling) bulk.refusals.set(message, pending);
156
160
  throw new XpRefusal('locked-placement', message, {
157
161
  experimentId: test.id
158
162
  }, 409);
@@ -1,9 +1,10 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import type { CollectionAfterChangeHook, CollectionAfterOperationHook, CollectionBeforeChangeHook, CollectionBeforeDeleteHook, CollectionBeforeOperationHook, PayloadRequest } from 'payload';
3
3
  import type { DocId } from '../types/contracts.js';
4
+ import { type PublicationFlags } from '../blocks/placementPublication.js';
4
5
  import { type PlacementTest } from '../db/placements.js';
5
6
  import { type BulkPlacementRemoval } from '../db/bulkPlacementRemoval.js';
6
- type OperationFrame = {
7
+ type OperationFrame = PublicationFlags & {
7
8
  collection: string;
8
9
  request?: PayloadRequest;
9
10
  draft: boolean;
@@ -17,8 +18,13 @@ type OperationFrame = {
17
18
  detached?: boolean;
18
19
  parent?: OperationFrame;
19
20
  bulk?: BulkPlacementRemoval;
21
+ duplicateFromID?: DocId;
22
+ selectedLocales?: string[];
23
+ publicationWrites?: Map<string, Set<string>>;
20
24
  };
21
25
  export declare const pageGuardOperationScope: AsyncLocalStorage<OperationFrame | undefined>;
26
+ /** Both Publish All and Restore can return a locale-projected document. */
27
+ export declare function writesAllPublicationLocales(req: PayloadRequest, collection: string): boolean;
22
28
  /** Must be first: buildBeforeOperation invokes its first hook synchronously,
23
29
  * before the operation registers its await continuation. Later host hooks may
24
30
  * await nested operations; those keep separate async contexts. No IO here.
@@ -1,6 +1,7 @@
1
1
  import { refuseNewNestedTests } from './puckNestedTests.js';
2
2
  import { hasLocalizedFields } from '../transitions/contentFields.js';
3
3
  import { AsyncLocalStorage } from 'node:async_hooks';
4
+ import { isDeepStrictEqual } from 'node:util';
4
5
  import { assertReadCommitted } from '../db/adapter.js';
5
6
  import { previousPublishedContent, storedContent, placementWriteContent } from '../db/appends.js';
6
7
  import { lockPlacementScope, sortLockKeys } from '../db/locks.js';
@@ -8,7 +9,8 @@ import { txExecutor, pooledExecutor } from '../db/executor.js';
8
9
  import { normalisePath } from '../runtime/normalisePath.js';
9
10
  import { XpNoTransactionError, XpRefusal } from '../errors.js';
10
11
  import { placementGuardCopy, pageGuardCopy, READINESS_COPY } from '../testSurface/copy/readiness.js';
11
- import { allPlacementSlugs, mergedPlacementLocales, placementDocumentPaths } from '../blocks/placementLocale.js';
12
+ import { allPlacementSlugs, localizedPlacementAfter, mergedPlacementLocales, placementDocumentPaths, placementReader, selectPlacementLocales } from '../blocks/placementLocale.js';
13
+ import { allLocalesStatus, usesLocalizedPublication } from '../blocks/placementPublication.js';
12
14
  import { isObject } from '../blocks/model.js';
13
15
  import { placementTests, removableBlockTests, appendPlacementDoc } from '../db/placements.js';
14
16
  import { isPageBusy } from '../db/pageBusy.js';
@@ -44,6 +46,10 @@ const operationFrame = (req, slug)=>{
44
46
  }
45
47
  return frame?.scoped && frame.collection === slug && (frame.restore || frame.request === req) ? frame : undefined;
46
48
  };
49
+ /** Both Publish All and Restore can return a locale-projected document. */ export function writesAllPublicationLocales(req, collection) {
50
+ const call = operationFrame(req, collection);
51
+ return Boolean(call && !call.draft && (call.publishAllLocales || call.restore));
52
+ }
47
53
  /** Must be first: buildBeforeOperation invokes its first hook synchronously,
48
54
  * before the operation registers its await continuation. Later host hooks may
49
55
  * await nested operations; those keep separate async contexts. No IO here.
@@ -92,6 +98,10 @@ export const pageGuardBeforeOperation = ({ args, operation })=>{
92
98
  versionId: operation === 'restoreVersion' ? call.id : undefined,
93
99
  isBulk,
94
100
  publishSpecificLocale: call.publishSpecificLocale,
101
+ publishAllLocales: call.publishAllLocales,
102
+ unpublishAllLocales: call.unpublishAllLocales,
103
+ duplicateFromID: call.duplicateFromID,
104
+ selectedLocales: call.selectedLocales,
95
105
  bulk,
96
106
  pending: false
97
107
  });
@@ -170,7 +180,7 @@ function optionsOf(req) {
170
180
  function registration(req, slug) {
171
181
  return optionsOf(req).pages?.collections.find((entry)=>entry.slug === slug);
172
182
  }
173
- const active = (test)=>test.status === 'running' || test.status === 'decided';
183
+ const active = (test)=>test.status === 'running' || test.status === 'paused' || test.status === 'decided';
174
184
  const documentPathsOf = (req, collection, rows)=>{
175
185
  const page = registration(req, collection);
176
186
  return page ? placementDocumentPaths(req, collection, rows, 'all-locales', (doc)=>page.pathOf(doc)) : [];
@@ -232,8 +242,10 @@ export const pageGuardBeforeDelete = async ({ req, id, collection })=>{
232
242
  try {
233
243
  const page = registration(req, collection.slug);
234
244
  // Keep the earlier page guard's baseline read and every refusal intact.
235
- const published = page ? await previousPublishedContent(req, collection.slug, id) : await storedContent(req, collection.slug, id);
245
+ const localized = usesLocalizedPublication(req, collection.slug, collection);
246
+ const published = page && !localized ? await previousPublishedContent(req, collection.slug, id) : await storedContent(req, collection.slug, id);
236
247
  if (!published || published._status === 'draft') return;
248
+ if (localized && (!isObject(published._status) || !Object.values(published._status).includes('published'))) return;
237
249
  const paths = sortLockKeys(documentPathsOf(req, collection.slug, [
238
250
  published
239
251
  ]).map(normalisePath));
@@ -262,8 +274,12 @@ export const pageGuardBeforeDelete = async ({ req, id, collection })=>{
262
274
  }
263
275
  };
264
276
  export const pageGuardBeforeChange = async ({ req, collection, originalDoc, operation, data })=>{
277
+ if (operation !== 'create' && operation !== 'update') return data;
265
278
  const drafts = Boolean(collection.versions && collection.versions.drafts);
266
279
  const call = operationFrame(req, collection.slug);
280
+ if (usesLocalizedPublication(req, collection.slug, collection)) {
281
+ return guardLocalizedSave(req, collection, originalDoc, operation, data, call);
282
+ }
267
283
  if (drafts && call?.draft && (call.restore || data._status !== 'published')) {
268
284
  await blockRemovalRule.prepare(req, collection.slug, undefined, data, false);
269
285
  return data;
@@ -339,8 +355,165 @@ export const pageGuardBeforeChange = async ({ req, collection, originalDoc, oper
339
355
  mapBusy(error);
340
356
  }
341
357
  };
342
- /** Unwrapped: these writes must fail the publish closed, unlike the best-effort audit. */ export const pageGuardAfterChange = async ({ req, collection, doc })=>{
358
+ function changedPublicationLocales(req, collection, before, after, locales) {
359
+ const reader = placementReader(req, collection);
360
+ const result = new Set(locales);
361
+ for (const view of reader.documentViews){
362
+ if (result.has(view.locale) || !reader.isPublished(before, view) && !reader.isPublished(after, view)) continue;
363
+ const previous = reader.read(before, 'all-locales', view).doc;
364
+ const next = reader.read(after, 'all-locales', view).doc;
365
+ if (!isDeepStrictEqual({
366
+ ...previous,
367
+ updatedAt: undefined
368
+ }, {
369
+ ...next,
370
+ updatedAt: undefined
371
+ })) result.add(view.locale);
372
+ }
373
+ return result;
374
+ }
375
+ async function guardLocalizedSave(req, collection, originalDoc, operation, data, call) {
376
+ if (call?.draft && (call.restore || operation === 'create' && call.duplicateFromID == null || operation === 'update' && data._status !== 'published')) return data;
377
+ const slug = collection.slug;
378
+ const id = operation === 'update' ? originalDoc.id : undefined;
379
+ const key = id == null ? '' : String(id);
380
+ const localization = req.payload.config.localization;
381
+ if (!localization) return data;
382
+ try {
383
+ const status = allLocalesStatus(req, call, data._status, operation);
384
+ const locales = status && localization.filterAvailableLocales ? (await localization.filterAvailableLocales({
385
+ locales: localization.locales,
386
+ req
387
+ })).map((entry)=>typeof entry === 'string' ? entry : entry.code) : localization.localeCodes;
388
+ const all = status ? {
389
+ status,
390
+ locales
391
+ } : undefined;
392
+ if (call?.bulk?.change) call.bulk.change.all = all;
393
+ const main = id == null ? undefined : await storedContent(req, slug, id);
394
+ const sourceID = id ?? call?.duplicateFromID;
395
+ let base = sourceID == null ? undefined : await placementWriteContent(req, slug, sourceID, id == null ? await storedContent(req, slug, sourceID) : main, {
396
+ versionId: call?.versionId,
397
+ bulk: call?.isBulk,
398
+ draft: call?.draft,
399
+ trashing: Boolean(collection.trash && data.deletedAt != null)
400
+ });
401
+ if (operation === 'create' && call?.selectedLocales?.length && base) {
402
+ base = selectPlacementLocales(req, slug, base, new Set(call.selectedLocales));
403
+ }
404
+ // Restore hooks receive the default locale for validation, but Payload
405
+ // starts with the selected version's entire locale map.
406
+ const after = localizedPlacementAfter(req, slug, main, base, call?.restore ? data : {
407
+ ...originalDoc,
408
+ ...data
409
+ }, {
410
+ status: call?.restore ? data._status : data._status ?? originalDoc?._status,
411
+ all,
412
+ restore: call?.restore
413
+ });
414
+ const requested = new Set(all?.locales ?? (call?.restore || req.locale === 'all' ? locales : [
415
+ req.locale || localization.defaultLocale
416
+ ]));
417
+ const changed = changedPublicationLocales(req, slug, main, after, requested);
418
+ const reader = placementReader(req, slug);
419
+ const page = registration(req, slug);
420
+ const trashing = Boolean(collection.trash && after.deletedAt != null);
421
+ const before = collection.trash && main?.deletedAt != null ? undefined : main;
422
+ const views = reader.documentViews.filter((view)=>changed.has(view.locale)).map((view)=>{
423
+ const old = reader.isPublished(before, view) ? reader.read(before, 'all-locales', view) : undefined;
424
+ const next = !trashing && reader.isPublished(after, view) ? reader.read(after, 'all-locales', view) : undefined;
425
+ const oldPath = old?.doc ? page?.pathOf(old.doc) : undefined;
426
+ const nextPath = next?.doc ? page?.pathOf(next.doc) : undefined;
427
+ return {
428
+ beforeSlugs: old?.slugs ?? [],
429
+ afterSlugs: next?.slugs ?? [],
430
+ oldPath,
431
+ nextPath
432
+ };
433
+ });
434
+ const beforeSlugs = views.flatMap((view)=>view.beforeSlugs);
435
+ const afterSlugs = views.flatMap((view)=>view.afterSlugs);
436
+ const paths = sortLockKeys(views.flatMap(({ oldPath, nextPath })=>[
437
+ oldPath,
438
+ nextPath
439
+ ].flatMap((path)=>path == null ? [] : [
440
+ normalisePath(path)
441
+ ])));
442
+ const exec = await req.transactionID == null ? pooledExecutor(req.payload) : txExecutor(req);
443
+ let tests = await placementTests(exec);
444
+ const removal = await blockRemovalRule.prepare(req, slug, before, after, trashing, exec, tests, 'all-locales');
445
+ const noTransaction = ()=>{
446
+ if (tests.some((test)=>test.kind === 'block' && active(test) && afterSlugs.includes(test.slug))) throw new XpNoTransactionError('Save this page with transactions on.');
447
+ };
448
+ if (await req.transactionID == null) noTransaction();
449
+ else {
450
+ try {
451
+ await assertReadCommitted(req);
452
+ await lockPlacementScope(exec, guardExperimentIds(tests, [
453
+ ...beforeSlugs,
454
+ ...afterSlugs
455
+ ], slug, paths, req.context.xpHeldExperiments, taggedIds([
456
+ before,
457
+ after
458
+ ]), removal.affected.map((test)=>test.id)), paths);
459
+ tests = await placementTests(exec);
460
+ } catch (error) {
461
+ if (!(error instanceof XpNoTransactionError)) throw error;
462
+ tests = await placementTests(pooledExecutor(req.payload));
463
+ noTransaction();
464
+ }
465
+ }
466
+ const pageTests = tests.filter((test)=>!test.pageCollection || test.pageCollection === slug);
467
+ for (const { oldPath, nextPath, beforeSlugs, afterSlugs } of views){
468
+ if (oldPath != null && oldPath !== nextPath) protect(pageTests, normalisePath(oldPath));
469
+ if (nextPath != null) refuseInteraction(tests, beforeSlugs, afterSlugs, oldPath == null ? [] : [
470
+ normalisePath(oldPath)
471
+ ], [
472
+ normalisePath(nextPath)
473
+ ], slug);
474
+ }
475
+ if (!trashing) refuseNewNestedTests(req, slug, before, after, tests, changed);
476
+ if (id != null && removal.affected.length) {
477
+ const removingPage = trashing || [
478
+ ...removal.views.values()
479
+ ].flat().every((view)=>!reader.isPublished(after, view));
480
+ await blockRemovalRule.check(req, tests, removal.affected, slug, id, removingPage, removal.views, call?.bulk, removal.hidden);
481
+ }
482
+ if (call) (call.publicationWrites ??= new Map()).set(key, changed);
483
+ return data;
484
+ } catch (error) {
485
+ mapBusy(error);
486
+ }
487
+ }
488
+ /** Unwrapped: these writes must fail the publish closed, unlike the best-effort audit. */ export const pageGuardAfterChange = async ({ req, collection, doc, operation })=>{
343
489
  const call = operationFrame(req, collection.slug);
490
+ if (usesLocalizedPublication(req, collection.slug, collection)) {
491
+ const write = call?.publicationWrites?.get(operation === 'create' ? '' : String(doc.id));
492
+ if (call?.draft && !write || await req.transactionID == null) return doc;
493
+ try {
494
+ const stored = await storedContent(req, collection.slug, doc.id);
495
+ if (!stored) throw new Error('The saved placement row was not found.');
496
+ const reader = placementReader(req, collection.slug);
497
+ const locales = write ?? new Set(reader.views.map((view)=>view.locale));
498
+ const slugs = new Set(reader.views.flatMap((view)=>locales.has(view.locale) && reader.isPublished(stored, view) && (!collection.trash || stored.deletedAt == null) ? reader.read(stored, 'all-locales', view).slugs : []));
499
+ const claims = req.context.xpPlacementRemovals;
500
+ const exec = txExecutor(req);
501
+ for (const test of (await placementTests(exec))){
502
+ if (test.kind !== 'block') continue;
503
+ if (active(test) && slugs.has(test.slug)) await appendPlacementDoc(exec, test.id, test.phase, {
504
+ collection: collection.slug,
505
+ id: doc.id
506
+ });
507
+ if (claims && claims.transaction === await req.transactionID) releaseRestoredRemovalClaims(req, collection.slug, {
508
+ ...stored,
509
+ id: doc.id
510
+ }, test, locales);
511
+ }
512
+ return doc;
513
+ } catch (error) {
514
+ mapBusy(error);
515
+ }
516
+ }
344
517
  const drafts = Boolean(collection.versions && collection.versions.drafts);
345
518
  if (!call?.draft && (drafts && doc._status !== 'published' || collection.trash && doc.deletedAt != null)) observeUnpublishedRemoval(req, collection.slug, doc.id);
346
519
  if (drafts && (doc._status !== 'published' || call?.draft && call.restore)) return doc;
@@ -5,4 +5,4 @@ import { type PayloadRequest } from 'payload';
5
5
  export declare function refuseNewNestedTests(req: PayloadRequest, collection: string, before: Record<string, unknown> | undefined, after: Record<string, unknown>, tests: readonly {
6
6
  slug: string;
7
7
  name: string;
8
- }[]): void;
8
+ }[], locales?: ReadonlySet<string>): void;
@@ -5,13 +5,15 @@ import { nestedTests, nestedTestKey, nestedTestLabel, nestedTestSlug, nearestOut
5
5
  import { nestedTestCopy } from '../puck/nestedTestCopy.js';
6
6
  /** Called by the page guard with its published baseline and merged write, only on publish.
7
7
  * Puck's public reducer bypasses slot disallow; this server check covers that path.
8
- */ export function refuseNewNestedTests(req, collection, before, after, tests) {
8
+ */ export function refuseNewNestedTests(req, collection, before, after, tests, locales) {
9
9
  const options = req.payload.config.custom?.xp;
10
10
  const registration = puckCollections(options).find((entry)=>entry.slug === collection);
11
11
  if (!registration) return;
12
12
  const reader = placementReader(req, collection, options);
13
13
  for (const view of reader.views){
14
+ if (locales && !locales.has(view.locale) || !reader.isPublished(after, view)) continue;
14
15
  const read = (doc)=>{
16
+ if (!reader.isPublished(doc, view)) return [];
15
17
  const content = reader.read(doc, 'all-locales', view);
16
18
  return content.editor === 'puck' ? nestedTests(content.doc?.[registration.field]) : [];
17
19
  };
@@ -0,0 +1,15 @@
1
+ import type { Status } from '../types/status.js';
2
+ export declare const STATUS_LABELS: {
3
+ draft: string;
4
+ running: string;
5
+ stopped: string;
6
+ decided: string;
7
+ archived: string;
8
+ scheduled: string;
9
+ paused: string;
10
+ };
11
+ export type DisplayStatus = keyof typeof STATUS_LABELS;
12
+ export declare function displayStatus({ status, startedAt }: {
13
+ status: Status;
14
+ startedAt?: string | null;
15
+ }, now?: number): DisplayStatus;
@@ -0,0 +1,12 @@
1
+ export const STATUS_LABELS = {
2
+ draft: 'Draft',
3
+ running: 'Running',
4
+ stopped: 'Stopped',
5
+ decided: 'Decided',
6
+ archived: 'Archived',
7
+ scheduled: 'Scheduled',
8
+ paused: 'Paused'
9
+ };
10
+ export function displayStatus({ status, startedAt }, now = Date.now()) {
11
+ return status === 'running' && Date.parse(startedAt ?? '') > now ? 'scheduled' : status;
12
+ }
@@ -1,10 +1,14 @@
1
+ import { type FrozenCohortRule } from '../cohorts/rule.js';
1
2
  import type { PayloadRequest } from 'payload';
2
3
  import type { Arm, DocId, ExperimentKind, ExposurePolicy, Status, TargetingRule, UnitType } from '../types/contracts.js';
3
4
  import type { Manifest, ManifestExperiment } from '../types/manifest.js';
4
5
  import type { AttributeKeys } from '../runtime/targeting.js';
6
+ import type { ExperimentSchedule, PauseInterval } from '../schedule/types.js';
5
7
  type TypedTargetingRule = ManifestExperiment['targeting'][number];
6
8
  export interface ManifestCompileOptions {
7
9
  attributeKeys?: AttributeKeys;
10
+ /** @internal */
11
+ now?: () => Date;
8
12
  onInvalid?(slug: string, reason: string): void;
9
13
  }
10
14
  export interface ManifestPhase {
@@ -13,10 +17,13 @@ export interface ManifestPhase {
13
17
  seed: string;
14
18
  arms: Arm[];
15
19
  allocation: number;
16
- targeting: Array<TargetingRule & {
20
+ targeting: Array<(TargetingRule & {
17
21
  type?: TypedTargetingRule['type'];
18
- }>;
22
+ }) | FrozenCohortRule>;
19
23
  endedAt?: string | null;
24
+ startedAt?: string | null;
25
+ schedule?: ExperimentSchedule | null;
26
+ pauses?: PauseInterval[] | null;
20
27
  }
21
28
  export interface ManifestInputExperiment {
22
29
  id: DocId;
@@ -43,6 +50,11 @@ export interface ManifestInputExperiment {
43
50
  export interface ManifestInputs {
44
51
  experiments: ManifestInputExperiment[];
45
52
  flagDefaults: Manifest['flagDefaults'];
53
+ cohortSourcePhases?: Array<{
54
+ experiment: DocId;
55
+ phase: number;
56
+ endedAt?: string | null;
57
+ }>;
46
58
  excludeIds?: DocId[];
47
59
  pruneFlagDefaultIds?: DocId[];
48
60
  }
@@ -51,12 +63,11 @@ export declare function loadManifestInputs(req: PayloadRequest, { excludeIds, pr
51
63
  pruneFlagDefaultIds?: DocId[];
52
64
  signal?: AbortSignal;
53
65
  }): Promise<ManifestInputs>;
54
- /** Pure compiler. Assignment config comes exclusively from the frozen phase. */
55
66
  /**
56
67
  * Pure manifest builder (exported from `/rsc` for host tests). Pass the same `attributeKeys` as the plugin options,
57
68
  * or legacy untyped targeting rules are dropped. Its input shape may change in a pre-1.0 minor.
58
69
  */
59
- export declare function compileManifest(inputs: ManifestInputs, revision: number, { attributeKeys, onInvalid }?: ManifestCompileOptions): Manifest;
70
+ export declare function compileManifest(inputs: ManifestInputs, revision: number, { attributeKeys, onInvalid, now }?: ManifestCompileOptions): Manifest;
60
71
  /** Take the state lock before reading inputs. Under READ COMMITTED, a builder
61
72
  * waiting for another transition then sees that transition's committed changes,
62
73
  * so a later revision cannot overwrite the manifest with pre-lock input state.
@@ -1,7 +1,13 @@
1
+ import { isCohortRule } from '../cohorts/rule.js';
1
2
  import { txExecutor } from '../db/executor.js';
2
3
  import { bumpRevision, writeManifest } from '../db/state.js';
4
+ import { LATE_BEACON_GRACE_MS } from '../db/snapshots.js';
3
5
  import { XpRefusal } from '../errors.js';
4
6
  import { xpOptionsFromReq } from '../options/fromReq.js';
7
+ const sourceId = (experiment, phase)=>JSON.stringify([
8
+ String(experiment),
9
+ phase
10
+ ]);
5
11
  export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaultIds = [], signal } = {}) {
6
12
  signal?.throwIfAborted();
7
13
  // §7.8 manifest reads: transitions compile all live/archived routing state.
@@ -80,6 +86,42 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
80
86
  } : {}
81
87
  });
82
88
  }
89
+ const sources = new Map();
90
+ for (const experiment of experiments){
91
+ for (const rule of experiment.currentPhase?.targeting ?? []){
92
+ if (isCohortRule(rule) && 'key' in rule) sources.set(sourceId(rule.experiment, rule.phase), rule);
93
+ }
94
+ }
95
+ let cohortSourcePhases;
96
+ if (sources.size) {
97
+ // §7.8 manifest reads: frozen cohort rules refer to exact rounds, including stopped sources.
98
+ const phases = await req.payload.find({
99
+ collection: 'xp-phases',
100
+ req,
101
+ overrideAccess: true,
102
+ depth: 0,
103
+ limit: 0,
104
+ where: {
105
+ or: [
106
+ ...sources.values()
107
+ ].map((rule)=>({
108
+ experiment: {
109
+ equals: rule.experiment
110
+ },
111
+ phase: {
112
+ equals: rule.phase
113
+ }
114
+ }))
115
+ },
116
+ select: {
117
+ experiment: true,
118
+ phase: true,
119
+ endedAt: true
120
+ }
121
+ });
122
+ signal?.throwIfAborted();
123
+ cohortSourcePhases = phases.docs;
124
+ }
83
125
  // §7.8 manifest reads: defaults are part of the private compiled manifest.
84
126
  const state = await req.payload.findGlobal({
85
127
  slug: 'xp-state',
@@ -90,6 +132,7 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
90
132
  return {
91
133
  experiments,
92
134
  flagDefaults: state.flagDefaults ?? {},
135
+ cohortSourcePhases,
93
136
  excludeIds,
94
137
  pruneFlagDefaultIds
95
138
  };
@@ -111,12 +154,34 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
111
154
  });
112
155
  inputs.flagDefaults = defaults;
113
156
  }
114
- /** Pure compiler. Assignment config comes exclusively from the frozen phase. */ /**
157
+ function compileActive(phase, now) {
158
+ const { schedule, startedAt } = phase;
159
+ // The phase may open at a later instant than the configured start.
160
+ let from = schedule?.startAt;
161
+ if (startedAt && Date.parse(startedAt) > now.getTime() && (!from || Date.parse(startedAt) > Date.parse(from))) from = startedAt;
162
+ if (!schedule && !from) return undefined;
163
+ return {
164
+ tz: schedule?.timeZone ?? 'UTC',
165
+ windows: schedule?.windows ?? [],
166
+ ...from ? {
167
+ from: new Date(from).toISOString()
168
+ } : {},
169
+ ...schedule?.endAt ? {
170
+ to: new Date(schedule.endAt).toISOString()
171
+ } : {}
172
+ };
173
+ }
174
+ /**
115
175
  * Pure manifest builder (exported from `/rsc` for host tests). Pass the same `attributeKeys` as the plugin options,
116
176
  * or legacy untyped targeting rules are dropped. Its input shape may change in a pre-1.0 minor.
117
- */ export function compileManifest(inputs, revision, { attributeKeys, onInvalid } = {}) {
177
+ */ export function compileManifest(inputs, revision, { attributeKeys, onInvalid, now = ()=>new Date() } = {}) {
178
+ const compiledAt = now();
118
179
  const excluded = new Set(inputs.excludeIds?.map(String));
119
180
  const prunedDefaults = new Set(inputs.pruneFlagDefaultIds?.map(String));
181
+ const sourceEnds = new Map(inputs.cohortSourcePhases?.map((source)=>[
182
+ sourceId(source.experiment, source.phase),
183
+ source.endedAt
184
+ ]));
120
185
  const manifest = {
121
186
  v: 1,
122
187
  revision,
@@ -153,7 +218,19 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
153
218
  if (experiment.status !== 'running' && experiment.status !== 'decided') continue;
154
219
  if (!phase) throw new Error(`Missing current phase for experiment ${experiment.slug}`);
155
220
  const targeting = [];
221
+ const cohorts = [];
156
222
  for (const rule of phase.targeting ?? []){
223
+ if (isCohortRule(rule)) {
224
+ if (!('key' in rule) || !rule.key) break;
225
+ const endedAt = sourceEnds.get(sourceId(rule.experiment, rule.phase));
226
+ const closedAtMs = endedAt ? Date.parse(endedAt) + LATE_BEACON_GRACE_MS : NaN;
227
+ cohorts.push({
228
+ key: rule.key,
229
+ include: rule.include,
230
+ sourceClosedAt: Number.isFinite(closedAtMs) ? new Date(closedAtMs).toISOString() : null
231
+ });
232
+ continue;
233
+ }
157
234
  // Legacy phases have no stored type. Only those consult today's registry.
158
235
  const type = rule.type ?? (attributeKeys && Object.hasOwn(attributeKeys, rule.attribute) ? attributeKeys[rule.attribute]?.type : undefined);
159
236
  if (type !== 'string' && type !== 'number' && type !== 'boolean') break;
@@ -164,7 +241,7 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
164
241
  type
165
242
  });
166
243
  }
167
- if (targeting.length !== (phase.targeting ?? []).length) {
244
+ if (targeting.length + cohorts.length !== (phase.targeting ?? []).length) {
168
245
  onInvalid?.(experiment.slug, 'untyped-targeting-rule');
169
246
  continue;
170
247
  }
@@ -179,6 +256,8 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
179
256
  slices: experiment.layerSlices
180
257
  };
181
258
  }
259
+ const active = experiment.status === 'running' ? compileActive(phase, compiledAt) : undefined;
260
+ const resumedAt = experiment.status === 'running' ? phase.pauses?.at(-1)?.to : undefined;
182
261
  const compiled = {
183
262
  id: experiment.id,
184
263
  slug: experiment.slug,
@@ -208,6 +287,9 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
208
287
  }),
209
288
  targeting,
210
289
  exposurePolicy: experiment.exposurePolicy,
290
+ ...cohorts.length ? {
291
+ cohorts
292
+ } : {},
211
293
  deferrable: targeting.some((rule)=>rule.attribute === 'loggedIn' || rule.attribute === 'staff'),
212
294
  ...experiment.flagPoint ? {
213
295
  flagPoint: experiment.flagPoint
@@ -215,6 +297,12 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
215
297
  ...layer ? {
216
298
  layer
217
299
  } : {},
300
+ ...active ? {
301
+ active
302
+ } : {},
303
+ ...resumedAt ? {
304
+ resumedAt: new Date(resumedAt).toISOString()
305
+ } : {},
218
306
  ...decision?.winnerArm ? {
219
307
  winnerArm: decision.winnerArm
220
308
  } : {}
package/dist/onInit.js CHANGED
@@ -1,4 +1,4 @@
1
- import { puckCollections } from './options.js';
1
+ import { isValidTimeZone, puckCollections } from './options.js';
2
2
  import { pageGuardEnterOperation } from './hooks/pageGuard.js';
3
3
  import { findRegisteredBlocksField } from './blocks/formState.js';
4
4
  import { EXPERIMENT_BLOCK_SLUG } from './blocks/model.js';
@@ -29,6 +29,9 @@ function registeredPaths(fields, name, parent = []) {
29
29
  }
30
30
  export function createOnInit(options) {
31
31
  return async (payload)=>{
32
+ if (options.timeZone !== undefined && !isValidTimeZone(options.timeZone)) {
33
+ throw new Error('Experiments timeZone must be an IANA time zone');
34
+ }
32
35
  const rateLimit = options.events?.rateLimit;
33
36
  if (rateLimit !== false && typeof rateLimit !== 'function') {
34
37
  throw new Error('Experiments requires events.rateLimit to be a client-address rate limiter, or false if you rate-limit the events route upstream.');
@@ -43,11 +46,6 @@ export function createOnInit(options) {
43
46
  ]);
44
47
  for (const collection of payload.config.collections ?? []){
45
48
  if (!guarded.has(collection.slug)) continue;
46
- // Page-only guards also read the raw main row's scalar _status when
47
- // protecting unpublishes and restores; localized status breaks those too.
48
- if (payload.config.localization && payload.config.experimental?.localizeStatus && collection.versions && collection.versions.drafts && collection.versions.drafts.localizeStatus) {
49
- throw new Error(`Experiments collection ${collection.slug} does not support versions.drafts.localizeStatus. Use a shared publication status.`);
50
- }
51
49
  if (collection.hooks) {
52
50
  const hooks = collection.hooks.beforeOperation ?? [];
53
51
  collection.hooks.beforeOperation = [
package/dist/options.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ExperimentsPluginOptions, ResolvedOptions } from './types/contracts.js';
2
+ export { isValidTimeZone } from './schedule/activeTime.js';
2
3
  /** Resolve once per registration list; every consumer shares the same field defaults. */
3
4
  export declare function puckCollections(options: Pick<ExperimentsPluginOptions, 'puck'>): Array<{
4
5
  slug: string;