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

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 (294) hide show
  1. package/README.md +12 -12
  2. package/dist/admin/blocks/BlockPanel.js +6 -4
  3. package/dist/admin/blocks/inject.js +1 -0
  4. package/dist/admin/blocks/model.d.ts +3 -2
  5. package/dist/admin/blocks/model.js +9 -5
  6. package/dist/admin/copy/blocks.d.ts +3 -2
  7. package/dist/admin/copy/blocks.js +8 -7
  8. package/dist/admin/surface/ResultsRoute.js +18 -11
  9. package/dist/admin/surface/TestsHome.d.ts +2 -1
  10. package/dist/admin/surface/TestsHome.js +131 -44
  11. package/dist/admin/surface/TestsSurface.js +3 -0
  12. package/dist/admin/surface/home.model.d.ts +2 -0
  13. package/dist/admin/surface/newTest/PageWizard.js +9 -2
  14. package/dist/admin/surface/newTest/newTest.css +1 -1
  15. package/dist/admin/surface/results/ResultsHeader.js +11 -6
  16. package/dist/admin/surface/test/TestPage.js +3 -3
  17. package/dist/admin/views/TestsSurfaceClient.d.ts +3 -0
  18. package/dist/admin/views/TestsSurfaceClient.js +11 -0
  19. package/dist/admin/views/buildSurfaceProps.js +10 -3
  20. package/dist/blocks/bindings.js +3 -2
  21. package/dist/blocks/formState.js +1 -1
  22. package/dist/blocks/placementLanguages.d.ts +7 -0
  23. package/dist/blocks/placementLanguages.js +27 -0
  24. package/dist/blocks/placementLocale.d.ts +21 -7
  25. package/dist/blocks/placementLocale.js +218 -67
  26. package/dist/collections/experiments/config.js +8 -3
  27. package/dist/collections/experiments/deleteGuard.js +2 -2
  28. package/dist/collections/experiments/lockHook.js +21 -2
  29. package/dist/collections/experiments/pickSlug.js +2 -0
  30. package/dist/collections/metricsGuards.js +2 -0
  31. package/dist/collections/serialize.js +5 -4
  32. package/dist/constants.d.ts +1 -0
  33. package/dist/constants.js +1 -0
  34. package/dist/db/adapter.d.ts +9 -1
  35. package/dist/db/adapter.js +77 -1
  36. package/dist/db/appends.d.ts +13 -0
  37. package/dist/db/appends.js +49 -0
  38. package/dist/db/bulkPlacementRemoval.js +8 -4
  39. package/dist/db/delete.d.ts +1 -1
  40. package/dist/db/delete.js +2 -4
  41. package/dist/db/events.d.ts +9 -0
  42. package/dist/db/events.js +42 -8
  43. package/dist/db/executor.d.ts +7 -1
  44. package/dist/db/executor.js +7 -3
  45. package/dist/db/results.d.ts +5 -1
  46. package/dist/db/results.js +21 -5
  47. package/dist/db/snapshots.d.ts +1 -0
  48. package/dist/endpoints/contentLocale.d.ts +6 -0
  49. package/dist/endpoints/contentLocale.js +15 -0
  50. package/dist/endpoints/deleteImpact.d.ts +6 -0
  51. package/dist/endpoints/deleteImpact.js +207 -0
  52. package/dist/endpoints/events.js +103 -39
  53. package/dist/endpoints/index.js +9 -8
  54. package/dist/endpoints/pages.js +7 -3
  55. package/dist/endpoints/placementStatus.js +13 -5
  56. package/dist/endpoints/preflight.d.ts +1 -1
  57. package/dist/endpoints/preflight.js +17 -2
  58. package/dist/endpoints/results.d.ts +1 -1
  59. package/dist/endpoints/results.js +6 -2
  60. package/dist/endpoints/routeId.d.ts +2 -2
  61. package/dist/endpoints/routeId.js +11 -5
  62. package/dist/endpoints/summary.js +46 -12
  63. package/dist/endpoints/transitions.js +37 -24
  64. package/dist/errors.d.ts +4 -0
  65. package/dist/errors.js +6 -0
  66. package/dist/events/request.d.ts +6 -2
  67. package/dist/events/request.js +35 -8
  68. package/dist/events/rows.d.ts +1 -1
  69. package/dist/events/rows.js +24 -8
  70. package/dist/events/writable.d.ts +9 -0
  71. package/dist/events/writable.js +13 -0
  72. package/dist/exports/adminClient.d.ts +1 -1
  73. package/dist/exports/adminClient.js +1 -1
  74. package/dist/exports/index.d.ts +1 -1
  75. package/dist/exports/rsc.d.ts +1 -0
  76. package/dist/exports/rsc.js +1 -0
  77. package/dist/goals/fairness.js +38 -31
  78. package/dist/hooks/blockRemovalRule.d.ts +2 -2
  79. package/dist/hooks/blockRemovalRule.js +16 -14
  80. package/dist/hooks/hostHook.js +6 -2
  81. package/dist/hooks/pageGuard.d.ts +3 -0
  82. package/dist/hooks/pageGuard.js +37 -23
  83. package/dist/hooks/puckNestedTests.d.ts +8 -0
  84. package/dist/hooks/puckNestedTests.js +36 -0
  85. package/dist/lib/fetchAllDocs.d.ts +1 -1
  86. package/dist/lib/placementPages.d.ts +2 -1
  87. package/dist/lib/placementPages.js +10 -2
  88. package/dist/manifest/compile.d.ts +2 -1
  89. package/dist/manifest/compile.js +13 -6
  90. package/dist/onInit.js +14 -0
  91. package/dist/options.js +5 -0
  92. package/dist/proxy/pageNavigation.d.ts +4 -0
  93. package/dist/proxy/pageNavigation.js +28 -0
  94. package/dist/proxy/resolve.js +52 -25
  95. package/dist/puck/ExperimentPicker.js +40 -37
  96. package/dist/puck/editor/ConfigureTestDrawer.d.ts +8 -4
  97. package/dist/puck/editor/ConfigureTestDrawer.js +5 -2
  98. package/dist/puck/editor/ExperimentSlotEditor.js +313 -158
  99. package/dist/puck/editor/LeftoverVersions.d.ts +1 -1
  100. package/dist/puck/editor/LeftoverVersions.js +40 -43
  101. package/dist/puck/editor/QuickTestActions.d.ts +5 -2
  102. package/dist/puck/editor/QuickTestActions.js +16 -4
  103. package/dist/puck/editor/ResultsReadout.d.ts +2 -1
  104. package/dist/puck/editor/ResultsReadout.js +2 -1
  105. package/dist/puck/editor/VersionBuilder.d.ts +31 -3
  106. package/dist/puck/editor/VersionBuilder.js +336 -74
  107. package/dist/puck/editor/armWrites.js +1 -1
  108. package/dist/puck/editor/armsCache.js +1 -3
  109. package/dist/puck/editor/blockClipboard.d.ts +16 -0
  110. package/dist/puck/editor/blockClipboard.js +20 -0
  111. package/dist/puck/editor/copy.d.ts +12 -2
  112. package/dist/puck/editor/copy.js +13 -2
  113. package/dist/puck/editor/editor.chrome.css +118 -3
  114. package/dist/puck/editor/editor.css +131 -8
  115. package/dist/puck/editor/editor.model.d.ts +3 -1
  116. package/dist/puck/editor/editor.model.js +2 -2
  117. package/dist/puck/editor/localPlacements.d.ts +1 -0
  118. package/dist/puck/editor/localPlacements.js +12 -0
  119. package/dist/puck/editor/placementsCache.d.ts +22 -12
  120. package/dist/puck/editor/placementsCache.js +62 -49
  121. package/dist/puck/editor/usePageSaveReadiness.d.ts +9 -0
  122. package/dist/puck/editor/usePageSaveReadiness.js +34 -0
  123. package/dist/puck/editor/usePlacementNotice.d.ts +2 -2
  124. package/dist/puck/editor/usePlacementNotice.js +6 -4
  125. package/dist/puck/experimentSlug.d.ts +2 -0
  126. package/dist/puck/experimentSlug.js +3 -0
  127. package/dist/puck/nestedTestCopy.d.ts +8 -0
  128. package/dist/puck/nestedTestCopy.js +22 -0
  129. package/dist/puck/nestedTests.d.ts +17 -0
  130. package/dist/puck/nestedTests.js +30 -0
  131. package/dist/puck/slotConfig.d.ts +1 -1
  132. package/dist/puck/slotConfig.js +17 -4
  133. package/dist/puck/visibility.d.ts +2 -3
  134. package/dist/puck/visibility.js +11 -7
  135. package/dist/results/aggregate.d.ts +6 -3
  136. package/dist/results/aggregate.js +9 -9
  137. package/dist/results/health.d.ts +8 -0
  138. package/dist/results/health.js +28 -0
  139. package/dist/results/identityCredit.d.ts +1 -0
  140. package/dist/results/identityCredit.js +4 -1
  141. package/dist/results/verdict.js +2 -1
  142. package/dist/runtime/cookie.d.ts +10 -2
  143. package/dist/runtime/cookie.js +38 -6
  144. package/dist/runtime/cookieOptions.d.ts +6 -0
  145. package/dist/runtime/cookieOptions.js +14 -0
  146. package/dist/runtime/proxyRuntime.d.ts +1 -0
  147. package/dist/runtime/proxyRuntime.js +18 -8
  148. package/dist/runtime/signing.d.ts +1 -0
  149. package/dist/runtime/signing.js +5 -0
  150. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  151. package/dist/sanitizeReadinessDetail.js +20 -2
  152. package/dist/server/getAssignments.js +11 -10
  153. package/dist/server/recordContentChange.d.ts +1 -1
  154. package/dist/server/recordContentChange.js +45 -21
  155. package/dist/server/resolveExperimentBlocks.js +2 -4
  156. package/dist/server/resolveExperimentData.js +4 -7
  157. package/dist/server/runResults.js +52 -14
  158. package/dist/server/startExperiment.d.ts +20 -0
  159. package/dist/server/startExperiment.js +70 -0
  160. package/dist/server/trackConversion.js +10 -13
  161. package/dist/testSurface/PreviewLinks.js +6 -2
  162. package/dist/testSurface/actions/DecideDialog.d.ts +4 -1
  163. package/dist/testSurface/actions/DecideDialog.js +32 -14
  164. package/dist/testSurface/actions/MakeContentResult.d.ts +4 -3
  165. package/dist/testSurface/actions/MakeContentResult.js +9 -1
  166. package/dist/testSurface/api.d.ts +11 -8
  167. package/dist/testSurface/api.js +27 -11
  168. package/dist/testSurface/contentLocaleURL.d.ts +2 -0
  169. package/dist/testSurface/contentLocaleURL.js +3 -0
  170. package/dist/testSurface/copy/actions.d.ts +1 -0
  171. package/dist/testSurface/copy/actions.js +1 -0
  172. package/dist/testSurface/copy/common.d.ts +6 -0
  173. package/dist/testSurface/copy/common.js +11 -5
  174. package/dist/testSurface/copy/languages.d.ts +12 -0
  175. package/dist/testSurface/copy/languages.js +8 -0
  176. package/dist/testSurface/copy/metrics.d.ts +1 -0
  177. package/dist/testSurface/copy/metrics.js +1 -0
  178. package/dist/testSurface/copy/readiness.d.ts +13 -2
  179. package/dist/testSurface/copy/readiness.js +19 -2
  180. package/dist/testSurface/copy/results.d.ts +5 -2
  181. package/dist/testSurface/copy/results.js +5 -2
  182. package/dist/testSurface/copy/testPage.d.ts +40 -1
  183. package/dist/testSurface/copy/testPage.js +53 -1
  184. package/dist/testSurface/placementLabel.d.ts +8 -0
  185. package/dist/testSurface/placementLabel.js +24 -0
  186. package/dist/testSurface/placements/placementLabels.d.ts +2 -0
  187. package/dist/testSurface/placements/placementLabels.js +2 -1
  188. package/dist/testSurface/readPreflight.d.ts +5 -0
  189. package/dist/testSurface/readPreflight.js +7 -0
  190. package/dist/testSurface/readinessRead.d.ts +3 -0
  191. package/dist/testSurface/readinessRead.js +4 -0
  192. package/dist/testSurface/results/VerdictHero.d.ts +2 -1
  193. package/dist/testSurface/results/VerdictHero.js +5 -1
  194. package/dist/testSurface/results/results.css +1 -1
  195. package/dist/testSurface/results/results.model.d.ts +1 -1
  196. package/dist/testSurface/results/results.model.js +6 -2
  197. package/dist/testSurface/surface/contracts.d.ts +10 -1
  198. package/dist/testSurface/surface/editorPlacement.d.ts +7 -2
  199. package/dist/testSurface/surface/editorPlacement.js +19 -1
  200. package/dist/testSurface/surface/pageBlock/pageBlock.model.js +4 -3
  201. package/dist/testSurface/surface/pageBlock/parts.js +24 -6
  202. package/dist/testSurface/surface/pagePicker/PageCombobox.js +20 -6
  203. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +4 -2
  204. package/dist/testSurface/surface/readiness/ActionDialogs.js +39 -34
  205. package/dist/testSurface/surface/readiness/Banner.js +23 -12
  206. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +4 -3
  207. package/dist/testSurface/surface/readiness/SaveStatus.js +15 -15
  208. package/dist/testSurface/surface/readiness/readiness.model.d.ts +6 -1
  209. package/dist/testSurface/surface/readiness/readiness.model.js +116 -12
  210. package/dist/testSurface/surface/readiness/useTransition.d.ts +4 -4
  211. package/dist/testSurface/surface/readiness/useTransition.js +12 -10
  212. package/dist/testSurface/surface/results/ReleasePages.d.ts +4 -2
  213. package/dist/testSurface/surface/results/ReleasePages.js +5 -4
  214. package/dist/testSurface/surface/results/ResultsBody.d.ts +4 -2
  215. package/dist/testSurface/surface/results/ResultsBody.js +86 -43
  216. package/dist/testSurface/surface/results/useResults.d.ts +11 -7
  217. package/dist/testSurface/surface/results/useResults.js +3 -2
  218. package/dist/testSurface/surface/setting/parts.js +58 -18
  219. package/dist/testSurface/surface/test/AdvancedSection.js +1 -0
  220. package/dist/testSurface/surface/test/DeleteTest.d.ts +19 -0
  221. package/dist/testSurface/surface/test/DeleteTest.js +262 -0
  222. package/dist/testSurface/surface/test/GoalSection.js +7 -3
  223. package/dist/testSurface/surface/test/LengthSection.js +3 -0
  224. package/dist/testSurface/surface/test/PageHoldout.js +4 -1
  225. package/dist/testSurface/surface/test/ReadinessBar.js +1 -1
  226. package/dist/testSurface/surface/test/TargetingSection.js +77 -12
  227. package/dist/testSurface/surface/test/TestSurface.js +97 -15
  228. package/dist/testSurface/surface/test/VersionsSection.js +56 -29
  229. package/dist/testSurface/surface/test/fields.d.ts +29 -4
  230. package/dist/testSurface/surface/test/fields.js +159 -39
  231. package/dist/testSurface/surface/test/pageParts.js +14 -5
  232. package/dist/testSurface/surface/test/testPage.model.d.ts +1 -0
  233. package/dist/testSurface/surface/test/testPage.model.js +6 -0
  234. package/dist/testSurface/surface/testDocument.model.d.ts +3 -0
  235. package/dist/testSurface/surface/testDocument.model.js +4 -1
  236. package/dist/testSurface/surface/useTestDocument.d.ts +23 -4
  237. package/dist/testSurface/surface/useTestDocument.js +425 -162
  238. package/dist/testSurface/useApi.d.ts +9 -6
  239. package/dist/testSurface/useOnTestReturn.d.ts +2 -0
  240. package/dist/testSurface/useOnTestReturn.js +27 -0
  241. package/dist/testSurface/useReadinessPolling.js +3 -1
  242. package/dist/transitions/addMetric.d.ts +1 -4
  243. package/dist/transitions/allocate.d.ts +2 -2
  244. package/dist/transitions/allocate.js +3 -1
  245. package/dist/transitions/archive.d.ts +1 -1
  246. package/dist/transitions/archive.js +3 -2
  247. package/dist/transitions/checkStart.d.ts +5 -1
  248. package/dist/transitions/checkStart.js +130 -16
  249. package/dist/transitions/contentFields.js +9 -5
  250. package/dist/transitions/decide.d.ts +1 -1
  251. package/dist/transitions/decide.js +5 -3
  252. package/dist/transitions/deleteExperiment.d.ts +2 -2
  253. package/dist/transitions/deleteExperiment.js +17 -7
  254. package/dist/transitions/kernel.d.ts +2 -0
  255. package/dist/transitions/kernel.js +9 -4
  256. package/dist/transitions/makeContent.d.ts +2 -1
  257. package/dist/transitions/makeContent.js +17 -12
  258. package/dist/transitions/nestedPlacementNames.d.ts +5 -0
  259. package/dist/transitions/nestedPlacementNames.js +32 -0
  260. package/dist/transitions/pageVersions.js +3 -1
  261. package/dist/transitions/phaseRecord.d.ts +2 -0
  262. package/dist/transitions/phaseRecord.js +5 -0
  263. package/dist/transitions/placementInteractions.d.ts +3 -3
  264. package/dist/transitions/placementInteractions.js +15 -11
  265. package/dist/transitions/placements.d.ts +28 -1
  266. package/dist/transitions/placements.js +223 -60
  267. package/dist/transitions/preflightData.d.ts +5 -3
  268. package/dist/transitions/preflightData.js +126 -37
  269. package/dist/transitions/releaseHoldout.d.ts +2 -1
  270. package/dist/transitions/releaseHoldout.js +3 -1
  271. package/dist/transitions/releasePages.d.ts +2 -1
  272. package/dist/transitions/releasePages.js +3 -1
  273. package/dist/transitions/resolveCaps.d.ts +2 -4
  274. package/dist/transitions/start.d.ts +6 -8
  275. package/dist/transitions/start.js +70 -34
  276. package/dist/transitions/startReads.d.ts +7 -0
  277. package/dist/transitions/startReads.js +28 -0
  278. package/dist/transitions/stop.d.ts +2 -1
  279. package/dist/transitions/stop.js +3 -2
  280. package/dist/types/contracts.d.ts +6 -3
  281. package/dist/types/endpoints.d.ts +86 -9
  282. package/dist/types/endpoints.js +1 -1
  283. package/dist/types/runtime.d.ts +15 -9
  284. package/dist/types/snapshot.d.ts +2 -0
  285. package/dist/types/surface.d.ts +2 -0
  286. package/dist/ui/Button.js +2 -2
  287. package/dist/ui/ChipsInput.d.ts +8 -1
  288. package/dist/ui/ChipsInput.js +17 -4
  289. package/dist/ui/Inputs.d.ts +4 -3
  290. package/dist/ui/Inputs.js +9 -9
  291. package/dist/ui/SelectControl.d.ts +33 -0
  292. package/dist/ui/SelectControl.js +504 -0
  293. package/dist/ui/ui.css +13 -5
  294. package/package.json +3 -2
