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

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 (254) hide show
  1. package/README.md +2 -8
  2. package/dist/admin/MetricSourceSelect.js +10 -3
  3. package/dist/admin/armSelect/armSelect.model.d.ts +1 -1
  4. package/dist/admin/blocks/BlockPanel.d.ts +1 -0
  5. package/dist/admin/blocks/BlockPanel.js +75 -29
  6. package/dist/admin/blocks/model.js +5 -4
  7. package/dist/admin/copy/blocks.d.ts +14 -11
  8. package/dist/admin/copy/blocks.js +33 -22
  9. package/dist/admin/copy/goals.d.ts +15 -8
  10. package/dist/admin/copy/goals.js +18 -8
  11. package/dist/admin/copy/newTest.d.ts +10 -7
  12. package/dist/admin/copy/newTest.js +14 -7
  13. package/dist/admin/copy/status.d.ts +1 -1
  14. package/dist/admin/copy/status.js +2 -1
  15. package/dist/admin/pageCollections.d.ts +1 -0
  16. package/dist/admin/pageCollections.js +3 -0
  17. package/dist/admin/placementStatus.model.js +5 -3
  18. package/dist/admin/status.model.d.ts +1 -0
  19. package/dist/admin/status.model.js +2 -1
  20. package/dist/admin/surface/ResultsRoute.js +4 -8
  21. package/dist/admin/surface/SurfaceShell.d.ts +4 -2
  22. package/dist/admin/surface/SurfaceShell.js +28 -3
  23. package/dist/admin/surface/TestRowMenu.d.ts +13 -0
  24. package/dist/admin/surface/TestRowMenu.js +163 -0
  25. package/dist/admin/surface/TestsHome.d.ts +4 -3
  26. package/dist/admin/surface/TestsHome.js +186 -47
  27. package/dist/admin/surface/TestsSurface.js +2 -1
  28. package/dist/admin/surface/goals/DeleteGoalDialog.d.ts +7 -0
  29. package/dist/admin/surface/goals/DeleteGoalDialog.js +42 -0
  30. package/dist/admin/surface/goals/GoalForm.d.ts +1 -0
  31. package/dist/admin/surface/goals/GoalForm.js +280 -198
  32. package/dist/admin/surface/goals/GoalsList.js +102 -33
  33. package/dist/admin/surface/goals/data.d.ts +2 -0
  34. package/dist/admin/surface/goals/data.js +9 -0
  35. package/dist/admin/surface/goals/goals.css +3 -2
  36. package/dist/admin/surface/goals/goals.model.d.ts +2 -2
  37. package/dist/admin/surface/goals/goals.model.js +7 -12
  38. package/dist/admin/surface/home.model.d.ts +15 -8
  39. package/dist/admin/surface/home.model.js +22 -18
  40. package/dist/admin/surface/newTest/NewTest.d.ts +3 -3
  41. package/dist/admin/surface/newTest/NewTest.js +156 -96
  42. package/dist/admin/surface/newTest/PageWizard.d.ts +4 -1
  43. package/dist/admin/surface/newTest/PageWizard.js +93 -68
  44. package/dist/admin/surface/newTest/newTest.css +28 -11
  45. package/dist/admin/surface/results/ResultsHeader.d.ts +1 -1
  46. package/dist/admin/surface/results/ResultsHeader.js +90 -63
  47. package/dist/admin/surface/surface.css +29 -0
  48. package/dist/admin/surface/test/TestPage.js +46 -38
  49. package/dist/admin/surface/useXpStepNav.d.ts +11 -0
  50. package/dist/admin/surface/useXpStepNav.js +14 -0
  51. package/dist/admin/views/TestsSurfaceClient.js +27 -3
  52. package/dist/admin/views/buildSurfaceProps.js +18 -66
  53. package/dist/arms/copy.d.ts +13 -3
  54. package/dist/arms/copy.js +5 -4
  55. package/dist/blocks/createExperimentBlock.js +1 -1
  56. package/dist/blocks/formState.js +1 -1
  57. package/dist/collections/experiments/armInvariants.js +8 -5
  58. package/dist/collections/metrics.js +12 -5
  59. package/dist/collections/serialize.js +3 -2
  60. package/dist/db/pageCopies.d.ts +5 -0
  61. package/dist/db/pageCopies.js +31 -0
  62. package/dist/db/snapshots.d.ts +1 -0
  63. package/dist/endpoints/duplicateOriginal.d.ts +38 -0
  64. package/dist/endpoints/duplicateOriginal.js +414 -0
  65. package/dist/endpoints/editorSurface.js +1 -1
  66. package/dist/endpoints/index.js +20 -0
  67. package/dist/endpoints/pages.js +245 -66
  68. package/dist/endpoints/placementStatus.js +1 -0
  69. package/dist/endpoints/results.js +3 -0
  70. package/dist/endpoints/testVersion.d.ts +2 -0
  71. package/dist/endpoints/testVersion.js +38 -0
  72. package/dist/endpoints/transitions.js +4 -5
  73. package/dist/exports/index.d.ts +1 -1
  74. package/dist/goals/picker/copy.js +1 -1
  75. package/dist/goals/sourceLabel.d.ts +2 -0
  76. package/dist/goals/sourceLabel.js +4 -0
  77. package/dist/hooks/trackPageCopies.d.ts +11 -0
  78. package/dist/hooks/trackPageCopies.js +7 -0
  79. package/dist/labels/arms.d.ts +3 -0
  80. package/dist/labels/arms.js +8 -0
  81. package/dist/options.d.ts +2 -0
  82. package/dist/options.js +18 -2
  83. package/dist/plugin.js +56 -2
  84. package/dist/puck/editor/ConfigureTestDrawer.d.ts +7 -7
  85. package/dist/puck/editor/ConfigureTestDrawer.js +36 -26
  86. package/dist/puck/editor/ExperimentSlotEditor.d.ts +2 -1
  87. package/dist/puck/editor/ExperimentSlotEditor.js +219 -106
  88. package/dist/puck/editor/LeftoverVersions.js +17 -32
  89. package/dist/puck/editor/QuickTestActions.d.ts +2 -2
  90. package/dist/puck/editor/QuickTestActions.js +44 -34
  91. package/dist/puck/editor/ResultsReadout.d.ts +3 -1
  92. package/dist/puck/editor/ResultsReadout.js +28 -16
  93. package/dist/puck/editor/VersionBuilder.d.ts +4 -2
  94. package/dist/puck/editor/VersionBuilder.js +42 -63
  95. package/dist/puck/editor/armWrites.js +1 -1
  96. package/dist/puck/editor/copy.d.ts +10 -6
  97. package/dist/puck/editor/copy.js +22 -12
  98. package/dist/puck/editor/editor.chrome.css +9 -8
  99. package/dist/puck/editor/editor.css +14 -9
  100. package/dist/puck/editor/placementsCache.d.ts +1 -1
  101. package/dist/puck/editor/placementsCache.js +9 -17
  102. package/dist/puck/editor/usePageSaveReadiness.d.ts +1 -4
  103. package/dist/puck/editor/usePageSaveReadiness.js +18 -21
  104. package/dist/puck/editor/usePlacementNotice.d.ts +2 -2
  105. package/dist/puck/editor/usePlacementNotice.js +4 -5
  106. package/dist/puck/nestedTestCopy.js +2 -2
  107. package/dist/puck/slotConfig.d.ts +1 -1
  108. package/dist/puck/slotConfig.js +1 -1
  109. package/dist/results/analyse.d.ts +2 -0
  110. package/dist/results/analyse.js +2 -2
  111. package/dist/results/verdict.d.ts +4 -4
  112. package/dist/results/verdict.js +13 -10
  113. package/dist/server/runResults.js +2 -1
  114. package/dist/testSurface/PreviewLinks.d.ts +2 -1
  115. package/dist/testSurface/PreviewLinks.js +3 -3
  116. package/dist/testSurface/actions/DecideDialog.d.ts +7 -4
  117. package/dist/testSurface/actions/DecideDialog.js +71 -59
  118. package/dist/testSurface/actions/LifecycleAction.d.ts +17 -0
  119. package/dist/testSurface/actions/LifecycleAction.js +107 -0
  120. package/dist/testSurface/actions/MakeContentResult.js +1 -1
  121. package/dist/testSurface/actions/actions.model.d.ts +13 -5
  122. package/dist/testSurface/actions/actions.model.js +75 -22
  123. package/dist/testSurface/actions/decide.model.d.ts +1 -0
  124. package/dist/testSurface/actions/decide.model.js +1 -0
  125. package/dist/testSurface/allocation.model.js +6 -3
  126. package/dist/testSurface/api.d.ts +4 -1
  127. package/dist/testSurface/api.js +22 -14
  128. package/dist/testSurface/copy/actions.d.ts +36 -14
  129. package/dist/testSurface/copy/actions.js +39 -17
  130. package/dist/testSurface/copy/advanced.d.ts +10 -0
  131. package/dist/testSurface/copy/advanced.js +10 -0
  132. package/dist/testSurface/copy/arms.d.ts +1 -1
  133. package/dist/testSurface/copy/arms.js +1 -1
  134. package/dist/testSurface/copy/audience.d.ts +4 -3
  135. package/dist/testSurface/copy/audience.js +5 -4
  136. package/dist/testSurface/copy/common.d.ts +6 -6
  137. package/dist/testSurface/copy/common.js +6 -6
  138. package/dist/testSurface/copy/metrics.d.ts +6 -0
  139. package/dist/testSurface/copy/metrics.js +8 -0
  140. package/dist/testSurface/copy/pages.d.ts +67 -7
  141. package/dist/testSurface/copy/pages.js +74 -7
  142. package/dist/testSurface/copy/readiness.d.ts +8 -6
  143. package/dist/testSurface/copy/readiness.js +19 -10
  144. package/dist/testSurface/copy/recommendation.d.ts +1 -22
  145. package/dist/testSurface/copy/recommendation.js +2 -22
  146. package/dist/testSurface/copy/results.d.ts +16 -10
  147. package/dist/testSurface/copy/results.js +19 -11
  148. package/dist/testSurface/copy/review.d.ts +13 -10
  149. package/dist/testSurface/copy/review.js +14 -10
  150. package/dist/testSurface/copy/setting.d.ts +1 -2
  151. package/dist/testSurface/copy/setting.js +1 -2
  152. package/dist/testSurface/copy/surface.d.ts +11 -2
  153. package/dist/testSurface/copy/surface.js +14 -11
  154. package/dist/testSurface/copy/testPage.d.ts +16 -10
  155. package/dist/testSurface/copy/testPage.js +24 -18
  156. package/dist/testSurface/format/date.d.ts +5 -2
  157. package/dist/testSurface/format/date.js +24 -8
  158. package/dist/testSurface/format/roundProgress.d.ts +6 -0
  159. package/dist/testSurface/format/roundProgress.js +15 -0
  160. package/dist/testSurface/format/useDateFormatter.d.ts +3 -0
  161. package/dist/testSurface/format/useDateFormatter.js +8 -0
  162. package/dist/testSurface/labels.d.ts +1 -2
  163. package/dist/testSurface/labels.js +2 -3
  164. package/dist/testSurface/lockedNotice.model.d.ts +2 -0
  165. package/dist/testSurface/lockedNotice.model.js +31 -0
  166. package/dist/testSurface/readPreflight.d.ts +0 -1
  167. package/dist/testSurface/readPreflight.js +0 -1
  168. package/dist/testSurface/results/CiChart.js +2 -1
  169. package/dist/testSurface/results/DataTable.d.ts +1 -1
  170. package/dist/testSurface/results/DataTable.js +4 -3
  171. package/dist/testSurface/results/VerdictHero.d.ts +1 -1
  172. package/dist/testSurface/results/legacy.d.ts +0 -5
  173. package/dist/testSurface/results/legacy.js +0 -14
  174. package/dist/testSurface/results/results.css +2 -2
  175. package/dist/testSurface/results/results.model.d.ts +8 -3
  176. package/dist/testSurface/results/results.model.js +25 -21
  177. package/dist/testSurface/results/snapshot.d.ts +2 -0
  178. package/dist/testSurface/results/snapshot.js +3 -0
  179. package/dist/testSurface/surface/contracts.d.ts +6 -1
  180. package/dist/testSurface/surface/editorPlacement.d.ts +1 -1
  181. package/dist/testSurface/surface/editorPlacement.js +1 -1
  182. package/dist/testSurface/surface/pageBlock/pageBlock.model.js +1 -1
  183. package/dist/testSurface/surface/pageBlock/parts.js +25 -12
  184. package/dist/testSurface/surface/pagePicker/CopyRoute.d.ts +8 -1
  185. package/dist/testSurface/surface/pagePicker/CopyRoute.js +243 -22
  186. package/dist/testSurface/surface/pagePicker/PageCombobox.d.ts +15 -4
  187. package/dist/testSurface/surface/pagePicker/PageCombobox.js +298 -209
  188. package/dist/testSurface/surface/pagePicker/pagePicker.css +73 -10
  189. package/dist/testSurface/surface/pagePicker/pagePicker.model.d.ts +5 -3
  190. package/dist/testSurface/surface/pagePicker/pagePicker.model.js +17 -2
  191. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +5 -3
  192. package/dist/testSurface/surface/readiness/ActionDialogs.js +213 -207
  193. package/dist/testSurface/surface/readiness/Banner.d.ts +5 -1
  194. package/dist/testSurface/surface/readiness/Banner.js +109 -148
  195. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +5 -2
  196. package/dist/testSurface/surface/readiness/SaveStatus.js +8 -7
  197. package/dist/testSurface/surface/readiness/readiness.model.d.ts +14 -5
  198. package/dist/testSurface/surface/readiness/readiness.model.js +62 -12
  199. package/dist/testSurface/surface/readiness/useTransition.d.ts +3 -1
  200. package/dist/testSurface/surface/readiness/useTransition.js +49 -8
  201. package/dist/testSurface/surface/results/ReleasePages.d.ts +4 -3
  202. package/dist/testSurface/surface/results/ReleasePages.js +41 -41
  203. package/dist/testSurface/surface/results/ResultsBody.d.ts +7 -2
  204. package/dist/testSurface/surface/results/ResultsBody.js +170 -110
  205. package/dist/testSurface/surface/results/recommendation.model.d.ts +6 -9
  206. package/dist/testSurface/surface/results/recommendation.model.js +15 -59
  207. package/dist/testSurface/surface/results/useResults.d.ts +6 -2
  208. package/dist/testSurface/surface/setting/parts.js +31 -28
  209. package/dist/testSurface/surface/setting/setting.css +2 -1
  210. package/dist/testSurface/surface/test/AdvancedSection.js +10 -4
  211. package/dist/testSurface/surface/test/DeleteTest.d.ts +5 -1
  212. package/dist/testSurface/surface/test/DeleteTest.js +63 -55
  213. package/dist/testSurface/surface/test/GoalSection.js +11 -11
  214. package/dist/testSurface/surface/test/LengthSection.js +21 -13
  215. package/dist/testSurface/surface/test/PageHoldout.d.ts +1 -1
  216. package/dist/testSurface/surface/test/PageHoldout.js +7 -7
  217. package/dist/testSurface/surface/test/ReadinessBar.d.ts +2 -1
  218. package/dist/testSurface/surface/test/ReadinessBar.js +4 -10
  219. package/dist/testSurface/surface/test/Section.js +8 -0
  220. package/dist/testSurface/surface/test/TargetingSection.js +7 -2
  221. package/dist/testSurface/surface/test/TestSurface.js +17 -43
  222. package/dist/testSurface/surface/test/VersionsSection.js +93 -70
  223. package/dist/testSurface/surface/test/fields.d.ts +4 -3
  224. package/dist/testSurface/surface/test/fields.js +10 -16
  225. package/dist/testSurface/surface/test/pageParts.js +13 -7
  226. package/dist/testSurface/surface/test/testPage.css +9 -2
  227. package/dist/testSurface/surface/useTestDocument.d.ts +1 -3
  228. package/dist/testSurface/surface/useTestDocument.js +110 -52
  229. package/dist/testSurface/surface/watchTestDocument.d.ts +15 -0
  230. package/dist/testSurface/surface/watchTestDocument.js +181 -0
  231. package/dist/testSurface/surfaceUrls.d.ts +1 -0
  232. package/dist/testSurface/surfaceUrls.js +4 -0
  233. package/dist/testSurface/useApi.d.ts +3 -0
  234. package/dist/transitions/addMetric.d.ts +1 -1
  235. package/dist/transitions/addMetric.js +5 -1
  236. package/dist/transitions/kernel.d.ts +2 -0
  237. package/dist/transitions/kernel.js +1 -1
  238. package/dist/transitions/pageAddress.d.ts +6 -0
  239. package/dist/transitions/pageAddress.js +71 -0
  240. package/dist/transitions/pageVersions.d.ts +1 -1
  241. package/dist/transitions/preflightData.js +10 -2
  242. package/dist/transitions/start.d.ts +1 -1
  243. package/dist/transitions/start.js +8 -5
  244. package/dist/types/armKey.d.ts +2 -0
  245. package/dist/types/armKey.js +1 -0
  246. package/dist/types/contracts.d.ts +11 -1
  247. package/dist/types/endpoints.d.ts +38 -9
  248. package/dist/types/endpoints.js +1 -1
  249. package/dist/types/surface.d.ts +7 -9
  250. package/dist/ui/Dialog.d.ts +21 -2
  251. package/dist/ui/Dialog.js +101 -4
  252. package/dist/ui/Inputs.js +0 -1
  253. package/dist/ui/ui.css +5 -1
  254. package/package.json +2 -2
