@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
@@ -1,49 +1,63 @@
1
+ import { flattenTopLevelFields, formatAdminURL } from 'payload/shared';
1
2
  import { placementReader } from '../blocks/placementLocale.js';
3
+ import { findDraftPageByPath, PAGE_ADDRESS_FIELDS } from '../transitions/pageAddress.js';
2
4
  import { normalisePath } from '../runtime/normalisePath.js';
5
+ import { blockPageSlugs, hasPuckEditor } from '../options.js';
3
6
  import { XpRefusal } from '../errors.js';
7
+ const PAGE_SIZE = 20;
8
+ const MAX_PAGE = 1000;
9
+ const MAX_SEARCH_IDS = PAGE_SIZE * MAX_PAGE;
10
+ const pageResponse = (body)=>Response.json(body, {
11
+ headers: {
12
+ 'Cache-Control': 'private, no-store'
13
+ }
14
+ });
15
+ const textValue = (value)=>typeof value === 'string' && value.trim() ? value : undefined;
16
+ const anyFilter = (filters)=>filters.length > 1 ? {
17
+ or: filters
18
+ } : filters[0];
19
+ function requiresPublished(where) {
20
+ const status = Array.isArray(where._status) ? undefined : where._status;
21
+ const allowed = status?.in;
22
+ return status?.equals === 'published' || allowed === 'published' || Array.isArray(allowed) && allowed.length === 1 && allowed[0] === 'published' || Boolean(where.and?.some(requiresPublished)) || Boolean(where.or?.length && where.or.every(requiresPublished));
23
+ }
4
24
  export async function handlePages(req, { options }) {
5
25
  const query = new URL(req.url ?? 'http://xp.invalid').searchParams;
6
- const collection = options.pages?.collections.find((entry)=>entry.slug === query.get('collection'));
7
- if (!collection) throw new XpRefusal('unknown-collection', "That page type isn't set up for tests.", undefined, 422);
8
- const reader = placementReader(req, collection.slug, options);
26
+ const slug = query.get('collection') ?? '';
27
+ const collection = options.pages?.collections.find((entry)=>entry.slug === slug);
28
+ const blockMode = query.get('mode') === 'block';
29
+ if (blockMode ? !blockPageSlugs(options).includes(slug) : !collection) {
30
+ throw new XpRefusal('unknown-collection', "That page type isn't set up for tests.", undefined, 422);
31
+ }
32
+ const reader = placementReader(req, slug, options);
33
+ const input = req.locale === 'all' ? 'all-locales' : 'localized';
9
34
  const path = query.get('path');
10
- if (path !== null && (!path.length || path.length > 2048 || query.has('q'))) throw new XpRefusal('invalid-body', 'Enter a valid request body.', undefined, 422);
35
+ if (path !== null && (blockMode || !path.length || path.length > 2048 || query.has('q'))) throw new XpRefusal('invalid-body', 'Enter a valid request body.', undefined, 422);
11
36
  const page = Number(query.get('page') ?? 1);
12
- if (!Number.isSafeInteger(page) || page < 1 || page > 1000) throw new XpRefusal('invalid-body', 'Choose a valid page.', undefined, 422);
13
- const config = req.payload.config.collections.find((entry)=>entry.slug === collection.slug);
14
- const titleField = config?.admin.useAsTitle ?? 'title';
37
+ if (!Number.isSafeInteger(page) || page < 1 || page > MAX_PAGE) throw new XpRefusal('invalid-body', 'Choose a valid page.', undefined, 422);
38
+ const config = req.payload.config.collections.find((entry)=>entry.slug === slug);
39
+ const fields = flattenTopLevelFields(config?.fields ?? []);
40
+ const title = config?.admin.useAsTitle;
41
+ const titleField = title && title !== 'id' ? title : fields.some((field)=>field.name === 'title') ? 'title' : title ?? 'id';
15
42
  const drafts = Boolean(config?.versions && config.versions.drafts);
16
- const q = query.get('q')?.trim().slice(0, 100);
17
- if (path !== null) {
43
+ if (path !== null && collection) {
18
44
  const found = await collection.findByPath(path, req);
19
- if (!found) return Response.json({
20
- docs: [],
21
- hasNextPage: false
22
- }, {
23
- headers: {
24
- 'Cache-Control': 'no-store'
25
- }
26
- });
27
- const main = await req.payload.findByID({
28
- collection: collection.slug,
45
+ const main = found ? await req.payload.findByID({
46
+ collection: slug,
29
47
  id: found.id,
30
48
  req,
31
49
  overrideAccess: false,
32
50
  depth: 0,
33
51
  draft: false,
34
52
  disableErrors: true
35
- });
36
- if (!main) return Response.json({
53
+ }) : await findDraftPageByPath(req, collection, path);
54
+ if (!main) return pageResponse({
37
55
  docs: [],
38
56
  hasNextPage: false
39
- }, {
40
- headers: {
41
- 'Cache-Control': 'no-store'
42
- }
43
57
  });
44
58
  const published = !drafts || main._status === 'published';
45
59
  const row = published ? main : await req.payload.findByID({
46
- collection: collection.slug,
60
+ collection: slug,
47
61
  id: main.id,
48
62
  req,
49
63
  overrideAccess: false,
@@ -51,74 +65,239 @@ export async function handlePages(req, { options }) {
51
65
  draft: true,
52
66
  disableErrors: true
53
67
  });
54
- if (!row) return Response.json({
68
+ if (!row) return pageResponse({
55
69
  docs: [],
56
70
  hasNextPage: false
57
- }, {
58
- headers: {
59
- 'Cache-Control': 'no-store'
60
- }
61
71
  });
62
- const doc = reader.read(row, req.locale === 'all' ? 'all-locales' : 'localized').doc;
72
+ const doc = reader.read(row, input).doc;
63
73
  const rawPath = collection.pathOf(doc);
64
- return Response.json({
74
+ if (!found && (!rawPath || normalisePath(rawPath) !== normalisePath(path))) return pageResponse({
75
+ docs: [],
76
+ hasNextPage: false
77
+ });
78
+ return pageResponse({
65
79
  docs: [
66
80
  {
67
81
  id: main.id,
68
- title: titleField !== 'id' && typeof doc[titleField] === 'string' && String(doc[titleField]).trim() ? String(doc[titleField]) : '',
82
+ title: titleField !== 'id' ? textValue(doc[titleField]) ?? '' : '',
69
83
  path: rawPath,
70
84
  pathKey: rawPath === null ? null : normalisePath(rawPath),
71
85
  published
72
86
  }
73
87
  ],
74
88
  hasNextPage: false
75
- }, {
76
- headers: {
77
- 'Cache-Control': 'no-store'
89
+ });
90
+ }
91
+ const q = query.get('q')?.trim().slice(0, 100) ?? '';
92
+ const addressFields = PAGE_ADDRESS_FIELDS.filter((name)=>fields.some((field)=>field.name === name));
93
+ const searchFields = new Set([
94
+ titleField,
95
+ ...addressFields,
96
+ ...config?.admin.listSearchableFields ?? []
97
+ ]);
98
+ const searchable = q ? await Promise.all(fields.map(async (field)=>{
99
+ if (field.type !== 'text' && field.type !== 'textarea' || field.hidden || field.virtual || !searchFields.has(field.name)) return;
100
+ if (field.access?.read && !await field.access.read({
101
+ req
102
+ })) return;
103
+ return field.name;
104
+ })) : [];
105
+ const filters = searchable.flatMap((field)=>{
106
+ if (!field) return [];
107
+ const term = field === 'slug' || field === 'pageSegment' ? q.replace(/^\/+|\/+$/g, '') : q;
108
+ return term ? [
109
+ {
110
+ [field]: {
111
+ like: term
112
+ }
113
+ }
114
+ ] : [];
115
+ });
116
+ const fieldFilter = anyFilter([
117
+ ...filters
118
+ ]);
119
+ // A generated address may not have its own queryable field, and a live path
120
+ // can differ from the latest draft. The host's exact lookup covers both cases.
121
+ if (q.startsWith('/') && collection) {
122
+ const found = await collection.findByPath(q, req);
123
+ if (found) filters.push({
124
+ id: {
125
+ equals: found.id
126
+ }
127
+ });
128
+ }
129
+ if (q && !filters.length) return pageResponse({
130
+ docs: [],
131
+ hasNextPage: false,
132
+ totalDocs: 0
133
+ });
134
+ // Payload applies the read constraint to the latest version when draft is
135
+ // true. A manager scoped to published content needs to browse the live rows.
136
+ const readScope = drafts ? await config?.access?.read?.({
137
+ req
138
+ }) : undefined;
139
+ const readDrafts = drafts && !(readScope && typeof readScope === 'object' && requiresPublished(readScope));
140
+ let searchTruncated = false;
141
+ if (readDrafts && fieldFilter) {
142
+ // Include live matches in the draft query before sorting and paging.
143
+ // Cap the ID lookup to the number of rows the picker can show.
144
+ const matches = await req.payload.find({
145
+ collection: slug,
146
+ req,
147
+ overrideAccess: false,
148
+ depth: 0,
149
+ draft: false,
150
+ where: {
151
+ and: [
152
+ {
153
+ _status: {
154
+ equals: 'published'
155
+ }
156
+ },
157
+ fieldFilter
158
+ ]
159
+ },
160
+ select: {
161
+ id: true
162
+ },
163
+ pagination: false,
164
+ sort: '-id',
165
+ limit: MAX_SEARCH_IDS + 1
166
+ });
167
+ searchTruncated = matches.docs.length > MAX_SEARCH_IDS;
168
+ if (matches.docs.length) filters.push({
169
+ id: {
170
+ in: matches.docs.slice(0, MAX_SEARCH_IDS).map((doc)=>doc.id)
78
171
  }
79
172
  });
80
173
  }
174
+ const where = anyFilter(filters);
175
+ const block = options.blocks?.collections.find((entry)=>entry.slug === slug);
176
+ const hasTimestamp = config?.timestamps !== false;
177
+ const hasDocCallbacks = collection || blockMode && (block?.appliesTo || options.admin?.editorUrl);
178
+ const metadata = Object.fromEntries([
179
+ titleField,
180
+ ...addressFields,
181
+ ...hasTimestamp ? [
182
+ 'updatedAt'
183
+ ] : [],
184
+ ...drafts ? [
185
+ '_status'
186
+ ] : []
187
+ ].map((field)=>[
188
+ field,
189
+ true
190
+ ]));
81
191
  const result = await req.payload.find({
82
- collection: collection.slug,
192
+ collection: slug,
83
193
  req,
84
194
  overrideAccess: false,
85
195
  depth: 0,
86
- draft: false,
87
- sort: '-createdAt',
88
- limit: 20,
196
+ draft: readDrafts,
197
+ sort: hasTimestamp ? [
198
+ '-updatedAt',
199
+ '-id'
200
+ ] : '-id',
201
+ limit: PAGE_SIZE,
89
202
  page,
90
- where: q && titleField !== 'id' ? {
91
- [titleField]: {
92
- like: q
93
- }
94
- } : undefined
203
+ where,
204
+ // Host callbacks can inspect arbitrary fields. Only picker metadata leaves this endpoint.
205
+ select: hasDocCallbacks ? undefined : metadata
95
206
  });
96
- const docs = await Promise.all(result.docs.map(async (main)=>{
97
- const published = !drafts || main._status === 'published';
98
- const row = published ? main : await req.payload.findByID({
99
- collection: collection.slug,
100
- id: main.id,
207
+ const draftIds = readDrafts ? result.docs.filter((doc)=>doc._status === 'draft').map((doc)=>doc.id) : [];
208
+ const publishedById = new Map();
209
+ if (draftIds.length) {
210
+ // Read only the matching live rows, in one bounded query. Whole-page choices
211
+ // use the currently served path even when a newer edit changes that path.
212
+ const live = await req.payload.find({
213
+ collection: slug,
101
214
  req,
102
215
  overrideAccess: false,
103
216
  depth: 0,
104
- draft: true
217
+ draft: false,
218
+ where: {
219
+ id: {
220
+ in: draftIds
221
+ },
222
+ _status: {
223
+ equals: 'published'
224
+ }
225
+ },
226
+ limit: PAGE_SIZE,
227
+ select: !blockMode && collection ? undefined : {
228
+ _status: true
229
+ }
105
230
  });
106
- const doc = reader.read(row, req.locale === 'all' ? 'all-locales' : 'localized').doc;
107
- const path = collection.pathOf(doc);
108
- return {
109
- id: main.id,
110
- title: String(doc[titleField] ?? main.id),
111
- path,
112
- pathKey: path === null ? null : normalisePath(path),
113
- published
231
+ for (const doc of live.docs)if (doc._status === 'published') publishedById.set(String(doc.id), doc);
232
+ }
233
+ const docs = result.docs.flatMap((row)=>{
234
+ const placement = reader.read(row, input);
235
+ const doc = placement.doc;
236
+ const live = publishedById.get(String(row.id));
237
+ const published = !drafts || row._status === 'published' || live !== undefined;
238
+ const pathDoc = !blockMode && live ? reader.read(live, input).doc : doc;
239
+ const rawPath = collection?.pathOf(pathDoc) ?? null;
240
+ const storedAddress = blockMode ? addressFields.reduce((value, field)=>value ?? textValue(pathDoc[field]), undefined) : undefined;
241
+ const address = rawPath ?? storedAddress;
242
+ const draftAddress = !blockMode && live ? collection?.pathOf(doc) : null;
243
+ const updatedAt = textValue(doc.updatedAt);
244
+ const title = doc[titleField];
245
+ const item = {
246
+ id: row.id,
247
+ title: textValue(title) ?? (typeof title === 'number' ? String(title) : String(row.id)),
248
+ path: rawPath,
249
+ pathKey: rawPath === null ? null : normalisePath(rawPath),
250
+ published,
251
+ status: live ? 'changed' : published ? 'published' : 'draft',
252
+ ...address ? {
253
+ address
254
+ } : {},
255
+ ...draftAddress && draftAddress !== rawPath ? {
256
+ draftAddress
257
+ } : {},
258
+ ...updatedAt ? {
259
+ updatedAt
260
+ } : {}
114
261
  };
115
- }));
116
- return Response.json({
262
+ if (!blockMode) return [
263
+ item
264
+ ];
265
+ const editor = placement.editor;
266
+ if (editor === 'page') return [];
267
+ let customUrl;
268
+ try {
269
+ customUrl = textValue(options.admin?.editorUrl?.({
270
+ collection: slug,
271
+ id: row.id,
272
+ draft: true,
273
+ editor,
274
+ doc
275
+ }));
276
+ } catch {}
277
+ const editorUrl = customUrl ?? formatAdminURL({
278
+ adminRoute: req.payload.config.routes.admin,
279
+ path: `/collections/${slug}/${encodeURIComponent(String(row.id))}`
280
+ });
281
+ return [
282
+ {
283
+ ...item,
284
+ editor,
285
+ editorUrl
286
+ }
287
+ ];
288
+ });
289
+ const mayFilter = blockMode && Boolean(block?.appliesTo) && !hasPuckEditor(options, slug);
290
+ const hasNextPage = page < MAX_PAGE && result.hasNextPage;
291
+ const pageLimitReached = !hasNextPage && (result.hasNextPage || searchTruncated);
292
+ return pageResponse({
117
293
  docs,
118
- hasNextPage: result.hasNextPage
119
- }, {
120
- headers: {
121
- 'Cache-Control': 'no-store'
294
+ hasNextPage,
295
+ ...pageLimitReached ? {
296
+ pageLimitReached
297
+ } : {},
298
+ ...mayFilter || searchTruncated ? {} : {
299
+ totalDocs: result.totalDocs,
300
+ pagingCounter: result.pagingCounter
122
301
  }
123
302
  });
124
303
  }
@@ -218,6 +218,7 @@ export async function handlePlacementStatus(req, { options }) {
218
218
  status: test.status,
219
219
  role: arm.kind === 'control' ? 'original' : 'version',
220
220
  armLabel: arm.label,
221
+ controlLabel: original?.label,
221
222
  winner: [
222
223
  'decided',
223
224
  'archived'
@@ -82,6 +82,9 @@ export async function handleResults(req, { options }) {
82
82
  phaseKind: record.phaseKind,
83
83
  startedAt: String(record.startedAt),
84
84
  endedAt: record.endedAt == null ? null : String(record.endedAt),
85
+ ...record.phaseKind === 'test' && record.analysis?.plannedDurationDays != null ? {
86
+ plannedDurationDays: record.analysis.plannedDurationDays
87
+ } : {},
85
88
  arms: record.arms.map(({ key, label, kind })=>({
86
89
  key,
87
90
  label,
@@ -0,0 +1,2 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ export declare function handleTestVersion(req: PayloadRequest): Promise<Response>;
@@ -0,0 +1,38 @@
1
+ import { routeId } from './routeId.js';
2
+ export async function handleTestVersion(req) {
3
+ const id = routeId(req);
4
+ const headers = {
5
+ 'Cache-Control': 'private, no-store'
6
+ };
7
+ const doc = id === undefined ? null : await req.payload.findByID({
8
+ collection: 'xp-experiments',
9
+ id,
10
+ req,
11
+ overrideAccess: false,
12
+ depth: 0,
13
+ disableErrors: true,
14
+ select: {
15
+ updatedAt: true,
16
+ status: true,
17
+ phase: true
18
+ }
19
+ });
20
+ if (!doc) return Response.json({
21
+ errors: [
22
+ {
23
+ code: 'not-found',
24
+ message: 'Experiment not found'
25
+ }
26
+ ]
27
+ }, {
28
+ status: 404,
29
+ headers
30
+ });
31
+ return Response.json({
32
+ updatedAt: doc.updatedAt,
33
+ status: doc.status,
34
+ phase: doc.phase ?? 0
35
+ }, {
36
+ headers
37
+ });
38
+ }
@@ -95,13 +95,12 @@ export async function handleAddMetric(req, ctx) {
95
95
  const value = await body(req);
96
96
  if (!value || !only(value, [
97
97
  'metric',
98
- 'role'
99
- ]) || !(typeof value.metric === 'string' && value.metric.trim() || typeof value.metric === 'number' && Number.isSafeInteger(value.metric)) || value.role !== 'secondary' && value.role !== 'guardrail') return invalidBody();
100
- const metric = value.metric, role = value.role;
98
+ 'role',
99
+ 'phase'
100
+ ]) || !validPhase(value.phase) || !(typeof value.metric === 'string' && value.metric.trim() || typeof value.metric === 'number' && Number.isSafeInteger(value.metric)) || value.role !== 'secondary' && value.role !== 'guardrail') return invalidBody();
101
101
  return respond(req, (id)=>addMetric(req, {
102
+ ...value,
102
103
  experimentId: id,
103
- metric,
104
- role,
105
104
  options: ctx.options
106
105
  }));
107
106
  }
@@ -2,7 +2,7 @@ export { createExperimentsPlugin } from '../plugin.js';
2
2
  export { defineFlagPoint, defineMetricSource } from '../define.js';
3
3
  export { contentDone } from '../contentDone.js';
4
4
  export { createArmSelectField } from '../fields/armSelect.js';
5
- export type { SerializedFlagPoint, SerializedMetricSource, SerializedAttributeKeys, EditableField, Assignment, Assignments, FlagPointResult, ClientAssignments, RenderedExposure, DocId, PreviewPlacement, Attributes, ExposurePolicy, ExperimentKind, Status, UnitType, ArmKey, ArmKind, TargetingRule, Arm, ParamField, MetricSource, FlagPoint, RateLimiter, ExperimentsAccess, ExperimentsPluginOptions, ExperimentsPageCollection, ArmIssueCode, RefusalCode, ReadinessCode, ErrorEnvelope, TransitionSuccess, StartExperimentFirstStartDetail, StartExperimentResult, StartExperimentWarning, AllocateBody, AddMetricBody, AddMetricWarning, AddMetricResult, ClickKeysResult, PagesResult, PlacementStatusResult, PageTestStatus, DeleteImpactResult, RoundBody, DecideBody, ArchiveBody, MakeContentResult, DismissContentEntryBody, DismissContentEntryResult, RestoreContentEntryBody, RestoreContentEntryResult, ContentReport, PreflightResult, PreviewTokenResult, PhaseSummary, ResultsResponse, SummaryResponse, EventBody, FlagDefault, Manifest, ManifestExperiment, ArmSlot, ExperimentRef, ExperimentSlotProps, ExperimentsProxyRuntimeOptions, ExperimentsProxyRuntime, ExperimentsServerRuntimeOptions, ExperimentsServerRuntime, VerdictCode, Snapshot, MetricUnavailableReason, ContentReportReason, } from '../types/index.js';
5
+ export type { SerializedFlagPoint, SerializedMetricSource, SerializedAttributeKeys, EditableField, Assignment, Assignments, FlagPointResult, ClientAssignments, RenderedExposure, DocId, PreviewPlacement, Attributes, ExposurePolicy, ExperimentKind, Status, UnitType, ArmKey, ArmKind, TargetingRule, Arm, ParamField, MetricSource, FlagPoint, RateLimiter, ExperimentsAccess, ExperimentsPluginOptions, ExperimentsPageCollection, ArmIssueCode, RefusalCode, ReadinessCode, ErrorEnvelope, TransitionSuccess, StartExperimentFirstStartDetail, StartExperimentResult, StartExperimentWarning, AllocateBody, AddMetricBody, AddMetricWarning, AddMetricResult, ClickKeysResult, PageRow, PagesResult, CopyPagePlan, CopyPageResult, PlacementStatusResult, PageTestStatus, DeleteImpactResult, RoundBody, DecideBody, ArchiveBody, MakeContentResult, DismissContentEntryBody, DismissContentEntryResult, RestoreContentEntryBody, RestoreContentEntryResult, ContentReport, PreflightResult, PreviewTokenResult, PhaseSummary, ResultsResponse, SummaryResponse, EventBody, FlagDefault, Manifest, ManifestExperiment, ArmSlot, ExperimentRef, ExperimentSlotProps, ExperimentsProxyRuntimeOptions, ExperimentsProxyRuntime, ExperimentsServerRuntimeOptions, ExperimentsServerRuntime, VerdictCode, Snapshot, MetricUnavailableReason, ContentReportReason, } from '../types/index.js';
6
6
  export { createExperimentBlock } from '../blocks/createExperimentBlock.js';
7
7
  export { EXPERIMENT_BLOCK_SLUG } from '../blocks/model.js';
8
8
  export type { HostBlock, ExperimentBlock, ExperimentBlockGroup, ResolvedHostBlock, ResolvedExperimentBlocks } from '../blocks/model.js';
@@ -19,6 +19,6 @@
19
19
  export function puckGoalRefusal(rawKey, block, malformed, more = 0) {
20
20
  // A malformed key can be any length; keep the dialog readable.
21
21
  const key = rawKey.length > 64 ? `${rawKey.slice(0, 64)}…` : rawKey;
22
- const sentence = malformed ? `Click goal "${key}" on the ${block} block isn't a valid short name. Use lowercase letters, numbers, - and _, then publish.` : `Click goal "${key}" doesn't exist yet. Create it with "+ New click goal" on the ${block} block, then publish.`;
22
+ const sentence = malformed ? `Click goal "${key}" on the ${block} block isn't a valid short name. Use lowercase letters, numbers, - and _.` : `Click goal "${key}" doesn't exist yet. Create it with "+ New click goal" on the ${block} block.`;
23
23
  return sentence + (more > 0 ? ` (and ${more} more)` : '');
24
24
  }
@@ -0,0 +1,2 @@
1
+ /** Present unlabelled source keys in sentence case. */
2
+ export declare function goalSourceLabel(key: string): string;
@@ -0,0 +1,4 @@
1
+ /** Present unlabelled source keys in sentence case. */ export function goalSourceLabel(key) {
2
+ const words = key.replace(/^(?:events|click):/, '').replace(/[-_]+/g, ' ').trim().toLowerCase();
3
+ return words.charAt(0).toUpperCase() + words.slice(1);
4
+ }
@@ -0,0 +1,11 @@
1
+ import type { CollectionAfterChangeHook } from 'payload';
2
+ import type { DocId } from '../types/contracts.js';
3
+ declare module 'payload' {
4
+ interface RequestContext {
5
+ xpDuplicate?: {
6
+ collection: string;
7
+ created: DocId[];
8
+ };
9
+ }
10
+ }
11
+ export declare const trackPageCopies: CollectionAfterChangeHook;
@@ -0,0 +1,7 @@
1
+ export const trackPageCopies = ({ collection, context, operation, doc })=>{
2
+ const tracking = context.xpDuplicate;
3
+ if (operation === 'create' && tracking?.collection === collection.slug) {
4
+ tracking.created.push(doc.id);
5
+ }
6
+ return doc;
7
+ };
@@ -5,3 +5,6 @@ export declare const ARM_LABELS: {
5
5
  readonly variantC: "Variant C";
6
6
  readonly holdout: "Holdout";
7
7
  };
8
+ export declare function controlVersionLabel(label?: string): string;
9
+ /** Use an article with the default name and capitalize the phrase at sentence start. */
10
+ export declare function controlVersionName(label?: string, sentenceStart?: boolean): string;
@@ -5,3 +5,11 @@ export const ARM_LABELS = {
5
5
  variantC: 'Variant C',
6
6
  holdout: 'Holdout'
7
7
  };
8
+ export function controlVersionLabel(label) {
9
+ return typeof label === 'string' && label.trim() || ARM_LABELS.control;
10
+ }
11
+ /** Use an article with the default name and capitalize the phrase at sentence start. */ export function controlVersionName(label, sentenceStart = false) {
12
+ const name = controlVersionLabel(label);
13
+ if (name.toLowerCase() === ARM_LABELS.control.toLowerCase()) return `${sentenceStart ? 'The' : 'the'} ${name}`;
14
+ return sentenceStart ? name.replace(/\p{L}/u, (letter)=>letter.toUpperCase()) : name;
15
+ }
package/dist/options.d.ts CHANGED
@@ -9,3 +9,5 @@ export declare function resolveOptions<TUser extends {
9
9
  }>(input: ExperimentsPluginOptions<TUser>): ResolvedOptions<TUser>;
10
10
  /** One published-row rule shared by scans, bindings, writes and editor links. */
11
11
  export declare function documentEditor(options: Pick<ExperimentsPluginOptions, 'puck' | 'blocks'>, collection: string, doc: Record<string, unknown>): 'puck' | 'blocks' | 'page';
12
+ export declare function hasPuckEditor(options: Pick<ExperimentsPluginOptions, 'puck'>, collection: string): boolean;
13
+ export declare function blockPageSlugs(options: Pick<ExperimentsPluginOptions, 'puck' | 'blocks'>): string[];
package/dist/options.js CHANGED
@@ -18,6 +18,9 @@ const normalisedCollections = new WeakMap();
18
18
  normalisedCollections.set(resolved, resolved);
19
19
  return resolved;
20
20
  }
21
+ function enabledPuckCollections(options) {
22
+ return options.puck?.enabled === false ? [] : puckCollections(options);
23
+ }
21
24
  export function resolveOptions(input) {
22
25
  if (typeof input?.access?.manage !== 'function') throw new Error('Experiments access.manage must be a function');
23
26
  const origin = publicEventOrigin(input.events?.origin);
@@ -82,6 +85,9 @@ export function resolveOptions(input) {
82
85
  }
83
86
  if (entry.copyUrl !== undefined && !validCopyUrl(entry.copyUrl)) throw new Error('Experiments copyUrl must be a root-relative path');
84
87
  if (entry.copyLabel !== undefined && entry.copyUrl === undefined) throw new Error('Experiments copyLabel requires copyUrl');
88
+ if (entry.copy !== undefined && typeof entry.copy !== 'boolean' && (!entry.copy || typeof entry.copy !== 'object' || Array.isArray(entry.copy) || typeof entry.copy.overrides !== 'function')) {
89
+ throw new Error('Experiments pages.collections[].copy must be a boolean or an object with an overrides function');
90
+ }
85
91
  slugs.add(entry.slug);
86
92
  }
87
93
  }
@@ -191,7 +197,17 @@ function validCopyUrl(value) {
191
197
  }
192
198
  /** One published-row rule shared by scans, bindings, writes and editor links. */ export function documentEditor(options, collection, doc) {
193
199
  const block = options.blocks?.collections.find((entry)=>entry.slug === collection);
194
- const puck = options.puck?.enabled !== false && puckCollections(options).some((entry)=>entry.slug === collection);
195
200
  if (block && (block.appliesTo ? block.appliesTo(doc) : true)) return 'blocks';
196
- return puck ? 'puck' : 'page';
201
+ return hasPuckEditor(options, collection) ? 'puck' : 'page';
202
+ }
203
+ export function hasPuckEditor(options, collection) {
204
+ return enabledPuckCollections(options).some((entry)=>entry.slug === collection);
205
+ }
206
+ export function blockPageSlugs(options) {
207
+ return [
208
+ ...new Set([
209
+ ...enabledPuckCollections(options),
210
+ ...options.blocks?.collections ?? []
211
+ ].map((entry)=>entry.slug))
212
+ ];
197
213
  }