@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,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(()=>{
@@ -1,5 +1,6 @@
1
1
  import { type PayloadRequest } from 'payload';
2
2
  import type { DocId, ResolvedOptions } from '../types/contracts.js';
3
+ import { type PublicationStatus } from './placementPublication.js';
3
4
  export type PlacementInput = 'all-locales' | 'localized';
4
5
  export declare function placementLocaleContent(req: PayloadRequest, collection: string, doc: Record<string, unknown> | undefined, input: PlacementInput): Record<string, unknown> | undefined;
5
6
  /** The single document → locale view → editor/placements boundary. Compiled schemas are shared per sanitized config.
@@ -8,6 +9,7 @@ export declare function placementLocaleContent(req: PayloadRequest, collection:
8
9
  export declare function placementReader(req: PayloadRequest, collection: string, options?: Pick<ResolvedOptions, "puck" | "blocks">): {
9
10
  views: PlacementLocaleView[];
10
11
  documentViews: PlacementLocaleView[];
12
+ isPublished(doc: Record<string, unknown> | null | undefined, view: PlacementLocaleView): boolean;
11
13
  read(doc: Record<string, unknown> | null | undefined, input: PlacementInput, view?: PlacementLocaleView): {
12
14
  view: PlacementLocaleView;
13
15
  readonly doc: Record<string, unknown> | undefined;
@@ -32,6 +34,18 @@ export declare function placementLocaleViews(req: PayloadRequest, collection: st
32
34
  export declare function removedPlacementViews(req: PayloadRequest, collection: string, before: Record<string, unknown> | undefined, after: Record<string, unknown>, removingPage: boolean, input?: PlacementInput): RemovedPlacementViews;
33
35
  /** Rebuild unchanged locale maps around a flattened hook write before reading each view. */
34
36
  export declare function mergedPlacementLocales(req: PayloadRequest, collection: string, before: Record<string, unknown> | undefined, after: Record<string, unknown>): Record<string, unknown>;
37
+ export declare function selectPlacementLocales(req: PayloadRequest, collection: string, doc: Record<string, unknown>, keep: ReadonlySet<string>): Record<string, unknown>;
38
+ /** Predict the main row Payload will write, keeping the stored status map
39
+ * separate from the locale-hoisted hook data and its validation locale.
40
+ */
41
+ export declare function localizedPlacementAfter(req: PayloadRequest, collection: string, main: Record<string, unknown> | undefined, base: Record<string, unknown> | undefined, data: Record<string, unknown>, { status, all, restore, }: {
42
+ status: unknown;
43
+ all?: {
44
+ status: PublicationStatus;
45
+ locales: string[];
46
+ };
47
+ restore?: boolean;
48
+ }): Record<string, unknown>;
35
49
  /** Project host document adapters before they run. Callers own path normalization
36
50
  * and use sortLockKeys for the existing experiment → page-path lock ordering. */
37
51
  export declare function placementDocumentPaths(req: PayloadRequest, collection: string, docs: Array<Record<string, unknown> | undefined>, input: PlacementInput, pathOf: (doc: Record<string, unknown>) => string | null): string[];
@@ -4,6 +4,8 @@ import { documentEditor, puckCollections } from '../options.js';
4
4
  import { placementSlugs } from './bindings.js';
5
5
  import { contentBlocks, hasLocalizedFields } from '../transitions/contentFields.js';
6
6
  import { isObject } from './model.js';
7
+ import { isPublicationStatus, payloadPublishesAllByDefault, publicationStatusInLocale, publishedInLocale, usesLocalizedPublication } from './placementPublication.js';
8
+ import { usesRelationalBlocks } from '../db/adapter.js';
7
9
  const identity = (data)=>data;
8
10
  // Sanitized schemas are immutable. Weak ownership keeps separate Payload configs
9
11
  // (and test harnesses) isolated; locale transforms survive individual readers/saves.
@@ -33,7 +35,7 @@ const localeTransforms = new WeakMap();
33
35
  const cached = compiled.get(fields);
34
36
  if (cached) return cached;
35
37
  let project;
36
- const transform = (data, write, previous)=>project(data, write, previous);
38
+ const transform = (data, write, previous, options)=>project(data, write, previous, options);
37
39
  compiled.set(fields, transform);
38
40
  const steps = flattenTopLevelFields(fields).flatMap((field)=>{
39
41
  if (!('name' in field) || !field.name) return [];
@@ -62,15 +64,31 @@ const localeTransforms = new WeakMap();
62
64
  })) : undefined;
63
65
  if (!localized && !children && !variants) return [];
64
66
  return [
65
- (data, write, previous)=>{
67
+ (data, write, previous, options)=>{
66
68
  if (!(name in data)) return data;
67
69
  let value = data[name];
68
70
  const prior = previous?.[name];
69
- if (localized && write) value = {
70
- ...isObject(prior) ? prior : {},
71
- [locale]: value
72
- };
73
- else {
71
+ const keep = options?.keep;
72
+ if (localized && keep) {
73
+ if (isObject(value)) value = Object.fromEntries(Object.entries(value).filter(([code])=>keep.has(code)));
74
+ } else if (localized && write) {
75
+ const existing = isObject(prior) ? prior : {};
76
+ // Relational blocks have no stored locale value when there are no
77
+ // rows. The visitor will see fallback content in that locale.
78
+ const storedValue = (input)=>options?.omitEmptyBlocks && field.type === 'blocks' && Array.isArray(input) && input.length === 0 ? undefined : input;
79
+ if (locale !== 'all') value = {
80
+ ...existing,
81
+ [locale]: storedValue(value)
82
+ };
83
+ else if (payloadPublishesAllByDefault) value = {
84
+ ...existing,
85
+ ...Object.fromEntries(Object.entries(isObject(value) ? value : {}).map(([code, input])=>[
86
+ code,
87
+ storedValue(input)
88
+ ]))
89
+ };
90
+ else if (Object.keys(existing).length) value = existing;
91
+ } else {
74
92
  if (localized) {
75
93
  const values = isObject(value) ? value : {};
76
94
  value = values[locale];
@@ -89,7 +107,7 @@ const localeTransforms = new WeakMap();
89
107
  const visit = (row, old)=>{
90
108
  if (!isObject(row)) return row;
91
109
  const transform = children ?? (variants && typeof row.blockType === 'string' ? variants.get(row.blockType) : undefined);
92
- return transform ? transform(row, write, isObject(old) ? old : undefined) : row;
110
+ return transform ? transform(row, write, isObject(old) ? old : undefined, options) : row;
93
111
  };
94
112
  if (children || variants) {
95
113
  if (Array.isArray(value)) {
@@ -105,7 +123,7 @@ const localeTransforms = new WeakMap();
105
123
  }
106
124
  ];
107
125
  });
108
- project = (data, write = false, previous)=>steps.reduce((result, step)=>step(result, write, previous), data);
126
+ project = (data, write = false, previous, options)=>steps.reduce((result, step)=>step(result, write, previous, options), data);
109
127
  return transform;
110
128
  }
111
129
  const transform = hasLocalizedFields(config.fields ?? [], payloadConfig) ? compile(config.fields ?? []) : identity;
@@ -120,9 +138,13 @@ export function placementLocaleContent(req, collection, doc, input) {
120
138
  */ export function placementReader(req, collection, options = req.payload.config.custom?.xp) {
121
139
  const views = placementLocaleViews(req, collection, options);
122
140
  const transforms = new Map();
141
+ const localizedStatus = usesLocalizedPublication(req, collection);
123
142
  return {
124
143
  views,
125
144
  documentViews: schemaLocaleViews(req, collection),
145
+ isPublished (doc, view) {
146
+ return !localizedStatus || publishedInLocale(doc, view.locale);
147
+ },
126
148
  read (doc, input, view) {
127
149
  const requested = view ?? {
128
150
  locale: req.locale ?? '',
@@ -153,6 +175,11 @@ export function placementLocaleContent(req, collection, doc, input) {
153
175
  transforms.set(key, transform);
154
176
  }
155
177
  content = transform(doc);
178
+ // Content can fall back to another locale. Publication status cannot.
179
+ if (localizedStatus) content = {
180
+ ...content,
181
+ _status: publicationStatusInLocale(doc, locale)
182
+ };
156
183
  }
157
184
  return content;
158
185
  };
@@ -175,7 +202,7 @@ export function placementLocaleContent(req, collection, doc, input) {
175
202
  export function allPlacementSlugs(req, collection, doc, input) {
176
203
  const reader = placementReader(req, collection);
177
204
  return [
178
- ...new Set(reader.views.flatMap((view)=>reader.read(doc, input, view).slugs))
205
+ ...new Set(reader.views.flatMap((view)=>reader.isPublished(doc, view) ? reader.read(doc, input, view).slugs : []))
179
206
  ];
180
207
  }
181
208
  export const placementDocumentKey = (collection, id, view)=>JSON.stringify([
@@ -198,7 +225,7 @@ export function localeRequest(req, view) {
198
225
  /** Audits may contain localized arm-select tags outside registered editors. */ function schemaLocaleViews(req, collection) {
199
226
  const localization = req.payload.config.localization;
200
227
  const config = req.payload.config.collections?.find((entry)=>entry.slug === collection);
201
- return localization && hasLocalizedFields(config?.fields ?? [], req.payload.config) ? (localization.localeCodes ?? localization.locales.map((entry)=>typeof entry === 'string' ? entry : entry.code)).map((locale)=>({
228
+ return localization && (usesLocalizedPublication(req, collection, config) || hasLocalizedFields(config?.fields ?? [], req.payload.config)) ? (localization.localeCodes ?? localization.locales.map((entry)=>typeof entry === 'string' ? entry : entry.code)).map((locale)=>({
202
229
  locale,
203
230
  fallbackLocale: sanitizeFallbackLocale({
204
231
  fallbackLocale: null,
@@ -220,7 +247,7 @@ export function localeRequest(req, view) {
220
247
  ...(options.blocks?.collections ?? []).filter((entry)=>entry.slug === collection).map((entry)=>entry.field)
221
248
  ]);
222
249
  const localized = config && hasLocalizedFields(config.fields ?? [], req.payload.config) && (Boolean(options.blocks?.collections.some((entry)=>entry.slug === collection && entry.appliesTo)) || flattenTopLevelFields(config.fields ?? []).some((field)=>'name' in field && names.has(field.name) && ('localized' in field && field.localized || 'fields' in field && hasLocalizedFields(field.fields, req.payload.config) || field.type === 'blocks' && hasLocalizedFields(contentBlocks(field, req.payload.config.blocks).flatMap((block)=>block.fields), req.payload.config))));
223
- return localization && localized ? (localization.localeCodes ?? localization.locales.map((entry)=>typeof entry === 'string' ? entry : entry.code)).map((locale)=>({
250
+ return localization && (localized || usesLocalizedPublication(req, collection, config)) ? (localization.localeCodes ?? localization.locales.map((entry)=>typeof entry === 'string' ? entry : entry.code)).map((locale)=>({
224
251
  locale,
225
252
  fallbackLocale: sanitizeFallbackLocale({
226
253
  fallbackLocale: null,
@@ -243,8 +270,9 @@ export function localeRequest(req, view) {
243
270
  const reader = placementReader(req, collection);
244
271
  const rawAfter = input === 'all-locales' ? after : mergedPlacementLocales(req, collection, before, after);
245
272
  for (const view of reader.views){
273
+ if (!reader.isPublished(before, view)) continue;
246
274
  const previous = reader.read(before, 'all-locales', view).slugs;
247
- const next = removingPage ? [] : reader.read(rawAfter, 'all-locales', view).slugs;
275
+ const next = removingPage || !reader.isPublished(rawAfter, view) ? [] : reader.read(rawAfter, 'all-locales', view).slugs;
248
276
  for (const slug of previous.filter((slug)=>!next.includes(slug)))result.set(slug, [
249
277
  ...result.get(slug) ?? [],
250
278
  view
@@ -257,10 +285,49 @@ export function localeRequest(req, view) {
257
285
  if (!localization || req.locale === 'all') return after;
258
286
  return localeTransform(req.payload.config, collection, req.locale || localization.defaultLocale, false)(after, true, before);
259
287
  }
288
+ export function selectPlacementLocales(req, collection, doc, keep) {
289
+ return localeTransform(req.payload.config, collection, '', false)(doc, false, undefined, {
290
+ keep
291
+ });
292
+ }
293
+ /** Predict the main row Payload will write, keeping the stored status map
294
+ * separate from the locale-hoisted hook data and its validation locale.
295
+ */ export function localizedPlacementAfter(req, collection, main, base, data, { status, all, restore }) {
296
+ const localization = req.payload.config.localization;
297
+ if (!localization) return data;
298
+ const locale = req.locale || localization.defaultLocale;
299
+ const selected = isObject(status) ? status[locale] : status;
300
+ // V3 merges every single-locale live update with main. V4 does that on
301
+ // publish, while unpublish uses the unmerged result of beforeChange.
302
+ const isolatedPublish = !restore && !all && payloadPublishesAllByDefault && selected === 'published' && locale !== 'all';
303
+ let source = !restore && !all && main && (!payloadPublishesAllByDefault || isolatedPublish) ? main : base;
304
+ const before = isObject(source?._status) ? source._status : {};
305
+ const statuses = {
306
+ ...before
307
+ };
308
+ if (isolatedPublish && main) {
309
+ source = selectPlacementLocales(req, collection, main, new Set(Object.keys(before).filter((code)=>before[code] === 'published')));
310
+ }
311
+ if (all) for (const code of all.locales)statuses[code] = all.status;
312
+ else if (locale !== 'all' && isPublicationStatus(selected)) statuses[locale] = selected;
313
+ else if (locale === 'all' && isObject(status) && (payloadPublishesAllByDefault || !main)) Object.assign(statuses, status);
314
+ else if (locale === 'all' && payloadPublishesAllByDefault && isPublicationStatus(status) && !Object.keys(before).length) {
315
+ for (const code of localization.localeCodes)statuses[code] = status;
316
+ }
317
+ const merged = localeTransform(req.payload.config, collection, locale, false)(data, true, source, {
318
+ omitEmptyBlocks: usesRelationalBlocks(req.payload)
319
+ });
320
+ return {
321
+ ...source,
322
+ ...merged,
323
+ _status: statuses
324
+ };
325
+ }
260
326
  /** Project host document adapters before they run. Callers own path normalization
261
327
  * and use sortLockKeys for the existing experiment → page-path lock ordering. */ export function placementDocumentPaths(req, collection, docs, input, pathOf) {
262
328
  const reader = placementReader(req, collection);
263
329
  return docs.flatMap((raw)=>reader.documentViews.flatMap((view)=>{
330
+ if (!reader.isPublished(raw, view)) return [];
264
331
  const doc = reader.read(raw, input, view).doc;
265
332
  const path = doc ? pathOf(doc) : null;
266
333
  return path === null ? [] : [
@@ -0,0 +1,18 @@
1
+ import type { PayloadRequest, SanitizedCollectionConfig } from 'payload';
2
+ export declare const payloadPublishesAllByDefault: boolean;
3
+ export declare function usesLocalizedPublication(req: PayloadRequest, collection: string, config?: SanitizedCollectionConfig): boolean;
4
+ export type PublicationStatus = 'published' | 'draft';
5
+ export type PublicationFlags = {
6
+ draft?: boolean;
7
+ restore?: boolean;
8
+ publishAllLocales?: boolean;
9
+ unpublishAllLocales?: boolean;
10
+ };
11
+ export declare function isPublicationStatus(value: unknown): value is PublicationStatus;
12
+ export declare function allLocalesStatus(req: PayloadRequest, flags: PublicationFlags | undefined, status: unknown, operation: 'create' | 'update'): PublicationStatus | undefined;
13
+ export declare function publicationStatusInLocale(doc: Record<string, unknown> | null | undefined, locale: string): PublicationStatus | undefined;
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;
@@ -0,0 +1,31 @@
1
+ import * as payloadCore from 'payload';
2
+ import { isObject } from './model.js';
3
+ // Payload 4 dropped createLocalReq and made a non-draft locale=all save an
4
+ // all-locale publish by default. Payload 3 requires the explicit flag.
5
+ export const payloadPublishesAllByDefault = !('createLocalReq' in payloadCore);
6
+ export function usesLocalizedPublication(req, collection, config) {
7
+ const versions = (config ?? req.payload.config.collections?.find((entry)=>entry.slug === collection))?.versions;
8
+ return Boolean(req.payload.config.localization && versions && versions.drafts && versions.drafts.localizeStatus);
9
+ }
10
+ export function isPublicationStatus(value) {
11
+ return value === 'published' || value === 'draft';
12
+ }
13
+ export function allLocalesStatus(req, flags, status, operation) {
14
+ if (flags?.unpublishAllLocales && status === 'draft') return 'draft';
15
+ const publishAll = flags?.publishAllLocales ?? (operation === 'update' && payloadPublishesAllByDefault && req.locale === 'all');
16
+ if (!flags?.draft && publishAll && status === 'published') return 'published';
17
+ }
18
+ export function publicationStatusInLocale(doc, locale) {
19
+ const status = isObject(doc?._status) ? doc._status[locale] : undefined;
20
+ return isPublicationStatus(status) ? status : undefined;
21
+ }
22
+ export function publishedInLocale(doc, locale) {
23
+ return publicationStatusInLocale(doc, locale) === 'published';
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
+ }
@@ -8,4 +8,5 @@ export declare class XpTransactionIsolationError extends APIError {
8
8
  export declare function initTransitionTransaction(req: PayloadRequest, deadline?: number): Promise<boolean>;
9
9
  export declare function assertReadCommitted(req: PayloadRequest): Promise<void>;
10
10
  export declare function assertPostgresAdapter(payload: Payload): void;
11
+ export declare function usesRelationalBlocks(payload: Payload): boolean;
11
12
  export declare function probeTransactions(payload: Payload): Promise<void>;
@@ -81,6 +81,9 @@ export function assertPostgresAdapter(payload) {
81
81
  // @payloadcms/db-postgres/dist/index.js:133 declares this package marker.
82
82
  if (payload.db.packageName !== '@payloadcms/db-postgres') throw new Error('Experiments requires @payloadcms/db-postgres');
83
83
  }
84
+ export function usesRelationalBlocks(payload) {
85
+ return payload.db.blocksAsJSON !== true;
86
+ }
84
87
  export async function probeTransactions(payload) {
85
88
  const id = await payload.db.beginTransaction();
86
89
  if (id == null) throw new Error('Experiments transactions are disabled');
@@ -34,7 +34,8 @@ export interface PlacementSavePath {
34
34
  /** Payload 3.90.2: updateByID starts from the latest version; update (bulk)
35
35
  * starts from main rows except draft/trash saves. utilities/update then replaces
36
36
  * unselected locales with the latest published version (publishSpecificLocale).
37
- * Localized publication status is refused at init. Restore uses the selected version. */
37
+ * Localized status uses the main row for a single-locale publish. The caller
38
+ * selects that base separately. Restore uses the selected version. */
38
39
  export declare function placementMergeBase(path: PlacementSavePath): 'restore' | 'main' | 'published' | 'latest';
39
40
  export declare function placementWriteContent(req: PayloadRequest, collection: string, id: DocId, main: Record<string, unknown> | undefined, path?: PlacementSavePath): Promise<Record<string, unknown> | undefined>;
40
41
  /** Read the main collection row BEFORE the host write. Draft version retention
@@ -21,7 +21,8 @@ import { qualifiedTable, quoteIdentifier as quote } from './sql.js';
21
21
  /** Payload 3.90.2: updateByID starts from the latest version; update (bulk)
22
22
  * starts from main rows except draft/trash saves. utilities/update then replaces
23
23
  * unselected locales with the latest published version (publishSpecificLocale).
24
- * Localized publication status is refused at init. Restore uses the selected version. */ export function placementMergeBase(path) {
24
+ * Localized status uses the main row for a single-locale publish. The caller
25
+ * selects that base separately. Restore uses the selected version. */ export function placementMergeBase(path) {
25
26
  if (path.versionId != null) return 'restore';
26
27
  if (path.publishSpecificLocale) return 'published';
27
28
  return path.bulk && !path.draft && !path.trashing ? 'main' : 'latest';
@@ -1,5 +1,6 @@
1
1
  import type { PayloadRequest, Where } from 'payload';
2
2
  import { type PlacementLocaleView } from '../blocks/placementLocale.js';
3
+ import { type PublicationStatus } from '../blocks/placementPublication.js';
3
4
  import type { DocId } from '../types/contracts.js';
4
5
  export interface BulkPlacementRemoval {
5
6
  documents: Set<string>;
@@ -8,6 +9,10 @@ export interface BulkPlacementRemoval {
8
9
  data?: Record<string, unknown>;
9
10
  draft: boolean;
10
11
  deleting: boolean;
12
+ all?: {
13
+ status: PublicationStatus;
14
+ locales: string[];
15
+ };
11
16
  };
12
17
  refusals: Map<string, string>;
13
18
  }
@@ -1,4 +1,5 @@
1
- import { placementLocaleContent, mergedPlacementLocales, removedPlacementViews, placementDocumentKey } from '../blocks/placementLocale.js';
1
+ import { localizedPlacementAfter, placementLocaleContent, mergedPlacementLocales, removedPlacementViews, placementDocumentKey } from '../blocks/placementLocale.js';
2
+ import { usesLocalizedPublication } from '../blocks/placementPublication.js';
2
3
  // Payload starts/ends a transaction per bulk document with this adapter option.
3
4
  export function usesBulkDocumentTransactions(req) {
4
5
  return req.payload.db.bulkOperationsSingleTransaction === true;
@@ -105,7 +106,11 @@ const operationRequestState = Symbol('xpPlacementRequestState');
105
106
  ...input === 'all-locales' ? doc : placementLocaleContent(req, collection, doc, 'all-locales'),
106
107
  ...change.data
107
108
  };
108
- const after = input === 'all-locales' ? pending : mergedPlacementLocales(req, collection, doc, pending);
109
+ const localized = usesLocalizedPublication(req, collection);
110
+ const after = localized ? localizedPlacementAfter(req, collection, doc, doc, pending, {
111
+ status: change.data?._status ?? pending._status,
112
+ all: change.all
113
+ }) : input === 'all-locales' ? pending : mergedPlacementLocales(req, collection, doc, pending);
109
114
  const views = removedPlacementViews(req, collection, doc, after, change.deleting || after.deletedAt != null || after._status === 'draft', 'all-locales');
110
115
  return (views.get(slug) ?? []).some((removed)=>placementDocumentKey(collection, doc.id, removed) === placementDocumentKey(collection, doc.id, view));
111
116
  }
@@ -1,4 +1,4 @@
1
1
  import type { DocId } from '../types/contracts.js';
2
2
  import type { Executor } from './executor.js';
3
- /** Current running round, independent of manifest compilation and typed targeting. */
4
- export declare function pageContentBindings(exec: Executor, collection: string, paths: readonly string[]): Promise<DocId[]>;
3
+ /** Current round, independent of manifest compilation and typed targeting. */
4
+ export declare function pageContentBindings(exec: Executor, collection: string, paths: readonly string[], includePaused?: boolean): Promise<DocId[]>;
@@ -1,14 +1,14 @@
1
1
  import { TABLES, COLUMNS } from './names.js';
2
2
  import { qualifiedTable, quoteIdentifier as q } from './sql.js';
3
3
  import { normalisePath } from '../runtime/normalisePath.js';
4
- /** Current running round, independent of manifest compilation and typed targeting. */ // Legacy tests without pageCollection match the same path in any collection; stored collections narrow the match.
5
- export async function pageContentBindings(exec, collection, paths) {
4
+ /** Current round, independent of manifest compilation and typed targeting. */ // Legacy tests without pageCollection match the same path in any collection; stored collections narrow the match.
5
+ export async function pageContentBindings(exec, collection, paths, includePaused = false) {
6
6
  if (!paths.length) return [];
7
7
  const e = COLUMNS.experiments, p = COLUMNS.phases;
8
8
  const { rows } = await exec.query(`SELECT x.${q(e.id)} AS id, p.${q(p.arms)} AS arms
9
9
  FROM ${qualifiedTable(exec, TABLES.experiments)} x JOIN ${qualifiedTable(exec, TABLES.phases)} p
10
10
  ON p.${q(p.experimentId)} = x.${q(e.id)} AND p.${q(p.phase)} = x.${q(e.phase)}
11
- WHERE x.${q(e.kind)} = 'page' AND x.${q(e.status)} = 'running'
11
+ WHERE x.${q(e.kind)} = 'page' AND x.${q(e.status)} ${includePaused ? "IN ('running', 'paused')" : "= 'running'"}
12
12
  AND (x.${q(e.pageCollection)} = $1 OR x.${q(e.pageCollection)} IS NULL)`, [
13
13
  collection
14
14
  ]);
@@ -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,6 +1,7 @@
1
1
  import type { PayloadRequest } from 'payload';
2
+ import type { PublicationStatus } from '../blocks/placementPublication.js';
2
3
  import type { Arm, DocId } from '../types/contracts.js';
3
- import type { Executor } from './executor.js';
4
+ import { type Executor } from './executor.js';
4
5
  export interface PlacementDoc {
5
6
  collection: string;
6
7
  id: DocId;
@@ -27,6 +28,10 @@ export declare function removableBlockTests(exec: Executor, slugs: readonly stri
27
28
  export declare function placementPathContent(req: PayloadRequest, collection: string, id: DocId): Promise<(Record<string, unknown> & {
28
29
  id: DocId;
29
30
  }) | null>;
31
+ /** Read localized publication from the main collection's locale table.
32
+ * The caller supplies the IDs selected by the placement read.
33
+ */
34
+ export declare function storedPlacementStatuses(req: PayloadRequest, collection: string, ids: readonly DocId[]): Promise<Map<string, Record<string, PublicationStatus>>>;
30
35
  /** Caller holds E. Never coalesce null: old rounds must continue to scan. */
31
36
  export declare function appendPlacementDoc(exec: Executor, experimentId: DocId, phase: number, doc: PlacementDoc): Promise<void>;
32
37
  /** Deciding a stopped modern round restores routing on its detached rescan.
@@ -1,3 +1,4 @@
1
+ import { pooledExecutor, txExecutor } from './executor.js';
1
2
  import { COLUMNS, TABLES } from './names.js';
2
3
  import { qualifiedTable, quoteIdentifier as q } from './sql.js';
3
4
  /** Raw reads only: guard discovery includes every status, interaction checks filter under the locks. */ export async function placementTests(exec) {
@@ -35,6 +36,31 @@ import { qualifiedTable, quoteIdentifier as q } from './sql.js';
35
36
  overrideAccess: true
36
37
  });
37
38
  }
39
+ /** Read localized publication from the main collection's locale table.
40
+ * The caller supplies the IDs selected by the placement read.
41
+ */ export async function storedPlacementStatuses(req, collection, ids) {
42
+ const statuses = new Map();
43
+ if (!ids.length) return statuses;
44
+ const db = req.payload.db;
45
+ // Resolve the adapter's table name, including a collection's custom dbName.
46
+ const camelCase = !/[_:.-]|\s/.test(collection) && /[a-z][A-Z]|[A-Z][a-z]/.test(collection);
47
+ const key = camelCase ? collection.replace(/(.)([A-Z]+)/g, (_match, first, rest)=>`${first} ${[
48
+ ...rest
49
+ ].join(' ')}`) : collection;
50
+ const main = db.tableNameMap.get(key.toLowerCase().replace(/[\W_]+/g, '_').replace(/^_|_$/g, ''));
51
+ if (!main) throw new Error(`The placement table for ${collection} was not found.`);
52
+ const exec = await req.transactionID == null ? pooledExecutor(req.payload) : txExecutor(req);
53
+ const table = qualifiedTable(exec, `${main}${db.localesSuffix}`);
54
+ const params = ids.map((_, i)=>`$${i + 1}`).join(', ');
55
+ const { rows } = await exec.query(`SELECT _parent_id AS id, _locale AS locale, _status AS status FROM ${table} WHERE _parent_id IN (${params})`, [
56
+ ...ids
57
+ ]);
58
+ for (const { id, locale, status } of rows)statuses.set(String(id), {
59
+ ...statuses.get(String(id)),
60
+ [locale]: status
61
+ });
62
+ return statuses;
63
+ }
38
64
  /** Caller holds E. Never coalesce null: old rounds must continue to scan. */ export async function appendPlacementDoc(exec, experimentId, phase, doc) {
39
65
  const p = COLUMNS.phases, column = q(p.placementDocs);
40
66
  await exec.query(`UPDATE ${qualifiedTable(exec, TABLES.phases)} SET ${column} = ${column} || $1::jsonb
@@ -24,6 +24,7 @@ export declare function preparePageCopy<TUser extends {
24
24
  reader: {
25
25
  views: import("../blocks/placementLocale.js").PlacementLocaleView[];
26
26
  documentViews: import("../blocks/placementLocale.js").PlacementLocaleView[];
27
+ isPublished(doc: Record<string, unknown> | null | undefined, view: import("../blocks/placementLocale.js").PlacementLocaleView): boolean;
27
28
  read(doc: Record<string, unknown> | null | undefined, input: import("../blocks/placementLocale.js").PlacementInput, view?: import("../blocks/placementLocale.js").PlacementLocaleView): {
28
29
  view: import("../blocks/placementLocale.js").PlacementLocaleView;
29
30
  readonly doc: Record<string, unknown> | undefined;