@@ -0,0 +1,414 @@
1
+ import { Forbidden, ValidationError } from 'payload';
2
+ import { flattenTopLevelFields, formatAdminURL } from 'payload/shared';
3
+ import { placementReader } from '../blocks/placementLocale.js';
4
+ import { XP_IF_UPDATED_AT_HEADER } from '../constants.js';
5
+ import { collectionLabel } from '../collections/labels.js';
6
+ import { transactionSession } from '../db/executor.js';
7
+ import { lockPagePaths } from '../db/locks.js';
8
+ import { committedPageCopyIds } from '../db/pageCopies.js';
9
+ import { lockExperimentUpdatedAt } from '../db/staleEdit.js';
10
+ import { currentTxid } from '../db/txid.js';
11
+ import { XpRefusal } from '../errors.js';
12
+ import { safeError } from '../log.js';
13
+ import { normalisePath } from '../runtime/normalisePath.js';
14
+ import { orphanedPages, PAGE_COPY } from '../testSurface/copy/pages.js';
15
+ import { contentBlocks, hasLocalizedFields } from '../transitions/contentFields.js';
16
+ import { withTransition } from '../transitions/kernel.js';
17
+ import { PAGE_ADDRESS_FIELDS as addressFields } from '../transitions/pageAddress.js';
18
+ import { resolvePageCollection } from '../transitions/pageCollection.js';
19
+ import { requireCurrentRound } from '../transitions/phaseRecord.js';
20
+ import { readBody } from './readBody.js';
21
+ import { routeId } from './routeId.js';
22
+ import { relationshipId } from '../transitions/checkStart.js';
23
+ const homeFields = [
24
+ 'isHomepage',
25
+ 'homepage',
26
+ 'isHomePage'
27
+ ];
28
+ const invalid = ()=>new XpRefusal('invalid-body', PAGE_COPY.copyUnavailable, undefined, 422);
29
+ const refused = (message = PAGE_COPY.copyUnavailable)=>new XpRefusal('copy-unavailable', message, undefined, 422);
30
+ const transactionLost = ()=>new XpRefusal('transaction-lost', PAGE_COPY.copyTransactionLost, undefined, 500);
31
+ const stale = (label)=>new XpRefusal('stale-edit', PAGE_COPY.copyChanged(label), undefined, 409);
32
+ const response = (value)=>Response.json(value, {
33
+ headers: {
34
+ 'Cache-Control': 'private, no-store'
35
+ }
36
+ });
37
+ async function readTest(req, id) {
38
+ const doc = await req.payload.findByID({
39
+ collection: 'xp-experiments',
40
+ id,
41
+ req,
42
+ overrideAccess: false,
43
+ depth: 0,
44
+ disableErrors: true
45
+ });
46
+ if (!doc) throw new XpRefusal('not-found', PAGE_COPY.copyChanged(), undefined, 404);
47
+ return doc;
48
+ }
49
+ /** Payload's duplicate hydrates source fields with overrideAccess internally. */ function hasProtectedFields(fields, config, seen = new Set()) {
50
+ return fields.some((field)=>{
51
+ if (seen.has(field) || 'disableDuplicate' in field && field.disableDuplicate) return false;
52
+ seen.add(field);
53
+ return Boolean('access' in field && field.access?.read || 'fields' in field && hasProtectedFields(field.fields, config, seen) || field.type === 'tabs' && field.tabs.some((tab)=>tab.access?.read || hasProtectedFields(tab.fields, config, seen)) || field.type === 'blocks' && contentBlocks(field, config.blocks).some((block)=>hasProtectedFields(block.fields, config, seen)));
54
+ });
55
+ }
56
+ async function readOriginal(req, collection, id, label) {
57
+ const read = (draft)=>req.payload.findByID({
58
+ collection,
59
+ id,
60
+ draft,
61
+ depth: 0,
62
+ req,
63
+ overrideAccess: false,
64
+ disableErrors: true
65
+ });
66
+ const published = await read(false);
67
+ const latest = await read(true);
68
+ if (!published || published._status !== 'published' || !latest || latest._status !== 'published' || typeof published.updatedAt !== 'string' || published.updatedAt !== latest.updatedAt) throw refused(PAGE_COPY.copyOriginal(label));
69
+ return published;
70
+ }
71
+ export async function preparePageCopy(req, options, test, key, confirmed) {
72
+ const arms = test.arms ?? [];
73
+ const control = arms.find((arm)=>arm.kind === 'control');
74
+ if (confirmed) {
75
+ if (confirmed.updatedAt !== test.updatedAt) throw stale(control?.label);
76
+ }
77
+ if (test.kind !== 'page' || ![
78
+ 'draft',
79
+ 'stopped'
80
+ ].includes(test.status)) throw stale(control?.label);
81
+ const arm = arms.find((arm)=>arm.key === key && arm.kind === 'variant');
82
+ if (!arm || arm.pageTarget) throw stale(control?.label);
83
+ const originalPath = control?.pageTarget;
84
+ const entry = await resolvePageCollection(req, options, {
85
+ pageCollection: test.pageCollection,
86
+ arms
87
+ }, true);
88
+ if (!entry?.copy) throw new XpRefusal('copy-not-enabled', PAGE_COPY.copyNotEnabled, undefined, 422);
89
+ if (!originalPath) throw refused(PAGE_COPY.copyChooseOriginal(control?.label));
90
+ const overridesFor = entry.copy === true ? undefined : entry.copy.overrides;
91
+ const config = req.payload.collections[entry.slug]?.config;
92
+ if (!config || config.upload || config.timestamps === false) throw refused();
93
+ if (hasProtectedFields(config.fields, req.payload.config)) throw refused(PAGE_COPY.copyProtected);
94
+ if (config.disableDuplicate) throw refused(PAGE_COPY.copyDisabled);
95
+ if (!config.versions?.drafts) throw refused(PAGE_COPY.copyNoDrafts);
96
+ if (hasLocalizedFields(config.fields, req.payload.config)) throw refused(PAGE_COPY.copyLocalized(control?.label));
97
+ const match = await entry.findByPath(originalPath, req);
98
+ if (!match?.published) throw refused(PAGE_COPY.copyOriginal(control?.label));
99
+ const original = await readOriginal(req, entry.slug, match.id, control?.label);
100
+ const sourcePath = entry.pathOf(original);
101
+ if (!sourcePath || normalisePath(sourcePath) !== normalisePath(originalPath)) throw refused(PAGE_COPY.copyOriginal(control?.label));
102
+ const reader = placementReader(req, entry.slug, options);
103
+ if (reader.read(original, 'localized').slugs.length) throw refused(PAGE_COPY.copyEmbeddedTest(control?.label));
104
+ const fields = flattenTopLevelFields(config.fields);
105
+ const useAsTitle = config.admin.useAsTitle;
106
+ const titleField = typeof useAsTitle === 'string' && !addressFields.includes(useAsTitle) && useAsTitle !== 'id' ? useAsTitle : 'title';
107
+ const homeFlags = fields.flatMap((field)=>field.type === 'checkbox' && typeof field.name === 'string' && homeFields.includes(field.name) ? [
108
+ field.name
109
+ ] : []);
110
+ const requiredUniqueFields = fields.flatMap((field)=>typeof field.name === 'string' && 'unique' in field && field.unique && 'required' in field && field.required ? [
111
+ field.name
112
+ ] : []);
113
+ const hasSlugHistory = fields.some((field)=>field.name === 'slugHistory' && (field.type === 'array' || field.type === 'json'));
114
+ const position = arms.filter((arm)=>arm.kind === 'variant').indexOf(arm);
115
+ const suffix = `-variant-${String.fromCharCode(97 + position)}`;
116
+ const base = normalisePath(originalPath);
117
+ const rootName = addressFields.map((name)=>original[name]).find((value)=>typeof value === 'string' && /^\/?[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*\/?$/i.test(value));
118
+ const pathBase = base === '/' ? `/${rootName?.replace(/^\/+|\/+$/g, '') ?? 'home'}` : base;
119
+ const used = new Set(arms.flatMap((item)=>item.pageTarget ? [
120
+ normalisePath(item.pageTarget)
121
+ ] : []));
122
+ for(let attempt = 1; attempt <= 30; attempt++){
123
+ const ending = attempt === 1 ? suffix : `${suffix}-${attempt}`;
124
+ const path = pathBase + ending;
125
+ if (confirmed && path !== confirmed.path || used.has(path)) continue;
126
+ const data = Object.fromEntries(homeFlags.map((name)=>[
127
+ name,
128
+ false
129
+ ]));
130
+ if (hasSlugHistory) data.slugHistory = [];
131
+ if (typeof original[titleField] === 'string') data[titleField] = original[titleField];
132
+ for (const field of fields){
133
+ if (field.type !== 'text' || field.virtual || !addressFields.includes(field.name)) continue;
134
+ const value = original[field.name];
135
+ if (typeof value !== 'string' || !value.trim() || value === '/') {
136
+ data[field.name] = field.name === 'path' ? path : field.name === 'pageSegment' ? path.split('/').at(-1) : path.slice(1);
137
+ } else if (field.name === 'pageSegment' || base === '/' || base.endsWith(normalisePath('/' + value.replace(/^\/+/, '')))) {
138
+ data[field.name] = normalisePath(value) + ending;
139
+ }
140
+ }
141
+ if (overridesFor) {
142
+ const overrides = await overridesFor({
143
+ ...original
144
+ }, {
145
+ req,
146
+ path,
147
+ suffix: ending
148
+ });
149
+ if (overrides === null) throw refused();
150
+ Object.assign(data, overrides);
151
+ }
152
+ const proposed = {
153
+ ...original,
154
+ ...data
155
+ };
156
+ const projectedPath = entry.pathOf(proposed);
157
+ if (projectedPath === null || normalisePath(projectedPath) !== path || !path.startsWith('/') || path.startsWith('//') || /[?#\\\s]/.test(path) || homeFlags.some((name)=>proposed[name] !== false)) throw refused(PAGE_COPY.copyAddress);
158
+ // A checked read cannot see a hidden page. Require the inferred address to
159
+ // depend on a unique field, so the insert also checks hidden and racing rows.
160
+ if (!overridesFor && !fields.some((field)=>field.type === 'text' && field.unique && typeof data[field.name] === 'string' && addressFields.includes(field.name) && entry.pathOf({
161
+ ...proposed,
162
+ [field.name]: original[field.name]
163
+ }) !== projectedPath)) throw refused(PAGE_COPY.copyAddress);
164
+ const rawTitle = proposed[titleField];
165
+ const title = typeof rawTitle === 'string' && rawTitle.trim() ? rawTitle : path;
166
+ const addressQueries = fields.flatMap((field)=>field.type === 'text' && !field.virtual && addressFields.includes(field.name) && (field.name !== 'pageSegment' || field.unique) && typeof data[field.name] === 'string' ? [
167
+ {
168
+ [field.name]: {
169
+ equals: data[field.name]
170
+ }
171
+ }
172
+ ] : []);
173
+ // findByPath can report an occupied published address even when the latest draft changed it.
174
+ if (await entry.findByPath(path, req)) continue;
175
+ if (addressQueries.length) {
176
+ const occupied = (draft)=>req.payload.find({
177
+ collection: entry.slug,
178
+ req,
179
+ overrideAccess: false,
180
+ draft,
181
+ depth: 0,
182
+ limit: 1,
183
+ pagination: false,
184
+ where: {
185
+ or: addressQueries
186
+ }
187
+ });
188
+ if ((await occupied(false)).docs.length || (await occupied(true)).docs.length) continue;
189
+ }
190
+ const plan = {
191
+ title,
192
+ path,
193
+ phase: test.phase,
194
+ updatedAt: test.updatedAt,
195
+ originalId: original.id,
196
+ originalUpdatedAt: original.updatedAt
197
+ };
198
+ if (confirmed && (title !== confirmed.title || String(plan.originalId) !== String(confirmed.originalId) || plan.originalUpdatedAt !== confirmed.originalUpdatedAt)) throw stale(control?.label);
199
+ return {
200
+ plan,
201
+ data,
202
+ entry,
203
+ titleField,
204
+ homeFlags,
205
+ hasSlugHistory,
206
+ requiredUniqueFields,
207
+ original,
208
+ arms,
209
+ reader
210
+ };
211
+ }
212
+ if (confirmed) throw stale(control?.label);
213
+ throw refused(PAGE_COPY.copyAddress);
214
+ }
215
+ async function reportOrphanedCopies(req, entry, ids, titleField) {
216
+ const committed = await committedPageCopyIds(req.payload, entry.slug, ids);
217
+ if (!committed.length) return;
218
+ const pages = await Promise.all(committed.map(async (id)=>{
219
+ try {
220
+ const page = await req.payload.findByID({
221
+ collection: entry.slug,
222
+ id,
223
+ req,
224
+ overrideAccess: false,
225
+ draft: false,
226
+ depth: 0,
227
+ disableErrors: true
228
+ });
229
+ if (page) {
230
+ const title = page[titleField];
231
+ const path = entry.pathOf(page);
232
+ return {
233
+ id,
234
+ ...typeof title === 'string' && title.trim() ? {
235
+ title
236
+ } : {},
237
+ path
238
+ };
239
+ }
240
+ } catch (cause) {
241
+ req.payload.logger.warn({
242
+ err: safeError(cause),
243
+ collection: entry.slug,
244
+ id
245
+ }, 'Could not read a committed test page copy');
246
+ }
247
+ return {
248
+ id,
249
+ path: null
250
+ };
251
+ }));
252
+ const label = collectionLabel(req.payload.collections[entry.slug]?.config.labels.plural, entry.slug, req);
253
+ throw new XpRefusal('copy-orphaned', orphanedPages(pages, label), {
254
+ collection: entry.slug,
255
+ pages
256
+ }, 500);
257
+ }
258
+ async function confirmBody(req) {
259
+ const value = await readBody(req).catch(()=>null);
260
+ if (!value || typeof value.arm !== 'string' || !Number.isSafeInteger(value.phase) || typeof value.path !== 'string' || typeof value.title !== 'string' || typeof value.updatedAt !== 'string' || !Number.isFinite(Date.parse(value.updatedAt)) || typeof value.originalUpdatedAt !== 'string' || !(typeof value.originalId === 'number' || typeof value.originalId === 'string') || req.headers.get(XP_IF_UPDATED_AT_HEADER) !== value.updatedAt) throw invalid();
261
+ return value;
262
+ }
263
+ export async function handleDuplicateOriginal(req, { options }) {
264
+ const id = routeId(req);
265
+ if (id === undefined) throw invalid();
266
+ let controlLabel;
267
+ const readCopyTest = async ()=>{
268
+ const test = await readTest(req, id);
269
+ controlLabel = test.arms?.find((arm)=>arm.kind === 'control')?.label;
270
+ return test;
271
+ };
272
+ try {
273
+ if (req.method === 'GET') {
274
+ const arm = new URL(req.url ?? 'http://xp.invalid').searchParams.get('arm');
275
+ if (!arm) throw invalid();
276
+ const { plan } = await preparePageCopy(req, options, await readCopyTest(), arm);
277
+ return response(plan);
278
+ }
279
+ const confirmed = await confirmBody(req);
280
+ const before = await readCopyTest();
281
+ const { result } = await withTransition(req, {
282
+ experimentId: id,
283
+ layerId: relationshipId(before.layer),
284
+ bump: false,
285
+ edit: true,
286
+ requireOwnedTransaction: true
287
+ }, async ({ exec })=>{
288
+ const transactionId = await req.transactionID;
289
+ const xid = await currentTxid(exec);
290
+ const isLive = async ()=>await req.transactionID === transactionId && await transactionSession(req).then(()=>currentTxid(exec)).catch(()=>undefined) === xid;
291
+ const test = await readCopyTest();
292
+ requireCurrentRound(confirmed.phase, test.phase);
293
+ await lockPagePaths(exec, [
294
+ confirmed.path
295
+ ]);
296
+ const updatedAt = await lockExperimentUpdatedAt(exec, id);
297
+ if (updatedAt === null || new Date(updatedAt).getTime() !== Date.parse(confirmed.updatedAt)) throw stale(controlLabel);
298
+ const { plan, data, entry, titleField, homeFlags, hasSlugHistory, requiredUniqueFields, original, arms, reader } = await preparePageCopy(req, options, test, confirmed.arm, confirmed);
299
+ if (!await isLive()) throw transactionLost();
300
+ const previous = req.context.xpDuplicate;
301
+ const tracking = {
302
+ collection: entry.slug,
303
+ created: []
304
+ };
305
+ req.context.xpDuplicate = tracking;
306
+ let created;
307
+ try {
308
+ created = await req.payload.duplicate({
309
+ collection: entry.slug,
310
+ id: original.id,
311
+ req,
312
+ overrideAccess: false,
313
+ draft: true,
314
+ depth: 0,
315
+ data
316
+ });
317
+ } catch (cause) {
318
+ await reportOrphanedCopies(req, entry, tracking.created, titleField);
319
+ if (cause instanceof Forbidden) throw new XpRefusal('copy-no-access', PAGE_COPY.copyNoAccess, undefined, 422);
320
+ if (cause instanceof ValidationError && cause.data?.errors.some((error)=>error.message === (req.t?.('error:valueMustBeUnique') ?? 'Value must be unique'))) {
321
+ throw new XpRefusal('copy-unique-field', PAGE_COPY.copyUnique, undefined, 422);
322
+ }
323
+ throw cause;
324
+ } finally{
325
+ if (previous === undefined) delete req.context.xpDuplicate;
326
+ else req.context.xpDuplicate = previous;
327
+ }
328
+ if (!await isLive()) {
329
+ await reportOrphanedCopies(req, entry, [
330
+ ...tracking.created,
331
+ created.id
332
+ ], titleField);
333
+ throw transactionLost();
334
+ }
335
+ // Read the main row as the manager. A host hook can replace the title,
336
+ // address or status during Create, so verify before linking the copy.
337
+ const copy = await req.payload.findByID({
338
+ collection: entry.slug,
339
+ id: created.id,
340
+ req,
341
+ overrideAccess: false,
342
+ draft: false,
343
+ depth: 0,
344
+ disableErrors: true
345
+ });
346
+ const copyPath = copy && entry.pathOf(copy);
347
+ const rawTitle = copy?.[titleField];
348
+ const copyTitle = typeof rawTitle === 'string' && rawTitle.trim() ? rawTitle : plan.path;
349
+ if (!copy || copy._status !== 'draft' || !copyPath || normalisePath(copyPath) !== plan.path || copyTitle !== plan.title || homeFlags.some((name)=>copy[name] !== false) || hasSlugHistory && (!Array.isArray(copy.slugHistory) || copy.slugHistory.length > 0) || reader.read(copy, 'localized').slugs.length) throw refused();
350
+ if (requiredUniqueFields.some((name)=>copy[name] == null || copy[name] === '')) throw refused();
351
+ if ((await readOriginal(req, entry.slug, original.id, controlLabel)).updatedAt !== original.updatedAt) throw stale(controlLabel);
352
+ const occupant = await entry.findByPath(plan.path, req);
353
+ if (occupant && (occupant.published || String(occupant.id) !== String(copy.id))) throw refused(PAGE_COPY.copyAddress);
354
+ if (!await isLive()) throw transactionLost();
355
+ const doc = await req.payload.update({
356
+ collection: 'xp-experiments',
357
+ id,
358
+ req,
359
+ overrideAccess: false,
360
+ depth: 0,
361
+ data: {
362
+ arms: arms.map((arm)=>arm.key === confirmed.arm ? {
363
+ ...arm,
364
+ pageTarget: copyPath
365
+ } : arm)
366
+ }
367
+ });
368
+ if (!await isLive()) throw transactionLost();
369
+ return {
370
+ doc,
371
+ copy,
372
+ collection: entry.slug,
373
+ path: copyPath,
374
+ title: plan.title
375
+ };
376
+ });
377
+ const { copy, collection, path, title, doc } = result;
378
+ let editorUrl = formatAdminURL({
379
+ adminRoute: req.payload.config.routes.admin,
380
+ path: `/collections/${collection}/${encodeURIComponent(String(copy.id))}`
381
+ });
382
+ try {
383
+ editorUrl = options.admin?.editorUrl?.({
384
+ collection,
385
+ id: copy.id,
386
+ draft: true,
387
+ editor: 'page',
388
+ doc: copy
389
+ }) || editorUrl;
390
+ } catch (cause) {
391
+ req.payload.logger.warn({
392
+ err: safeError(cause),
393
+ collection
394
+ }, 'Could not open the copied test page in its custom editor');
395
+ }
396
+ return response({
397
+ doc,
398
+ copy: {
399
+ id: copy.id,
400
+ title,
401
+ path,
402
+ editorUrl
403
+ }
404
+ });
405
+ } catch (cause) {
406
+ if (cause instanceof XpRefusal) throw cause;
407
+ if (cause instanceof Forbidden) throw refused(PAGE_COPY.copyOriginal(controlLabel));
408
+ req.payload.logger.warn({
409
+ err: safeError(cause),
410
+ experimentId: id
411
+ }, 'Could not make a test page copy');
412
+ throw refused();
413
+ }
414
+ }
@@ -22,7 +22,7 @@ import { buildSurfaceProps } from '../admin/views/buildSurfaceProps.js';
22
22
  'Cache-Control': 'private, no-store'
23
23
  }
24
24
  });
