@delmaredigital/payload-experiments 0.5.1 → 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.
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
- import { useConfig, useDocumentInfo } from '@payloadcms/ui';
3
+ import { useConfig, useDocumentInfo, useLocale } from '@payloadcms/ui';
4
4
  import { useEffect, useMemo, useState } from 'react';
5
5
  import { formatAdminURL } from 'payload/shared';
6
6
  import { createApi } from '../testSurface/api.js';
@@ -8,8 +8,10 @@ import { pageStatusCopy } from './placementStatus.model.js';
8
8
  /** Manage-only endpoint: access-filtered editors see no status or error text. */ export function PlacementStatus(_props) {
9
9
  const { id, collectionSlug } = useDocumentInfo();
10
10
  const { config } = useConfig();
11
- const api = useMemo(()=>createApi(config.routes.api), [
12
- config.routes.api
11
+ const locale = useLocale()?.code;
12
+ const api = useMemo(()=>createApi(config.routes.api, locale), [
13
+ config.routes.api,
14
+ locale
13
15
  ]);
14
16
  const [tests, setTests] = useState([]);
15
17
  useEffect(()=>{
@@ -12,3 +12,7 @@ export declare function isPublicationStatus(value: unknown): value is Publicatio
12
12
  export declare function allLocalesStatus(req: PayloadRequest, flags: PublicationFlags | undefined, status: unknown, operation: 'create' | 'update'): PublicationStatus | undefined;
13
13
  export declare function publicationStatusInLocale(doc: Record<string, unknown> | null | undefined, locale: string): PublicationStatus | undefined;
14
14
  export declare function publishedInLocale(doc: Record<string, unknown> | null | undefined, locale: string): boolean;
15
+ /** The locale of a single-document read. All-locale callers can choose an explicit view. */
16
+ export declare function publicationLocale(req: PayloadRequest): string | undefined;
17
+ /** Local API reads can already have projected the status to the selected locale. */
18
+ export declare function pagePublicationStatus(doc: Record<string, unknown> | null | undefined, locale?: string): PublicationStatus | undefined;
@@ -22,3 +22,10 @@ export function publicationStatusInLocale(doc, locale) {
22
22
  export function publishedInLocale(doc, locale) {
23
23
  return publicationStatusInLocale(doc, locale) === 'published';
24
24
  }
25
+ /** The locale of a single-document read. All-locale callers can choose an explicit view. */ export function publicationLocale(req) {
26
+ return req.locale && req.locale !== 'all' ? req.locale : req.payload.config.localization ? req.payload.config.localization.defaultLocale : undefined;
27
+ }
28
+ /** Local API reads can already have projected the status to the selected locale. */ export function pagePublicationStatus(doc, locale) {
29
+ const status = doc?._status;
30
+ return isPublicationStatus(status) ? status : locale ? publicationStatusInLocale(doc, locale) : undefined;
31
+ }
@@ -4,6 +4,8 @@ import type { DocId } from '../types/contracts.js';
4
4
  export declare function pageVersionContent(req: PayloadRequest, collection: string, id: DocId): Promise<(Record<string, unknown> & {
5
5
  id: DocId;
6
6
  }) | null>;
7
+ /** Path selection only, after checking access to the page. Version content is not needed. */
8
+ export declare function hasPublishedPageVersion(req: PayloadRequest, collection: string, id: DocId, locale?: string): Promise<boolean>;
7
9
  /** §7.8: status computes a page's published (or never-published draft) path. */
8
10
  export declare function statusPageContent(req: PayloadRequest, collection: string, id: DocId): Promise<(Record<string, unknown> & {
9
11
  id: DocId;
@@ -1,3 +1,4 @@
1
+ import { pagePublicationStatus, publicationLocale, usesLocalizedPublication } from '../blocks/placementPublication.js';
1
2
  /** §7.8: version-identical compares published content raw (ids stripped). */ export async function pageVersionContent(req, collection, id) {
2
3
  return req.payload.db.findOne({
3
4
  collection,
@@ -11,25 +12,16 @@
11
12
  overrideAccess: true
12
13
  });
13
14
  }
14
- /** §7.8: status computes a page's published (or never-published draft) path. */ export async function statusPageContent(req, collection, id) {
15
- const doc = await req.payload.db.findOne({
16
- collection,
17
- req,
18
- where: {
19
- id: {
20
- equals: id
21
- }
22
- },
23
- // Adapter read: status computes a page's published (or never-published draft) path.
24
- overrideAccess: true
25
- });
26
- if (!doc || doc._status !== 'draft') return doc;
27
- // A formerly published but currently unpublished page still uses its stored main-row path.
15
+ /** Path selection only, after checking access to the page. Version content is not needed. */ export async function hasPublishedPageVersion(req, collection, id, locale) {
28
16
  const published = await req.payload.db.findVersions({
29
17
  collection,
30
18
  req,
19
+ locale,
31
20
  limit: 1,
32
21
  pagination: false,
22
+ select: {
23
+ id: true
24
+ },
33
25
  where: {
34
26
  and: [
35
27
  {
@@ -47,14 +39,36 @@
47
39
  // Adapter read: status computes a page's published (or never-published draft) path.
48
40
  overrideAccess: true
49
41
  });
50
- if (published.docs.length) return doc;
42
+ return published.docs.length > 0;
43
+ }
44
+ /** §7.8: status computes a page's published (or never-published draft) path. */ export async function statusPageContent(req, collection, id) {
45
+ const locale = usesLocalizedPublication(req, collection) ? publicationLocale(req) : undefined;
46
+ const doc = await req.payload.db.findOne({
47
+ collection,
48
+ req,
49
+ locale,
50
+ where: {
51
+ id: {
52
+ equals: id
53
+ }
54
+ },
55
+ // Adapter read: status computes a page's published (or never-published draft) path.
56
+ overrideAccess: true
57
+ });
58
+ if (!doc || (locale ? pagePublicationStatus(doc, locale) === 'published' : doc._status !== 'draft')) return doc;
59
+ // A formerly published locale keeps its main row. A sibling's publication history is independent.
60
+ if (await hasPublishedPageVersion(req, collection, id, locale)) return doc;
51
61
  // §7.8: status computes a page's published (or never-published draft) path.
52
62
  const latest = await req.payload.db.findVersions({
53
63
  collection,
54
64
  req,
55
65
  limit: 1,
56
66
  pagination: false,
57
- sort: '-updatedAt',
67
+ locale,
68
+ sort: locale ? [
69
+ '-updatedAt',
70
+ '-id'
71
+ ] : '-updatedAt',
58
72
  where: {
59
73
  and: [
60
74
  {
@@ -62,7 +76,11 @@
62
76
  equals: id
63
77
  }
64
78
  },
65
- {
79
+ locale ? {
80
+ 'version._status': {
81
+ equals: 'draft'
82
+ }
83
+ } : {
66
84
  latest: {
67
85
  equals: true
68
86
  }
@@ -1,5 +1,7 @@
1
1
  import { flattenTopLevelFields, formatAdminURL } 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 { findDraftPageByPath, PAGE_ADDRESS_FIELDS } from '../transitions/pageAddress.js';
4
6
  import { normalisePath } from '../runtime/normalisePath.js';
5
7
  import { blockPageSlugs, hasPuckEditor } from '../options.js';
@@ -40,6 +42,7 @@ export async function handlePages(req, { options }) {
40
42
  const title = config?.admin.useAsTitle;
41
43
  const titleField = title && title !== 'id' ? title : fields.some((field)=>field.name === 'title') ? 'title' : title ?? 'id';
42
44
  const drafts = Boolean(config?.versions && config.versions.drafts);
45
+ const locale = usesLocalizedPublication(req, slug, config) ? publicationLocale(req) : undefined;
43
46
  if (path !== null && collection) {
44
47
  const found = await collection.findByPath(path, req);
45
48
  const main = found ? await req.payload.findByID({
@@ -55,8 +58,9 @@ export async function handlePages(req, { options }) {
55
58
  docs: [],
56
59
  hasNextPage: false
57
60
  });
58
- const published = !drafts || main._status === 'published';
59
- const row = published ? main : await req.payload.findByID({
61
+ const published = !drafts || pagePublicationStatus(main, locale) === 'published';
62
+ const useMain = published || Boolean(locale && (!found || await hasPublishedPageVersion(req, slug, main.id, locale)));
63
+ const row = useMain ? main : await req.payload.findByID({
60
64
  collection: slug,
61
65
  id: main.id,
62
66
  req,
@@ -204,11 +208,12 @@ export async function handlePages(req, { options }) {
204
208
  // Host callbacks can inspect arbitrary fields. Only picker metadata leaves this endpoint.
205
209
  select: hasDocCallbacks ? undefined : metadata
206
210
  });
207
- const draftIds = readDrafts ? result.docs.filter((doc)=>doc._status === 'draft').map((doc)=>doc.id) : [];
208
- const publishedById = new Map();
211
+ const localizedPaths = Boolean(locale && collection && !blockMode);
212
+ const draftIds = readDrafts ? result.docs.filter((doc)=>localizedPaths || pagePublicationStatus(doc, locale) === 'draft').map((doc)=>doc.id) : [];
213
+ const mainById = new Map();
209
214
  if (draftIds.length) {
210
- // Read only the matching live rows, in one bounded query. Whole-page choices
211
- // use the currently served path even when a newer edit changes that path.
215
+ // Read the matching main rows in one bounded query. Localized drafts can
216
+ // carry a sibling's publication state, so only main confirms what is live.
212
217
  const live = await req.payload.find({
213
218
  collection: slug,
214
219
  req,
@@ -219,27 +224,39 @@ export async function handlePages(req, { options }) {
219
224
  id: {
220
225
  in: draftIds
221
226
  },
222
- _status: {
223
- equals: 'published'
224
- }
227
+ ...!localizedPaths ? {
228
+ _status: {
229
+ equals: 'published'
230
+ }
231
+ } : {}
225
232
  },
226
233
  limit: PAGE_SIZE,
227
234
  select: !blockMode && collection ? undefined : {
228
235
  _status: true
229
236
  }
230
237
  });
231
- for (const doc of live.docs)if (doc._status === 'published') publishedById.set(String(doc.id), doc);
238
+ await Promise.all(live.docs.map(async (doc)=>{
239
+ const published = pagePublicationStatus(doc, locale) === 'published';
240
+ if (!published && !localizedPaths) return;
241
+ const usePath = published || await hasPublishedPageVersion(req, slug, doc.id, locale);
242
+ mainById.set(String(doc.id), {
243
+ doc,
244
+ published,
245
+ usePath
246
+ });
247
+ }));
232
248
  }
233
249
  const docs = result.docs.flatMap((row)=>{
234
250
  const placement = reader.read(row, input);
235
251
  const doc = placement.doc;
236
- const live = publishedById.get(String(row.id));
237
- const published = !drafts || row._status === 'published' || live !== undefined;
238
- const pathDoc = !blockMode && live ? reader.read(live, input).doc : doc;
252
+ const main = mainById.get(String(row.id));
253
+ const versionPublished = pagePublicationStatus(row, locale) === 'published';
254
+ const published = !drafts || (main?.published ?? versionPublished);
255
+ const pathDoc = !blockMode && main?.usePath ? reader.read(main.doc, input).doc : doc;
239
256
  const rawPath = collection?.pathOf(pathDoc) ?? null;
240
257
  const storedAddress = blockMode ? addressFields.reduce((value, field)=>value ?? textValue(pathDoc[field]), undefined) : undefined;
241
258
  const address = rawPath ?? storedAddress;
242
- const draftAddress = !blockMode && live ? collection?.pathOf(doc) : null;
259
+ const draftAddress = !blockMode && main?.usePath ? collection?.pathOf(doc) : null;
243
260
  const updatedAt = textValue(doc.updatedAt);
244
261
  const title = doc[titleField];
245
262
  const item = {
@@ -248,7 +265,7 @@ export async function handlePages(req, { options }) {
248
265
  path: rawPath,
249
266
  pathKey: rawPath === null ? null : normalisePath(rawPath),
250
267
  published,
251
- status: live ? 'changed' : published ? 'published' : 'draft',
268
+ status: main?.published && (!localizedPaths || !versionPublished || draftAddress !== rawPath) ? 'changed' : published ? 'published' : 'draft',
252
269
  ...address ? {
253
270
  address
254
271
  } : {},
@@ -1,4 +1,5 @@
1
- import { placementReader } from '../blocks/placementLocale.js';
1
+ import { localeRequest, placementReader } from '../blocks/placementLocale.js';
2
+ import { isPublicationStatus, publicationLocale, usesLocalizedPublication } from '../blocks/placementPublication.js';
2
3
  import { readBody } from './readBody.js';
3
4
  import { safeError } from '../log.js';
4
5
  import { statusPageContent } from '../db/pageContent.js';
@@ -18,6 +19,7 @@ const error = (status, code, message)=>Response.json({
18
19
  const object = (v)=>!!v && typeof v === 'object' && !Array.isArray(v);
19
20
  const id = (v)=>typeof v === 'string' && !!v.trim() || typeof v === 'number' && Number.isSafeInteger(v);
20
21
  export async function handlePlacementStatus(req, { options }) {
22
+ const fallbackLocale = req.fallbackLocale;
21
23
  let value;
22
24
  try {
23
25
  value = await readBody(req);
@@ -161,22 +163,64 @@ export async function handlePlacementStatus(req, { options }) {
161
163
  collection,
162
164
  id,
163
165
  req,
166
+ fallbackLocale,
164
167
  overrideAccess: false,
165
168
  depth: 0,
166
169
  draft: false
167
170
  });
168
171
  const registration = options.pages?.collections.find((entry)=>entry.slug === collection);
169
- const raw = registration ? await statusPageContent(req, collection, id) : null;
170
- const doc = placementReader(req, collection, options).read(raw, 'all-locales').doc;
171
- const rawPath = doc && registration ? registration.pathOf(doc) : null;
172
- const path = rawPath;
173
- const pathKey = path === null ? null : normalisePath(path);
172
+ const reader = placementReader(req, collection, options);
173
+ const localizedStatus = usesLocalizedPublication(req, collection);
174
+ const readPath = async (viewReq)=>{
175
+ if (!registration) return null;
176
+ const raw = await statusPageContent(viewReq, collection, id);
177
+ const input = localizedStatus && isPublicationStatus(raw?._status) ? 'localized' : 'all-locales';
178
+ const view = {
179
+ locale: viewReq.locale ?? '',
180
+ fallbackLocale: viewReq.fallbackLocale ?? false
181
+ };
182
+ const doc = reader.read(raw, input, view).doc;
183
+ return doc ? registration.pathOf(doc) : null;
184
+ };
185
+ let pathsByLocale;
186
+ if (registration && localizedStatus && req.locale === 'all') {
187
+ const paths = await Promise.all(reader.documentViews.map(async (view)=>{
188
+ const viewReq = localeRequest(req, {
189
+ ...view,
190
+ fallbackLocale: fallbackLocale ?? view.fallbackLocale
191
+ });
192
+ const readable = await req.payload.findByID({
193
+ collection,
194
+ id,
195
+ req: viewReq,
196
+ fallbackLocale: viewReq.fallbackLocale,
197
+ overrideAccess: false,
198
+ depth: 0,
199
+ draft: false,
200
+ disableErrors: true
201
+ });
202
+ return [
203
+ view.locale,
204
+ readable ? await readPath(viewReq) : null
205
+ ];
206
+ }));
207
+ pathsByLocale = Object.fromEntries(paths);
208
+ }
209
+ const path = pathsByLocale ? pathsByLocale[publicationLocale(req) ?? ''] ?? null : await readPath(req);
210
+ const pathKeys = new Set((pathsByLocale ? Object.values(pathsByLocale) : [
211
+ path
212
+ ]).flatMap((path)=>path === null ? [] : [
213
+ normalisePath(path)
214
+ ]));
174
215
  const status = {
175
216
  path,
217
+ ...pathsByLocale ? {
218
+ pathsByLocale
219
+ } : {},
176
220
  tests: []
177
221
  };
178
222
  for (const test of tests){
179
- if (test.kind !== 'page' || path === null || test.decision?.pagesReleasedAt || test.decision?.discardedAt || test.status === 'archived' && !test.decision?.winnerArm) continue;
223
+ if (test.kind !== 'page' || !pathKeys.size || test.decision?.pagesReleasedAt || test.decision?.discardedAt || test.status === 'archived' && !test.decision?.winnerArm) continue;
180
224
  const round = rounds.get(test.slug);
181
225
  if (!collections.has(test.slug)) collections.set(test.slug, await resolvePageCollection(req, options, {
182
226
  ...test,
@@ -184,7 +228,7 @@ export async function handlePlacementStatus(req, { options }) {
184
228
  }));
185
229
  const testCollection = collections.get(test.slug);
186
230
  if (testCollection?.slug !== collection) continue;
187
- const arm = round.arms.find((arm)=>arm.kind !== 'holdout' && arm.pageTarget && normalisePath(arm.pageTarget) === pathKey);
231
+ const arm = round.arms.find((arm)=>arm.kind !== 'holdout' && arm.pageTarget && pathKeys.has(normalisePath(arm.pageTarget)));
188
232
  if (!arm) continue;
189
233
  const winner = round.arms.find((arm)=>arm.key === test.decision?.winnerArm);
190
234
  const original = round.arms.find((arm)=>arm.kind === 'control');
@@ -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
  }, {
@@ -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
  }
@@ -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.1",
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",