@delmaredigital/payload-experiments 0.4.0-rc.3 → 0.4.0-rc.4

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 (301) hide show
  1. package/dist/admin/LayerUsage.js +1 -1
  2. package/dist/admin/MetricSourceSelect.js +2 -2
  3. package/dist/admin/PlacementStatus.js +1 -1
  4. package/dist/admin/TestsDashboardCards.js +2 -2
  5. package/dist/admin/TestsNavLink.js +2 -2
  6. package/dist/admin/blocks/BlockPanel.js +3 -3
  7. package/dist/admin/blocks/TestBlockField.js +3 -3
  8. package/dist/admin/blocks/formApi.js +1 -1
  9. package/dist/admin/blocks/model.js +1 -1
  10. package/dist/admin/blocks/statusCache.js +1 -1
  11. package/dist/admin/components/RootViewMessage.js +1 -1
  12. package/dist/admin/copy/blocks.d.ts +2 -2
  13. package/dist/admin/copy/blocks.js +3 -2
  14. package/dist/admin/copy/goals.d.ts +5 -1
  15. package/dist/admin/copy/goals.js +9 -3
  16. package/dist/admin/goals/XpGoalField.js +155 -129
  17. package/dist/admin/goals/xpGoalField.css +2 -3
  18. package/dist/admin/status.model.js +1 -1
  19. package/dist/admin/surface/ResultsRoute.d.ts +2 -1
  20. package/dist/admin/surface/ResultsRoute.js +4 -3
  21. package/dist/admin/surface/SurfaceShell.js +2 -2
  22. package/dist/admin/surface/TestsHome.d.ts +1 -1
  23. package/dist/admin/surface/TestsHome.js +3 -3
  24. package/dist/admin/surface/TestsSurface.js +2 -2
  25. package/dist/admin/surface/goals/GoalForm.d.ts +1 -1
  26. package/dist/admin/surface/goals/GoalForm.js +55 -7
  27. package/dist/admin/surface/goals/GoalsList.d.ts +1 -1
  28. package/dist/admin/surface/goals/GoalsList.js +4 -4
  29. package/dist/admin/surface/goals/data.js +2 -2
  30. package/dist/admin/surface/goals/goals.css +7 -0
  31. package/dist/admin/surface/goals/goals.model.d.ts +11 -1
  32. package/dist/admin/surface/goals/goals.model.js +43 -0
  33. package/dist/admin/surface/home.model.d.ts +1 -1
  34. package/dist/admin/surface/home.model.js +5 -5
  35. package/dist/admin/surface/newTest/NewTest.d.ts +1 -1
  36. package/dist/admin/surface/newTest/NewTest.js +1 -1
  37. package/dist/admin/surface/newTest/PageWizard.d.ts +1 -1
  38. package/dist/admin/surface/newTest/PageWizard.js +13 -13
  39. package/dist/admin/surface/results/ResultsHeader.d.ts +2 -2
  40. package/dist/admin/surface/results/ResultsHeader.js +8 -8
  41. package/dist/admin/surface/test/TestPage.d.ts +1 -2
  42. package/dist/admin/surface/test/TestPage.js +45 -156
  43. package/dist/admin/views/ExperimentsRootView.js +1 -1
  44. package/dist/admin/views/TestsNavLinkServer.js +1 -1
  45. package/dist/admin/views/renderCollectionList.js +1 -1
  46. package/dist/admin/views/renderTestsSurface.js +1 -1
  47. package/dist/blocks/placementLocale.d.ts +21 -0
  48. package/dist/blocks/placementLocale.js +115 -0
  49. package/dist/collections/experiments/config.js +1 -1
  50. package/dist/collections/metrics.js +1 -1
  51. package/dist/db/bulkPlacementRemoval.d.ts +30 -0
  52. package/dist/db/bulkPlacementRemoval.js +107 -0
  53. package/dist/db/placements.d.ts +2 -0
  54. package/dist/db/placements.js +8 -0
  55. package/dist/endpoints/editorSurface.d.ts +3 -0
  56. package/dist/endpoints/editorSurface.js +31 -0
  57. package/dist/endpoints/index.js +28 -1
  58. package/dist/errors.d.ts +1 -0
  59. package/dist/errors.js +2 -0
  60. package/dist/fields/xpGoal.js +1 -1
  61. package/dist/goals/picker/clickGoalPicker.model.d.ts +8 -1
  62. package/dist/goals/picker/clickGoalPicker.model.js +20 -2
  63. package/dist/goals/picker/copy.d.ts +4 -2
  64. package/dist/goals/picker/copy.js +4 -2
  65. package/dist/goals/picker/useClickGoalPicker.d.ts +1 -1
  66. package/dist/goals/picker/useClickGoalPicker.js +4 -2
  67. package/dist/hooks/blockRemovalRule.d.ts +29 -0
  68. package/dist/hooks/blockRemovalRule.js +141 -0
  69. package/dist/hooks/pageGuard.d.ts +24 -2
  70. package/dist/hooks/pageGuard.js +178 -24
  71. package/dist/lib/placementPages.d.ts +9 -0
  72. package/dist/{admin/previewLinks.model.js → lib/placementPages.js} +1 -4
  73. package/dist/onInit.js +22 -0
  74. package/dist/plugin.js +2 -1
  75. package/dist/puck/ExperimentPicker.js +25 -10
  76. package/dist/puck/copy.d.ts +4 -1
  77. package/dist/puck/copy.js +4 -1
  78. package/dist/puck/editor/ConfigureTestDrawer.d.ts +21 -0
  79. package/dist/puck/editor/ConfigureTestDrawer.js +147 -0
  80. package/dist/puck/editor/CreateExperimentDrawer.d.ts +11 -2
  81. package/dist/puck/editor/CreateExperimentDrawer.js +69 -9
  82. package/dist/puck/editor/EditorControls.d.ts +14 -0
  83. package/dist/puck/editor/EditorControls.js +99 -0
  84. package/dist/puck/editor/ExperimentSlotEditor.js +317 -51
  85. package/dist/puck/editor/ResultsReadout.js +3 -5
  86. package/dist/puck/editor/VersionBuilder.js +2 -2
  87. package/dist/puck/editor/armsCache.d.ts +3 -1
  88. package/dist/puck/editor/armsCache.js +20 -3
  89. package/dist/puck/editor/copy.d.ts +18 -2
  90. package/dist/puck/editor/copy.js +19 -3
  91. package/dist/puck/editor/editor.chrome.css +33 -0
  92. package/dist/puck/editor/editor.css +39 -0
  93. package/dist/puck/editor/editor.model.d.ts +14 -0
  94. package/dist/puck/editor/editor.model.js +58 -1
  95. package/dist/puck/editor/editorSurface.d.ts +10 -0
  96. package/dist/puck/editor/editorSurface.js +65 -0
  97. package/dist/puck/editor/localPlacements.d.ts +2 -0
  98. package/dist/puck/editor/localPlacements.js +29 -0
  99. package/dist/puck/editor/placementsCache.d.ts +19 -0
  100. package/dist/puck/editor/placementsCache.js +83 -0
  101. package/dist/puck/editor/xpGoalPuckEditorField.js +109 -98
  102. package/dist/puck/experimentSlotField.d.ts +3 -0
  103. package/dist/puck/experimentSlotField.js +15 -4
  104. package/dist/{admin → testSurface}/actions/DecideDialog.d.ts +2 -1
  105. package/dist/{admin → testSurface}/actions/DecideDialog.js +6 -4
  106. package/dist/{admin → testSurface}/api.js +4 -5
  107. package/dist/{admin → testSurface}/copy/common.d.ts +2 -0
  108. package/dist/{admin → testSurface}/copy/common.js +2 -0
  109. package/dist/{admin → testSurface}/copy/readiness.d.ts +3 -0
  110. package/dist/{admin → testSurface}/copy/readiness.js +3 -0
  111. package/dist/{admin → testSurface}/copy/testPage.d.ts +3 -0
  112. package/dist/{admin → testSurface}/copy/testPage.js +7 -2
  113. package/dist/testSurface/format/adminURL.d.ts +7 -0
  114. package/dist/testSurface/format/adminURL.js +9 -0
  115. package/dist/{admin → testSurface}/placements/placementLabels.js +1 -1
  116. package/dist/{admin → testSurface}/previewLinks.model.d.ts +1 -6
  117. package/dist/testSurface/previewLinks.model.js +4 -0
  118. package/dist/testSurface/results/results.css +64 -0
  119. package/dist/{admin → testSurface}/surface/contracts.d.ts +1 -0
  120. package/dist/{admin → testSurface}/surface/pageBlock/parts.js +6 -6
  121. package/dist/testSurface/surface/pagePicker/pagePicker.css +10 -0
  122. package/dist/{admin → testSurface}/surface/readiness/useTransition.js +1 -0
  123. package/dist/{admin → testSurface}/surface/results/ResultsBody.d.ts +2 -2
  124. package/dist/{admin → testSurface}/surface/results/ResultsBody.js +18 -11
  125. package/dist/testSurface/surface/setting/setting.css +17 -0
  126. package/dist/testSurface/surface/test/GoalSection.d.ts +4 -0
  127. package/dist/{admin → testSurface}/surface/test/GoalSection.js +3 -2
  128. package/dist/testSurface/surface/test/TestSurface.d.ts +18 -0
  129. package/dist/testSurface/surface/test/TestSurface.js +152 -0
  130. package/dist/testSurface/surface/test/VersionsSection.d.ts +5 -0
  131. package/dist/{admin → testSurface}/surface/test/VersionsSection.js +12 -6
  132. package/dist/testSurface/surface/test/testPage.css +92 -0
  133. package/dist/{admin → testSurface}/surface/useTestDocument.d.ts +5 -1
  134. package/dist/{admin → testSurface}/surface/useTestDocument.js +34 -3
  135. package/dist/{admin → testSurface}/surfaceUrls.js +1 -1
  136. package/dist/transitions/placementInteractions.js +1 -1
  137. package/dist/transitions/placements.d.ts +27 -8
  138. package/dist/transitions/placements.js +77 -6
  139. package/dist/transitions/start.js +2 -2
  140. package/dist/types/endpoints.d.ts +1 -1
  141. package/dist/ui/Dialog.d.ts +4 -1
  142. package/dist/ui/Dialog.js +41 -3
  143. package/dist/ui/Drawer.d.ts +10 -0
  144. package/dist/ui/Drawer.js +29 -0
  145. package/dist/ui/Tabs.d.ts +3 -3
  146. package/dist/ui/Tabs.js +35 -33
  147. package/dist/ui/ui.css +6 -0
  148. package/package.json +1 -1
  149. package/dist/admin/actions/ConfirmDialog.d.ts +0 -19
  150. package/dist/admin/actions/ConfirmDialog.js +0 -149
  151. package/dist/admin/results/results.css +0 -64
  152. package/dist/admin/styles.css +0 -10
  153. package/dist/admin/styles.d.ts +0 -2
  154. package/dist/admin/styles.js +0 -3
  155. package/dist/admin/surface/pagePicker/pagePicker.css +0 -10
  156. package/dist/admin/surface/setting/setting.css +0 -17
  157. package/dist/admin/surface/test/GoalSection.d.ts +0 -2
  158. package/dist/admin/surface/test/VersionsSection.d.ts +0 -4
  159. package/dist/admin/surface/test/testPage.css +0 -92
  160. /package/dist/{admin → testSurface}/PreviewLinks.d.ts +0 -0
  161. /package/dist/{admin → testSurface}/PreviewLinks.js +0 -0
  162. /package/dist/{admin → testSurface}/actions/MakeContentResult.d.ts +0 -0
  163. /package/dist/{admin → testSurface}/actions/MakeContentResult.js +0 -0
  164. /package/dist/{admin → testSurface}/actions/actions.model.d.ts +0 -0
  165. /package/dist/{admin → testSurface}/actions/actions.model.js +0 -0
  166. /package/dist/{admin → testSurface}/actions/decide.model.d.ts +0 -0
  167. /package/dist/{admin → testSurface}/actions/decide.model.js +0 -0
  168. /package/dist/{admin → testSurface}/allocation.model.d.ts +0 -0
  169. /package/dist/{admin → testSurface}/allocation.model.js +0 -0
  170. /package/dist/{admin → testSurface}/api.d.ts +0 -0
  171. /package/dist/{admin → testSurface}/arms/arms.model.d.ts +0 -0
  172. /package/dist/{admin → testSurface}/arms/arms.model.js +0 -0
  173. /package/dist/{admin → testSurface}/arms/pageTarget.model.d.ts +0 -0
  174. /package/dist/{admin → testSurface}/arms/pageTarget.model.js +0 -0
  175. /package/dist/{admin → testSurface}/arms/params.model.d.ts +0 -0
  176. /package/dist/{admin → testSurface}/arms/params.model.js +0 -0
  177. /package/dist/{admin → testSurface}/copy/actions.d.ts +0 -0
  178. /package/dist/{admin → testSurface}/copy/actions.js +0 -0
  179. /package/dist/{admin → testSurface}/copy/advanced.d.ts +0 -0
  180. /package/dist/{admin → testSurface}/copy/advanced.js +0 -0
  181. /package/dist/{admin → testSurface}/copy/arms.d.ts +0 -0
  182. /package/dist/{admin → testSurface}/copy/arms.js +0 -0
  183. /package/dist/{admin → testSurface}/copy/audience.d.ts +0 -0
  184. /package/dist/{admin → testSurface}/copy/audience.js +0 -0
  185. /package/dist/{admin → testSurface}/copy/metrics.d.ts +0 -0
  186. /package/dist/{admin → testSurface}/copy/metrics.js +0 -0
  187. /package/dist/{admin → testSurface}/copy/pages.d.ts +0 -0
  188. /package/dist/{admin → testSurface}/copy/pages.js +0 -0
  189. /package/dist/{admin → testSurface}/copy/recommendation.d.ts +0 -0
  190. /package/dist/{admin → testSurface}/copy/recommendation.js +0 -0
  191. /package/dist/{admin → testSurface}/copy/results.d.ts +0 -0
  192. /package/dist/{admin → testSurface}/copy/results.js +0 -0
  193. /package/dist/{admin → testSurface}/copy/review.d.ts +0 -0
  194. /package/dist/{admin → testSurface}/copy/review.js +0 -0
  195. /package/dist/{admin → testSurface}/copy/setting.d.ts +0 -0
  196. /package/dist/{admin → testSurface}/copy/setting.js +0 -0
  197. /package/dist/{admin → testSurface}/copy/surface.d.ts +0 -0
  198. /package/dist/{admin → testSurface}/copy/surface.js +0 -0
  199. /package/dist/{admin → testSurface}/format/date.d.ts +0 -0
  200. /package/dist/{admin → testSurface}/format/date.js +0 -0
  201. /package/dist/{admin → testSurface}/labels.d.ts +0 -0
  202. /package/dist/{admin → testSurface}/labels.js +0 -0
  203. /package/dist/{admin → testSurface}/lockedNotice.model.d.ts +0 -0
  204. /package/dist/{admin → testSurface}/lockedNotice.model.js +0 -0
  205. /package/dist/{admin → testSurface}/metricSource.model.d.ts +0 -0
  206. /package/dist/{admin → testSurface}/metricSource.model.js +0 -0
  207. /package/dist/{admin → testSurface}/placements/placementLabels.d.ts +0 -0
  208. /package/dist/{admin → testSurface}/placements/placementLabels.model.d.ts +0 -0
  209. /package/dist/{admin → testSurface}/placements/placementLabels.model.js +0 -0
  210. /package/dist/{admin → testSurface}/placements/usePlacementLabels.d.ts +0 -0
  211. /package/dist/{admin → testSurface}/placements/usePlacementLabels.js +0 -0
  212. /package/dist/{admin → testSurface}/reload.d.ts +0 -0
  213. /package/dist/{admin → testSurface}/reload.js +0 -0
  214. /package/dist/{admin → testSurface}/results/CappedCell.d.ts +0 -0
  215. /package/dist/{admin → testSurface}/results/CappedCell.js +0 -0
  216. /package/dist/{admin → testSurface}/results/CiChart.d.ts +0 -0
  217. /package/dist/{admin → testSurface}/results/CiChart.js +0 -0
  218. /package/dist/{admin → testSurface}/results/DataQualityPanel.d.ts +0 -0
  219. /package/dist/{admin → testSurface}/results/DataQualityPanel.js +0 -0
  220. /package/dist/{admin → testSurface}/results/DataTable.d.ts +0 -0
  221. /package/dist/{admin → testSurface}/results/DataTable.js +0 -0
  222. /package/dist/{admin → testSurface}/results/StatTile.d.ts +0 -0
  223. /package/dist/{admin → testSurface}/results/StatTile.js +0 -0
  224. /package/dist/{admin → testSurface}/results/VerdictHero.d.ts +0 -0
  225. /package/dist/{admin → testSurface}/results/VerdictHero.js +0 -0
  226. /package/dist/{admin → testSurface}/results/chart.model.d.ts +0 -0
  227. /package/dist/{admin → testSurface}/results/chart.model.js +0 -0
  228. /package/dist/{admin → testSurface}/results/format.d.ts +0 -0
  229. /package/dist/{admin → testSurface}/results/format.js +0 -0
  230. /package/dist/{admin → testSurface}/results/legacy.d.ts +0 -0
  231. /package/dist/{admin → testSurface}/results/legacy.js +0 -0
  232. /package/dist/{admin → testSurface}/results/releasePages.model.d.ts +0 -0
  233. /package/dist/{admin → testSurface}/results/releasePages.model.js +0 -0
  234. /package/dist/{admin → testSurface}/results/results.model.d.ts +0 -0
  235. /package/dist/{admin → testSurface}/results/results.model.js +0 -0
  236. /package/dist/{admin → testSurface}/results/snapshot.d.ts +0 -0
  237. /package/dist/{admin → testSurface}/results/snapshot.js +0 -0
  238. /package/dist/{admin → testSurface}/review/review.model.d.ts +0 -0
  239. /package/dist/{admin → testSurface}/review/review.model.js +0 -0
  240. /package/dist/{admin → testSurface}/surface/contracts.js +0 -0
  241. /package/dist/{admin → testSurface}/surface/pageBlock/pageBlock.model.d.ts +0 -0
  242. /package/dist/{admin → testSurface}/surface/pageBlock/pageBlock.model.js +0 -0
  243. /package/dist/{admin → testSurface}/surface/pageBlock/parts.d.ts +0 -0
  244. /package/dist/{admin → testSurface}/surface/pagePicker/CopyRoute.d.ts +0 -0
  245. /package/dist/{admin → testSurface}/surface/pagePicker/CopyRoute.js +0 -0
  246. /package/dist/{admin → testSurface}/surface/pagePicker/PageCombobox.d.ts +0 -0
  247. /package/dist/{admin → testSurface}/surface/pagePicker/PageCombobox.js +0 -0
  248. /package/dist/{admin → testSurface}/surface/pagePicker/pagePicker.model.d.ts +0 -0
  249. /package/dist/{admin → testSurface}/surface/pagePicker/pagePicker.model.js +0 -0
  250. /package/dist/{admin → testSurface}/surface/readiness/ActionDialogs.d.ts +0 -0
  251. /package/dist/{admin → testSurface}/surface/readiness/ActionDialogs.js +0 -0
  252. /package/dist/{admin → testSurface}/surface/readiness/Banner.d.ts +0 -0
  253. /package/dist/{admin → testSurface}/surface/readiness/Banner.js +0 -0
  254. /package/dist/{admin → testSurface}/surface/readiness/SaveStatus.d.ts +0 -0
  255. /package/dist/{admin → testSurface}/surface/readiness/SaveStatus.js +0 -0
  256. /package/dist/{admin → testSurface}/surface/readiness/parts.d.ts +0 -0
  257. /package/dist/{admin → testSurface}/surface/readiness/parts.js +0 -0
  258. /package/dist/{admin → testSurface}/surface/readiness/readiness.model.d.ts +0 -0
  259. /package/dist/{admin → testSurface}/surface/readiness/readiness.model.js +0 -0
  260. /package/dist/{admin → testSurface}/surface/readiness/useTransition.d.ts +0 -0
  261. /package/dist/{admin → testSurface}/surface/results/ReleasePages.d.ts +0 -0
  262. /package/dist/{admin → testSurface}/surface/results/ReleasePages.js +0 -0
  263. /package/dist/{admin → testSurface}/surface/results/recommendation.model.d.ts +0 -0
  264. /package/dist/{admin → testSurface}/surface/results/recommendation.model.js +0 -0
  265. /package/dist/{admin → testSurface}/surface/results/useResults.d.ts +0 -0
  266. /package/dist/{admin → testSurface}/surface/results/useResults.js +0 -0
  267. /package/dist/{admin → testSurface}/surface/setting/parts.d.ts +0 -0
  268. /package/dist/{admin → testSurface}/surface/setting/parts.js +0 -0
  269. /package/dist/{admin → testSurface}/surface/setting/setting.model.d.ts +0 -0
  270. /package/dist/{admin → testSurface}/surface/setting/setting.model.js +0 -0
  271. /package/dist/{admin → testSurface}/surface/test/AdvancedSection.d.ts +0 -0
  272. /package/dist/{admin → testSurface}/surface/test/AdvancedSection.js +0 -0
  273. /package/dist/{admin → testSurface}/surface/test/LengthSection.d.ts +0 -0
  274. /package/dist/{admin → testSurface}/surface/test/LengthSection.js +0 -0
  275. /package/dist/{admin → testSurface}/surface/test/PageHoldout.d.ts +0 -0
  276. /package/dist/{admin → testSurface}/surface/test/PageHoldout.js +0 -0
  277. /package/dist/{admin → testSurface}/surface/test/Rail.d.ts +0 -0
  278. /package/dist/{admin → testSurface}/surface/test/Rail.js +0 -0
  279. /package/dist/{admin → testSurface}/surface/test/ReadinessBar.d.ts +0 -0
  280. /package/dist/{admin → testSurface}/surface/test/ReadinessBar.js +0 -0
  281. /package/dist/{admin → testSurface}/surface/test/Section.d.ts +0 -0
  282. /package/dist/{admin → testSurface}/surface/test/Section.js +0 -0
  283. /package/dist/{admin → testSurface}/surface/test/TargetingSection.d.ts +0 -0
  284. /package/dist/{admin → testSurface}/surface/test/TargetingSection.js +0 -0
  285. /package/dist/{admin → testSurface}/surface/test/fields.d.ts +0 -0
  286. /package/dist/{admin → testSurface}/surface/test/fields.js +0 -0
  287. /package/dist/{admin → testSurface}/surface/test/jumpToSection.d.ts +0 -0
  288. /package/dist/{admin → testSurface}/surface/test/jumpToSection.js +0 -0
  289. /package/dist/{admin → testSurface}/surface/test/pageParts.d.ts +0 -0
  290. /package/dist/{admin → testSurface}/surface/test/pageParts.js +0 -0
  291. /package/dist/{admin → testSurface}/surface/test/testPage.model.d.ts +0 -0
  292. /package/dist/{admin → testSurface}/surface/test/testPage.model.js +0 -0
  293. /package/dist/{admin → testSurface}/surface/testDocument.model.d.ts +0 -0
  294. /package/dist/{admin → testSurface}/surface/testDocument.model.js +0 -0
  295. /package/dist/{admin → testSurface}/surfaceUrls.d.ts +0 -0
  296. /package/dist/{admin → testSurface}/targeting/targeting.model.d.ts +0 -0
  297. /package/dist/{admin → testSurface}/targeting/targeting.model.js +0 -0
  298. /package/dist/{admin → testSurface}/theme.d.ts +0 -0
  299. /package/dist/{admin → testSurface}/theme.js +0 -0
  300. /package/dist/{admin → testSurface}/useApi.d.ts +0 -0
  301. /package/dist/{admin → testSurface}/useApi.js +0 -0
