@delmaredigital/payload-experiments 0.5.0 → 0.5.2

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 (39) hide show
  1. package/dist/admin/PlacementStatus.js +5 -3
  2. package/dist/blocks/placementLocale.d.ts +14 -0
  3. package/dist/blocks/placementLocale.js +80 -13
  4. package/dist/blocks/placementPublication.d.ts +18 -0
  5. package/dist/blocks/placementPublication.js +31 -0
  6. package/dist/db/adapter.d.ts +1 -0
  7. package/dist/db/adapter.js +3 -0
  8. package/dist/db/appends.d.ts +2 -1
  9. package/dist/db/appends.js +2 -1
  10. package/dist/db/bulkPlacementRemoval.d.ts +5 -0
  11. package/dist/db/bulkPlacementRemoval.js +7 -2
  12. package/dist/db/pageBindings.d.ts +2 -2
  13. package/dist/db/pageBindings.js +3 -3
  14. package/dist/db/pageContent.d.ts +2 -0
  15. package/dist/db/pageContent.js +35 -17
  16. package/dist/db/placements.d.ts +6 -1
  17. package/dist/db/placements.js +26 -0
  18. package/dist/endpoints/duplicateOriginal.d.ts +1 -0
  19. package/dist/endpoints/pages.js +32 -15
  20. package/dist/endpoints/placementStatus.js +52 -8
  21. package/dist/hooks/blockRemovalRule.d.ts +1 -1
  22. package/dist/hooks/blockRemovalRule.js +5 -4
  23. package/dist/hooks/pageGuard.d.ts +7 -1
  24. package/dist/hooks/pageGuard.js +176 -3
  25. package/dist/hooks/puckNestedTests.d.ts +1 -1
  26. package/dist/hooks/puckNestedTests.js +3 -1
  27. package/dist/onInit.js +0 -5
  28. package/dist/server/recordContentChange.d.ts +1 -1
  29. package/dist/server/recordContentChange.js +42 -20
  30. package/dist/testSurface/api.js +1 -1
  31. package/dist/transitions/decide.js +5 -2
  32. package/dist/transitions/pageAddress.js +42 -4
  33. package/dist/transitions/placementInteractions.d.ts +7 -2
  34. package/dist/transitions/placementInteractions.js +8 -6
  35. package/dist/transitions/placements.d.ts +4 -3
  36. package/dist/transitions/placements.js +28 -14
  37. package/dist/transitions/start.js +3 -1
  38. package/dist/types/endpoints.d.ts +2 -0
  39. package/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import { placementReader } from '../blocks/placementLocale.js';
2
+ import { publishedInLocale, usesLocalizedPublication } from '../blocks/placementPublication.js';
2
3
  import { puckExperimentSlug } from '../puck/experimentSlug.js';
3
4
  import { puckVisibility } from '../puck/visibility.js';
4
5
  import { EXPERIMENT_BLOCK_SLUG, hostBlocks } from '../blocks/model.js';
