@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,20 +1,25 @@
1
+ import { withSlotsFor } from '../arms/model.js';
2
+ import { nestedPlacementNames, nameNestedPlacements } from './nestedPlacementNames.js';
3
+ import { nestedTestCopy } from '../puck/nestedTestCopy.js';
1
4
  import { goalContent } from '../goals/fairness.js';
5
+ import { browserWritableMetric } from '../events/writable.js';
2
6
  import { detached } from './placementInteractions.js';
3
7
  import { lockAndRescanPlacements, placementInteractions } from './placementInteractions.js';
4
8
  import { lockPagePaths } from '../db/locks.js';
5
9
  import { lockMetricsForFreeze } from '../db/metricUsage.js';
6
10
  import { DEFAULT_SEQUENTIAL_TUNING_PARAMETER } from '../constants.js';
7
11
  import { claimSlices } from '../db/slices.js';
8
- import { READINESS_COPY, asymmetricGoalsCopy, sameAddressCopy, interactingTestsCopy, pageInUseCopy, unpublishedPageCopy } from '../testSurface/copy/readiness.js';
12
+ import { READINESS_COPY, asymmetricGoalsCopy, firstStartOnlyCopy, sameAddressCopy, interactingTestsCopy, pageInUseCopy, unpublishedPageCopy } from '../testSurface/copy/readiness.js';
9
13
  import { GROUP_LABELS } from '../testSurface/copy/arms.js';
10
14
  import { XpRefusal } from '../errors.js';
11
15
  import { isOpValid } from '../targeting/ops.js';
12
16
  import { newSeed } from '../runtime/seed.js';
13
17
  import { checkStart, pageTargetPaths, relationshipId } from './checkStart.js';
14
18
  import { withTransition } from './kernel.js';
15
- import { writePhaseRecord } from './phaseRecord.js';
16
- import { loadPageTestsInUse, loadStartInputs, unpublishedPageTargets } from './preflightData.js';
19
+ import { requireCurrentRound, writePhaseRecord } from './phaseRecord.js';
20
+ import { loadPageTestsInUse, loadStartInputsBatch, readStartInputExperiment, unpublishedPageTargets } from './preflightData.js';
17
21
  import { resolveCaps } from './resolveCaps.js';