@@ -0,0 +1,141 @@
1
+ import { removableBlockTests } from '../db/placements.js';
2
+ import { XpNoTransactionError, XpRefusal } from '../errors.js';
3
+ import { lastBlockPlacementCopy, pendingBlockRemovalCopy, bulkBlockRemovalCopy } from '../testSurface/copy/readiness.js';
4
+ import { hasOtherPublishedBlockPlacement } from '../transitions/placements.js';
5
+ import { bulkRemoves } from '../db/bulkPlacementRemoval.js';
6
+ import { localeRequest, placementLocaleContent, removedPlacementViews, placementDocumentKey } from '../blocks/placementLocale.js';
7
+ import { placementSlugs } from '../blocks/bindings.js';
8
+ export function releaseRemovalClaim(req, collection, id, ownKeys) {
9
+ const claims = req.context.xpPlacementRemovals;
10
+ for (const [test, documents] of claims?.tests ?? [])for (const key of documents){
11
+ const [slug, docId] = JSON.parse(key);
12
+ if (slug !== collection || docId !== String(id) || ownKeys && !ownKeys.get(test)?.has(key)) continue;
13
+ const count = claims?.counts?.get(test)?.get(key) ?? 1;
14
+ if (ownKeys && count > 1) claims.counts.get(test).set(key, count - 1);
15
+ else {
16
+ documents.delete(`${key}`);
17
+ claims?.counts?.get(test)?.delete(`${key}`);
18
+ claims?.absent?.delete(`${test}:${key}`);
19
+ }
20
+ }
21
+ }
22
+ /** A removal must have reached afterChange before a later write can restore it.
23
+ * A write merely retaining another locale cannot clear an in-flight removal.
24
+ */ export function observeUnpublishedRemoval(req, collection, id) {
25
+ const claims = req.context.xpPlacementRemovals;
26
+ if (!claims) return;
27
+ claims.absent ??= new Set();
28
+ for (const [test, documents] of claims.tests)for (const key of documents){
29
+ const [slug, docId] = JSON.parse(key);
30
+ if (slug === collection && docId === String(id)) claims.absent.add(`${test}:${key}`);
31
+ }
32
+ }
33
+ export function releaseRestoredRemovalClaims(req, collection, doc, test) {
34
+ const claims = req.context.xpPlacementRemovals;
35
+ if (!claims) return;
36
+ claims.absent ??= new Set();
37
+ for (const key of claims.tests.get(String(test.id)) ?? []){
38
+ const [slug, id, view] = JSON.parse(key);
39
+ if (slug !== collection || id !== String(doc.id)) continue;
40
+ const marker = `${test.id}:${key}`;
41
+ if (!placementSlugs(req.payload.config.custom.xp, collection, placementLocaleContent(localeRequest(req, view), collection, doc)).includes(test.slug)) claims.absent.add(marker);
42
+ else if (claims.absent.has(marker) && (claims.counts?.get(String(test.id))?.get(key) ?? 1) === 1) {
43
+ claims.tests.get(String(test.id)).delete(`${key}`);
44
+ claims.counts?.get(String(test.id))?.delete(`${key}`);
45
+ claims.absent.delete(`${marker}`);
46
+ }
47
+ }
48
+ }
49
+ // Separate removal-rule entry points let tests observe its IO independently
50
+ // of the earlier page-path and publish guards.
51
+ export const blockRemovalRule = {
52
+ async prepare (req, collection, before, after, removingPage, exec, tests) {
53
+ const views = removedPlacementViews(req, collection, before, after, removingPage);
54
+ const affected = views.size ? await blockRemovalRule.discover(exec, [
55
+ ...views.keys()
56
+ ], tests) : [];
57
+ return {
58
+ views,
59
+ affected
60
+ };
61
+ },
62
+ async discover (exec, removed, tests) {
63
+ if (tests) return tests.filter((test)=>test.kind === 'block' && [
64
+ 'draft',
65
+ 'stopped',
66
+ 'running'
67
+ ].includes(test.status) && removed.includes(test.slug));
68
+ return (await removableBlockTests(exec, removed)).map((test)=>({
69
+ ...test,
70
+ kind: 'block',
71
+ pageCollection: null,
72
+ phase: 0,
73
+ arms: [],
74
+ placementDocs: null
75
+ }));
76
+ },
77
+ claim (req, transaction, affected, collection, id, views) {
78
+ let claims = req.context.xpPlacementRemovals;
79
+ if (!claims) req.context.xpPlacementRemovals = claims = {
80
+ transaction,
81
+ tests: new Map()
82
+ };
83
+ claims.counts ??= new Map();
84
+ claims.absent ??= new Set();
85
+ if (claims.transaction !== transaction) {
86
+ claims.transaction = transaction;
87
+ claims.tests.clear();
88
+ claims.counts.clear();
89
+ claims.absent.clear();
90
+ }
91
+ for (const test of affected){
92
+ const documents = claims.tests.get(String(test.id)) ?? new Set();
93
+ const counts = claims.counts.get(String(test.id)) ?? new Map();
94
+ for (const view of views.get(test.slug) ?? []){
95
+ const key = placementDocumentKey(collection, id, view);
96
+ documents.add(key);
97
+ counts.set(key, (counts.get(key) ?? 0) + 1);
98
+ }
99
+ claims.tests.set(String(test.id), documents);
100
+ claims.counts.set(String(test.id), counts);
101
+ }
102
+ return claims;
103
+ },
104
+ async check (req, current, affected, collection, id, removingPage, views, bulk) {
105
+ const transaction = await req.transactionID;
106
+ // Claim only after every earlier guard passed. These claims cover subsequent
107
+ // writes; the complete bulk selection covers siblings before any can decide.
108
+ const claims = transaction == null ? undefined : blockRemovalRule.claim(req, transaction, affected, collection, id, views);
109
+ const ownKeys = new Map(affected.map((test)=>[
110
+ String(test.id),
111
+ new Set((views.get(test.slug) ?? []).map((view)=>placementDocumentKey(collection, id, view)))
112
+ ]));
113
+ try {
114
+ for (const test of affected){
115
+ if (!current.some((row)=>String(row.id) === String(test.id) && row.kind === 'block' && row.status === 'running')) continue;
116
+ const documents = claims?.tests.get(String(test.id));
117
+ let excludedSibling = false;
118
+ if (await hasOtherPublishedBlockPlacement(req, req.payload.config.custom.xp, test.slug, (slug, docId, view, doc)=>{
119
+ const key = placementDocumentKey(slug, docId, view);
120
+ if (ownKeys.get(String(test.id))?.has(key)) return true;
121
+ if (bulkRemoves(bulk, req, slug, doc, test.slug, view) || documents?.has(key)) {
122
+ excludedSibling = true;
123
+ return true;
124
+ }
125
+ return false;
126
+ })) continue;
127
+ if (transaction == null) throw new XpNoTransactionError('Save this page with transactions on.');
128
+ // Bulk selection is immutable through every sibling's decision, including
129
+ // earlier rule refusals. afterOperation explains unrelated failed writes.
130
+ const message = excludedSibling ? bulk ? bulkBlockRemovalCopy(test.name) : pendingBlockRemovalCopy(test.name) : lastBlockPlacementCopy(test.name, removingPage);
131
+ if (bulk && excludedSibling) bulk.refusals.set(message, pendingBlockRemovalCopy(test.name));
132
+ throw new XpRefusal('locked-placement', message, {
133
+ experimentId: test.id
134
+ }, 409);
135
+ }
136
+ } catch (error) {
137
+ releaseRemovalClaim(req, collection, id, ownKeys);
138
+ throw error;
139
+ }
140
+ }
141
+ };
@@ -1,9 +1,31 @@
1
- import type { CollectionAfterChangeHook, CollectionAfterOperationHook, CollectionBeforeChangeHook, CollectionBeforeDeleteHook, CollectionBeforeOperationHook } from 'payload';
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import type { CollectionAfterChangeHook, CollectionAfterOperationHook, CollectionBeforeChangeHook, CollectionBeforeDeleteHook, CollectionBeforeOperationHook, PayloadRequest } from 'payload';
3
+ import type { DocId } from '../types/contracts.js';
2
4
  import { type PlacementTest } from '../db/placements.js';