@@ -1,6 +1,6 @@
1
1
  import { asymmetricGoal, goalContent, goalPlacementDetail, LEGACY_FAIRNESS } from '../goals/fairness.js';
2
2
  import { XpAnalysisError } from '../errors.js';
3
- import { canonicalHealth, mergePageHealth } from '../results/health.js';
3
+ import { canonicalHealth, mergePageHealth, rapidBrowserEvents } from '../results/health.js';
4
4
  import { safeError } from '../log.js';
5
5
  import { createLocalReq } from 'payload';
6
6
  import { resultsCandidates, resultsExecutor, writeSnapshots } from '../db/snapshots.js';
@@ -11,6 +11,14 @@ import { analysePhase } from '../results/analyse.js';
11
11
  import { firstExposures, perUnitValues, timestampMs } from '../results/aggregate.js';
12
12
  import { rolloutAnalysisUnits } from '../results/rolloutUnits.js';
13
13
  import { creditUserEvents, eligibleIdentityLinks } from '../results/identityCredit.js';
14
+ function* convertingUnits(units, values, ages) {
15
+ for (const [id, value] of values){
16
+ if (value > 0) yield {
17
+ arm: units.get(id).arm,
18
+ unitAgeMs: ages.get(id)?.unitAgeMs
19
+ };
20
+ }
21
+ }
14
22
  async function analyseCandidate(exec, candidate, options, now, deadline, unavailableMetrics, logger) {
15
23
  const { phase } = candidate;
16
24
  // Rollout assignment preserves the original test ranges, but its SRM compares
@@ -53,6 +61,10 @@ async function analyseCandidate(exec, candidate, options, now, deadline, unavail
53
61
  ...units
54
62
  ].filter(([id])=>eligible.has(id)));
