@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
@@ -31,7 +31,10 @@ import { timestampMs } from './aggregate.js';
31
31
  events.push({
32
32
  unitId: eligible[0].anonymousId,
33
33
  value: event.value,
34
- ts: event.ts
34
+ ts: event.ts,
35
+ ...event.unitAgeMs === undefined ? {} : {
36
+ unitAgeMs: event.unitAgeMs
37
+ }
35
38
  });
36
39
  if (new Set(eligible.map((link)=>units.get(link.anonymousId).arm)).size > 1) {
37
40
  conflicts.add(event.userId);
@@ -1,4 +1,5 @@
1
1
  import { ARM_LABELS } from '../labels/arms.js';
2
+ import { RESULTS_COPY } from '../testSurface/copy/results.js';
2
3
  function percent(value) {
3
4
  if (value === null) return '…';
4
5
  const rounded = Math.round(value * 100);
@@ -44,7 +45,7 @@ function chance(value) {
44
45
  return make(rollout ? 'R1' : 1, 'unavailable', `Results unavailable: ${input.primary.name} could not be read.`, 'Recompute; if it persists, contact a developer.', 'The main outcome could not be loaded.', null);
45
46
  }
46
47
  if (input.srm.flagged || input.exposures.multiArmShare >= 0.01) {
47
- return make(rollout ? 'R1' : 2, 'data-problem', "Data problem: traffic isn't splitting as set.", "Don't trust these results. Check for caching or a page placed twice; contact a developer.", 'The people counted do not match the expected split.', null);
48
+ return make(rollout ? 'R1' : 2, 'data-problem', "Data problem: traffic isn't splitting as set.", input.srm.flagged ? RESULTS_COPY.srmAction : "Don't trust these results. Ask a developer to check for caching or a page placed twice.", 'The people counted do not match the expected split.', null);
48
49
  }
49
50
  const compared = input.exposures.perArm.filter((item)=>rollout || item.kind !== 'holdout');
50
51
  const minimum = compared.length ? Math.min(...compared.map((item)=>item.n)) : 0;
@@ -1,10 +1,17 @@
1
1
  import { NextRequest } from 'next/server.js';
2
2
  import type { ExperimentsProxyRuntime } from '../types/runtime.js';
3
3
  export declare function mintUnitId(): string;
4
- export declare function encodeUnitCookie(unitId: string, secrets: readonly string[]): string;
5
- export declare function verifyUnitCookie(cookie: string | undefined, secrets: readonly string[]): string | null;
4
+ export declare function encodeUnitCookie(unitId: string, secrets: readonly string[], issuedAtMs?: number | 'legacy', renewedAtMs?: number): string;
5
+ interface SignedUnit {
6
+ unitId: string;
7
+ issuedAtMs: number | 'legacy';
8
+ renewedAtMs: number | null;
9
+ }
10
+ export declare function verifySignedUnit(cookie: string | undefined, secrets: readonly string[], maxAgeMs: number, now?: number, legacyCutoffMs?: number): SignedUnit | null;
11
+ export declare function unitCookieMaxAgeMs(runtime: Pick<ExperimentsProxyRuntime, 'cookie'>): number;
6
12
  /** Use Next's cookie selection everywhere: the last cookie of a given name wins. */
7
13
  export declare function readUnitCookie(input: Headers | NextRequest, runtime: Pick<ExperimentsProxyRuntime, 'cookie' | 'secrets'>): string | null;
14
+ export declare function readSignedUnit(input: Headers | NextRequest, runtime: Pick<ExperimentsProxyRuntime, 'cookie' | 'secrets'>, now?: number): SignedUnit | null;
8
15
  export declare function cookieAttributes(runtime: Pick<ExperimentsProxyRuntime, 'cookie'>, { https }: {
9
16
  https: boolean;
10
17
  }): {
@@ -15,3 +22,4 @@ export declare function cookieAttributes(runtime: Pick<ExperimentsProxyRuntime,
15
22
  path: string;
16
23
  maxAge: number;
17
24
  };
25
+ export {};
@@ -1,30 +1,62 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { NextRequest } from 'next/server.js';
3
+ import { DAY_MS, LEGACY_COOKIE_CUTOFF_MS } from './cookieOptions.js';
3
4
  import { sign, verify } from './signing.js';
4
5
  export function mintUnitId() {
5
6
  return randomBytes(16).toString('base64url');
6
7
  }
7
- export function encodeUnitCookie(unitId, secrets) {
8
+ export function encodeUnitCookie(unitId, secrets, issuedAtMs = Date.now(), renewedAtMs = issuedAtMs === 'legacy' ? Date.now() : issuedAtMs) {
8
9
  if (!/^[A-Za-z0-9_-]+$/.test(unitId)) throw new Error('Invalid unit id');
9
- return `${unitId}.${sign(`xp:unit:${unitId}`, secrets)}`;
10
+ if (!validTimes(issuedAtMs, renewedAtMs)) throw new Error('Invalid unit cookie time');
11
+ const payload = `${unitId}.${issuedAtMs}.${renewedAtMs}`;
12
+ return `v2.${payload}.${sign(`xp:unit:v2:${payload}`, secrets)}`;
10
13
  }
11
- export function verifyUnitCookie(cookie, secrets) {
14
+ function validTimes(issuedAtMs, renewedAtMs) {
15
+ return Number.isSafeInteger(renewedAtMs) && renewedAtMs >= 0 && (issuedAtMs === 'legacy' || Number.isSafeInteger(issuedAtMs) && issuedAtMs >= 0 && issuedAtMs <= renewedAtMs);
16
+ }
17
+ export function verifySignedUnit(cookie, secrets, maxAgeMs, now = Date.now(), legacyCutoffMs = LEGACY_COOKIE_CUTOFF_MS) {
12
18
  if (typeof cookie !== 'string') return null;
19
+ const acceptsLegacy = now < Math.min(legacyCutoffMs, LEGACY_COOKIE_CUTOFF_MS);
20
+ const timed = /^v2\.(([A-Za-z0-9_-]+)\.(legacy|0|[1-9][0-9]{0,15})\.(0|[1-9][0-9]{0,15}))\.([A-Za-z0-9_-]{43})$/.exec(cookie);
21
+ if (timed) {
22
+ const payload = timed[1], unitId = timed[2], time = timed[3], renewal = timed[4], mac = timed[5];
23
+ const issuedAtMs = time === 'legacy' ? time : Number(time);
24
+ const renewedAtMs = Number(renewal);
25
+ if (issuedAtMs === 'legacy' && !acceptsLegacy) return null;
26
+ return validTimes(issuedAtMs, renewedAtMs) && now - renewedAtMs < maxAgeMs && verify(`xp:unit:v2:${payload}`, mac, secrets) ? {
27
+ unitId,
28
+ issuedAtMs,
29
+ renewedAtMs
30
+ } : null;
31
+ }
32
+ if (!acceptsLegacy) return null;
13
33
  const match = /^([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]{43})$/.exec(cookie);
14
- return match && verify(`xp:unit:${match[1]}`, match[2], secrets) ? match[1] : null;
34
+ return match && verify(`xp:unit:${match[1]}`, match[2], secrets) ? {
35
+ unitId: match[1],
36
+ issuedAtMs: 'legacy',
37
+ renewedAtMs: null
38
+ } : null;
39
+ }
40
+ export function unitCookieMaxAgeMs(runtime) {
41
+ // Set-Cookie's Max-Age is an integer number of seconds. Verify the same lifetime.
42
+ return Math.floor(runtime.cookie.maxAgeDays * (DAY_MS / 1000)) * 1000;
15
43
  }
16
44
  /** Use Next's cookie selection everywhere: the last cookie of a given name wins. */ export function readUnitCookie(input, runtime) {
45
+ return readSignedUnit(input, runtime)?.unitId ?? null;
46
+ }
47
+ export function readSignedUnit(input, runtime, now = Date.now()) {
17
48
  const request = input instanceof Headers ? new NextRequest('https://xp.invalid/', {
18
49
  headers: input
19
50
  }) : input;
20
- return verifyUnitCookie(request.cookies.get(runtime.cookie.name)?.value, runtime.secrets);
51
+ const cutoff = runtime.cookie.legacyCutoff;
52
+ return verifySignedUnit(request.cookies.get(runtime.cookie.name)?.value, runtime.secrets, unitCookieMaxAgeMs(runtime), now, cutoff === undefined ? undefined : Date.parse(cutoff));
21
53
  }
22
54
  export function cookieAttributes(runtime, { https }) {
23
55
  return {
24
56
  httpOnly: true,
25
57
  sameSite: 'lax',
26
58
  path: '/',
27
- maxAge: runtime.cookie.maxAgeDays * 86400,
59
+ maxAge: unitCookieMaxAgeMs(runtime) / 1000,
28
60
  ...https ? {
29
61
  secure: true
30
62
  } : {},
@@ -0,0 +1,6 @@
1
+ export declare const LEGACY_COOKIE_CUTOFF_MS: number;
2
+ export declare const DAY_MS = 86400000;
3
+ export declare function assertCookieOptions({ maxAgeDays, legacyCutoff }: {
4
+ maxAgeDays: number;
5
+ legacyCutoff?: string;
6
+ }): void;
@@ -0,0 +1,14 @@
1
+ // 400 days after the end of the December 2, 2026 rollout day (UTC).
2
+ export const LEGACY_COOKIE_CUTOFF_MS = Date.UTC(2028, 0, 7);
3
+ export const DAY_MS = 86_400_000;
4
+ export function assertCookieOptions({ maxAgeDays, legacyCutoff }) {
5
+ if (!Number.isFinite(maxAgeDays) || maxAgeDays * DAY_MS < 1000 || maxAgeDays > 400) {
6
+ throw new Error('Experiments cookie.maxAgeDays must be a number from one second in days (1/86400) through 400.');
7
+ }
8
+ if (legacyCutoff !== undefined) {
9
+ const cutoff = typeof legacyCutoff === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(legacyCutoff) ? Date.parse(legacyCutoff) : NaN;
10
+ if (!Number.isFinite(cutoff) || cutoff > LEGACY_COOKIE_CUTOFF_MS || new Date(cutoff).toISOString().slice(0, 10) !== legacyCutoff) {
11
+ throw new Error('Experiments cookie.legacyCutoff must be a UTC date (YYYY-MM-DD) on or before 2028-01-07.');
12
+ }
13
+ }
14
+ }
@@ -1,2 +1,3 @@
1
1
  import type { ExperimentsProxyRuntime, ExperimentsProxyRuntimeOptions } from '../types/runtime.js';
2
+ export declare function assertUnitRateLimit(rateLimitUnit: unknown): void;
2
3
  export declare function defineExperimentsProxyRuntime(opts: ExperimentsProxyRuntimeOptions): ExperimentsProxyRuntime;
@@ -1,22 +1,32 @@
1
1
  import { XP_COOKIE } from '../constants.js';
2
+ import { assertSigningSecrets } from './signing.js';
3
+ import { assertCookieOptions } from './cookieOptions.js';
4
+ export function assertUnitRateLimit(rateLimitUnit) {
5
+ if (rateLimitUnit !== false && typeof rateLimitUnit !== 'function') {
6
+ throw new Error('Experiments requires rateLimitUnit to be a client-address rate limiter, or false if you rate-limit unit issuance upstream.');
7
+ }
8
+ }
2
9
  export function defineExperimentsProxyRuntime(opts) {
3
10
  const secrets = typeof opts.secret === 'string' ? [
4
11
  opts.secret
5
- ] : [
6
- ...opts.secret
7
- ];
8
- if (!secrets.length || secrets.some((secret)=>!secret.trim())) throw new Error('At least one non-empty secret is required');
12
+ ] : opts.secret;
13
+ assertSigningSecrets(secrets);
14
+ assertUnitRateLimit(opts.rateLimitUnit);
15
+ const maxAgeDays = opts.cookie?.maxAgeDays;
9
16
  const cookie = Object.freeze({
10
17
  ...opts.cookie,
11
18
  name: opts.cookie?.name ?? XP_COOKIE,
12
- maxAgeDays: opts.cookie?.maxAgeDays ?? 365
19
+ maxAgeDays: maxAgeDays === undefined ? 365 : maxAgeDays
13
20
  });
14
- Object.freeze(secrets);
21
+ assertCookieOptions(cookie);
15
22
  return Object.freeze({
16
- secrets,
23
+ secrets: Object.freeze([
24
+ ...secrets
25
+ ]),
17
26
  apiRoute: opts.apiRoute,
18
27
  cookie,
19
28
  loadManifest: opts.loadManifest,
20
- getUnit: opts.getUnit
29
+ getUnit: opts.getUnit,
30
+ rateLimitUnit: opts.rateLimitUnit
21
31
  });
22
32
  }
@@ -1,3 +1,4 @@
1
+ export declare function assertSigningSecrets(secrets: readonly string[]): void;
1
2
  /** New signatures use the first key; verification accepts the entire rotation. */
2
3
  export declare function sign(value: string, secrets: readonly string[]): string;
3
4
  export declare function verify(value: string, mac: string, secrets: readonly string[]): boolean;
@@ -1,4 +1,9 @@
1
1
  import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ export function assertSigningSecrets(secrets) {
3
+ if (!Array.isArray(secrets) || !secrets.length || Array.from(secrets).some((secret)=>typeof secret !== 'string' || secret.trim().length < 32)) {
4
+ throw new Error('Experiments requires at least one signing secret. Each signing secret must contain at least 32 characters.');
5
+ }
6
+ }
2
7
  /** New signatures use the first key; verification accepts the entire rotation. */ export function sign(value, secrets) {
3
8
  if (!secrets.length || !secrets[0]) throw new Error('A signing secret is required');
4
9
  return createHmac('sha256', secrets[0]).update(value).digest('base64url');
@@ -2,6 +2,6 @@ import type { ReadinessCode } from './types/endpoints.js';
2
2
  /** Summary details contain identifiers only. Project known shapes rather than
3
3
  * recursively copying host objects: titles, messages and placement detail are text.
4
4
  * Other checks use authored client fallbacks and need no detail (including slot
5
- * counts and layer capacity, which are not identifiers).
5
+ * counts and layer capacity, which are not identifiers). Empty slots carry only version keys.
6
6
  */
7
- export declare function sanitizeReadinessDetail(code: ReadinessCode, detail: unknown): unknown;
7
+ export declare function sanitizeReadinessDetail(code: ReadinessCode, detail: unknown, draftReadySlots?: readonly string[]): unknown;
@@ -13,8 +13,8 @@ const failure = (value)=>value === 'placements-failed' || value === 'forbidden'
13
13
  /** Summary details contain identifiers only. Project known shapes rather than
14
14
  * recursively copying host objects: titles, messages and placement detail are text.
15
15
  * Other checks use authored client fallbacks and need no detail (including slot
16
- * counts and layer capacity, which are not identifiers).
17
- */ export function sanitizeReadinessDetail(code, detail) {
16
+ * counts and layer capacity, which are not identifiers). Empty slots carry only version keys.
17
+ */ export function sanitizeReadinessDetail(code, detail, draftReadySlots = []) {
18
18
  switch(code){
19
19
  case 'goal-in-some-versions':
20
20
  {
@@ -63,6 +63,24 @@ const failure = (value)=>value === 'placements-failed' || value === 'forbidden'
63
63
  } : undefined;
64
64
  case 'no-placements':
65
65
  return failure(detail) ? detail : undefined;
66
+ case 'empty-slot':
67
+ {
68
+ const rows = (Array.isArray(detail) ? detail : [
69
+ detail
70
+ ]).filter(object);
71
+ const missing = [
72
+ ...new Set(rows.flatMap((row)=>Array.isArray(row.missing) ? row.missing : []).filter((value)=>arm(value) && value !== 'holdout'))
73
+ ];
74
+ if (!missing.length) return undefined;
75
+ const reportedReady = object(detail) && Array.isArray(detail.draftReady) ? detail.draftReady : draftReadySlots;
76
+ const draftReady = missing.filter((slot)=>reportedReady.includes(slot));
77
+ return {
78
+ missing,
79
+ ...draftReady.length ? {
80
+ draftReady
81
+ } : {}
82
+ };
83
+ }
66
84
  case 'placement-removed':
67
85
  return undefined;
68
86
  case 'page-in-use':
@@ -53,7 +53,8 @@ async function readAssignments(runtime, suppliedUser) {
53
53
  sessionUnknown: unit.sessionUnknown
54
54
  };
55
55
  let user = consent === false ? null : suppliedUser;
56
- const canResolveUser = consent !== false && (suppliedUser !== undefined || Boolean(runtime.getUser));
56
+ const canAssignUser = consent !== false && (hasContext || Boolean(visitorId));
57
+ const canResolveUser = canAssignUser && (suppliedUser !== undefined || Boolean(runtime.getUser));
57
58
  let userFailed = false;
58
59
  const resolveUser = async ()=>{
59
60
  if (user !== undefined) return user;
@@ -68,14 +69,14 @@ async function readAssignments(runtime, suppliedUser) {
68
69
  };
69
70
  const value = requestHeaders.get(XP_HEADER);
70
71
  // Consent-false proxy headers are signed without either identity.
71
- let headerUserId = visitorId ? unit.userId : undefined;
72
+ let headerUserId = canAssignUser ? unit.userId : undefined;
72
73
  const authenticate = (userId)=>verifiedHeaderRevision(value, {
73
74
  secrets: proxy.secrets,
74
75
  visitorId,
75
76
  userId
76
77
  });
77
78
  let revision = authenticate(headerUserId);
78
- if (revision === null && visitorId && value && (runtime.getUser || suppliedUser)) {
79
+ if (revision === null && value && canResolveUser) {
79
80
  const resolved = await resolveUser();
80
81
  if (resolved) {
81
82
  const resolvedId = runtime.userIdOf(resolved);
@@ -108,13 +109,14 @@ async function readAssignments(runtime, suppliedUser) {
108
109
  userFailed = true;
109
110
  }
110
111
  }
111
- const userId = visitorId ? user === undefined ? unit.userId : user ? runtime.userIdOf(user) : undefined : undefined;
112
+ const userId = canAssignUser ? user === undefined ? unit.userId : user ? runtime.userIdOf(user) : undefined : undefined;
113
+ const token = hasContext ? verifyPreviewToken(request.nextUrl.searchParams.get('xp_preview') ?? '', proxy.secrets) : null;
112
114
  const context = {
113
115
  visitorId,
114
116
  userId,
115
117
  staff: decoded?.staff === true || unit.attributes.staff === true || attributes.staff === true,
116
118
  bot: decoded?.bot === true || isBot(requestHeaders.get('user-agent')),
117
- preview: decoded?.preview ?? false,
119
+ preview: decoded?.preview === true || !visitorId && token !== null,
118
120
  sessionUnknown: needsUser && canResolveUser && !userFailed ? false : decoded?.sessionUnknown ?? unit.sessionUnknown ?? false,
119
121
  method: request.method
120
122
  };
@@ -159,10 +161,10 @@ async function readAssignments(runtime, suppliedUser) {
159
161
  }
160
162
  };
161
163
  const slugs = new Set(hasContext ? decoded.deferred : []);
162
- if (visitorId && user !== undefined && userId !== headerUserId) {
164
+ if (canAssignUser && user !== undefined && userId !== headerUserId) {
163
165
  for (const e of manifest.experiments)if (e.unitType === 'user') slugs.add(e.slug);
164
166
  }
165
- if (visitorId && slugs.size && canResolveUser && !userFailed) {
167
+ if (slugs.size && canResolveUser && !userFailed) {
166
168
  try {
167
169
  const resolved = assign(manifest, {
168
170
  visitorId,
@@ -179,7 +181,7 @@ async function readAssignments(runtime, suppliedUser) {
179
181
  userFailed = true;
180
182
  }
181
183
  }
182
- } else if (!visitorId || !hasContext) result = controlAssignments(manifest, context);
184
+ } else if (!visitorId && !userId || !hasContext) result = controlAssignments(manifest, context);
183
185
  else {
184
186
  try {
185
187
  result = assign(manifest, {
@@ -202,7 +204,6 @@ async function readAssignments(runtime, suppliedUser) {
202
204
  }
203
205
  fillFlagPoints(result, manifest);
204
206
  fillHostDefaults(result);
205
- const token = hasContext ? verifyPreviewToken(request.nextUrl.searchParams.get('xp_preview') ?? '', proxy.secrets) : null;
206
207
  if (token && visitorId && payload) {
207
208
  const live = manifest.experiments.find((e)=>e.id === token.e && e.phase === token.p && e.arms.some((a)=>a.key === token.a));
208
209
  if (live) {
@@ -219,7 +220,7 @@ async function readAssignments(runtime, suppliedUser) {
219
220
  fillFlagPoints(result, manifest);
220
221
  } else await previewDraft(payload, await resolveUser(), token, result, requestHeaders);
221
222
  }
222
- if (suppressExposure(result) || !hasContext || !visitorId || payloadFailed || userFailed || mustResolveStaff && !runtime.getUser && suppliedUser === undefined) {
223
+ if (suppressExposure(result) || !hasContext || payloadFailed || userFailed || mustResolveStaff && !runtime.getUser && suppliedUser === undefined) {
223
224
  for (const assignment of Object.values(result.bySlug))assignment.exposable = false;
224
225
  for (const point of Object.values(result.flagPoints))point.exposable = false;
225
226
  }
@@ -2,6 +2,6 @@ import type { CollectionAfterChangeHook, CollectionBeforeChangeHook } from 'payl
2
2
  /** Paired raw beforeChange capture: previousDoc may be an autosaved draft. */
3
3
  export declare function capturePublishedContent({ req, collection, originalDoc, operation }: Parameters<CollectionBeforeChangeHook>[0]): Promise<void>;
4
4
  type ContentChangeArgs = Pick<Parameters<CollectionAfterChangeHook>[0], 'doc' | 'previousDoc' | 'req' | 'collection'>;
5
- /** Publish-only host helper. Audit failures are logged, never thrown into saves. */
5
+ /** Publish-only host helper. Audit failures are logged after savepoint recovery. */
6
6
  export declare function recordContentChange(args: ContentChangeArgs): Promise<void>;
7
7
  export {};
@@ -1,14 +1,17 @@
1
+ import { placementReader } from '../blocks/placementLocale.js';
2
+ import { puckExperimentSlug } from '../puck/experimentSlug.js';
1
3
  import { puckVisibility } from '../puck/visibility.js';
2
4
  import { EXPERIMENT_BLOCK_SLUG, hostBlocks } from '../blocks/model.js';
3
5
  import { safeError } from '../log.js';
4
6
  import { isDeepStrictEqual } from 'node:util';
7
+ import { XpTransactionIsolationError } from '../db/adapter.js';
5
8
  import { appendContentChange, contentChangeSavepoint, previousPublishedContent, runningContentExperiment, storedContent } from '../db/appends.js';
6
9
  import { txExecutor } from '../db/executor.js';
7
10
  import { pageContentBindings } from '../db/pageBindings.js';
8
11
  import { sortLockKeys } from '../db/locks.js';
9
12
  import { normalisePath } from '../runtime/normalisePath.js';
10
13
  import { comparableContent } from '../transitions/pageVersions.js';
11
- import { documentEditor, puckCollections } from '../options.js';
14
+ import { puckCollections } from '../options.js';
12
15
  import { withTransition } from '../transitions/kernel.js';
13
16
  import { normaliseContentRelationships } from './normaliseContentRelationships.js';
14
17
  const slots = [
@@ -39,7 +42,7 @@ function bindings(data, puck) {
39
42
  if (!object(value) || visibility?.get(value)?.hidden) return;
40
43
  if (puck && value.type === 'ExperimentSlot' && object(value.props)) {
41
44
  const props = value.props;
42
- const slug = typeof props.experiment === 'string' ? props.experiment : object(props.experiment) ? props.experiment.slug : undefined;
45
+ const slug = puckExperimentSlug(props.experiment);
43
46
  if (typeof slug === 'string' && slug) add('slug', slug, {
44
47
  id: props.id,
45
48
  ...Object.fromEntries(slots.map((slot)=>[
@@ -79,11 +82,17 @@ const baselineKey = (collection, id)=>`${collection}:${id}`;
79
82
  doc: audit.result
80
83
  };
81
84
  }
82
- /** Publish-only host helper. Audit failures are logged, never thrown into saves. */ export async function recordContentChange(args) {
85
+ /** Publish-only host helper. Audit failures are logged after savepoint recovery. */ export async function recordContentChange(args) {
83
86
  try {
84
87
  await auditContentChange(args);
85
88
  } catch (error) {
86
- console.error('[payload-experiments] contentChanges failed; the document was saved without it', safeError(error));
89
+ try {
90
+ // The isolation check already logged the reason once for this transaction.
91
+ if (error instanceof XpTransactionIsolationError) return;
92
+ } catch {}
93
+ try {
94
+ console.error('[payload-experiments] contentChanges failed; the document was saved without it', safeError(error));
95
+ } catch {}
87
96
  }
88
97
  }
89
98
  async function auditContentChange({ doc, previousDoc, req, collection }) {
@@ -104,9 +113,10 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
104
113
  }
105
114
  const options = req.payload.config.custom?.xp;
106
115
  const registration = puckCollections(options ?? {}).find((entry)=>entry.slug === collection.slug);
107
- const changes = (previous, current)=>{
108
- const after = bindings(registration && object(current) ? current[registration.field] : current, Boolean(registration) && documentEditor(options ?? {}, collection.slug, object(current) ? current : {}) === 'puck');
109
- const before = bindings(registration && object(previous) ? previous[registration.field] : previous, Boolean(registration) && documentEditor(options ?? {}, collection.slug, object(previous) ? previous : {}) === 'puck');
116
+ const reader = placementReader(req, collection.slug, options ?? {});
117
+ const changesOne = (previous, current)=>{
118
+ const after = bindings(registration && object(current) ? current[registration.field] : current, Boolean(registration) && reader.read(object(current) ? current : undefined, 'localized').editor === 'puck');
119
+ const before = bindings(registration && object(previous) ? previous[registration.field] : previous, Boolean(registration) && reader.read(object(previous) ? previous : undefined, 'localized').editor === 'puck');
110
120
  const blockRegistration = options?.blocks?.collections.find((entry)=>entry.slug === collection.slug);
111
121
  for (const [row, found] of [
112
122
  [
@@ -118,7 +128,7 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
118
128
  after
119
129
  ]
120
130
  ]){
121
- if (!blockRegistration || !object(row) || documentEditor(options ?? {}, collection.slug, row) !== 'blocks') continue;
131
+ if (!blockRegistration || !object(row) || reader.read(row, 'localized').editor !== 'blocks') continue;
122
132
  for (const block of hostBlocks(row[blockRegistration.field])){
123
133
  if (block.blockType !== (blockRegistration.blockSlug ?? EXPERIMENT_BLOCK_SLUG) || typeof block.experiment !== 'string') continue;
124
134
  const key = 'slug:' + block.experiment;
@@ -138,6 +148,9 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
138
148
  ])
139
149
  ].filter((key)=>!isDeepStrictEqual(before.get(key)?.contents, after.get(key)?.contents)).map((key)=>after.get(key) ?? before.get(key));
140
150
  };
151
+ const changes = (previous, current, input)=>(input === 'all-locales' ? reader.documentViews : [
152
+ undefined
153
+ ]).flatMap((view)=>changesOne(reader.read(object(previous) ? previous : undefined, input, view).doc, reader.read(object(current) ? current : undefined, input, view).doc));
141
154
  // Include discovery reads in the savepoint: a SQL read error also aborts Postgres.
142
155
  // An explicit host call must supply its afterChange request's transaction.
143
156
  const executor = txExecutor(req);
@@ -154,11 +167,11 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
154
167
  if (!current) throw new Error('The saved content row was not found.');
155
168
  beforeRow = baseline.doc;
156
169
  afterRow = current;
157
- changed = changes(beforeRow, afterRow);
170
+ changed = changes(beforeRow, afterRow, 'all-locales');
158
171
  } else {
159
172
  beforeRow = normalise(previousDoc);
160
173
  afterRow = normalise(doc);
161
- changed = changes(beforeRow, afterRow);
174
+ changed = changes(beforeRow, afterRow, 'localized');
162
175
  }
163
176
  const experiments = new Map();
164
177
  for (const binding of changed){
@@ -166,17 +179,26 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
166
179
  if (experiment) experiments.set(String(experiment.id), experiment.id);
167
180
  }
168
181
  const page = options?.pages?.collections.find((entry)=>entry.slug === collection.slug);
169
- if (page?.contentOf && !isDeepStrictEqual(comparableContent(object(beforeRow) ? page.contentOf(beforeRow) : undefined), comparableContent(object(afterRow) ? page.contentOf(afterRow) : undefined))) {
170
- const paths = [
171
- beforeRow,
172
- afterRow
173
- ].flatMap((row)=>{
174
- const path = object(row) ? page.pathOf(row) : null;
175
- return path === null ? [] : [
176
- normalisePath(path)
177
- ];
178
- });
179
- for (const id of (await pageContentBindings(executor, collection.slug, paths)))experiments.set(String(id), id);
182
+ if (page?.contentOf) {
183
+ const input = baseline || req.locale === 'all' ? 'all-locales' : 'localized';
184
+ const paths = new Set();
185
+ for (const view of input === 'all-locales' ? reader.documentViews : [
186
+ undefined
187
+ ]){
188
+ const before = reader.read(object(beforeRow) ? beforeRow : undefined, input, view).doc;
189
+ const after = reader.read(object(afterRow) ? afterRow : undefined, input, view).doc;
190
+ if (isDeepStrictEqual(comparableContent(before ? page.contentOf(before) : undefined), comparableContent(after ? page.contentOf(after) : undefined))) continue;
191
+ for (const doc of [
192
+ before,
193
+ after
194
+ ]){
195
+ const path = doc ? page.pathOf(doc) : null;
196
+ if (path !== null) paths.add(normalisePath(path));
197
+ }
198
+ }
199
+ if (paths.size) for (const id of (await pageContentBindings(executor, collection.slug, sortLockKeys([
200
+ ...paths
201
+ ]))))experiments.set(String(id), id);
180
202
  }
181
203
  // Successful audit locks persist until commit; acquire multiple E locks in order.
182
204
  for (const key of sortLockKeys([
@@ -188,6 +210,8 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
188
210
  bump: false,
189
211
  audit: true
190
212
  }, async ({ exec })=>{
213
+ // Keep the recheck and append on the executor. A failed nested Local API
214
+ // call would kill the host transaction before the savepoint could recover.
191
215
  const experiment = await runningContentExperiment(exec, {
192
216
  field: 'id',
193
217
  value: experimentId
@@ -1,5 +1,5 @@
1
1
  import { BLOCK_SLOTS, EXPERIMENT_BLOCK_SLUG, hostBlocks, slotBlocks } from '../blocks/model.js';
2
- import { manifestOf, suppressExposure } from './context.js';
2
+ import { suppressExposure } from './context.js';
3
3
  export function resolveExperimentBlocks(blocks, assignments, { blockSlug = EXPERIMENT_BLOCK_SLUG } = {}) {
4
4
  const result = {
5
5
  blocks: [],
@@ -18,10 +18,8 @@ export function resolveExperimentBlocks(blocks, assignments, { blockSlug = EXPER
18
18
  }
19
19
  const slug = typeof block.experiment === 'string' ? block.experiment : '';
20
20
  const assignment = Object.hasOwn(assignments.bySlug, slug) ? assignments.bySlug[slug] : undefined;
21
- const experiment = manifestOf(assignments)?.experiments.find((e)=>e.slug === slug);
22
- const arm = experiment?.arms.find((a)=>a.key === assignment?.arm);
23
21
  const archived = Object.hasOwn(assignments.archivedWinners, slug) ? assignments.archivedWinners[slug] : undefined;
24
- const slot = assignment ? assignment.arm === 'holdout' ? 'control' : arm?.slot ?? assignment.arm : archived ?? 'control';
22
+ const slot = assignment ? assignment.arm === 'holdout' ? 'control' : assignment.arm : archived ?? 'control';
25
23
  const selected = BLOCK_SLOTS.includes(slot) ? slotBlocks(block, slot) : [];
26
24
  const content = selected.length ? selected : slotBlocks(block, 'control');
27
25
  const group = {
@@ -1,5 +1,6 @@
1
+ import { puckExperimentSlug } from '../puck/experimentSlug.js';
1
2
  import { puckVisibility } from '../puck/visibility.js';
2
- import { manifestOf, suppressExposure } from './context.js';
3
+ import { suppressExposure } from './context.js';
3
4
  export function resolveExperimentData(puckData, assignments) {
4
5
  const visibility = puckVisibility(puckData);
5
6
  const rendered = new Map();
@@ -9,7 +10,6 @@ export function resolveExperimentData(puckData, assignments) {
9
10
  'variantB',
10
11
  'variantC'
11
12
  ];
12
- const manifest = manifestOf(assignments);
13
13
  function walk(value) {
14
14
  if (Array.isArray(value)) return value.map(walk).filter((item)=>item !== undefined);
15
15
  if (!value || typeof value !== 'object') return value;
@@ -27,13 +27,10 @@ export function resolveExperimentData(puckData, assignments) {
27
27
  delete clean.xpSlot;
28
28
  delete clean.xpArm;
29
29
  delete clean.xpExpose;
30
- const ref = props.experiment;
31
- const slug = typeof ref?.slug === 'string' ? ref.slug : undefined;
30
+ const slug = puckExperimentSlug(props.experiment);
32
31
  const assignment = slug && Object.hasOwn(assignments.bySlug, slug) ? assignments.bySlug[slug] : undefined;
33
- const experiment = manifest?.experiments.find((e)=>e.slug === slug);
34
- const arm = experiment?.arms.find((a)=>a.key === assignment?.arm);
35
32
  const archived = slug && Object.hasOwn(assignments.archivedWinners, slug) ? assignments.archivedWinners[slug] : undefined;
36
- const selected = assignment ? assignment.arm === 'holdout' ? 'control' : arm?.slot ?? assignment.arm : archived ?? 'control';
33
+ const selected = assignment ? assignment.arm === 'holdout' ? 'control' : assignment.arm : archived ?? 'control';
37
34
  const slot = slots.includes(selected) ? selected : 'control';
38
35
  clean.xpSlot = slot;
39
36
  if (assignment) {