5
+ import { type BulkPlacementRemoval } from '../db/bulkPlacementRemoval.js';
6
+ type OperationFrame = {
7
+ collection: string;
8
+ request?: PayloadRequest;
9
+ draft: boolean;
10
+ restore: boolean;
11
+ pending?: boolean;
12
+ scoped?: boolean;
13
+ complete?: boolean;
14
+ detached?: boolean;
15
+ parent?: OperationFrame;
16
+ bulk?: BulkPlacementRemoval;
17
+ };
18
+ export declare const pageGuardOperationScope: AsyncLocalStorage<OperationFrame | undefined>;
19
+ /** Must be first: buildBeforeOperation invokes its first hook synchronously,
20
+ * before the operation registers its await continuation. Later host hooks may
21
+ * await nested operations; those keep separate async contexts. No IO here.
22
+ */
23
+ export declare const pageGuardEnterOperation: CollectionBeforeOperationHook;
3
24
  export declare const pageGuardBeforeOperation: CollectionBeforeOperationHook;
4
25
  export declare const pageGuardAfterOperation: CollectionAfterOperationHook;
5
- export declare function guardExperimentIds(tests: readonly PlacementTest[], slugs: readonly string[], collection: string, paths: readonly string[], held: unknown, tags?: Set<string>): string[];
26
+ export declare function guardExperimentIds(tests: readonly PlacementTest[], slugs: readonly string[], collection: string, paths: readonly string[], held: unknown, tags?: Set<string>, discovered?: readonly DocId[]): string[];
6
27
  export declare const pageGuardBeforeDelete: CollectionBeforeDeleteHook;