22
+ import { findStartDocuments, readStartState } from './startReads.js';
18
23
  export async function readExperiment(req, id) {
19
24
  // §7.8: internal lookup serves the authorised transition write. Preserve
20
25
  // admin-only analysis.method/kind for freezing; return access-filtered docs.
@@ -35,6 +40,7 @@ export async function readExperiment(req, id) {
35
40
  }
36
41
  export function refuse(code, detail) {
37
42
  const messages = {
43
+ 'nested-tests': nestedTestCopy.readiness(detail),
38
44
  'goal-in-some-versions': asymmetricGoalsCopy(detail),
39
45
  'placements-changed': "This test's pages changed while it was starting. Try again.",
40
46
  'page-busy': "One of this test's pages is being saved right now. Try again in a moment.",
@@ -79,15 +85,16 @@ export function refuse(code, detail) {
79
85
  ].includes(code);
80
86
  throw new XpRefusal(code, messages[code] ?? 'The experiment is not ready to start.', detail, code === 'entry-not-found' ? 404 : conflict ? 409 : 422);
81
87
  }
82
- export async function updateExperiment(req, id, data) {
83
- // §7.8: access-authorised transition writes locked plugin fields.
84
- await req.payload.update({
88
+ export async function updateExperiment(req, id, data, system = false) {
89
+ // §7.8: an authorized manager transition or trusted system Start writes locked plugin fields.
90
+ const updated = await req.payload.update({
85
91
  collection: 'xp-experiments',
86
92
  req,
87
93
  id,
88
94
  data,
89
95
  overrideAccess: true
90
96
  });
97
+ if (system) return updated;
91
98
  const { docs } = await req.payload.find({
92
99
  collection: 'xp-experiments',
93
100
  req,
@@ -103,14 +110,16 @@ export async function updateExperiment(req, id, data) {
103
110
  if (!docs[0]) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
104
111
  return docs[0];
105
112
  }
106
- export async function start(req, { experimentId, options }) {
107
- const input = await loadStartInputs(req, options, experimentId);
113
+ async function prepareStart(req, options, before, system) {
114
+ const input = (await loadStartInputsBatch(req, options, [
115
+ before
116
+ ], false, system)).get(String(before.id));
108
117
  if (!input) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
109
- const full = await readExperiment(req, experimentId);
110
- if (full.updatedAt !== input.experiment.updatedAt) refuse('stale-draft');
118
+ const full = await readExperiment(req, before.id);
119
+ if (full.updatedAt !== before.updatedAt) refuse('stale-draft');
111
120
  // Review reads respect field access; internal writes must preserve hidden config.
112
121
  input.experiment = {
113
- ...input.experiment,
122
+ ...before,
114
123
  kind: full.kind,
115
124
  analysis: full.analysis
116
125
  };
@@ -118,26 +127,54 @@ export async function start(req, { experimentId, options }) {
118
127
  // ReadinessCode to RefusalCode, which intentionally excludes warnings.
119
128
  const failed = checkStart(input).find((check)=>!check.ok);
120
129
  if (failed && failed.code !== 'page-targets-unchecked' && failed.code !== 'make-content-unsupported') refuse(failed.code, failed.detail);
121
- const before = input.experiment;
122
- const updatedAt = before.updatedAt;
123
130
  const at = new Date();
124
131
  const caps = await resolveCaps(input.metrics, options.metricSources ?? [], at);
125
- const { result: doc, revision } = await withTransition(req, {
132
+ return {
133
+ input,
134
+ at,
135
+ caps
136
+ };
137
+ }
138
+ export async function start(req, { experimentId, options, phase: expectedPhase, system = false, onlyIfNeverStarted = false }) {
139
+ const before = await readStartInputExperiment(req, experimentId, system);
140
+ if (!before) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
141
+ const { updatedAt } = before;
142
+ const prepared = await prepareStart(req, options, before, system).catch((error)=>{
143
+ if (!onlyIfNeverStarted && expectedPhase === undefined) throw error;
144
+ // Conditional Start checks the locked document before reporting a preflight failure.
145
+ return {
146
+ error
147
+ };
148
+ });
149
+ const kind = 'error' in prepared ? before.kind : prepared.input.experiment.kind;
150
+ const { result: { doc, detail }, revision } = await withTransition(req, {
126
151
  experimentId,
127
152
  layerId: relationshipId(before.layer),
128
- flagPointId: before.kind === 'flag' ? before.flagPoint : undefined
153
+ flagPointId: kind === 'flag' ? before.flagPoint : undefined,
154
+ requireOwnedTransaction: system
129
155
  }, async ({ req, exec })=>{
130
156
  const current = await readExperiment(req, experimentId);
157
+ // A concurrent Start or Stop must yield the locked status before considering a stale snapshot.
158
+ if (onlyIfNeverStarted && (current.status !== 'draft' || (current.phase ?? 0) !== 0)) {
159
+ const detail = {
160
+ status: current.status,
161
+ phase: current.phase ?? 0
162
+ };
163
+ throw new XpRefusal('first-start-only', firstStartOnlyCopy(current.status), detail, 409);
164
+ }
165
+ requireCurrentRound(expectedPhase, current.phase);
131
166
  if (current.updatedAt !== updatedAt) refuse('stale-draft');
132
167
  if (current.status !== 'draft' && current.status !== 'stopped') refuse('invalid-status');
168
+ if ('error' in prepared) throw prepared.error;
169
+ const { input, at, caps } = prepared;
133
170
  let placementDocs;
134
171
  if (current.kind === 'block') {
135
- const rescan = await lockAndRescanPlacements(req, exec, options, current, input.placements ?? []);
172
+ const rescan = await lockAndRescanPlacements(req, exec, options, current, input.placements ?? [], system);
136
173
  placementDocs = rescan.docs;
137
174
  const failure = checkStart({
138
175
  ...input,
139
176
  experiment: current,
140
- placements: rescan.placements
177
+ placements: nameNestedPlacements(rescan.placements, await nestedPlacementNames(req, rescan.placements, system))
141
178
  }).find((check)=>!check.ok);
142
179
  if (failure && failure.code !== 'page-targets-unchecked' && failure.code !== 'make-content-unsupported') refuse(failure.code, failure.detail);
143
180
  }
@@ -152,7 +189,7 @@ export async function start(req, { experimentId, options }) {
152
189
  pageTestsInUse: await loadPageTestsInUse(req)
153
190
  }).find((check)=>check.code === 'page-in-use' && !check.ok);
154
191
  if (recheck) refuse('page-in-use', recheck.detail);
155
- const conflicts = await placementInteractions(req, exec, options, current, pageTargetPaths(current.arms));
192
+ const conflicts = await placementInteractions(req, exec, options, current, pageTargetPaths(current.arms), system);
156
193
  if (conflicts.length) refuse('interacting-tests', conflicts);
157
194
  if (options.pages) {
158
195
  // The page guard takes the same path locks, so a delete, unpublish or rename that committed
@@ -171,10 +208,8 @@ export async function start(req, { experimentId, options }) {
171
208
  }
172
209
  }
173
210
  if (current.kind === 'flag' && current.flagPoint) {
174
- const busy = await req.payload.find({
211
+ const busy = await findStartDocuments(req, {
175
212
  collection: 'xp-experiments',
176
- req,
177
- overrideAccess: false,
178
213
  depth: 0,
179
214
  limit: 2,
180
215
  where: {
@@ -194,15 +229,10 @@ export async function start(req, { experimentId, options }) {
194
229
  }
195
230
  ]
196
231
  }
197
- });
232
+ }, system);
198
233
  if (busy.docs.some((doc)=>String(doc.id) !== String(experimentId))) refuse('flag-point-busy');
199
234
  const point = options.flagPoints.find((point)=>point.id === current.flagPoint);
200
- const state = await req.payload.findGlobal({
201
- slug: 'xp-state',
202
- req,
203
- overrideAccess: false,
204
- depth: 0
205
- });
235
+ const state = await readStartState(req, system);
206
236
  const defaults = state.flagDefaults;
207
237
  current.arms = current.arms.map((arm)=>arm.kind === 'control' ? {
208
238
  ...arm,
@@ -262,15 +292,17 @@ export async function start(req, { experimentId, options }) {
262
292
  ...metric,
263
293
  metricId: metric.id,
264
294
  addedAt: startedAt,
295
+ browserWritable: browserWritableMetric(metric.source, options),
265
296
  role: String(relationshipId(current.metrics?.primary)) === String(metric.id) ? 'primary' : current.metrics?.guardrails?.some((id)=>String(relationshipId(id)) === String(metric.id)) ? 'guardrail' : 'secondary'
266
297
  }));
298
+ const arms = current.kind === 'block' ? withSlotsFor(current.arms, 'block') : current.arms;
267
299
  await writePhaseRecord(req, {
268
300
  experiment: experimentId,
269
301
  phase,
270
302
  phaseKind: 'test',
271
303
  seed,
272
304
  startedAt,
273
- arms: current.arms,
305
+ arms,
274
306
  allocation: current.allocation,
275
307
  allocationChanges: [],
276
308
  targeting,
@@ -300,21 +332,25 @@ export async function start(req, { experimentId, options }) {
300
332
  },
301
333
  contentChanges: []
302
334
  });
303
- return updateExperiment(req, experimentId, {
335
+ const doc = await updateExperiment(req, experimentId, {
304
336
  status: 'running',
305
337
  phase,
306
338
  seed,
307
339
  startedAt,
308
340
  stoppedAt: null,
309
341
  layerSlices,
310
- arms: current.arms
311
- });
342
+ arms
343
+ }, system);
344
+ return {
345
+ doc,
346
+ detail: caps.detail
347
+ };
312
348
  });
313
349
  return {
314
350
  doc,
315
351
  revision: revision,
316
- ...caps.detail.length ? {
317
- detail: caps.detail
352
+ ...detail.length ? {
353
+ detail
318
354
  } : {}
319
355
  };
320
356
  }
@@ -0,0 +1,7 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ type StartReadQuery = Parameters<PayloadRequest['payload']['find']>[0] & {
3
+ collection: 'xp-experiments' | 'xp-metrics' | 'xp-layers';
4
+ };
5
+ export declare function findStartDocuments(req: PayloadRequest, query: StartReadQuery, system?: boolean): Promise<import("payload").PaginatedDocs<import("payload").JsonObject & import("payload").TypeWithID>>;
6
+ export declare function readStartState(req: PayloadRequest, system?: boolean): Promise<import("payload").JsonObject>;
7
+ export {};
@@ -0,0 +1,28 @@
1
+ export function findStartDocuments(req, query, system = false) {
2
+ // §7.8: Start from trusted host code reads plugin readiness data without a manager actor.
3
+ if (system) return req.payload.find({
4
+ ...query,
5
+ req,
6
+ overrideAccess: true
7
+ });
8
+ return req.payload.find({
9
+ ...query,
10
+ req,
11
+ overrideAccess: false
12
+ });
13
+ }
14
+ export function readStartState(req, system = false) {
15
+ // §7.8: system Start needs the effective flag defaults even without a manager actor.
16
+ if (system) return req.payload.findGlobal({
17
+ slug: 'xp-state',
18
+ req,
19
+ overrideAccess: true,
20
+ depth: 0
21
+ });
22
+ return req.payload.findGlobal({
23
+ slug: 'xp-state',
24
+ req,
25
+ overrideAccess: false,
26
+ depth: 0
27
+ });
28
+ }
@@ -1,6 +1,7 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { DocId } from '../types/contracts.js';
3
- export declare function stop(req: PayloadRequest, { experimentId }: {
3
+ import type { RoundBody } from '../types/endpoints.js';
4
+ export declare function stop(req: PayloadRequest, { experimentId, phase: expectedPhase }: RoundBody & {
4
5
  experimentId: DocId;
5
6
  }): Promise<{
6
7
  doc: import("payload").JsonObject & import("payload").TypeWithID;
@@ -1,14 +1,15 @@
1
1
  import { relationshipId } from './checkStart.js';
2
2
  import { withTransition } from './kernel.js';
3
- import { setPhaseEndedAt } from './phaseRecord.js';
3
+ import { requireCurrentRound, setPhaseEndedAt } from './phaseRecord.js';
4
4
  import { readExperiment, refuse, updateExperiment } from './start.js';
5
- export async function stop(req, { experimentId }) {
5
+ export async function stop(req, { experimentId, phase: expectedPhase }) {
6
6
  const before = await readExperiment(req, experimentId);
7
7
  const { result: doc, revision } = await withTransition(req, {
8
8
  experimentId,
9
9
  layerId: relationshipId(before.layer)
10
10
  }, async ({ req })=>{
11
11
  const current = await readExperiment(req, experimentId);
12
+ requireCurrentRound(expectedPhase, current.phase);
12
13
  if (current.status !== 'running') refuse('invalid-status');
13
14
  const at = new Date().toISOString();
14
15
  await setPhaseEndedAt(req, experimentId, current.phase, at);
@@ -93,10 +93,11 @@ export interface FlagPoint {
93
93
  req: PayloadRequest;
94
94
  }): Promise<void>;
95
95
  }
96
- /** Host adapter: true permits the request; false drops it. */
96
+ /** Combine a trusted client-address cap with a limit for the verified unit. */
97
97
  export type RateLimiter = (args: {
98
98
  req: PayloadRequest;
99
99
  unitId: string;
100
+ unitType: UnitType;
100
101
  }) => boolean | Promise<boolean>;
101
102
  export type ExperimentsAccess = (args: {
102
103
  req: PayloadRequest;
@@ -173,11 +174,13 @@ export interface ExperimentsPluginOptions<TUser extends {
173
174
  field?: string;
174
175
  }>;
175
176
  };
176
- events?: {
177
+ events: {
177
178
  retentionDays?: number;
178
179
  maxBodyBytes?: number;
179
- rateLimit?: RateLimiter;
180
+ rateLimit: RateLimiter | false;
180
181
  dimensions?: string[];
182
+ /** Public HTTP(S) origin for clients without Fetch Metadata. Defaults to Payload's serverURL. */
183
+ origin?: string;
181
184
  };
182
185
  }
183
186
  /** Options required by the route table; CORE-02c resolves optional defaults. */
@@ -7,7 +7,7 @@ import type { Snapshot, VerdictCode } from './snapshot.js';
7
7
  export type ArmIssueCode = 'weights-total' | 'control-count' | 'control-first' | 'holdout-last' | 'holdout-count' | 'variant-count' | 'duplicate-key' | 'duplicate-slot' | 'slot-required' | 'invalid-key';
8
8
  /** Content-report dismiss/restore refusals (CORE-44). */
9
9
  export type ContentEntryRefusal = 'not-decided' | 'entry-not-found' | 'entry-ok' | 'entry-dismissed' | 'entry-not-dismissed';
10
- export type RefusalCode = ArmIssueCode | 'goal-in-some-versions' | 'placement-unchecked' | 'placement-unpublished' | 'duplicate-version-row' | 'interacting-tests' | 'placements-changed' | 'page-busy' | 'wrap-target-missing' | 'version-identical' | 'version-same-address' | 'unknown-collection' | 'not-found' | ContentEntryRefusal | 'no-planned-duration' | 'no-primary-metric' | 'no-placements' | 'placement-removed' | 'empty-slot' | 'page-in-use' | 'page-no-targets' | 'page-target-unpublished' | 'page-user-unit' | 'version-page-unavailable' | 'version-page-unchecked' | 'flag-no-point' | 'flag-params-invalid' | 'flag-point-busy' | 'flag-placement-missing' | 'layer-full' | 'layer-unit-mismatch' | 'unknown-metric-source' | 'unit-source-mismatch' | 'no-reach-per-day' | 'invalid-status' | 'stale-draft' | 'stale-edit' | 'commit-unverified' | 'allocation-lower' | 'confirmation-required' | 'invalid-winner' | 'slices-taken' | 'locked-placement' | 'not-implemented' | 'forbidden' | 'unauthenticated' | 'body-too-large' | 'invalid-body' | 'too-many-ids' | 'invalid-phase' | 'invalid-ids' | 'recompute-failed' | 'analysis-failed' | 'undeclared-targeting-key' | 'invalid-targeting-rule' | 'block-path-rule' | 'duplicate-metric';
10
+ export type RefusalCode = ArmIssueCode | 'nested-tests' | 'goal-in-some-versions' | 'placement-unchecked' | 'placement-unpublished' | 'duplicate-version-row' | 'interacting-tests' | 'placements-changed' | 'page-busy' | 'wrap-target-missing' | 'version-identical' | 'version-same-address' | 'unknown-collection' | 'not-found' | ContentEntryRefusal | 'no-planned-duration' | 'no-primary-metric' | 'no-placements' | 'placement-removed' | 'empty-slot' | 'page-in-use' | 'page-no-targets' | 'page-target-unpublished' | 'page-user-unit' | 'version-page-unavailable' | 'version-page-unchecked' | 'flag-no-point' | 'flag-params-invalid' | 'flag-point-busy' | 'flag-placement-missing' | 'layer-full' | 'layer-unit-mismatch' | 'unknown-metric-source' | 'unit-source-mismatch' | 'no-reach-per-day' | 'invalid-status' | 'first-start-only' | 'stale-draft' | 'stale-edit' | 'round-changed' | 'commit-unverified' | 'allocation-lower' | 'confirmation-required' | 'invalid-winner' | 'slices-taken' | 'locked-placement' | 'not-implemented' | 'forbidden' | 'unauthenticated' | 'body-too-large' | 'invalid-body' | 'too-many-ids' | 'invalid-phase' | 'invalid-ids' | 'recompute-failed' | 'analysis-failed' | 'undeclared-targeting-key' | 'invalid-targeting-rule' | 'block-path-rule' | 'duplicate-metric';
11
11
  export type ErrorEnvelope = {
12
12
  errors: Array<{
13
13
  code: RefusalCode;
@@ -19,8 +19,31 @@ export type TransitionSuccess = {
19
19
  doc: Record<string, unknown>;
20
20
  revision: number;
21
21
  };
22
- export type AllocateBody = {
23
- allocation: number;
22
+ export type StartExperimentWarning = {
23
+ metricId: DocId;
24
+ message: string;
25
+ };
26
+ export type StartExperimentFirstStartDetail = {
27
+ status: Status;
28
+ phase: number;
29
+ };
30
+ export type StartExperimentResult = {
31
+ status: 'started';
32
+ phase: number;
33
+ revision: number;
34
+ warnings: StartExperimentWarning[];
35
+ } | {
36
+ status: 'refused';
37
+ code: 'first-start-only';
38
+ message: string;
39
+ detail: StartExperimentFirstStartDetail;
40
+ } | {
41
+ status: 'refused';
42
+ code: Exclude<RefusalCode, 'not-found' | 'commit-unverified' | 'first-start-only'> | 'transaction-open';
43
+ message: string;
44
+ detail?: unknown;
45
+ } | {
46
+ status: 'not-found';
24
47
  };
25
48
  export type AddMetricWarning = {
26
49
  code: 'goal-in-some-versions' | 'goal-added-mid-test' | 'placement-unchecked';
@@ -33,12 +56,19 @@ export type AddMetricBody = {
33
56
  metric: DocId;
34
57
  role: 'secondary' | 'guardrail';
35
58
  };
36
- export type DecideBody = {
59
+ /** When omitted, the action applies to the current round. */
60
+ export type RoundBody = {
61
+ phase?: number;
62
+ };
63
+ export type AllocateBody = RoundBody & {
64
+ allocation: number;
65
+ };
66
+ export type DecideBody = RoundBody & {
37
67
  winnerArm: string;
38
68
  note?: string;
39
69
  confirmation?: string;
40
70
  };
41
- export type ArchiveBody = {
71
+ export type ArchiveBody = RoundBody & {
42
72
  mode: 'stopped' | 'after-content' | 'discard' | 'hard-coded';
43
73
  confirmation?: string;
44
74
  };
@@ -64,10 +94,23 @@ export type MakeContentResult = TransitionSuccess & {
64
94
  }>;
65
95
  };
66
96
  export type PreflightResult = {
97
+ /** Saved document version used for these checks. */
98
+ document?: {
99
+ status: Status;
100
+ phase?: number;
101
+ updatedAt?: string;
102
+ };
103
+ /** Content language selection and labels when block placements are localized. */
104
+ contentLocales?: {
105
+ selected: string;
106
+ labels: Record<string, string>;
107
+ };
67
108
  goalNotes?: Array<{
68
109
  metricId: DocId;
69
110
  message: string;
70
111
  }>;
112
+ /** Advisory only. This does not affect Start readiness. */
113
+ browserWritablePrimaryId?: DocId;
71
114
  checks: Array<{
72
115
  code: ReadinessCode;
73
116
  ok: boolean;
@@ -89,9 +132,14 @@ export type PreflightResult = {
89
132
  collection: string;
90
133
  id: DocId;
91
134
  title: string;
135
+ locales?: string[];
136
+ allLocales?: true;
137
+ localeCodes?: string[];
138
+ slotCount?: number;
92
139
  url?: string;
93
140
  editorUrl?: string;
94
141
  slots?: Record<ArmSlot, number>;
142
+ partlyFilledSlots?: ArmSlot[];
95
143
  ok: boolean;
96
144
  detail?: string;
97
145
  }>;
@@ -127,6 +175,7 @@ export interface PhaseSummary {
127
175
  kind: MetricSource['kind'];
128
176
  role: 'primary' | 'secondary' | 'guardrail';
129
177
  clickGoal?: true;
178
+ browserWritable?: true;
130
179
  resolvedCap?: number | null;
131
180
  historyUnits?: number;
132
181
  capNotice?: 'no-history';
@@ -183,16 +232,13 @@ export type EventBody = {
183
232
  attributes?: Record<string, string | number | boolean>;
184
233
  }>;
185
234
  };
186
- export type AccessKind = 'manage' | 'readResults' | 'surface' | 'manifestKey' | 'signedCookie';
235
+ export type AccessKind = 'manage' | 'readResults' | 'surface' | 'manifestKey' | 'browserEvents';
187
236
  export type EndpointContext<TUser extends {
188
237
  id: string | number;
189
238
  } = {
190
239
  id: string | number;
191
240
  }> = {
192
241
  options: ResolvedOptions<TUser>;
193
- unit?: {
194
- visitorId: string;
195
- };
196
242
  };
197
243
  export type ClickKeysResult = {
198
244
  keys: Array<{
@@ -251,6 +297,7 @@ export type PlacementStatusResult = {
251
297
  slot?: string;
252
298
  }>;
253
299
  winnerArm?: string;
300
+ discarded?: boolean;
254
301
  rollout: boolean;
255
302
  }>;
256
303
  };
@@ -261,3 +308,33 @@ export type WrapBlockBody = {
261
308
  blockId: string;
262
309
  experiment: string;
263
310
  };
311
+ /** Current visitor effect of deleting a draft or archived test; independent of its stored content report. */
312
+ export type DeleteImpactResult = {
313
+ effect: 'none';
314
+ } | {
315
+ effect: 'block';
316
+ controlLabel: string;
317
+ unreadablePages: number;
318
+ pageCount: number;
319
+ placements: Array<{
320
+ collection: string;
321
+ id: DocId;
322
+ title: string;
323
+ path: string | null;
324
+ locales?: string[];
325
+ allLocales?: true;
326
+ before: {
327
+ key: string;
328
+ label: string;
329
+ };
330
+ after: {
331
+ key: string;
332
+ label: string;
333
+ };
334
+ }>;
335
+ } | {
336
+ effect: 'page';
337
+ winnerPath: string;
338
+ addresses: string[];
339
+ afterPaths?: Record<string, string>;
340
+ };
@@ -1 +1 @@
1
- export { };
1
+ /** Current visitor effect of deleting a draft or archived test; independent of its stored content report. */ export { };
@@ -2,15 +2,21 @@ import type { Payload } from 'payload';
2
2
  import type { NextRequest } from 'next/server';
3
3
  import type { Attributes } from './contracts.js';
4
4
  import type { Manifest } from './manifest.js';
5
+ type CookieOptions = {
6
+ name?: string;
7
+ maxAgeDays?: number;
8
+ /** Reject pre-rc.9 visitor IDs, including upgraded cookies, starting on this UTC date. Can only shorten the release cutoff. */
9
+ legacyCutoff?: string;
10
+ domain?: string;
11
+ /** Called with a request whose URL is a placeholder outside the proxy; read cookies and headers only. */
12
+ consent?(req: NextRequest): boolean;
13
+ };
5
14
  export interface ExperimentsProxyRuntimeOptions {
6
15
  secret: string | string[];
7
16
  apiRoute: string;
8
- cookie?: {
9
- name?: string;
10
- maxAgeDays?: number;
11
- domain?: string; /** Called with a request whose URL is a placeholder outside the proxy; read cookies and headers only. */
12
- consent?(req: NextRequest): boolean;
13
- };
17
+ /** Limit new visitor IDs by trusted client address, or pass false when protected upstream. */
18
+ rateLimitUnit: false | ((req: NextRequest) => boolean | Promise<boolean>);
19
+ cookie?: CookieOptions;
14
20
  loadManifest?: (opts?: {
15
21
  ifRevision?: number;
16
22
  }) => Promise<Manifest | 'not-modified' | null>;
@@ -27,11 +33,10 @@ export interface ExperimentsProxyRuntimeOptions {
27
33
  export interface ExperimentsProxyRuntime {
28
34
  readonly secrets: readonly string[];
29
35
  readonly apiRoute: string;
30
- readonly cookie: {
36
+ readonly rateLimitUnit: ExperimentsProxyRuntimeOptions['rateLimitUnit'];
37
+ readonly cookie: CookieOptions & {
31
38
  name: string;
32
39
  maxAgeDays: number;
33
- domain?: string; /** Called with a request whose URL is a placeholder outside the proxy; read cookies and headers only. */
34
- consent?(req: NextRequest): boolean;
35
40
  };
36
41
  readonly loadManifest?: ExperimentsProxyRuntimeOptions['loadManifest'];
37
42
  readonly getUnit?: ExperimentsProxyRuntimeOptions['getUnit'];
@@ -57,3 +62,4 @@ export interface ExperimentsServerRuntime<TUser extends {
57
62
  userIdOf: NonNullable<ExperimentsServerRuntimeOptions<TUser>['userIdOf']>;
58
63
  attributesOf: NonNullable<ExperimentsServerRuntimeOptions<TUser>['attributesOf']>;
59
64
  }
65
+ export {};
@@ -12,6 +12,8 @@ export type SnapshotHealth = {
12
12
  id?: string | number;
13
13
  path?: string;
14
14
  };
15
+ } | {
16
+ code: 'rapid-browser-events';
15
17
  };
16
18
  import type { GaussianPrior } from '@delmaredigital/experiments-stats';
17
19
  import type { DocId, MetricSource } from './contracts.js';
@@ -7,6 +7,8 @@ export interface TestsSurfaceProps {
7
7
  returnToTest?: string;
8
8
  adminRoute: string;
9
9
  apiRoute: string;
10
+ contentLanguageLabels?: string[];
11
+ contentLocale?: string;
10
12
  collectionTitles?: Record<string, string>;
11
13
  userId?: string | number;
12
14
  userCollection?: string;
package/dist/ui/Button.js CHANGED
@@ -12,7 +12,7 @@ export function Button({ variant = 'secondary', size = 'md', disabled, busy, cla
12
12
  href: blocked ? undefined : href,
13
13
  role: blocked ? 'link' : undefined,
14
14
  "aria-disabled": blocked || undefined,
15
- "aria-busy": busy || undefined,
15
+ "aria-busy": busy || props['aria-busy'] || undefined,
16
16
  tabIndex: blocked ? -1 : rest.tabIndex,
17
17
  onClick: (event)=>{
18
18
  if (blocked) event.preventDefault();
@@ -26,7 +26,7 @@ export function Button({ variant = 'secondary', size = 'md', disabled, busy, cla
26
26
  type: props.type ?? 'button',
27
27
  className: classes,
28
28
  disabled: blocked,
29
- "aria-busy": busy || undefined,
29
+ "aria-busy": busy || props['aria-busy'] || undefined,
30
30
  children: children
31
31
  });
32
32
  }
@@ -9,5 +9,12 @@ export interface ChipsInputProps {
9
9
  placeholder?: string;
10
10
  disabled?: boolean;
11
11
  id: string;
12
+ draft?: {
13
+ value: string;
14
+ change: (value: string) => void;
15
+ submit: (value: string) => void;
16
+ discard: () => void;
17
+ describedBy?: string;
18
+ };
12
19
  }
13
- export declare function ChipsInput({ value, onChange, label, description, help, error, placeholder, disabled, id }: ChipsInputProps): import("react").JSX.Element;
20
+ export declare function ChipsInput({ value, onChange, label, description, help, error, placeholder, disabled, id, draft: managedDraft }: ChipsInputProps): import("react").JSX.Element;
@@ -2,11 +2,17 @@
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { useRef, useState } from 'react';
4
4
  import './ui.css';
5
- export function ChipsInput({ value, onChange, label, description, help = description, error, placeholder, disabled = false, id }) {
6
- const [draft, setDraft] = useState('');
5
+ export function ChipsInput({ value, onChange, label, description, help = description, error, placeholder, disabled = false, id, draft: managedDraft }) {
6
+ const [localDraft, setLocalDraft] = useState('');
7
+ const draft = managedDraft?.value ?? localDraft;
8
+ const setDraft = managedDraft?.change ?? setLocalDraft;
7
9
  const input = useRef(null);
8
10
  const commit = (text)=>{
9
11
  if (disabled) return;
12
+ if (managedDraft) {
13
+ managedDraft.submit(text);
14
+ return;
15
+ }
10
16
  const next = [
11
17
  ...new Set([
12
18
  ...value,
@@ -60,13 +66,20 @@ export function ChipsInput({ value, onChange, label, description, help = descrip
60
66
  "aria-invalid": Boolean(error) || undefined,
61
67
  "aria-describedby": [
62
68
  help ? `${id}-description` : '',
63
- error ? `${id}-error` : ''
69
+ error ? `${id}-error` : '',
70
+ managedDraft?.describedBy
64
71
  ].filter(Boolean).join(' ') || undefined,
65
72
  onChange: (event)=>setDraft(event.target.value),
66
73
  onBlur: ()=>{
67
74
  if (draft.trim()) commit(draft);
68
75
  },
69
76
  onKeyDown: (event)=>{
77
+ if (event.key === 'Escape' && managedDraft && draft) {
78
+ event.preventDefault();
79
+ event.stopPropagation();
80
+ managedDraft.discard();
81
+ return;
82
+ }
70
83
  if (disabled || event.nativeEvent.isComposing) return;
71
84
  if (event.key === 'Enter' || event.key === ',') {
72
85
  event.preventDefault();
@@ -78,7 +91,7 @@ export function ChipsInput({ value, onChange, label, description, help = descrip
78
91
  }
79
92
  },
80
93
  onPaste: (event)=>{
81
- if (disabled) return;
94
+ if (disabled || managedDraft) return;
82
95
  const pasted = event.clipboardData.getData('text');
83
96
  if (!pasted.includes(',')) return;
84
97
  event.preventDefault();