@@ -9,6 +10,7 @@ import { appendContentChange, contentChangeSavepoint, previousPublishedContent,
9
10
  import { txExecutor } from '../db/executor.js';
10
11
  import { pageContentBindings } from '../db/pageBindings.js';
11
12
  import { sortLockKeys } from '../db/locks.js';
13
+ import { writesAllPublicationLocales } from '../hooks/pageGuard.js';
12
14
  import { normalisePath } from '../runtime/normalisePath.js';
13
15
  import { comparableContent } from '../transitions/pageVersions.js';
14
16
  import { puckCollections } from '../options.js';
@@ -65,7 +67,7 @@ function bindings(data, puck) {
65
67
  return found;
66
68
  }
67
69
  const baselineKey = (collection, id)=>`${collection}:${id}`;
68
- /** Paired raw beforeChange capture: previousDoc may be an autosaved draft. */ export async function capturePublishedContent({ req, collection, originalDoc, operation }) {
70
+ /** Paired raw beforeChange capture: previousDoc may be an autosaved draft. */ export async function capturePublishedContent({ req, collection, originalDoc, operation, data }) {
69
71
  if (await req.transactionID == null) {
70
72
  req.payload.logger?.debug('[payload-experiments] contentChanges baseline skipped without a transaction');
71
73
  return;
@@ -76,10 +78,14 @@ const baselineKey = (collection, id)=>`${collection}:${id}`;
76
78
  delete baselines[key];
77
79
  const audit = await contentChangeSavepoint(txExecutor(req), async ()=>operation === 'create' ? undefined : collection.versions && collection.versions.drafts ? previousPublishedContent(req, collection.slug, id) : storedContent(req, collection.slug, id));
78
80
  if (!audit.ok) throw audit.error;
81
+ // Payload 3 passes the original status map to beforeChange on Publish All,
82
+ // including on host collections that install the audit without the guard.
83
+ const publishAllLocales = data?._status === 'published' && object(originalDoc?._status);
79
84
  baselines[key] = {
80
85
  collection: collection.slug,
81
86
  id,
82
- doc: audit.result
87
+ doc: audit.result,
88
+ publishAllLocales
83
89
  };
84
90
  }
85
91
  /** Publish-only host helper. Audit failures are logged after savepoint recovery. */ export async function recordContentChange(args) {
@@ -97,14 +103,19 @@ const baselineKey = (collection, id)=>`${collection}:${id}`;
97
103
  }
98
104
  async function auditContentChange({ doc, previousDoc, req, collection }) {
99
105
  const drafts = Boolean(collection.versions && collection.versions.drafts);
100
- if (drafts && doc._status !== 'published') return;
106
+ const localizedStatus = usesLocalizedPublication(req, collection.slug, collection);
107
+ const statusMap = localizedStatus && object(doc._status);
108
+ const baselines = req.context.xpPublishedContent;
109
+ const creating = previousDoc?.id == null;
110
+ const key = baselineKey(collection.slug, creating ? '__create__' : doc.id);
111
+ const baseline = baselines?.[key];
112
+ // Restore can supply the raw previous version alongside a projected result.
113
+ const allLocales = localizedStatus && (statusMap || req.locale === 'all' || baseline?.publishAllLocales || object(previousDoc?._status) || creating && doc._status === 'published' || writesAllPublicationLocales(req, collection.slug));
114
+ if (drafts && !allLocales && doc._status !== 'published') return;
101
115
  if (await req.transactionID == null) {
102
116
  req.payload.logger?.debug('[payload-experiments] contentChanges skipped without a transaction');
103
117
  return;
104
118
  }
105
- const baselines = req.context.xpPublishedContent;
106
- const key = baselineKey(collection.slug, previousDoc?.id == null ? '__create__' : doc.id);
107
- const baseline = baselines?.[key];
108
119
  if (baselines) delete baselines[key];
109
120
  // Missing capture must never turn an unchanged publish into a false marker.
110
121
  if (drafts && !baseline) {
@@ -148,9 +159,6 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
148
159
  ])
149
160
  ].filter((key)=>!isDeepStrictEqual(before.get(key)?.contents, after.get(key)?.contents)).map((key)=>after.get(key) ?? before.get(key));
150
161
  };
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));
154
162
  // Include discovery reads in the savepoint: a SQL read error also aborts Postgres.
155
163
  // An explicit host call must supply its afterChange request's transaction.
156
164
  const executor = txExecutor(req);
@@ -158,23 +166,41 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
158
166
  // Compare like with like. A captured baseline is adapter-raw, so it meets the stored row after the
159
167
  // write. Without one, previousDoc and doc are both afterRead documents (same locale projection,
160
168
  // hidden fields and field hooks) that differ only in depth, so only relationships are normalised.
161
- const locales = req.payload.config.localization ? req.payload.config.localization.localeCodes : [];
169
+ const localization = req.payload.config.localization;
170
+ const locales = localization ? localization.localeCodes : [];
162
171
  const normalise = (value)=>normaliseContentRelationships(value, collection.fields, req.payload.config.blocks, locales);
163
- let changed;
164
172
  let beforeRow, afterRow;
165
173
  if (baseline) {
166
174
  const current = await storedContent(req, collection.slug, doc.id);
167
175
  if (!current) throw new Error('The saved content row was not found.');
168
176
  beforeRow = baseline.doc;
169
177
  afterRow = current;
170
- changed = changes(beforeRow, afterRow, 'all-locales');
171
178
  } else {
172
179
  beforeRow = normalise(previousDoc);
173
180
  afterRow = normalise(doc);
174
- changed = changes(beforeRow, afterRow, 'localized');
175
181
  }