7
28
  export declare const pageGuardBeforeChange: CollectionBeforeChangeHook;
8
29
  /** Unwrapped: these writes must fail the publish closed, unlike the best-effort audit. */
9
30
  export declare const pageGuardAfterChange: CollectionAfterChangeHook;
31
+ export {};
@@ -1,37 +1,161 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { previousPublishedContent, storedContent } from '../db/appends.js';
2
3
  import { lockPlacementScope, sortLockKeys } from '../db/locks.js';
3
4
  import { txExecutor, pooledExecutor } from '../db/executor.js';
4
5
  import { normalisePath } from '../runtime/normalisePath.js';
5
6
  import { XpNoTransactionError, XpRefusal } from '../errors.js';
6
- import { placementGuardCopy, pageGuardCopy, READINESS_COPY } from '../admin/copy/readiness.js';
7
+ import { placementGuardCopy, pageGuardCopy, READINESS_COPY } from '../testSurface/copy/readiness.js';
7
8
  import { placementSlugs } from '../blocks/bindings.js';
8
9
  import { isObject } from '../blocks/model.js';
9
- import { placementTests, appendPlacementDoc } from '../db/placements.js';
10
+ import { placementTests, removableBlockTests, appendPlacementDoc } from '../db/placements.js';
10
11
  import { isPageBusy } from '../db/pageBusy.js';