25
- const { route: _route, id: _id, pages: _pages, returnToTest: _return, ...surface } = props;
25
+ const { route: _route, id: _id, returnToTest: _return, ...surface } = props;
26
26
  return Response.json(surface, {
27
27
  headers: {
28
28
  'Cache-Control': 'private, no-store'
@@ -8,10 +8,12 @@ import { handleManifest } from './manifest.js';
8
8
  import { handleEvents } from './events.js';
9
9
  import { handleStart, handleAllocate, handleAddMetric, handleStop, handleDecide, handleReleaseHoldout, handleReleasePages, handleMakeContent, handleDismissContentEntry, handleRestoreContentEntry, handleArchive } from './transitions.js';
10
10
  import { handlePreflight } from './preflight.js';
11
+ import { handleTestVersion } from './testVersion.js';
11
12
  import { handlePreviewToken } from './previewToken.js';
12
13
  import { handleResults } from './results.js';
13
14
  import { handleRecompute } from './recompute.js';
14
15
  import { handleWrapBlock } from './wrapBlock.js';
16
+ import { handleDuplicateOriginal } from './duplicateOriginal.js';
15
17
  import { handlePages } from './pages.js';
16
18
  import { handlePlacementStatus } from './placementStatus.js';
17
19
  import { handleSummary } from './summary.js';
@@ -106,6 +108,12 @@ export const ROUTES = [
106
108
  access: 'manage',
107
109
  handler: handlePreflight
108
110
  },
111
+ {
112
+ method: 'get',
113
+ path: '/xp/experiments/:id/version',
114
+ access: 'manage',
115
+ handler: handleTestVersion
116
+ },
109
117
  {
110
118
  method: 'get',
111
119
  path: '/xp/experiments/:id/preview-token',
@@ -148,6 +156,18 @@ export const ROUTES = [
148
156
  access: 'manage',
149
157
  handler: handlePages
150
158
  },
159
+ {
160
+ method: 'get',
161
+ path: '/xp/experiments/:id/duplicate-original',
162
+ access: 'manage',
163
+ handler: handleDuplicateOriginal
164
+ },
165
+ {
166
+ method: 'post',
167
+ path: '/xp/experiments/:id/duplicate-original',
168
+ access: 'manage',
169
+ handler: handleDuplicateOriginal
170
+ },
151
171
  {
152
172
  method: 'post',
153
173
  path: '/xp/placements/status',