55
63
  }
64
+ const comparedArms = new Set(analysisPhase.arms.filter((arm)=>phase.phaseKind === 'rollout' || arm.kind !== 'holdout').map((arm)=>arm.key));
65
+ // An age on an exposure is only written by browser ingestion, including
66
+ // browser-side manual exposures. Server-recorded exposures have unknown age.
67
+ let rapidActivity = rapidBrowserEvents(comparedArms, units.values());
56
68
  const ids = [
57
69
  ...units.keys()
58
70
  ];
@@ -93,9 +105,8 @@ async function analyseCandidate(exec, candidate, options, now, deadline, unavail
93
105
  // browser even if an earlier linked browser saw another arm or is ineligible.
94
106
  const direct = userKeyed ? [] : events.filter((event)=>units.has(event.unitId) || event.userId == null || !linked.has(event.userId));
95
107
  const userEvents = events.filter((event)=>userKeyed || !units.has(event.unitId) && event.userId != null && linked.has(event.userId)).map((event)=>({
96
- userId: String(event.userId ?? event.unitId),
97
- value: event.value,
98
- ts: event.ts
108
+ ...event,
109
+ userId: String(event.userId ?? event.unitId)
99
110
  }));
100
111
  const credited = creditUserEvents(units, identities, userEvents, (userId)=>identityConflicts.add(userId)).events;
101
112
  for (const event of direct)if (event.userId != null && linked.has(event.userId)) {
@@ -121,8 +132,10 @@ async function analyseCandidate(exec, candidate, options, now, deadline, unavail
121
132
  ...units.values()
122
133
  ].reduce((earliest, unit)=>Math.min(earliest, +unit.firstTs), timestampMs(phase.startedAt)));
123
134
  const preFrom = new Date(+from - 14 * 86_400_000);
135
+ const storedEvents = definition.source.startsWith('events:') || definition.source.startsWith('click:');
136
+ const readAge = storedEvents && definition.role === 'primary' && !rapidActivity;
124
137
  let events, covariates;
125
- if (definition.source.startsWith('events:') || definition.source.startsWith('click:')) {
138
+ if (storedEvents) {
126
139
  const eventName = definition.source.startsWith('click:') ? definition.source : definition.source.slice(7);
127
140
  if (!definition.source.startsWith('click:') && !options.eventSources?.some((source)=>source.name === eventName)) throw new XpAnalysisError('source-unavailable');
128
141
  const read = async (start)=>{
@@ -130,19 +143,24 @@ async function analyseCandidate(exec, candidate, options, now, deadline, unavail
130
143
  eventName,
131
144
  userIds: ids,
132
145
  from: start,
133
- to
146
+ to,
147
+ readAge
134
148
  });
135
149
  const direct = await metricEventRows(exec, {
136
150
  eventName,
137
151
  unitIds: ids,
138
152
  from: start,
139
- to
153
+ to,
154
+ readAge,
155
+ forVisitors: true
140
156
  });
141
157
  const signedIn = await metricEventRows(exec, {
142
158
  eventName,
143
159
  userIds,
144
160
  from: start,
145
- to
161
+ to,
162
+ readAge,
163
+ forVisitors: true
146
164
  });
147
165
  // The two lookups overlap when a linked user's own browser was exposed.
148
166
  return [
@@ -226,13 +244,26 @@ async function analyseCandidate(exec, candidate, options, now, deadline, unavail
226
244
  // The click-goal delta supersedes whole-phase attribution for mid-test adds.
227
245
  // Retain pre-period events for CUPED above; exclude them from the outcome.
228
246
  const outcomeEvents = definition.source.startsWith('click:') && definition.addedAt ? events.filter((event)=>timestampMs(event.ts) >= timestampMs(definition.addedAt)) : events;
247
+ const ages = new Map();
248
+ const values = perUnitValues(units, outcomeEvents, {
249
+ kind,
250
+ windowHours,
251
+ endedAt: to,
252
+ onAttributed: readAge ? (event, ts)=>{
253
+ if (event.unitAgeMs === undefined) return;
254
+ const previous = ages.get(event.unitId);
255
+ if (!previous || ts < previous.ts || ts === previous.ts && event.unitAgeMs > previous.unitAgeMs) {
256
+ ages.set(event.unitId, {
257
+ ts,
258
+ unitAgeMs: event.unitAgeMs
259
+ });
260
+ }
261
+ } : undefined
262
+ });
263
+ if (ages.size) rapidActivity = rapidBrowserEvents(comparedArms, convertingUnits(units, values, ages));
229
264
  metricData.push({
230
265
  metricId: definition.metricId,
231
- values: perUnitValues(units, outcomeEvents, {
232
- kind,
233
- windowHours,
234
- endedAt: to
235
- }),
266
+ values,
236
267
  ...covariates ? {
237
268
  covariates
238
269
  } : {}
@@ -287,6 +318,11 @@ async function analyseCandidate(exec, candidate, options, now, deadline, unavail
287
318
  winnerArm: phase.arms.find((arm)=>arm.kind !== 'holdout').key
288
319
  } : {}
289
320
  });
321
+ if (rapidActivity) snapshot.health = [
322
+ {
323
+ code: 'rapid-browser-events'
324
+ }
325
+ ];
290
326
  return snapshot;
291
327
  }
292
328
  export async function runResults(payload, { budgetMs = 20_000, experimentId, sweep = true } = {}) {
@@ -407,10 +443,12 @@ export async function runResults(payload, { budgetMs = 20_000, experimentId, swe
407
443
  for (const [index, snapshot] of snapshots.entries()){
408
444
  const previous = phases[index].previousHealth ?? phases[index].frozenSnapshot?.health ?? [];
409
445
  const unjudged = previous.filter((row)=>row.code === 'goal-in-some-versions' && content && content.unchecked.length > 0 && clicks.some((metric)=>metric.metricId === row.metricId && !asymmetricGoal(content, metric.source, arms)));
446
+ const activity = snapshot.health?.filter((row)=>row.code === 'rapid-browser-events') ?? [];
410
447
  snapshot.health = mergePageHealth(unjudged, [
411
448
  ...health,
412
449
  ...goals,
413
- ...unchecked
450
+ ...unchecked,
451
+ ...activity
414
452
  ]);
415
453
  if (content?.skipped && current.kind === 'block') snapshot.goalFairnessNotice = LEGACY_FAIRNESS;
416
454
  else delete snapshot.goalFairnessNotice;
@@ -0,0 +1,20 @@
1
+ import { type Payload, type PayloadRequest } from 'payload';
2
+ import type { DocId } from '../types/contracts.js';
3
+ import type { StartExperimentResult } from '../types/endpoints.js';
4
+ /** Start a test from trusted host code. Call this after your own transaction commits.
5
+ * Pass the caller's Payload request if available so an open transaction can be refused.
6
+ * Without it, Start can hang waiting for a lock your transaction already holds.
7
+ * If a thrown error has code `commit-unverified`, read the test's status before retrying.
8
+ * Start may have committed even though it could not verify the commit.
9
+ */
10
+ export declare function startExperiment(payload: Payload, { experiment, req, onlyIfNeverStarted }: {
11
+ experiment: {
12
+ id: DocId;
13
+ } | {
14
+ slug: string;
15
+ };
16
+ /** Pass the caller's request, if available, to detect an open transaction. */
17
+ req?: Pick<PayloadRequest, 'transactionID'>;
18
+ /** Require a draft with no prior round. By default, a stopped test can start a new round. */
19
+ onlyIfNeverStarted?: boolean;
20
+ }): Promise<StartExperimentResult>;
@@ -0,0 +1,70 @@
1
+ import { createLocalReq } from 'payload';
2
+ import { experimentId } from '../endpoints/routeId.js';
3
+ import { XpRefusal, XpStartTransactionOpen } from '../errors.js';
4
+ import { xpOptionsFromReq } from '../options/fromReq.js';
5
+ import { start } from '../transitions/start.js';
6
+ import { findStartDocuments } from '../transitions/startReads.js';
7
+ /** Start a test from trusted host code. Call this after your own transaction commits.
8
+ * Pass the caller's Payload request if available so an open transaction can be refused.
9
+ * Without it, Start can hang waiting for a lock your transaction already holds.
10
+ * If a thrown error has code `commit-unverified`, read the test's status before retrying.
11
+ * Start may have committed even though it could not verify the commit.
12
+ */ export async function startExperiment(payload, { experiment, req, onlyIfNeverStarted }) {
13
+ try {
14
+ if (req?.transactionID != null) throw new XpStartTransactionOpen();
15
+ const systemReq = await createLocalReq({}, payload);
16
+ const options = xpOptionsFromReq(systemReq);
17
+ const id = 'id' in experiment ? experimentId(systemReq, experiment.id) : (await findStartDocuments(systemReq, {
18
+ collection: 'xp-experiments',
19
+ depth: 0,
20
+ limit: 1,
21
+ where: {
22
+ slug: {
23
+ equals: experiment.slug
24
+ }
25
+ }
26
+ }, true)).docs[0]?.id;
27
+ if (id === undefined) return {
28
+ status: 'not-found'
29
+ };
30
+ const { doc, revision, detail } = await start(systemReq, {
31
+ experimentId: id,
32
+ options,
33
+ system: true,
34
+ onlyIfNeverStarted
35
+ });
36
+ return {
37
+ status: 'started',
38
+ phase: doc.phase,
39
+ revision,
40
+ warnings: detail ?? []
41
+ };
42
+ } catch (error) {
43
+ if (error instanceof XpStartTransactionOpen) return {
44
+ status: 'refused',
45
+ code: 'transaction-open',
46
+ message: error.message
47
+ };
48
+ if (!(error instanceof XpRefusal) || error.status === 500 || error.code === 'commit-unverified') throw error;
49
+ if (error.code === 'not-found') return {
50
+ status: 'not-found'
51
+ };
52
+ const { code, message, detail } = error;
53
+ if (code === 'first-start-only') {
54
+ return {
55
+ status: 'refused',
56
+ code,
57
+ message,
58
+ detail: detail
59
+ };
60
+ }
61
+ return {
62
+ status: 'refused',
63
+ code,
64
+ message,
65
+ ...detail === undefined ? {} : {
66
+ detail
67
+ }
68
+ };
69
+ }
70
+ }
@@ -1,7 +1,7 @@
1
1
  import { safeError } from '../log.js';
2
2
  import { NextRequest } from 'next/server.js';
3
3
  import { pooledExecutor } from '../db/executor.js';
4
- import { insertEvents } from '../db/events.js';
4
+ import { insertServerConversion } from '../db/events.js';
5
5
  import { readUnitCookie } from '../runtime/cookie.js';
6
6
  export async function trackConversion(serverRuntime, event) {
7
7
  let payload;
@@ -46,18 +46,15 @@ export async function trackConversion(serverRuntime, event) {
46
46
  }
47
47
  }
48
48
  if (!visitorId && !userId) return;
49
- await insertEvents(pooledExecutor(payload), [
50
- {
51
- type: 'conversion',
52
- eventName: event.eventName,
53
- value: event.value ?? 1,
54
- unitId: visitorId ?? userId,
55
- unitType: visitorId ? 'visitor' : 'user',
56
- userId,
57
- dedupeKey: `conversion:s:${event.idempotencyKey}`,
58
- ts: new Date().toISOString()
59
- }
60
- ], (message)=>payload.logger.error(message));
49
+ await insertServerConversion(pooledExecutor(payload), {
50
+ eventName: event.eventName,
51
+ value: event.value ?? 1,
52
+ unitId: visitorId ?? userId,
53
+ unitType: visitorId ? 'visitor' : 'user',
54
+ userId,
55
+ idempotencyKey: event.idempotencyKey,
56
+ ts: new Date().toISOString()
57
+ }, (message)=>payload.logger.error(message));
61
58
  } catch (error) {
62
59
  try {
63
60
  payload?.logger.error({
@@ -5,6 +5,7 @@ import { Button } from '../ui/Button.js';
5
5
  import { armLabel } from './labels.js';
6
6
  import { useApi } from './useApi.js';
7
7
  import { REVIEW_COPY as C } from './copy/review.js';
8
+ import { placementLabel } from './placementLabel.js';
8
9
  import { TEST_PAGE } from './copy/testPage.js';
9
10
  import { API_MESSAGES, refusalMessage } from './copy/common.js';
10
11
  import { actionablePreviewPages } from './previewLinks.model.js';
@@ -55,15 +56,16 @@ export function PreviewLinks({ experimentId, placements, arms, flagPoint, apiRou
55
56
  setBusy(false);
56
57
  }
57
58
  }
59
+ const pages = actionablePreviewPages(placements, flagPoint);
58
60
  return /*#__PURE__*/ _jsxs("div", {
59
61
  className: "xp-preview-links",
60
62
  children: [
61
- actionablePreviewPages(placements, flagPoint).map((placement)=>/*#__PURE__*/ _jsxs("div", {
63
+ pages.map((placement)=>/*#__PURE__*/ _jsxs("div", {
62
64
  className: "xp-preview-row",
63
65
  children: [
64
66
  /*#__PURE__*/ _jsxs("p", {
65
67
  children: [
66
- placement.title,
68
+ placementLabel(placement),
67
69
  placement.slotCount > 1 ? ` ${C.placedTimes(placement.slotCount)}` : null
68
70
  ]
69
71
  }),
@@ -73,6 +75,7 @@ export function PreviewLinks({ experimentId, placements, arms, flagPoint, apiRou
73
75
  placement.url ? arms.filter((arm)=>arm.kind !== 'holdout' && arm.key !== 'holdout').map((arm)=>/*#__PURE__*/ _jsxs(Button, {
74
76
  variant: "secondary",
75
77
  size: "sm",
78
+ "aria-label": pages.length > 1 ? `${C.preview} ${arm.label?.trim() || armLabel(arm.key)}: ${placementLabel(placement)}` : undefined,
76
79
  disabled: busy,
77
80
  onClick: ()=>{
78
81
  void preview(placement.url, arm.key);
@@ -87,6 +90,7 @@ export function PreviewLinks({ experimentId, placements, arms, flagPoint, apiRou
87
90
  variant: "link",
88
91
  size: "sm",
89
92
  href: placement.editorUrl,
93
+ "aria-label": pages.length > 1 ? `${TEST_PAGE.editOnPage}: ${placementLabel(placement)}` : undefined,
90
94
  children: TEST_PAGE.editOnPage
91
95
  }) : null
92
96
  ]
@@ -1,8 +1,11 @@
1
1
  import type { DocId } from '../../types/contracts.js';
2
2
  import type { PreflightResult } from '../../types/endpoints.js';
3
3
  import type { ActionGroup } from './actions.model.js';
4
- export declare function DecideDialog({ id, arms, checks, onClose, apiRoute, onSuccess }: {
4
+ export declare function DecideDialog({ id, phase, arms, checks, unavailable, onClose, apiRoute, onSuccess, onRefusal }: {
5
5
  apiRoute: string;
6
+ phase?: number;
7
+ onRefusal?: () => void;
8
+ unavailable?: boolean;
6
9
  onSuccess?: (doc?: Record<string, unknown>) => void;
7
10
  id: DocId;
8
11
  arms: readonly ActionGroup[];
@@ -10,10 +10,11 @@ import { RESULTS_COPY } from '../copy/results.js';
10
10
  import { ACTIONS_COPY as C, decideCopy } from '../copy/actions.js';
11
11
  import { decideState } from './decide.model.js';
12
12
  import { Dialog } from '../../ui/Dialog.js';
13
- export function DecideDialog({ id, arms, checks = [], onClose, apiRoute, onSuccess }) {
13
+ export function DecideDialog({ id, phase, arms, checks = [], unavailable, onClose, apiRoute, onSuccess, onRefusal }) {
14
14
  const api = useApi(apiRoute);
15
15
  const [snapshot, setSnapshot] = useState(null);
16
- const [chosenArm, setChosenArm] = useState(null);
16
+ const [chosen, setChosenArm] = useState();
17
+ const chosenArm = chosen === undefined ? snapshot?.verdict.recommendedArm ?? null : chosen;
17
18
  const [note, setNote] = useState('');
18
19
  const [typed, setTyped] = useState('');
19
20
  const [loading, setLoading] = useState(true);
@@ -22,6 +23,7 @@ export function DecideDialog({ id, arms, checks = [], onClose, apiRoute, onSucce
22
23
  const refreshing = useRef(false);
23
24
  const [error, setError] = useState(null);
24
25
  const [loadFailed, setLoadFailed] = useState(false);
26
+ const statusRefused = error?.code === 'round-changed' || error?.code === 'invalid-status';
25
27
  const state = decideState({
26
28
  snapshot,
27
29
  arms,
@@ -31,12 +33,13 @@ export function DecideDialog({ id, arms, checks = [], onClose, apiRoute, onSucce
31
33
  });
32
34
  useEffect(()=>{
33
35
  let current = true;
34
- void api.results(id).then((result)=>{
36
+ void api.results(id, {
37
+ phase
38
+ }).then((result)=>{
35
39
  if (!current) return;
36
40
  if (result.ok) {
37
41
  const next = result.data?.snapshot ?? null;
38
42
  setSnapshot(next);
39
- setChosenArm(next?.verdict.recommendedArm ?? null);
40
43
  } else {
41
44
  setError(result);
42
45
  setLoadFailed(true);
@@ -48,13 +51,16 @@ export function DecideDialog({ id, arms, checks = [], onClose, apiRoute, onSucce
48
51
  };
49
52
  }, [
50
53
  api,
51
- id
54
+ id,
55
+ phase
52
56
  ]);
53
57
  async function refresh() {
54
58
  if (refreshing.current) return;
55
59
  refreshing.current = true;
56
60
  setLoading(true);
57
- const result = await api.results(id);
61
+ const result = await api.results(id, {
62
+ phase
63
+ });
58
64
  refreshing.current = false;
59
65
  setLoading(false);
60
66
  if (result.ok) {
@@ -67,11 +73,15 @@ export function DecideDialog({ id, arms, checks = [], onClose, apiRoute, onSucce
67
73
  }
68
74
  }
69
75
  async function submit() {
70
- if (inFlight.current || loading || busy || !state.canSubmit || loadFailed) return;
76
+ if (unavailable || statusRefused || inFlight.current || loading || busy || !state.canSubmit || loadFailed) return;
71
77
  inFlight.current = true;
78
+ setChosenArm(chosenArm);
72
79
  setBusy(true);
73
80
  setError(null);
74
- const result = await api.decide(id, state.body);
81
+ const result = await api.decide(id, {
82
+ ...state.body,
83
+ phase
84
+ });
75
85
  if (result.ok) {
76
86
  if (onSuccess) onSuccess(result.data?.doc);
77
87
  else reloadPage();
@@ -79,14 +89,13 @@ export function DecideDialog({ id, arms, checks = [], onClose, apiRoute, onSucce
79
89
  } else {
80
90
  setError(result);
81
91
  if (result.code === 'confirmation-required') {
82
- setTyped('');
83
92
  await refresh();
84
- }
93
+ } else if (result.status === 409 || result.status === 403 || result.status === 401 || result.status === 404 || result.code === 'invalid-status') onRefusal?.();
85
94
  }
86
95
  inFlight.current = false;
87
96
  setBusy(false);
88
97
  }
89
- const enabled = !busy && !loading && !loadFailed && state.canSubmit;
98
+ const enabled = !unavailable && !statusRefused && !busy && !loading && !loadFailed && state.canSubmit;
90
99
  const label = state.options.find((option)=>option.value === chosenArm)?.label;
91
100
  return /*#__PURE__*/ _jsxs(Dialog, {
92
101
  open: true,
@@ -138,7 +147,10 @@ export function DecideDialog({ id, arms, checks = [], onClose, apiRoute, onSucce
138
147
  value: note,
139
148
  required: state.guarded,
140
149
  readOnly: busy,
141
- onChange: (event)=>setNote(event.target.value)
150
+ onChange: (event)=>{
151
+ if (chosenArm !== null) setChosenArm(chosenArm);
152
+ setNote(event.target.value);
153
+ }
142
154
  }),
143
155
  state.guarded && label ? /*#__PURE__*/ _jsxs(_Fragment, {
144
156
  children: [
@@ -156,13 +168,19 @@ export function DecideDialog({ id, arms, checks = [], onClose, apiRoute, onSucce
156
168
  label: C.confirmation,
157
169
  value: typed,
158
170
  readOnly: busy,
159
- onChange: (event)=>setTyped(event.target.value)
171
+ onChange: (event)=>{
172
+ setChosenArm(chosenArm);
173
+ setTyped(event.target.value);
174
+ }
160
175
  })
161
176
  ]
162
177
  }) : null,
163
178
  error ? /*#__PURE__*/ _jsx("p", {
164
179
  role: "alert",
165
180
  children: error.message
181
+ }) : unavailable ? /*#__PURE__*/ _jsx("p", {
182
+ role: "alert",
183
+ children: C.decisionUnavailable
166
184
  }) : null,
167
185
  /*#__PURE__*/ _jsx(Button, {
168
186
  disabled: !enabled,
@@ -171,7 +189,7 @@ export function DecideDialog({ id, arms, checks = [], onClose, apiRoute, onSucce
171
189
  },
172
190
  children: C.decide
173
191
  }),
174
- error?.retryable ? /*#__PURE__*/ _jsx(Button, {
192
+ !unavailable && error?.retryable ? /*#__PURE__*/ _jsx(Button, {
175
193
  disabled: busy || loading || !loadFailed && !state.canSubmit,
176
194
  onClick: ()=>{
177
195
  if (loadFailed) {
@@ -1,6 +1,6 @@
1
1
  import type { DocId } from '../../types/contracts.js';
2
- import type { MakeContentResult as Result } from '../../types/endpoints.js';
3
- import type { createApi } from '../api.js';
2
+ import type { DismissContentEntryResult, MakeContentResult as Result } from '../../types/endpoints.js';
3
+ import type { ApiResult, createApi } from '../api.js';
4
4
  type Props = {
5
5
  result: Result;
6
6
  onRetry: () => void | Promise<void>;
@@ -12,6 +12,7 @@ type Props = {
12
12
  onFinish?: () => void | Promise<void>;
13
13
  onBusyChange?: (busy: boolean) => void;
14
14
  onActionStart?: () => void;
15
+ onDocumentChange?: (result: ApiResult<DismissContentEntryResult>) => void | Promise<void>;
15
16
  };
16
- export declare function MakeContentResult({ result, onRetry, busy, id, api, canManage, isDecided, onFinish, onBusyChange, onActionStart }: Props): import("react").JSX.Element;
17
+ export declare function MakeContentResult({ result, onRetry, busy, id, api, canManage, isDecided, onFinish, onBusyChange, onActionStart, onDocumentChange }: Props): import("react").JSX.Element;
17
18
  export {};
@@ -6,7 +6,7 @@ import { Button } from '../../ui/Button.js';
6
6
  import { Banner } from '../../ui/Banner.js';
7
7
  import { API_MESSAGES } from '../copy/common.js';
8
8
  import { ACTIONS_COPY as C, contentReportCopy } from '../copy/actions.js';
9
- export function MakeContentResult({ result, onRetry, busy = false, id, api, canManage = false, isDecided = false, onFinish, onBusyChange, onActionStart }) {
9
+ export function MakeContentResult({ result, onRetry, busy = false, id, api, canManage = false, isDecided = false, onFinish, onBusyChange, onActionStart, onDocumentChange }) {
10
10
  const inFlight = useRef(false);
11
11
  const container = useRef(null);
12
12
  const focusTarget = useRef(null);
@@ -58,8 +58,16 @@ export function MakeContentResult({ result, onRetry, busy = false, id, api, canM
58
58
  });
59
59
  if (!response.ok) {
60
60
  setError(response.message);
61
+ if ([
62
+ 401,
63
+ 403,
64
+ 404,
65
+ 409,
66
+ 422
67
+ ].includes(response.status)) await onDocumentChange?.(response);
61
68
  return;
62
69
  }
70
+ await onDocumentChange?.(response);
63
71
  const decision = response.data?.doc.decision;
64
72
  const updated = decision?.contentReport?.docs?.find((doc)=>doc.collection === entry.collection && String(doc.id) === String(entry.id));
65
73
  if (!updated) {
@@ -1,5 +1,5 @@
1
1
  import type { DocId } from '../types/contracts.js';
2
- import type { WrapBlockBody, PagesResult, PlacementStatusBody, PlacementStatusResult, RestoreContentEntryBody, RestoreContentEntryResult, DismissContentEntryBody, DismissContentEntryResult, AddMetricBody, AllocateBody, ArchiveBody, DecideBody, MakeContentResult, AddMetricResult, ClickKeysResult, PreflightResult, PreviewTokenResult, RefusalCode, ResultsResponse, SummaryResponse, TransitionSuccess } from '../types/endpoints.js';
2
+ import type { DeleteImpactResult, WrapBlockBody, PagesResult, PlacementStatusBody, PlacementStatusResult, RestoreContentEntryBody, RestoreContentEntryResult, DismissContentEntryBody, DismissContentEntryResult, AddMetricBody, AllocateBody, ArchiveBody, DecideBody, MakeContentResult, AddMetricResult, ClickKeysResult, PreflightResult, PreviewTokenResult, RefusalCode, ResultsResponse, SummaryResponse, TransitionSuccess } from '../types/endpoints.js';
3
3
  import { refusalMessage } from './copy/common.js';
4
4
  export type ApiResult<T> = {
5
5
  ok: true;
@@ -12,14 +12,16 @@ export type ApiResult<T> = {
12
12
  retryable: boolean;
13
13
  };
14
14
  type RequestOptions = NonNullable<Parameters<typeof refusalMessage>[3]>;
15
- export declare function createApi(apiBase: string): {
15
+ export declare function createApi(apiBase: string, contentLocale?: string): {
16
16
  findTestIdBySlug: (slug: string) => Promise<Extract<ApiResult<DocId>, {
17
17
  ok: false;
18
18
  }> | {
19
19
  ok: true;
20
20
  data: DocId;
21
21
  }>;
22
- deleteTest: (id: DocId) => Promise<ApiResult<unknown>>;
22
+ deleteTest: (id: DocId, { draft }?: {
23
+ draft?: boolean;
24
+ }) => Promise<ApiResult<unknown>>;
23
25
  wrapBlock: (body: WrapBlockBody) => Promise<ApiResult<Record<string, unknown>>>;
24
26
  pages: (query: {
25
27
  collection: string;
@@ -28,18 +30,19 @@ export declare function createApi(apiBase: string): {
28
30
  page?: number;
29
31
  }, signal?: AbortSignal) => Promise<ApiResult<PagesResult>>;
30
32
  placementStatus: (body: PlacementStatusBody) => Promise<ApiResult<PlacementStatusResult>>;
31
- start: (id: DocId) => Promise<ApiResult<TransitionSuccess>>;
33
+ start: (id: DocId, phase?: number) => Promise<ApiResult<TransitionSuccess>>;
32
34
  allocate: (id: DocId, body: AllocateBody, options?: RequestOptions) => Promise<ApiResult<TransitionSuccess>>;
33
35
  addMetric: (id: DocId, body: AddMetricBody, options?: RequestOptions) => Promise<ApiResult<AddMetricResult>>;
34
- stop: (id: DocId) => Promise<ApiResult<TransitionSuccess>>;
36
+ stop: (id: DocId, phase?: number) => Promise<ApiResult<TransitionSuccess>>;
35
37
  decide: (id: DocId, body: DecideBody) => Promise<ApiResult<TransitionSuccess>>;
36
- releaseHoldout: (id: DocId) => Promise<ApiResult<TransitionSuccess>>;
37
- releasePages: (id: DocId) => Promise<ApiResult<TransitionSuccess>>;
38
- makeContent: (id: DocId) => Promise<ApiResult<MakeContentResult>>;
38
+ releaseHoldout: (id: DocId, phase?: number) => Promise<ApiResult<TransitionSuccess>>;
39
+ releasePages: (id: DocId, phase?: number) => Promise<ApiResult<TransitionSuccess>>;
40
+ makeContent: (id: DocId, phase?: number) => Promise<ApiResult<MakeContentResult>>;
39
41
  dismissContentEntry: (id: DocId, body: DismissContentEntryBody) => Promise<ApiResult<DismissContentEntryResult>>;
40
42
  restoreContentEntry: (id: DocId, body: RestoreContentEntryBody) => Promise<ApiResult<RestoreContentEntryResult>>;
41
43
  archive: (id: DocId, body: ArchiveBody) => Promise<ApiResult<TransitionSuccess>>;
42
44
  clickKeys: (id: DocId) => Promise<ApiResult<ClickKeysResult>>;
45
+ deleteImpact: (id: DocId, signal?: AbortSignal) => Promise<ApiResult<DeleteImpactResult>>;
43
46
  preflight: (id: DocId) => Promise<ApiResult<PreflightResult>>;
44
47
  previewToken: (id: DocId, arm: string) => Promise<ApiResult<PreviewTokenResult>>;
45
48
  results: (id: DocId, options?: {
@@ -1,6 +1,7 @@
1
+ import { contentLocaleURL } from './contentLocaleURL.js';
1
2
  import { API_MESSAGES, refusalMessage } from './copy/common.js';
2
3
  import { CONTENT_ENTRY_REFUSALS } from './copy/actions.js';
3
- export function createApi(apiBase) {
4
+ export function createApi(apiBase, contentLocale) {
4
5
  const collectionBase = `${apiBase.replace(/\/$/, '')}/xp-experiments`;
5
6
  const base = `${apiBase.replace(/\/$/, '')}/xp/experiments`;
6
7
  const route = (id, action)=>`${base}/${encodeURIComponent(id)}/${action}`;
@@ -83,11 +84,10 @@ export function createApi(apiBase) {
83
84
  data: id
84
85
  };
85
86
  },
86
- deleteTest: (id)=>request(()=>`${collectionBase}/${encodeURIComponent(id)}`, 'DELETE', undefined, {
87
- notFound: API_MESSAGES.testNoLongerDraft,
88
- forbidden: API_MESSAGES.testNoLongerDraft,
87
+ deleteTest: (id, { draft = false } = {})=>request(()=>`${collectionBase}/${encodeURIComponent(id)}`, 'DELETE', undefined, {
88
+ notFound: API_MESSAGES.testAlreadyDeleted,
89
89
  codes: {
90
- 'invalid-status': API_MESSAGES.testNoLongerDraft
90
+ 'invalid-status': draft ? API_MESSAGES.testNoLongerDraft : API_MESSAGES.deleteInvalidStatus
91
91
  }
92
92
  }),
93
93
  wrapBlock: (body)=>request(()=>`${apiBase.replace(/\/$/, '')}/xp/blocks/wrap`, 'POST', body),
@@ -104,19 +104,35 @@ export function createApi(apiBase) {
104
104
  } : {}
105
105
  })}`, 'GET', undefined, undefined, signal),
106
106
  placementStatus: (body)=>request(()=>`${apiBase.replace(/\/$/, '')}/xp/placements/status`, 'POST', body),
107
- start: (id)=>post(id, 'start'),
107
+ start: (id, phase)=>post(id, 'start', phase === undefined ? undefined : {
108
+ phase
109
+ }),
108
110
  allocate: (id, body, options)=>post(id, 'allocate', body, options),
109
111
  addMetric: (id, body, options)=>post(id, 'add-metric', body, options),
110
- stop: (id)=>post(id, 'stop'),
112
+ stop: (id, phase)=>post(id, 'stop', phase === undefined ? undefined : {
113
+ phase
114
+ }),
111
115
  decide: (id, body)=>post(id, 'decide', body),
112
- releaseHoldout: (id)=>post(id, 'release-holdout'),
113
- releasePages: (id)=>post(id, 'release-pages'),
114
- makeContent: (id)=>post(id, 'make-content'),
116
+ releaseHoldout: (id, phase)=>post(id, 'release-holdout', phase === undefined ? undefined : {
117
+ phase
118
+ }),
119
+ releasePages: (id, phase)=>post(id, 'release-pages', phase === undefined ? undefined : {
120
+ phase
121
+ }),
122
+ makeContent: (id, phase)=>post(id, 'make-content', phase === undefined ? undefined : {
123
+ phase
124
+ }),
115
125
  dismissContentEntry: (id, body)=>post(id, 'content-report/dismiss', body, CONTENT_ENTRY_REFUSALS),
116
126
  restoreContentEntry: (id, body)=>post(id, 'content-report/restore', body, CONTENT_ENTRY_REFUSALS),
117
127
  archive: (id, body)=>post(id, 'archive', body),
118
128
  clickKeys: (id)=>request(()=>route(id, 'click-keys'), 'GET'),
119
- preflight: (id)=>request(()=>route(id, 'preflight'), 'GET'),
129
+ deleteImpact: (id, signal)=>request(()=>contentLocaleURL(route(id, 'delete-impact'), contentLocale), 'GET', undefined, {
130
+ codes: {
131
+ 'invalid-status': API_MESSAGES.deleteInvalidStatus
132
+ },
133
+ fallback: API_MESSAGES.deleteImpactUnavailable
134
+ }, signal),
135
+ preflight: (id)=>request(()=>contentLocaleURL(route(id, 'preflight'), contentLocale), 'GET'),
120
136
  previewToken: (id, arm)=>request(()=>`${route(id, 'preview-token')}?arm=${encodeURIComponent(arm)}`, 'GET'),
121
137
  results: (id, options = {})=>request(()=>{
122
138
  const query = new URLSearchParams();
@@ -0,0 +1,2 @@
1
+ /** Only advisory metadata reads carry the content language. */
2
+ export declare const contentLocaleURL: (url: string, contentLocale?: string) => string;
@@ -0,0 +1,3 @@
1
+ /** Only advisory metadata reads carry the content language. */ export const contentLocaleURL = (url, contentLocale)=>`${url}${contentLocale ? `?${new URLSearchParams({
2
+ locale: contentLocale
3
+ })}` : ''}`;
@@ -1,5 +1,6 @@
1
1
  import type { AddMetricWarning } from '../../types/endpoints.js';
2
2
  export declare const ACTIONS_COPY: {
3
+ readonly decisionUnavailable: "This round can no longer be decided here. Copy your note before closing.";
3
4
  readonly start: "Start";
4
5
  readonly restart: "Start a new round";
5
6
  readonly stop: "Stop";
@@ -1,5 +1,6 @@
1
1
  import { asymmetricGoalsCopy, placementUncheckedCopy } from './readiness.js';
2
2
  export const ACTIONS_COPY = {
3
+ decisionUnavailable: 'This round can no longer be decided here. Copy your note before closing.',
3
4
  start: 'Start',
4
5
  restart: 'Start a new round',
5
6
  stop: 'Stop',