11
- // createLocalReq replaces context with a shallow copy on nested calls. Keep
12
- // the shared stack in that context so both the outer req and its proxies see it.
12
+ import { blockRemovalRule, releaseRemovalClaim, observeUnpublishedRemoval, releaseRestoredRemovalClaims } from './blockRemovalRule.js';
13
+ import { bulkPlacementRequest, placementOperationRequest, usesBulkDocumentTransactions } from '../db/bulkPlacementRemoval.js';
14
+ const operationIdentity = Symbol('xpPlacementOperation');
15
+ // Execution-local identity survives both concurrent bulk siblings and Payload's
16
+ // restoreVersion operation, which caches req before beforeOperation runs.
17
+ export const pageGuardOperationScope = new AsyncLocalStorage();
18
+ const entryIsFirst = (config)=>!config?.hooks?.beforeOperation || config.hooks.beforeOperation[0] === pageGuardEnterOperation;
13
19
  const operations = (req)=>req.context.xpPageGuardOperations;
20
+ const requestFrame = (req)=>req[operationIdentity];
21
+ const operationFrame = (req, slug)=>{
22
+ const ordered = entryIsFirst(req.payload.config.collections?.find((c)=>c.slug === slug));
23
+ const own = requestFrame(req);
24
+ // With broken entry order, only this operation's returned token can prove a
25
+ // draft save. Restore bypasses that token on its cached request; Payload sets
26
+ // this sticky marker there before beforeChange (restoreVersion.js:162). Any
27
+ // ambiguity runs the rule: it may refuse, but must never borrow a draft save.
28
+ if (!ordered) return !req.context.isRestoringVersion && own?.collection === slug && !own.restore && !own.complete ? own : undefined;
29
+ let frame = pageGuardOperationScope.getStore();
30
+ while(frame && (frame.complete || frame.detached))frame = frame.parent;
31
+ // The request token wins when a preceding hook breaks async entry propagation.
32
+ // Restore alone caches the original request before beforeOperation; accept its
33
+ // execution identity only when the request belongs to its ancestor operation.
34
+ if (own) {
35
+ if (frame?.scoped && frame.restore && frame.collection === slug && frame !== own) {
36
+ let parent = frame.parent;
37
+ while(parent && parent !== own)parent = parent.parent;
38
+ if (parent === own) return frame;
39
+ }
40
+ return own.collection === slug && !own.complete ? own : undefined;
41
+ }
42
+ return frame?.scoped && frame.collection === slug && (frame.restore || frame.request === req) ? frame : undefined;
43
+ };
44
+ /** Must be first: buildBeforeOperation invokes its first hook synchronously,
45
+ * before the operation registers its await continuation. Later host hooks may
46
+ * await nested operations; those keep separate async contexts. No IO here.
47
+ */ export const pageGuardEnterOperation = ({ args, operation })=>{
48
+ if (operation !== 'create' && operation !== 'update' && operation !== 'restoreVersion' && operation !== 'delete') return;
49
+ const call = args;
50
+ if (!entryIsFirst(call.collection.config)) return;
51
+ pageGuardOperationScope.enterWith({
52
+ collection: call.collection.config.slug,
53
+ request: args.req,
54
+ draft: call.draft === true,
55
+ restore: operation === 'restoreVersion',
56
+ pending: true,
57
+ scoped: true,
58
+ parent: pageGuardOperationScope.getStore()
59
+ });
60
+ };
14
61
  export const pageGuardBeforeOperation = ({ args, operation })=>{
15
- if (operation !== 'create' && operation !== 'update' && operation !== 'restoreVersion') return;
62
+ const req = args.req;
63
+ req.context.xpPlacementRemovals ??= {
64
+ transaction: undefined,
65
+ tests: new Map()
66
+ };
67
+ if (operation !== 'create' && operation !== 'update' && operation !== 'restoreVersion' && operation !== 'delete') return;
16
68
  const call = args;
17
69
  let collections = operations(call.req);
18
70
  if (!collections) call.req.context.xpPageGuardOperations = collections = new Map();
19
71
  const slug = call.collection.config.slug;
20
72
  const stack = collections.get(slug) ?? [];
21
- stack.push({
73
+ const entered = pageGuardOperationScope.getStore();
74
+ const frame = entryIsFirst(call.collection.config) && entered?.pending && entered.collection === slug ? entered : {
75
+ collection: slug,
76
+ request: req,
77
+ draft: false,
78
+ restore: false
79
+ };
80
+ const isBulk = Boolean(call.where) && (operation === 'update' || operation === 'delete');
81
+ const bulk = frame.scoped && isBulk ? {
82
+ documents: new Set(),
83
+ refusals: new Map()
84
+ } : undefined;
85
+ Object.assign(frame, {
86
+ request: req,
22
87
  draft: call.draft === true,
23
- restore: operation === 'restoreVersion'
88
+ restore: operation === 'restoreVersion',
89
+ bulk,
90
+ pending: false
24
91
  });
92
+ stack.push(frame);
25
93
  collections.set(slug, stack);
94
+ const scoped = placementOperationRequest(req, new Map([
95
+ [
96
+ operationIdentity,
97
+ frame
98
+ ]
99
+ ]), ()=>{
100
+ // Only ordered execution identity can attribute a cached-request rollback
101
+ // to a restore. An unscoped stack entry may be a stale failed restore.
102
+ const executing = pageGuardOperationScope.getStore();
103
+ if (executing?.scoped && executing.restore && !executing.complete && !executing.detached && executing.collection === slug) {
104
+ let parent = executing.parent;
105
+ while(parent && parent !== frame)parent = parent.parent;
106
+ if (parent === frame) {
107
+ finishOperation(executing.request ?? req, executing);
108
+ return;
109
+ }
110
+ }
111
+ // Payload uses the same request for per-document completion and its outer
112
+ // catch. Always detach shared tracking; the exact request token alone keeps
113
+ // bulk policy/selection for later siblings until afterOperation completes it.
114
+ if (isBulk && usesBulkDocumentTransactions(req)) detachOperation(req, frame);
115
+ else finishOperation(req, frame);
116
+ });
117
+ return {
118
+ ...args,
119
+ req: bulk ? bulkPlacementRequest(scoped, slug, call.where, call.data, call.draft === true, operation === 'delete', bulk) : scoped
120
+ };
26
121
  };
122
+ function detachOperation(req, frame) {
123
+ const collections = operations(req), stack = collections?.get(frame.collection);
124
+ const index = stack?.lastIndexOf(frame);
125
+ if (index != null && index >= 0) stack.splice(index, 1);
126
+ if (!stack?.length) collections?.delete(frame.collection);
127
+ frame.detached = true;
128
+ if (pageGuardOperationScope.getStore() === frame) pageGuardOperationScope.enterWith(frame.parent);
129
+ }
130
+ function finishOperation(req, frame) {
131
+ frame.complete = true;
132
+ detachOperation(req, frame);
133
+ }
134
+ // Collection afterError has no operation identity and is REST-only
135
+ // (Payload 3.90.2 utilities/routeError.js:69-78). Local API failures call
136
+ // killTransaction(args.req) (operations/update.js:362, delete.js:274), whose
137
+ // transactionID deletion is observed by the operation's request proxy above.
138
+ // Bulk transaction deletion detaches tracking; its request token keeps policy.
27
139
  export const pageGuardAfterOperation = ({ req, collection, operation, result })=>{
140
+ // buildAfterOperation passes args.req, including the restore's returned token
141
+ // (Payload 3.90.2 utilities/buildAfterOperation.js:11). Never finish a caller's
142
+ // token as a fallback for an unidentified restore.
143
+ const own = requestFrame(req);
144
+ const identified = own?.collection === collection.slug && !own.complete ? own : operationFrame(req, collection.slug);
145
+ const frame = operation === 'restoreVersion' && !identified?.restore ? undefined : identified;
146
+ const bulk = frame?.bulk;
28
147
  // beforeOperation reports by-id updates as 'update'; afterOperation reports 'updateByID'.
29
- if (operation === 'create' || operation === 'update' || operation === 'updateByID' || operation === 'restoreVersion') {
30
- const collections = operations(req);
31
- const stack = collections?.get(collection.slug);
32
- stack?.pop();
33
- if (!stack?.length) collections?.delete(collection.slug);
148
+ const mutates = operation === 'create' || operation === 'update' || operation === 'updateByID' || operation === 'restoreVersion' || operation === 'delete' || operation === 'deleteByID';
149
+ // Bulk Local API errors are returned per document, without invoking afterError.
150
+ if (result && typeof result === 'object' && 'errors' in result && Array.isArray(result.errors)) {
151
+ const failed = result.errors.some((error)=>error && !bulk?.refusals.has(error.message));
152
+ if (failed && bulk) for (const error of result.errors){
153
+ const conservative = bulk.refusals.get(error?.message);
154
+ if (conservative) error.message = conservative;
155
+ }
156
+ for (const error of result.errors)if (error && error.id != null) releaseRemovalClaim(req, collection.slug, error.id);
34
157
  }
158
+ if (mutates && frame) finishOperation(req, frame);
35
159
  return result;
36
160
  };
37
161
  function optionsOf(req) {
@@ -58,9 +182,15 @@ const pathsOf = (req, collection, rows)=>{
58
182
  }
59
183
  return ids;
60
184
  }
61
- export function guardExperimentIds(tests, slugs, collection, paths, held, tags = new Set()) {
185
+ export function guardExperimentIds(tests, slugs, collection, paths, held, tags = new Set(), discovered = []) {
62
186
  const excluded = new Set(Array.isArray(held) ? held.map(String) : []);
63
- return sortLockKeys(tests.filter((test)=>slugs.includes(test.slug) || tags.has(String(test.id)) || test.kind === 'page' && (!test.pageCollection || test.pageCollection === collection) && test.arms.some((a)=>typeof a.pageTarget === 'string' && paths.includes(normalisePath(a.pageTarget)))).map((test)=>String(test.id)).filter((id)=>!excluded.has(id)));
187
+ const ids = tests.filter((test)=>slugs.includes(test.slug) || tags.has(String(test.id)) || test.kind === 'page' && (!test.pageCollection || test.pageCollection === collection) && test.arms.some((a)=>typeof a.pageTarget === 'string' && paths.includes(normalisePath(a.pageTarget)))).map((test)=>String(test.id));
188
+ // A candidate may have committed after the broad audit discovery. Its indexed
189
+ // removal lookup must still contribute E, including when it is not running yet.
190
+ return sortLockKeys([
191
+ ...ids,
192
+ ...discovered.map(String)
193
+ ].filter((id)=>!excluded.has(id)));
64
194
  }
65
195
  function protect(tests, path) {
66
196
  for (const test of tests){
@@ -98,29 +228,43 @@ function mapBusy(error) {
98
228
  throw error;
99
229
  }
100
230
  export const pageGuardBeforeDelete = async ({ req, id, collection })=>{
101
- const page = registration(req, collection.slug);
102
- if (!page) return;
103
231
  try {
104
- const published = await previousPublishedContent(req, collection.slug, id);
232
+ const page = registration(req, collection.slug);
233
+ // Keep the earlier page guard's baseline read and every refusal intact.
234
+ const published = page ? await previousPublishedContent(req, collection.slug, id) : await storedContent(req, collection.slug, id);
105
235
  if (!published || published._status === 'draft') return;
106
236
  const paths = pathsOf(req, collection.slug, [
107
237
  published
108
238
  ]);
109
239
  const exec = await req.transactionID != null ? txExecutor(req) : pooledExecutor(req.payload);
110
- let tests = await placementTests(exec);
111
- if (await req.transactionID != null) {
112
- await lockPlacementScope(exec, guardExperimentIds(tests, placementSlugs(optionsOf(req), collection.slug, published), collection.slug, paths, req.context.xpHeldExperiments, taggedIds(published)), paths);
240
+ let tests = page ? await placementTests(exec) : undefined;
241
+ const { views, affected } = await blockRemovalRule.prepare(req, collection.slug, collection.trash && published.deletedAt != null ? undefined : published, {}, true, exec, tests);
242
+ if (!page) {
243
+ if (!affected.length) return;
244
+ if (await req.transactionID != null) {
245
+ await lockPlacementScope(exec, guardExperimentIds([], [], collection.slug, [], req.context.xpHeldExperiments, new Set(), affected.map((test)=>test.id)), []);
246
+ tests = (await removableBlockTests(exec, affected.map((test)=>test.slug))).map((test)=>({
247
+ ...test,
248
+ kind: 'block'
249
+ }));
250
+ } else tests = affected;
251
+ } else if (await req.transactionID != null) {
252
+ await lockPlacementScope(exec, guardExperimentIds(tests, placementSlugs(optionsOf(req), collection.slug, published), collection.slug, paths, req.context.xpHeldExperiments, taggedIds(published), affected.map((test)=>test.id)), paths);
113
253
  tests = await placementTests(exec);
114
254
  }
115
255
  for (const path of paths)protect(tests.filter((t)=>!t.pageCollection || t.pageCollection === collection.slug), path);
256
+ if (affected.length) await blockRemovalRule.check(req, tests, affected, collection.slug, id, true, views, operationFrame(req, collection.slug)?.bulk);
116
257
  } catch (error) {
117
258
  mapBusy(error);
118
259
  }
119
260
  };
120
261
  export const pageGuardBeforeChange = async ({ req, collection, originalDoc, operation, data })=>{
121
262
  const drafts = Boolean(collection.versions && collection.versions.drafts);
122
- const call = operations(req)?.get(collection.slug)?.at(-1);
123
- if (drafts && call?.draft && (call.restore || data._status !== 'published')) return data;
263
+ const call = operationFrame(req, collection.slug);
264
+ if (drafts && call?.draft && (call.restore || data._status !== 'published')) {
265
+ await blockRemovalRule.prepare(req, collection.slug, undefined, data, false);
266
+ return data;
267
+ }
124
268
  const after = operation === 'create' ? data : {
125
269
  ...originalDoc,
126
270
  ...data
@@ -142,6 +286,8 @@ export const pageGuardBeforeChange = async ({ req, collection, originalDoc, oper
142
286
  ]);
143
287
  const exec = await req.transactionID != null ? txExecutor(req) : pooledExecutor(req.payload);
144
288
  let tests = await placementTests(exec);
289
+ const trashing = Boolean(collection.trash && after.deletedAt != null);
290
+ const { views, affected } = await blockRemovalRule.prepare(req, collection.slug, collection.trash && before?.deletedAt != null ? undefined : before, after, trashing || drafts && after._status !== 'published', exec, tests);
145
291
  const publishes = !drafts || after._status === 'published';
146
292
  const noTransaction = ()=>{
147
293
  if (publishes && tests.some((t)=>t.kind === 'block' && active(t) && afterSlugs.includes(t.slug))) throw new XpNoTransactionError('Save this page with transactions on.');
@@ -155,7 +301,7 @@ export const pageGuardBeforeChange = async ({ req, collection, originalDoc, oper
155
301
  ], collection.slug, paths, req.context.xpHeldExperiments, taggedIds([
156
302
  before,
157
303
  after
158
- ])), paths);
304
+ ]), affected.map((test)=>test.id)), paths);
159
305
  tests = await placementTests(exec);
160
306
  } catch (error) {
161
307
  if (!(error instanceof XpNoTransactionError)) throw error;
@@ -173,26 +319,34 @@ export const pageGuardBeforeChange = async ({ req, collection, originalDoc, oper
173
319
  if (old != null && (unpublishing || trashing || page.pathOf(after) !== old)) protect(tests.filter((t)=>!t.pageCollection || t.pageCollection === collection.slug), normalisePath(old));
174
320
  }
175
321
  if (publishes) refuseInteraction(tests, beforeSlugs, afterSlugs, beforePaths, afterPaths, collection.slug);
322
+ if (affected.length) await blockRemovalRule.check(req, tests, affected, collection.slug, originalDoc.id, trashing || drafts && after._status !== 'published', views, call?.bulk);
176
323
  return data;
177
324
  } catch (error) {
178
325
  mapBusy(error);
179
326
  }
180
327
  };
181
328
  /** Unwrapped: these writes must fail the publish closed, unlike the best-effort audit. */ export const pageGuardAfterChange = async ({ req, collection, doc })=>{
182
- const call = operations(req)?.get(collection.slug)?.at(-1);
329
+ const call = operationFrame(req, collection.slug);
183
330
  const drafts = Boolean(collection.versions && collection.versions.drafts);
331
+ if (!call?.draft && (drafts && doc._status !== 'published' || collection.trash && doc.deletedAt != null)) observeUnpublishedRemoval(req, collection.slug, doc.id);
184
332
  if (drafts && (doc._status !== 'published' || call?.draft && call.restore)) return doc;
185
333
  if (await req.transactionID == null) return doc;
186
334
  try {
187
335
  const stored = await storedContent(req, collection.slug, doc.id);
188
336
  if (!stored) throw new Error('The saved placement row was not found.');
189
337
  const slugs = placementSlugs(optionsOf(req), collection.slug, stored);
338
+ // A later publish in this transaction can restore an earlier removal. Only
339
+ // clear its claim once the stored published row actually contains the block.
340
+ const claims = req.context.xpPlacementRemovals;
190
341
  const exec = txExecutor(req);
191
342
  for (const test of (await placementTests(exec))){
192
343
  if (test.kind === 'block' && active(test) && slugs.includes(test.slug)) await appendPlacementDoc(exec, test.id, test.phase, {
193
344
  collection: collection.slug,
194
345
  id: doc.id
195
346
  });
347
+ if (test.kind === 'block' && claims && claims.transaction === await req.transactionID && stored._status !== 'draft' && stored.deletedAt == null) {
348
+ releaseRestoredRemovalClaims(req, collection.slug, stored, test);
349
+ }
196
350
  }
197
351
  return doc;
198
352
  } catch (error) {
@@ -0,0 +1,9 @@
1
+ import type { PreflightResult } from '../types/endpoints.js';
2
+ type Placement = PreflightResult['placements'][number];
3
+ export type PreviewPage = Placement & {
4
+ key: string;
5
+ slotCount: number;
6
+ };
7
+ /** Preview URLs identify pages; counts use the most placements in any one version. */
8
+ export declare function placementPages(placements: readonly Placement[], flagPoint?: string): PreviewPage[];
9
+ export {};
@@ -1,4 +1,4 @@
1
- /** Preview URLs identify pages; counts use the most placements in any one version. */ export function previewPages(placements, flagPoint) {
1
+ /** Preview URLs identify pages; counts use the most placements in any one version. */ export function placementPages(placements, flagPoint) {
2
2
  const pages = new Map();
3
3
  for (const [index, placement] of placements.entries()){
4
4
  const key = `${placement.collection}\u0000${String(placement.id)}${placement.collection === flagPoint ? `\u0000${index}` : ''}`;
@@ -30,6 +30,3 @@
30
30
  ...pages.values()
31
31
  ].map(({ page })=>page);
32
32
  }
33
- /** Pages that offer something to do: a preview or an editor link. The section is hidden when none do. */ export function actionablePreviewPages(placements, flagPoint) {
34
- return previewPages(placements, flagPoint).filter((page)=>page.url || page.editorUrl);
35
- }
package/dist/onInit.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { puckCollections } from './options.js';
2
+ import { pageGuardEnterOperation } from './hooks/pageGuard.js';
1
3
  import { findRegisteredBlocksField } from './blocks/formState.js';
2
4
  import { EXPERIMENT_BLOCK_SLUG } from './blocks/model.js';
3
5
  import { contentBlocks } from './transitions/contentFields.js';
@@ -23,6 +25,26 @@ function registeredPaths(fields, name, parent = []) {
23
25
  }
24
26
  export function createOnInit(options) {
25
27
  return async (payload)=>{
28
+ const guarded = new Set([
29
+ ...options.puck?.enabled ? puckCollections(options).map((c)=>c.slug) : [],
30
+ ...(options.blocks?.collections ?? []).map((c)=>c.slug),
31
+ ...(options.pages?.collections ?? []).map((c)=>c.slug)
32
+ ]);
33
+ for (const collection of payload.config.collections ?? []){
34
+ if (!guarded.has(collection.slug)) continue;
35
+ // Page-only guards also read the raw main row's scalar _status when
36
+ // protecting unpublishes and restores; localized status breaks those too.
37
+ if (payload.config.localization && payload.config.experimental?.localizeStatus && collection.versions && collection.versions.drafts && collection.versions.drafts.localizeStatus) {
38
+ throw new Error(`Experiments collection ${collection.slug} does not support versions.drafts.localizeStatus. Use a shared publication status.`);
39
+ }
40
+ if (collection.hooks) {
41
+ const hooks = collection.hooks.beforeOperation ?? [];
42
+ collection.hooks.beforeOperation = [
43
+ pageGuardEnterOperation,
44
+ ...hooks.filter((hook)=>hook !== pageGuardEnterOperation)
45
+ ];
46
+ }
47
+ }
26
48
  for (const registration of options.blocks?.collections ?? []){
27
49
  const config = payload.config.collections.find((c)=>c.slug === registration.slug);
28
50
  const found = findRegisteredBlocksField(config?.fields ?? [], registration.field);
package/dist/plugin.js CHANGED
@@ -2,7 +2,7 @@ import { buildCollections } from './collections/index.js';
2
2
  import { buildEndpoints } from './endpoints/index.js';
3
3
  import { contentChangesBeforeHook, contentChangesHook } from './hooks/contentChanges.js';
4
4
  import { puckGoalsBeforeChange } from './hooks/puckGoals.js';
5
- import { pageGuardAfterChange, pageGuardAfterOperation, pageGuardBeforeChange, pageGuardBeforeDelete, pageGuardBeforeOperation } from './hooks/pageGuard.js';
5
+ import { pageGuardAfterChange, pageGuardAfterOperation, pageGuardEnterOperation, pageGuardBeforeChange, pageGuardBeforeDelete, pageGuardBeforeOperation } from './hooks/pageGuard.js';
6
6
  import { createOnInit } from './onInit.js';
7
7
  import { puckCollections, resolveOptions } from './options.js';
8
8
  import { injectTestBlock } from './admin/blocks/inject.js';
@@ -84,6 +84,7 @@ export function createExperimentsPlugin(input) {
84
84
  ] : []
85
85
  ],
86
86
  beforeOperation: [
87
+ pageGuardEnterOperation,
87
88
  ...collection.hooks?.beforeOperation ?? [],
88
89
  pageGuardBeforeOperation
89
90
  ],
@@ -26,7 +26,7 @@ export function ExperimentPicker({ value, onChange }) {
26
26
  });
27
27
  if (!active) return;
28
28
  if (!response.ok) {
29
- setState(response.status === 403 ? 'forbidden' : 'error');
29
+ setState(response.status === 401 || response.status === 403 ? 'forbidden' : 'error');
30
30
  return;
31
31
  }
32
32
  setExperiments(response.docs.filter(isExperimentOption).sort((a, b)=>(Date.parse(b.updatedAt ?? '') || 0) - (Date.parse(a.updatedAt ?? '') || 0)));
@@ -46,6 +46,29 @@ export function ExperimentPicker({ value, onChange }) {
46
46
  const selected = value ? String(value.id) : '';
47
47
  const query = search.trim().toLocaleLowerCase('en-US');
48
48
  const visible = experiments.filter((doc)=>String(doc.id) === selected || doc.name.toLocaleLowerCase('en-US').includes(query) || doc.slug.toLocaleLowerCase('en-US').includes(query));
49
+ if (state === 'loading') return /*#__PURE__*/ _jsxs("div", {
50
+ className: "xp-ui-field",
51
+ children: [
52
+ /*#__PURE__*/ _jsx("span", {
53
+ children: pickerCopy.label
54
+ }),
55
+ /*#__PURE__*/ _jsx("p", {
56
+ role: "status",
57
+ children: pickerCopy.loading
58
+ })
59
+ ]
60
+ });
61
+ if (state === 'forbidden') return /*#__PURE__*/ _jsxs("div", {
62
+ className: "xp-ui-field",
63
+ children: [
64
+ /*#__PURE__*/ _jsx("span", {
65
+ children: pickerCopy.label
66
+ }),
67
+ /*#__PURE__*/ _jsx("p", {
68
+ children: value ? pickerCopy.forbidden : pickerCopy.forbiddenUnbound
69
+ })
70
+ ]
71
+ });
49
72
  return /*#__PURE__*/ _jsxs("div", {
50
73
  className: "xp-ui-field",
51
74
  children: [
@@ -73,7 +96,6 @@ export function ExperimentPicker({ value, onChange }) {
73
96
  id: id,
74
97
  className: "xp-ui-input xp-ui-select",
75
98
  value: selected,
76
- disabled: state === 'loading',
77
99
  onChange: (event)=>{
78
100
  const experiment = experiments.find((doc)=>String(doc.id) === event.currentTarget.value);
79
101
  onChange(experiment ? {
@@ -100,14 +122,7 @@ export function ExperimentPicker({ value, onChange }) {
100
122
  }, doc.id))
101
123
  ]
102
124
  }),
103
- state === 'loading' ? /*#__PURE__*/ _jsx("div", {
104
- className: "xp-ui-banner",
105
- role: "status",
106
- children: /*#__PURE__*/ _jsx("p", {
107
- children: pickerCopy.loading
108
- })
109
- }) : null,
110
- state === 'error' || state === 'forbidden' ? /*#__PURE__*/ _jsx("div", {
125
+ state === 'error' ? /*#__PURE__*/ _jsx("div", {
111
126
  className: "xp-ui-banner xp-ui-banner--error",
112
127
  role: "alert",
113
128
  children: /*#__PURE__*/ _jsx("p", {
@@ -11,7 +11,10 @@ export declare const pickerCopy: {
11
11
  readonly search: "Search tests";
12
12
  readonly loading: "Loading tests…";
13
13
  readonly error: "Couldn't load tests.";
14
- readonly forbidden: "You can't see tests. Ask an admin.";
14
+ readonly forbidden: "You don't have access to this test. You can still edit its content.";
15
+ readonly forbiddenUnbound: "You don't have access to tests.";
16
+ readonly unavailable: "This test isn't available to you. You can still edit its content.";
17
+ readonly resultsOnly: "You can view this test's results.";
15
18
  readonly statuses: {
16
19
  readonly draft: "Draft";
17
20
  readonly running: "Running";
package/dist/puck/copy.js CHANGED
@@ -12,7 +12,10 @@ export const pickerCopy = {
12
12
  search: 'Search tests',
13
13
  loading: 'Loading tests…',
14
14
  error: "Couldn't load tests.",
15
- forbidden: "You can't see tests. Ask an admin.",
15
+ forbidden: "You don't have access to this test. You can still edit its content.",
16
+ forbiddenUnbound: "You don't have access to tests.",
17
+ unavailable: "This test isn't available to you. You can still edit its content.",
18
+ resultsOnly: "You can view this test's results.",
16
19
  statuses: {
17
20
  draft: 'Draft',
18
21
  running: 'Running',