182
+ const previous = object(beforeRow) ? beforeRow : undefined;
183
+ const current = object(afterRow) ? afterRow : undefined;
184
+ const locale = req.locale || (localization ? localization.defaultLocale : '');
185
+ const contentViews = (input)=>{
186
+ const views = input === 'all-locales' ? reader.documentViews : [
187
+ undefined
188
+ ];
189
+ return views.flatMap((view)=>{
190
+ // Draft versions can carry published statuses for untouched locales.
191
+ // Compare the main row and only the views this save can publish.
192
+ if (localizedStatus && view && (!allLocales && view.locale !== locale || statusMap && !publishedInLocale(doc, view.locale) || !publishedInLocale(current, view.locale))) return [];
193
+ const before = localizedStatus && view && !publishedInLocale(previous, view.locale) ? undefined : previous;
194
+ return [
195
+ [
196
+ reader.read(before, input, view).doc,
197
+ reader.read(current, input, view).doc
198
+ ]
199
+ ];
200
+ });
201
+ };
176
202
  const experiments = new Map();
177
- for (const binding of changed){
203
+ for (const binding of contentViews(baseline ? 'all-locales' : 'localized').flatMap(([before, after])=>changesOne(before, after))){
178
204
  const experiment = await runningContentExperiment(executor, binding);
179
205
  if (experiment) experiments.set(String(experiment.id), experiment.id);
180
206
  }
@@ -182,11 +208,7 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
182
208
  if (page?.contentOf) {
183
209
  const input = baseline || req.locale === 'all' ? 'all-locales' : 'localized';
184
210
  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;
211
+ for (const [before, after] of contentViews(input)){
190
212
  if (isDeepStrictEqual(comparableContent(before ? page.contentOf(before) : undefined), comparableContent(after ? page.contentOf(after) : undefined))) continue;
191
213
  for (const doc of [
192
214
  before,
@@ -198,7 +220,7 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
198
220
  }
199
221
  if (paths.size) for (const id of (await pageContentBindings(executor, collection.slug, sortLockKeys([
200
222
  ...paths
201
- ]))))experiments.set(String(id), id);
223
+ ]), localizedStatus)))experiments.set(String(id), id);
202
224
  }
203
225
  // Successful audit locks persist until commit; acquire multiple E locks in order.
204
226
  for (const key of sortLockKeys([
@@ -119,7 +119,7 @@ export function createApi(apiBase, contentLocale) {
119
119
  ...plan,
120
120
  arm
121
121
  }, undefined, undefined, plan.updatedAt),
122
- placementStatus: (body)=>request(()=>`${apiBase.replace(/\/$/, '')}/xp/placements/status`, 'POST', body),
122
+ placementStatus: (body)=>request(()=>contentLocaleURL(`${apiBase.replace(/\/$/, '')}/xp/placements/status`, contentLocale), 'POST', body),
123
123
  start: (id, phase)=>post(id, 'start', phase === undefined ? undefined : {
124
124
  phase
125
125
  }, {
@@ -18,7 +18,10 @@ import { requireStarted } from './scheduledRound.js';
18
18
  export async function decide(req, { experimentId, winnerArm, note, confirmation, phase: expectedPhase }) {
19
19
  const before = await readExperiment(req, experimentId);
20
20
  const options = req.payload.config.custom?.xp;
21
- const placements = before.status === 'stopped' && before.kind === 'block' ? await detached(req, ()=>scanPlacements(req, options, before.slug)) : [];
21
+ const placementScan = {
22
+ publishedOnly: 'localized'
23
+ };
24
+ const placements = before.status === 'stopped' && before.kind === 'block' ? await detached(req, ()=>scanPlacements(req, options, before.slug, placementScan)) : [];
22
25
  const { result: doc, revision } = await withTransition(req, {
23
26
  experimentId,
24
27
  layerId: relationshipId(before.layer),
@@ -64,7 +67,7 @@ export async function decide(req, { experimentId, winnerArm, note, confirmation,
64
67
  const rescan = await lockAndRescanPlacements(req, exec, options, {
65
68
  ...current,
66
69
  arms: test.arms
67
- }, placements);
70
+ }, placements, placementScan);
68
71
  if (rescan.placements.length === 0) refuse('placement-removed');
69
72
  await refreshPlacementDocs(exec, experimentId, test.phase, rescan.docs);
70
73
  }
@@ -1,5 +1,7 @@
1
1
  import { flattenTopLevelFields } from 'payload/shared';
2
2
  import { placementReader } from '../blocks/placementLocale.js';
3
+ import { pagePublicationStatus, publicationLocale, usesLocalizedPublication } from '../blocks/placementPublication.js';
4
+ import { hasPublishedPageVersion } from '../db/pageContent.js';
3
5
  import { normalisePath } from '../runtime/normalisePath.js';
4
6
  export const PAGE_ADDRESS_FIELDS = [
5
7
  'path',
@@ -40,15 +42,18 @@ export const PAGE_ADDRESS_FIELDS = [
40
42
  ] : [];
41
43
  });
42
44
  if (!filters.length) return undefined;
45
+ const locale = usesLocalizedPublication(req, entry.slug, config) ? publicationLocale(req) : undefined;
43
46
  const result = await req.payload.find({
44
47
  collection: entry.slug,
45
48
  req,
46
49
  overrideAccess: false,
47
50
  depth: 0,
48
- draft: false,
51
+ draft: Boolean(locale),
49
52
  pagination: false,
50
53
  limit: 20,
51
- where: {
54
+ where: locale ? {
55
+ or: filters
56
+ } : {
52
57
  and: [
53
58
  {
54
59
  _status: {
@@ -63,9 +68,42 @@ export const PAGE_ADDRESS_FIELDS = [
63
68
  });
64
69
  const reader = placementReader(req, entry.slug);
65
70
  const input = req.locale === 'all' ? 'all-locales' : 'localized';
66
- const candidates = result.docs.filter((row)=>{
71
+ const matchesPath = (row)=>{
67
72
  const address = entry.pathOf(reader.read(row, input).doc);
68
73
  return address !== null && normalisePath(address) === key;
69
- });
74
+ };
75
+ const candidates = result.docs.filter(matchesPath);
76
+ if (locale) {
77
+ const main = await req.payload.find({
78
+ collection: entry.slug,
79
+ req,
80
+ overrideAccess: false,
81
+ depth: 0,
82
+ draft: false,
83
+ pagination: false,
84
+ limit: 40,
85
+ where: {
86
+ or: [
87
+ ...filters,
88
+ {
89
+ id: {
90
+ in: candidates.map((row)=>row.id)
91
+ }
92
+ }
93
+ ]
94
+ }
95
+ });
96
+ const draftById = new Map(candidates.map((row)=>[
97
+ String(row.id),
98
+ row
99
+ ]));
100
+ const eligible = await Promise.all(main.docs.map(async (row)=>{
101
+ if (pagePublicationStatus(row, locale) === 'published') return undefined;
102
+ if (await hasPublishedPageVersion(req, entry.slug, row.id, locale)) return matchesPath(row) ? row : undefined;
103
+ return draftById.get(String(row.id));
104
+ }));
105
+ const matched = eligible.filter((row)=>row !== undefined);
106
+ return matched.length === 1 ? matched[0] : undefined;
107
+ }
70
108
  return candidates.length === 1 ? candidates[0] : undefined;
71
109
  }
@@ -5,9 +5,13 @@ import { type PlacementDoc } from '../db/placements.js';
5
5
  import { type BlockPlacement } from './placements.js';
6
6
  export declare function detached<T>(req: PayloadRequest, fn: () => Promise<T>): Promise<T>;
7
7
  export declare function uniquePlacementDocs(placements: readonly Pick<BlockPlacement, 'collection' | 'id'>[]): PlacementDoc[];
8
+ type PlacementScanOptions = {
9
+ system?: boolean;
10
+ publishedOnly?: 'localized';
11
+ };
8
12
  export declare function scanPlacements<TUser extends {
9
13
  id: DocId;
10
- }>(req: PayloadRequest, options: ResolvedOptions<TUser>, slug: string, system?: boolean): Promise<BlockPlacement[]>;
14
+ }>(req: PayloadRequest, options: ResolvedOptions<TUser>, slug: string, scan?: PlacementScanOptions): Promise<BlockPlacement[]>;
11
15
  export declare function placementPaths<TUser extends {
12
16
  id: DocId;
13
17
  }>(req: PayloadRequest, options: ResolvedOptions<TUser>, docs: readonly PlacementDoc[]): Promise<string[]>;
@@ -34,7 +38,8 @@ export declare function lockAndRescanPlacements<TUser extends {
34
38
  slug: string;
35
39
  kind: string;
36
40
  arms: Arm[];
37
- }, before: readonly BlockPlacement[], system?: boolean): Promise<{
41
+ }, before: readonly BlockPlacement[], scan?: PlacementScanOptions): Promise<{
38
42
  placements: BlockPlacement[];
39
43
  docs: PlacementDoc[];
40
44
  }>;
45
+ export {};
@@ -30,12 +30,12 @@ export function uniquePlacementDocs(placements) {
30
30
  ])).values()
31
31
  ];
32
32
  }
33
- export function scanPlacements(req, options, slug, system = false) {
33
+ export function scanPlacements(req, options, slug, scan) {
34
34
  return scanBlockPlacements(req, {
35
35
  slug,
36
36
  puckCollections: options.puck?.collections ?? [],
37
37
  blocksCollections: options.blocks?.collections ?? [],
38
- system
38
+ ...scan
39
39
  });
40
40
  }
41
41
  export async function placementPaths(req, options, docs) {
@@ -68,7 +68,9 @@ export async function placementInteractions(req, exec, options, experiment, path
68
68
  version: test.arms.some((a)=>a.kind === 'variant' && a.pageTarget && normalisePath(a.pageTarget) === path)
69
69
  });
70
70
  } else if (experiment.kind === 'page' && test.kind === 'block') {
71
- const docs = test.placementDocs ?? uniquePlacementDocs(await detached(req, ()=>scanPlacements(req, options, test.slug, system)));
71
+ const docs = test.placementDocs ?? uniquePlacementDocs(await detached(req, ()=>scanPlacements(req, options, test.slug, {
72
+ system
73
+ })));
72
74
  const relevant = docs.filter((doc)=>!experiment.pageCollection || doc.collection === experiment.pageCollection);
73
75
  for (const path of (await placementPaths(req, options, relevant)).filter((path)=>paths.includes(path)))result.push({
74
76
  experimentId: test.id,
@@ -82,14 +84,14 @@ export async function placementInteractions(req, exec, options, experiment, path
82
84
  }
83
85
  return result;
84
86
  }
85
- export async function lockAndRescanPlacements(req, exec, options, experiment, before, system = false) {
87
+ export async function lockAndRescanPlacements(req, exec, options, experiment, before, scan) {
86
88
  const paths = await placementPaths(req, options, uniquePlacementDocs(before));
87
89
  await lockPagePaths(exec, paths);
88
- const placements = await detached(req, ()=>scanPlacements(req, options, experiment.slug, system));
90
+ const placements = await detached(req, ()=>scanPlacements(req, options, experiment.slug, scan));
89
91
  const docs = uniquePlacementDocs(placements);
90
92
  const afterPaths = await placementPaths(req, options, docs);
91
93
  if (afterPaths.some((path)=>!paths.includes(path))) throw new XpRefusal('placements-changed', "This test's pages changed while it was starting. Try again.", undefined, 409);
92
- const conflicts = await placementInteractions(req, exec, options, experiment, paths, system);
94
+ const conflicts = await placementInteractions(req, exec, options, experiment, paths, scan?.system);
93
95
  if (conflicts.length) throw new XpRefusal('interacting-tests', interactingTestsCopy(conflicts[0].path, conflicts[0].status, conflicts[0].name, conflicts[0].version), conflicts, 409);
94
96
  return {
95
97
  placements,
@@ -2,6 +2,7 @@ import type { PayloadRequest } from 'payload';
2
2
  import type { Arm, DocId, FlagPoint, PreviewPlacement, ResolvedOptions } from '../types/contracts.js';
3
3
  import type { ArmSlot } from '../types/puck.js';
4
4
  import { type PlacementLocaleView } from '../blocks/placementLocale.js';
5
+ import type { BulkPlacementRemoval } from '../db/bulkPlacementRemoval.js';
5
6
  export interface BlockPlacement extends PreviewPlacement {
6
7
  nestedTests?: Array<{
7
8
  outer: string;
@@ -35,8 +36,8 @@ interface ScanOptions {
35
36
  puckCollections: NonNullable<ResolvedOptions['puck']>['collections'];
36
37
  blocksCollections: NonNullable<ResolvedOptions['blocks']>['collections'];
37
38
  compareVersions?: boolean;
38
- /** Read the current visitor surface without fetching newer unpublished drafts. */
39
- publishedOnly?: boolean;
39
+ /** Read the visitor surface, optionally keeping legacy draft discovery for scalar collections. */
40
+ publishedOnly?: boolean | 'localized';
40
41
  /** Hooks and manager-authorized visitor-impact reads must see every placement (CORE-21). */
41
42
  pageGuard?: true;
42
43
  /** Trusted server-side Start checks placements without a manager actor. */
@@ -48,7 +49,7 @@ interface ScanOptions {
48
49
  */
49
50
  export declare function hasOtherPublishedBlockPlacement(req: PayloadRequest, options: ResolvedOptions, slug: string, excluded: (collection: string, id: DocId, view: PlacementLocaleView, doc: Record<string, unknown> & {
50
51
  id: DocId;
51
- }) => boolean): Promise<boolean>;
52
+ }) => boolean, bulk?: BulkPlacementRemoval): Promise<boolean>;
52
53
  interface PublishedBlockPlacement {
53
54
  id: DocId;
54
55
  editor: 'puck' | 'blocks';
@@ -10,6 +10,8 @@ import { isDeepStrictEqual } from 'node:util';
10
10
  import { hasLocalizedFields } from './contentFields.js';
11
11
  import { localeRequest, placementReader } from '../blocks/placementLocale.js';
12
12
  import { puckCollections as normalisePuckCollections } from '../options.js';
13
+ import { publishedInLocale, usesLocalizedPublication } from '../blocks/placementPublication.js';
14
+ import { storedPlacementStatuses } from '../db/placements.js';
13
15
  const slots = [
14
16
  'control',
15
17
  'variantA',
@@ -18,6 +20,8 @@ const slots = [
18
20
  ];
19
21
  async function placementDocuments(req, query, readAll) {
20
22
  // §7.8: page guards, visitor impact and system Start need all placements to check the visitor surface.
23
+ // For draft:false, the adapter hydrates _status from the main locale rows
24
+ // alongside the localized fields. Draft versions are read separately.
21
25
  if (readAll) return req.payload.find({
22
26
  ...query,
23
27
  req,
@@ -46,7 +50,7 @@ function changedDocuments(docs, change, collection, draft, page, draftsEnabled)
46
50
  }
47
51
  /** Published rows only, one pass per collection across both editor registrations.
48
52
  * The exclusion predicate reads live transaction claims after each awaited page.
49
- */ export async function hasOtherPublishedBlockPlacement(req, options, slug, excluded) {
53
+ */ export async function hasOtherPublishedBlockPlacement(req, options, slug, excluded, bulk) {
50
54
  const scanReq = localeRequest(req, {
51
55
  locale: req.payload.config.localization ? 'all' : req.locale ?? '',
52
56
  fallbackLocale: false
@@ -56,6 +60,7 @@ function changedDocuments(docs, change, collection, draft, page, draftsEnabled)
56
60
  ...(options.blocks?.collections ?? []).map((entry)=>entry.slug)
57
61
  ]);
58
62
  for (const collection of collections){
63
+ const localized = usesLocalizedPublication(req, collection);
59
64
  const drafts = req.payload.config.collections?.some((c)=>c.slug === collection && c.versions && c.versions.drafts);
60
65
  const reader = placementReader(req, collection, options);
61
66
  let page = 1;
@@ -71,7 +76,7 @@ function changedDocuments(docs, change, collection, draft, page, draftsEnabled)
71
76
  locale: 'all',
72
77
  fallbackLocale: false
73
78
  } : {},
74
- ...drafts ? {
79
+ ...drafts && !localized ? {
75
80
  where: {
76
81
  _status: {
77
82
  equals: 'published'
@@ -79,7 +84,10 @@ function changedDocuments(docs, change, collection, draft, page, draftsEnabled)
79
84
  }
80
85
  } : {}
81
86
  }, true);
82
- if (result.docs.some((doc)=>doc._status !== 'draft' && doc.deletedAt == null && reader.views.some((view)=>reader.read(doc, 'all-locales', view).slugs.includes(slug) && !excluded(collection, doc.id, view, doc)))) return true;
87
+ const statuses = localized && bulk?.change?.collection === collection ? await storedPlacementStatuses(req, collection, result.docs.map((doc)=>doc.id)) : undefined;
88
+ if (result.docs.some((doc)=>doc._status !== 'draft' && doc.deletedAt == null && reader.views.some((view)=>reader.isPublished(doc, view) && (!statuses || publishedInLocale({
89
+ _status: statuses.get(String(doc.id))
90
+ }, view.locale)) && reader.read(doc, 'all-locales', view).slugs.includes(slug) && !excluded(collection, doc.id, view, doc)))) return true;
83
91
  if (!result.hasNextPage) break;
84
92
  page++;
85
93
  }
@@ -98,6 +106,7 @@ function changedDocuments(docs, change, collection, draft, page, draftsEnabled)
98
106
  ...puck,
99
107
  ...blocks
100
108
  ].map((entry)=>entry.slug))){
109
+ const localized = usesLocalizedPublication(req, collection);
101
110
  const drafts = req.payload.config.collections?.some((c)=>c.slug === collection && c.versions && c.versions.drafts);
102
111
  const reader = placementReader(req, collection, options);
103
112
  let page = 1;
@@ -114,7 +123,7 @@ function changedDocuments(docs, change, collection, draft, page, draftsEnabled)
114
123
  locale: 'all',
115
124
  fallbackLocale: false
116
125
  } : {},
117
- ...drafts ? {
126
+ ...drafts && !localized ? {
118
127
  where: {
119
128
  _status: {
120
129
  equals: 'published'
@@ -127,6 +136,7 @@ function changedDocuments(docs, change, collection, draft, page, draftsEnabled)
127
136
  for (const raw of result.docs){
128
137
  if (raw._status === 'draft' || raw.deletedAt != null) continue;
129
138
  for (const view of reader.views){
139
+ if (!reader.isPublished(raw, view)) continue;
130
140
  const placement = reader.read(raw, 'all-locales', view);
131
141
  const doc = placement.doc;
132
142
  const add = (contents, editor)=>placements.push({
@@ -204,6 +214,7 @@ export async function scanBlockPlacements(req, args) {
204
214
  collections: puckCollections
205
215
  }
206
216
  })){
217
+ const localizedStatus = usesLocalizedPublication(req, collection);
207
218
  const reader = placementReader(req, collection, {
208
219
  puck: {
209
220
  enabled: true,
@@ -217,7 +228,8 @@ export async function scanBlockPlacements(req, args) {
217
228
  const publishedIds = new Set();
218
229
  const publishedSlugs = new Map();
219
230
  const draftsEnabled = req.payload.config.collections?.some((config)=>config.slug === collection && config.versions && config.versions.drafts);
220
- for (const draft of args.publishedOnly ? [
231
+ const publishedOnly = args.publishedOnly === true || args.publishedOnly === 'localized' && localizedStatus;
232
+ for (const draft of publishedOnly ? [
221
233
  false
222
234
  ] : [
223
235
  false,
@@ -238,7 +250,7 @@ export async function scanBlockPlacements(req, args) {
238
250
  locale: 'all',
239
251
  fallbackLocale: false
240
252
  } : {},
241
- ...!draft && draftsEnabled ? {
253
+ ...!draft && draftsEnabled && !localizedStatus ? {
242
254
  where: {
243
255
  _status: {
244
256
  equals: 'published'
@@ -252,8 +264,8 @@ export async function scanBlockPlacements(req, args) {
252
264
  String(doc.id),
253
265
  view.locale
254
266
  ]);
255
- if (!draft && doc._status === 'draft') continue;
256
- if (draft && doc._status !== 'draft' && publishedIds.has(documentKey)) continue;
267
+ if (!draft && (doc._status === 'draft' || !reader.isPublished(localized, view))) continue;
268
+ if (draft && (localizedStatus ? reader.isPublished(localized, view) : doc._status !== 'draft') && publishedIds.has(documentKey)) continue;
257
269
  if (!draft) {
258
270
  editors.set(documentKey, reader.read(doc, 'localized').editor);
259
271
  publishedIds.add(documentKey);
@@ -299,7 +311,7 @@ export async function scanBlockPlacements(req, args) {
299
311
  locale: view.locale
300
312
  } : {},
301
313
  title: String(doc.title ?? doc.name ?? doc.id),
302
- published: !draft || doc._status === 'published',
314
+ published: !draft || !localizedStatus && doc._status === 'published',
303
315
  ...publishedSlugs.has(documentKey) ? {
304
316
  slug: publishedSlugs.get(documentKey)
305
317
  } : {},
@@ -343,6 +355,7 @@ export async function scanBlockPlacements(req, args) {
343
355
  }
344
356
  for (const registration of args.blocksCollections){
345
357
  const { slug: collection, field } = registration;
358
+ const localizedStatus = usesLocalizedPublication(req, collection);
346
359
  const reader = placementReader(req, collection, {
347
360
  puck: {
348
361
  enabled: true,
@@ -354,7 +367,8 @@ export async function scanBlockPlacements(req, args) {
354
367
  });
355
368
  const published = new Map();
356
369
  const draftsEnabled = req.payload.config.collections?.some((c)=>c.slug === collection && c.versions && c.versions.drafts);
357
- for (const draft of args.publishedOnly ? [
370
+ const publishedOnly = args.publishedOnly === true || args.publishedOnly === 'localized' && localizedStatus;
371
+ for (const draft of publishedOnly ? [
358
372
  false
359
373
  ] : [
360
374
  false,
@@ -375,7 +389,7 @@ export async function scanBlockPlacements(req, args) {
375
389
  locale: 'all',
376
390
  fallbackLocale: false
377
391
  } : {},
378
- ...!draft && draftsEnabled ? {
392
+ ...!draft && draftsEnabled && !localizedStatus ? {
379
393
  where: {
380
394
  _status: {
381
395
  equals: 'published'
@@ -389,9 +403,9 @@ export async function scanBlockPlacements(req, args) {
389
403
  String(doc.id),
390
404
  view.locale
391
405
  ]);
392
- if (!draft && doc._status === 'draft') continue;
406
+ if (!draft && (doc._status === 'draft' || !reader.isPublished(localized, view))) continue;
393
407
  if (!draft) published.set(documentKey, doc);
394
- else if (doc._status !== 'draft' && published.has(documentKey)) continue;
408
+ else if ((localizedStatus ? reader.isPublished(localized, view) : doc._status !== 'draft') && published.has(documentKey)) continue;
395
409
  const baseline = published.get(documentKey) ?? doc;
396
410
  if (reader.read(baseline, 'localized').editor !== 'blocks') continue;
397
411
  const raw = args.compareVersions && !draft && hostBlocks(doc[field]).some((block)=>block.blockType === (registration.blockSlug ?? EXPERIMENT_BLOCK_SLUG) && typeof block.experiment === 'string' && slugs.has(block.experiment)) ? reader.read(await comparison(collection, doc.id), 'all-locales', view).doc : undefined;
@@ -409,7 +423,7 @@ export async function scanBlockPlacements(req, args) {
409
423
  locale: view.locale
410
424
  } : {},
411
425
  title: String(doc.title ?? doc.name ?? doc.id),
412
- published: !draft || doc._status === 'published',
426
+ published: !draft || !localizedStatus && doc._status === 'published',
413
427
  ...typeof baseline.slug === 'string' ? {
414
428
  slug: baseline.slug
415
429
  } : {},
@@ -238,7 +238,9 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
238
238
  const controlLabel = current.arms.find((arm)=>arm.kind === 'control')?.label;
239
239
  let placementDocs;
240
240
  if (current.kind === 'block') {
241
- const rescan = await lockAndRescanPlacements(req, exec, options, current, input.placements ?? [], system);
241
+ const rescan = await lockAndRescanPlacements(req, exec, options, current, input.placements ?? [], {
242
+ system
243
+ });
242
244
  placementDocs = rescan.docs;
243
245
  const failure = checkStart({
244
246
  ...input,
@@ -362,6 +362,8 @@ export type PageTestStatus = {
362
362
  export type PlacementStatusResult = {
363
363
  docs: Record<string, {
364
364
  path: string | null;
365
+ /** With locale=all on a collection with localized status, path is the default locale's entry. */
366
+ pathsByLocale?: Record<string, string | null>;
365
367
  tests: PageTestStatus[];
366
368
  }>;
367
369
  slugs: Record<string, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@delmaredigital/payload-experiments",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "No-code A/B testing for Payload CMS and Next.js: block, page and flag experiments with holdouts, layers, exposure logging and honest statistics inside the admin — no vendor",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -125,7 +125,7 @@
125
125
  "bugs": {
126
126
  "url": "https://github.com/delmaredigital/payload-experiments/issues"
127
127
  },
128
- "homepage": "https://plugins.delmaredigital.com/docs/experiments",
128
+ "homepage": "https://plugins.delmaredigital.com/experiments",
129
129
  "devDependencies": {
130
130
  "@delmaredigital/payload-puck": "0.12.5",
131
131
  "payload": "^3.90.2",