payload-canvas 0.1.0 → 0.2.0

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 (124) hide show
  1. package/README.md +202 -26
  2. package/dist/admin/editor/Canvas.js +30 -8
  3. package/dist/admin/editor/Editor.js +2 -0
  4. package/dist/admin/editor/Inspector.js +14 -7
  5. package/dist/admin/editor/Outline.js +15 -9
  6. package/dist/admin/editor/Overlay.js +2 -1
  7. package/dist/admin/editor/actions.d.ts +5 -0
  8. package/dist/admin/editor/actions.js +23 -1
  9. package/dist/admin/editor/counts.d.ts +6 -0
  10. package/dist/admin/editor/counts.js +10 -0
  11. package/dist/admin/editor/dnd/displace.js +3 -1
  12. package/dist/admin/editor/editor.scss +53 -0
  13. package/dist/admin/editor/inline.d.ts +12 -0
  14. package/dist/admin/editor/inline.js +48 -3
  15. package/dist/admin/editor/insert/spots.js +4 -2
  16. package/dist/admin/editor/live/useMultiplayer.js +8 -2
  17. package/dist/admin/editor/media/ImageEditor.js +21 -15
  18. package/dist/admin/editor/media/actions.d.ts +13 -9
  19. package/dist/admin/editor/media/actions.js +67 -28
  20. package/dist/admin/editor/media/model.d.ts +8 -0
  21. package/dist/admin/editor/media/model.js +14 -6
  22. package/dist/admin/editor/menu/blockMenu.js +13 -8
  23. package/dist/admin/editor/regions/RegionOverlay.d.ts +18 -0
  24. package/dist/admin/editor/regions/RegionOverlay.js +44 -0
  25. package/dist/admin/editor/regions/RegionPane.d.ts +5 -0
  26. package/dist/admin/editor/regions/RegionPane.js +26 -0
  27. package/dist/admin/editor/regions/RegionRows.d.ts +1 -0
  28. package/dist/admin/editor/regions/RegionRows.js +23 -0
  29. package/dist/admin/editor/regions/controller.d.ts +73 -0
  30. package/dist/admin/editor/regions/controller.js +231 -0
  31. package/dist/admin/editor/regions/select.d.ts +17 -0
  32. package/dist/admin/editor/regions/select.js +31 -0
  33. package/dist/admin/editor/runtime.d.ts +6 -0
  34. package/dist/admin/editor/runtime.js +49 -4
  35. package/dist/admin/editor/sections/controller.d.ts +6 -2
  36. package/dist/admin/editor/sections/controller.js +9 -3
  37. package/dist/admin/editor/shortcuts.js +11 -4
  38. package/dist/admin/editor/storage.d.ts +7 -0
  39. package/dist/admin/editor/storage.js +15 -0
  40. package/dist/admin/editor/store.d.ts +39 -0
  41. package/dist/admin/editor/store.js +106 -2
  42. package/dist/admin/editor/templates/Bindable.js +1 -1
  43. package/dist/admin/editor/templates/SamplePicker.js +1 -1
  44. package/dist/admin/editor/topbar/DocumentActions.js +38 -5
  45. package/dist/admin/editor/topbar/closeSave.d.ts +50 -0
  46. package/dist/admin/editor/topbar/closeSave.js +90 -0
  47. package/dist/admin/editor/topbar/document.d.ts +10 -2
  48. package/dist/admin/editor/topbar/document.js +9 -1
  49. package/dist/admin/editor/topbar/drawerLabels.d.ts +22 -0
  50. package/dist/admin/editor/topbar/drawerLabels.js +69 -0
  51. package/dist/admin/editor/topbar/problems.d.ts +9 -0
  52. package/dist/admin/editor/topbar/problems.js +15 -1
  53. package/dist/admin/editor/topbar/settingsDrawer.js +88 -4
  54. package/dist/admin/editor/topbar/settingsFocus.d.ts +11 -0
  55. package/dist/admin/editor/topbar/settingsFocus.js +46 -0
  56. package/dist/admin/editor/ui/payloadA11y.d.ts +17 -0
  57. package/dist/admin/editor/ui/payloadA11y.js +12 -5
  58. package/dist/admin/editor/valueStore.d.ts +2 -0
  59. package/dist/admin/editor/valueStore.js +6 -0
  60. package/dist/core/dropTarget.js +3 -1
  61. package/dist/core/index.d.ts +2 -0
  62. package/dist/core/index.js +2 -0
  63. package/dist/core/payloadBlocks.d.ts +53 -0
  64. package/dist/core/payloadBlocks.js +391 -0
  65. package/dist/core/regions.d.ts +63 -0
  66. package/dist/core/regions.js +239 -0
  67. package/dist/core/types.d.ts +53 -0
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.js +1 -0
  70. package/dist/live/document.d.ts +9 -1
  71. package/dist/live/document.js +57 -17
  72. package/dist/live/draftAccess.d.ts +36 -0
  73. package/dist/live/draftAccess.js +146 -0
  74. package/dist/live/endpoints.d.ts +11 -2
  75. package/dist/live/endpoints.js +120 -10
  76. package/dist/live/fieldChecks.d.ts +3 -3
  77. package/dist/live/fieldsGuard.d.ts +56 -2
  78. package/dist/live/fieldsGuard.js +107 -11
  79. package/dist/live/index.d.ts +2 -0
  80. package/dist/live/index.js +2 -0
  81. package/dist/live/regions.d.ts +89 -0
  82. package/dist/live/regions.js +401 -0
  83. package/dist/live/runtime.d.ts +1 -1
  84. package/dist/live/runtime.js +5 -2
  85. package/dist/live/session.d.ts +74 -9
  86. package/dist/live/session.js +655 -123
  87. package/dist/live/storage.d.ts +97 -0
  88. package/dist/live/storage.js +269 -0
  89. package/dist/live/types.d.ts +64 -0
  90. package/dist/live/writeGate.d.ts +72 -0
  91. package/dist/live/writeGate.js +478 -0
  92. package/dist/mcp/index.js +56 -12
  93. package/dist/plugin/hook.d.ts +44 -6
  94. package/dist/plugin/hook.js +176 -20
  95. package/dist/plugin/index.d.ts +23 -1
  96. package/dist/plugin/index.js +172 -10
  97. package/dist/plugin/references.d.ts +4 -2
  98. package/dist/plugin/references.js +2 -0
  99. package/dist/plugin/sectionsBuilder.js +3 -3
  100. package/dist/protocol/index.d.ts +28 -2
  101. package/dist/react/canvas/BuilderCanvas.js +198 -8
  102. package/dist/react/canvas/frame.d.ts +70 -0
  103. package/dist/react/canvas/frame.js +66 -0
  104. package/dist/react/canvas/inline/dom.d.ts +7 -1
  105. package/dist/react/canvas/inline/dom.js +19 -9
  106. package/dist/react/canvas/inline/mapper.d.ts +26 -0
  107. package/dist/react/canvas/inline/mapper.js +59 -32
  108. package/dist/react/canvas/inline/session.d.ts +7 -1
  109. package/dist/react/canvas/inline/session.js +6 -2
  110. package/dist/react/canvas/measure.js +26 -1
  111. package/dist/react/index.d.ts +2 -0
  112. package/dist/react/index.js +2 -0
  113. package/dist/react/render/LayoutOutlet.d.ts +11 -0
  114. package/dist/react/render/LayoutOutlet.js +16 -0
  115. package/dist/react/render/canvasFrame.d.ts +46 -0
  116. package/dist/react/render/canvasFrame.js +59 -0
  117. package/dist/react/render/canvasServer.d.ts +13 -0
  118. package/dist/react/render/canvasServer.js +3 -0
  119. package/dist/react/render/canvasServerTypes.d.ts +17 -0
  120. package/dist/react/render/regions.d.ts +13 -0
  121. package/dist/react/render/regions.js +8 -0
  122. package/dist/react/server.d.ts +2 -1
  123. package/dist/react/server.js +1 -0
  124. package/package.json +1 -1
@@ -6,3 +6,5 @@ export { resolveOperations, splitLayoutErrors, actorFromUser, userLabel, payload
6
6
  export { liveEndpoints, sessionStream, sseFrame, requestActor, sessionTargetOf, targetOf, LIVE_PATH, SSE_HEADERS, type LiveEndpointOptions } from './endpoints.js';
7
7
  export { builderConfigOf, documentEndpoints, documentErrorsOf, loadDocMeta, payloadErrorMessage, restoreDocumentVersion, runPublishAction, BUILDER_CONFIG_KEY, type BuilderCollectionServer, type BuilderServerConfig, type DocMetaArgs, type DocumentEndpointOptions, type PublishCheck, } from './document.js';
8
8
  export { changedFields, createFieldClock, defaultFieldClock, KEEP_LOCK_CONTEXT, LOCKED_DOCUMENTS_SLUG, staleSaveMessage, type FieldClock, type FieldConflict, } from './fieldsGuard.js';
9
+ export { loadRegionAccess, loadRegionValues, regionAccessFrom, regionAccessAt, regionEndpoints, writeRegionFields, REGION_SAVE_CONTEXT, type RegionEndpointOptions, type RegionWriteOptions, type RegionWriteResult, } from './regions.js';
10
+ export { createWriteGate, defaultWriteGate, writeKey, type WriteGate, type WriteGateOptions } from './writeGate.js';
@@ -9,3 +9,5 @@ export { resolveOperations, splitLayoutErrors, actorFromUser, userLabel, payload
9
9
  export { liveEndpoints, sessionStream, sseFrame, requestActor, sessionTargetOf, targetOf, LIVE_PATH, SSE_HEADERS } from './endpoints.js';
10
10
  export { builderConfigOf, documentEndpoints, documentErrorsOf, loadDocMeta, payloadErrorMessage, restoreDocumentVersion, runPublishAction, BUILDER_CONFIG_KEY, } from './document.js';
11
11
  export { changedFields, createFieldClock, defaultFieldClock, KEEP_LOCK_CONTEXT, LOCKED_DOCUMENTS_SLUG, staleSaveMessage, } from './fieldsGuard.js';
12
+ export { loadRegionAccess, loadRegionValues, regionAccessFrom, regionAccessAt, regionEndpoints, writeRegionFields, REGION_SAVE_CONTEXT, } from './regions.js';
13
+ export { createWriteGate, defaultWriteGate, writeKey } from './writeGate.js';
@@ -0,0 +1,89 @@
1
+ import { type Endpoint, type PayloadRequest } from 'payload';
2
+ import { regionAccessAt } from '../core/regions.js';
3
+ import type { RegionConfig } from '../core/types.js';
4
+ import { type SettingsLocks } from './fieldsGuard.js';
5
+ import type { LiveRuntime } from './runtime.js';
6
+ import type { SessionTarget } from './session.js';
7
+ import type { LiveError, LiveFieldChange, LiveFieldConflict, RegionAccess } from './types.js';
8
+ import { type WriteGate } from './writeGate.js';
9
+ /** `context` flag of a save of region fields. */
10
+ export declare const REGION_SAVE_CONTEXT = "builderRegionFields";
11
+ type Doc = Record<string, unknown>;
12
+ export { regionAccessAt };
13
+ export declare const sameFieldValue: (a: unknown, b: unknown) => boolean;
14
+ /**
15
+ * What the user may read and change in the regions, from Payload's own document access
16
+ * (`docAccessOperation`: collection access and every field's `access`, for this document).
17
+ */
18
+ export declare function loadRegionAccess(req: PayloadRequest, target: SessionTarget, regions: readonly RegionConfig[]): Promise<RegionAccess>;
19
+ /** The regions' access from Payload's sanitized document permissions. */
20
+ export declare function regionAccessFrom(permissions: unknown, regions: readonly RegionConfig[]): RegionAccess;
21
+ /**
22
+ * The regions' values as the user may read them, in `locale` (ids, not documents): `values` with
23
+ * Payload's locale fallback, `storedValues` the locale's own values (see `LiveRegionsResponse`).
24
+ */
25
+ export declare function loadRegionValues(req: PayloadRequest, target: SessionTarget, regions: readonly RegionConfig[], locale: string | undefined): Promise<{
26
+ values: Doc;
27
+ storedValues: Doc;
28
+ updatedAt: string | null;
29
+ }>;
30
+ export type RegionWriteResult = {
31
+ ok: true;
32
+ values: Doc;
33
+ storedValues: Doc;
34
+ updatedAt: string | null;
35
+ changed: boolean;
36
+ } | {
37
+ ok: false;
38
+ status: number;
39
+ error: string;
40
+ conflicts?: LiveFieldConflict[];
41
+ errors?: LiveError[];
42
+ };
43
+ /** Checks the request body: a list of changes at paths inside the regions. */
44
+ export declare function parseChanges(regions: readonly RegionConfig[], body: unknown): LiveFieldChange[] | string;
45
+ export type RegionWriteOptions = {
46
+ target: SessionTarget;
47
+ regions: readonly RegionConfig[];
48
+ changes: LiveFieldChange[];
49
+ locale?: string;
50
+ runtime: LiveRuntime;
51
+ gate?: WriteGate;
52
+ settingsLocks?: SettingsLocks;
53
+ /** The user's access to the regions. Default: Payload's document access (`loadRegionAccess`). */
54
+ access?: typeof loadRegionAccess;
55
+ };
56
+ /**
57
+ * The new value with the stored values the editor never saw put back: fields of a group and of an
58
+ * array row (matched by row id) that the user may not read are missing from what the editor sent,
59
+ * and must not be erased by the save.
60
+ */
61
+ export declare function keepHidden(stored: unknown, incoming: unknown): unknown;
62
+ /**
63
+ * The paths a change really changes, compared with what the user can see now: leaves inside
64
+ * groups and array rows, or the array itself when rows come or go. Each needs update access, so a
65
+ * whole-group change cannot slip a field past its access rule.
66
+ */
67
+ export declare function changedPaths(before: unknown, after: unknown, path: string): string[];
68
+ /**
69
+ * Saves changes of region fields as the request's user: a draft when the collection has drafts
70
+ * (Publish publishes it with the layout), the document otherwise. The document's write gate is
71
+ * held from the fresh read to the commit. Refused:
72
+ * - 403 when the user may not change the document or one of the fields;
73
+ * - 409 when a field changed since the editor read it (`conflicts`), or while the same user has the
74
+ * settings drawer open (its form holds an older copy of the fields and would save it back);
75
+ * - 423 when someone else holds Payload's document lock (the Edit view or the settings drawer).
76
+ */
77
+ export declare function writeRegionFields(req: PayloadRequest, options: RegionWriteOptions): Promise<RegionWriteResult>;
78
+ export type RegionEndpointOptions = {
79
+ collections: Record<string, {
80
+ field: string;
81
+ regions?: RegionConfig[];
82
+ }>;
83
+ runtime: LiveRuntime;
84
+ gate?: WriteGate;
85
+ settingsLocks?: SettingsLocks;
86
+ /** The user's access to the regions. Default: Payload's document access. Tests pass a fake. */
87
+ access?: typeof loadRegionAccess;
88
+ };
89
+ export declare function regionEndpoints({ collections, runtime, gate, settingsLocks, access }: RegionEndpointOptions): Endpoint[];
@@ -0,0 +1,401 @@
1
+ // Endpoints of page regions: document fields outside the layout that the builder shows and edits
2
+ // (the collection's `regions` option, core/regions.ts).
3
+ //
4
+ // GET {api}/builder/live/:collection/:id/regions?locale= -> LiveRegionsResponse
5
+ // POST {api}/builder/live/:collection/:id/fields LiveFieldsRequest -> LiveFieldsResponse
6
+ //
7
+ // The fields stay the source of truth: a change goes through Payload's Local API as the user, so
8
+ // field access, hooks, validation, drafts, versions and the document lock apply as in the Edit
9
+ // view. The write gate (writeGate.ts) holds the document from the fresh read to the commit, so a
10
+ // region change never overwrites a session save or a settings drawer save, and the reverse.
11
+ import { addDataAndFileToRequest, docAccessOperation } from 'payload';
12
+ import { dataFields } from '../core/fields.js';
13
+ import { knownLocale, localeSettingsOf } from '../core/locale.js';
14
+ import { regionAccessAt, regionFieldOf, regionSelect, regionValues, setDocPath, valueAtDocPath } from '../core/regions.js';
15
+ import { isPlainObject } from '../core/tree.js';
16
+ import { payloadErrorMessage, payloadFieldErrors } from './apply.js';
17
+ import { LIVE_PATH, targetOf } from './endpoints.js';
18
+ import { defaultSettingsLocks, KEEP_LOCK_CONTEXT } from './fieldsGuard.js';
19
+ import { defaultWriteGate, writeKey } from './writeGate.js';
20
+ /** `context` flag of a save of region fields. */
21
+ export const REGION_SAVE_CONTEXT = 'builderRegionFields';
22
+ /** At most this many changes per request. */
23
+ const MAX_CHANGES = 50;
24
+ const PATH = /^[A-Za-z_$][\w$-]*(\.([A-Za-z_$][\w$-]*|\d+))*$/;
25
+ const api = (req) => req.payload;
26
+ const json = (body, status = 200) => Response.json(body, { status });
27
+ export { regionAccessAt };
28
+ function statusOf(error) {
29
+ const status = error?.status;
30
+ return typeof status === 'number' ? status : 500;
31
+ }
32
+ /** Payload's equality for a form value: empty values are equal, documents compare by id, keys in any order. */
33
+ function normalize(value) {
34
+ if (value === undefined || value === null || value === '')
35
+ return null;
36
+ if (Array.isArray(value))
37
+ return value.length === 0 ? null : value.map(normalize);
38
+ if (isPlainObject(value)) {
39
+ if ('id' in value && ('createdAt' in value || 'updatedAt' in value))
40
+ return normalize(value.id);
41
+ const out = {};
42
+ for (const key of Object.keys(value).toSorted()) {
43
+ const v = normalize(value[key]);
44
+ if (v !== null)
45
+ out[key] = v;
46
+ }
47
+ return Object.keys(out).length === 0 ? null : out;
48
+ }
49
+ return typeof value === 'number' || typeof value === 'boolean' ? String(value) : value;
50
+ }
51
+ export const sameFieldValue = (a, b) => JSON.stringify(normalize(a)) === JSON.stringify(normalize(b));
52
+ /** The request's locale when Payload has localization and knows it. */
53
+ function localeOf(req, value) {
54
+ const settings = localeSettingsOf(api(req).config.localization);
55
+ if (!settings)
56
+ return undefined;
57
+ return knownLocale(settings, typeof value === 'string' ? value : null);
58
+ }
59
+ /**
60
+ * True for an allowed right. Sanitized permissions say `true`; unsanitized ones and row-scoped
61
+ * collection access say `{ permission: true, where }` (the document matched the `where`).
62
+ */
63
+ const allowed = (right) => right === true || (isPlainObject(right) && right.permission === true);
64
+ /** Every data path (without row numbers) a region field holds: the field itself and the fields inside it. */
65
+ function dataPathsOf(path, field) {
66
+ const out = [path];
67
+ const f = field;
68
+ if (f.type === 'group' || f.type === 'array') {
69
+ for (const child of dataFields(f.fields))
70
+ out.push(...dataPathsOf(`${path}.${child.name}`, child));
71
+ }
72
+ return out;
73
+ }
74
+ /** The read and update rights at a path of Payload's sanitized field permissions. */
75
+ function permissionAt(fields, path) {
76
+ let level = fields;
77
+ let read = true;
78
+ let update = true;
79
+ for (const segment of path.split('.')) {
80
+ if (level === true)
81
+ return { read, update };
82
+ const entry = level[segment];
83
+ if (!entry)
84
+ return { read: false, update: false };
85
+ if (entry === true)
86
+ return { read, update };
87
+ read &&= allowed(entry.read);
88
+ update &&= allowed(entry.update);
89
+ level = entry.fields ?? true;
90
+ }
91
+ return { read, update };
92
+ }
93
+ /**
94
+ * What the user may read and change in the regions, from Payload's own document access
95
+ * (`docAccessOperation`: collection access and every field's `access`, for this document).
96
+ */
97
+ export async function loadRegionAccess(req, target, regions) {
98
+ const collection = req.payload.collections[target.collection];
99
+ if (!collection)
100
+ return {};
101
+ return regionAccessFrom(await docAccessOperation({ collection, id: target.id, req }), regions);
102
+ }
103
+ /** The regions' access from Payload's sanitized document permissions. */
104
+ export function regionAccessFrom(permissions, regions) {
105
+ const { update, fields } = (permissions ?? {});
106
+ const canUpdate = allowed(update);
107
+ const out = {};
108
+ for (const region of regions) {
109
+ for (const field of region.fields) {
110
+ for (const path of dataPathsOf(field.path, field.field)) {
111
+ const right = permissionAt(fields ?? true, path);
112
+ out[path] = { read: right.read, update: right.update && canUpdate };
113
+ }
114
+ }
115
+ }
116
+ return out;
117
+ }
118
+ // ---------------------------------------------------------------------------
119
+ // Reading and writing
120
+ // ---------------------------------------------------------------------------
121
+ /**
122
+ * The regions' values as the user may read them, in `locale` (ids, not documents): `values` with
123
+ * Payload's locale fallback, `storedValues` the locale's own values (see `LiveRegionsResponse`).
124
+ */
125
+ export async function loadRegionValues(req, target, regions, locale) {
126
+ const read = (fallback) => api(req).findByID({
127
+ collection: target.collection,
128
+ id: target.id,
129
+ depth: 0,
130
+ draft: target.drafts,
131
+ overrideAccess: false,
132
+ user: req.user,
133
+ select: regionSelect(regions),
134
+ ...(locale ? { locale } : {}),
135
+ ...(fallback ? {} : { fallbackLocale: 'none' }),
136
+ });
137
+ const doc = await read(true);
138
+ const values = regionValues(doc, regions);
139
+ const updatedAt = typeof doc.updatedAt === 'string' ? doc.updatedAt : null;
140
+ if (!req.payload.config.localization)
141
+ return { values, storedValues: values, updatedAt };
142
+ return { values, storedValues: ownValues(values, regionValues(await read(false), regions), regions), updatedAt };
143
+ }
144
+ /**
145
+ * The locale's own values for every region field path that `values` has: the own value, or `null`
146
+ * for none. Only paths the user may read (they are in `values`), so nothing else shows.
147
+ */
148
+ function ownValues(values, own, regions) {
149
+ let out = {};
150
+ for (const region of regions) {
151
+ for (const field of region.fields) {
152
+ if (valueAtDocPath(values, field.path) === undefined)
153
+ continue;
154
+ const value = valueAtDocPath(own, field.path);
155
+ const next = setDocPath(out, field.path, value === undefined ? null : value);
156
+ if (next.ok)
157
+ out = next.value;
158
+ }
159
+ }
160
+ return out;
161
+ }
162
+ /** Checks the request body: a list of changes at paths inside the regions. */
163
+ export function parseChanges(regions, body) {
164
+ const changes = isPlainObject(body) ? body.changes : undefined;
165
+ if (!Array.isArray(changes) || changes.length === 0)
166
+ return '`changes` must be a list of changes.';
167
+ if (changes.length > MAX_CHANGES)
168
+ return `At most ${MAX_CHANGES} changes per request.`;
169
+ const out = [];
170
+ for (const change of changes) {
171
+ if (!isPlainObject(change) || typeof change.path !== 'string' || !PATH.test(change.path))
172
+ return 'Every change needs a field `path`.';
173
+ if (!regionFieldOf(regions, change.path))
174
+ return `"${change.path}" is not a field of a region of this page.`;
175
+ if (!('value' in change))
176
+ return `The change of "${change.path}" has no \`value\`.`;
177
+ out.push({ path: change.path, value: change.value, ...('base' in change ? { base: change.base } : {}) });
178
+ }
179
+ return out;
180
+ }
181
+ /** A loaded document (an upload, a relationship): one value, compared by its id. */
182
+ const isDocument = (value) => 'id' in value && ('createdAt' in value || 'updatedAt' in value);
183
+ /**
184
+ * The new value with the stored values the editor never saw put back: fields of a group and of an
185
+ * array row (matched by row id) that the user may not read are missing from what the editor sent,
186
+ * and must not be erased by the save.
187
+ */
188
+ export function keepHidden(stored, incoming) {
189
+ if (isPlainObject(incoming) && isPlainObject(stored) && !isDocument(incoming)) {
190
+ const out = { ...stored };
191
+ for (const key of Object.keys(incoming))
192
+ out[key] = keepHidden(stored[key], incoming[key]);
193
+ return out;
194
+ }
195
+ if (Array.isArray(incoming) && Array.isArray(stored)) {
196
+ return incoming.map((row) => {
197
+ const id = isPlainObject(row) ? row.id : undefined;
198
+ const old = id === undefined || id === null ? undefined : stored.find((r) => isPlainObject(r) && r.id === id);
199
+ return old === undefined ? row : keepHidden(old, row);
200
+ });
201
+ }
202
+ return incoming;
203
+ }
204
+ /**
205
+ * The paths a change really changes, compared with what the user can see now: leaves inside
206
+ * groups and array rows, or the array itself when rows come or go. Each needs update access, so a
207
+ * whole-group change cannot slip a field past its access rule.
208
+ */
209
+ export function changedPaths(before, after, path) {
210
+ if (isPlainObject(after) && !isDocument(after) && (before === undefined || before === null || (isPlainObject(before) && !isDocument(before)))) {
211
+ const old = isPlainObject(before) ? before : {};
212
+ return Object.keys(after)
213
+ .filter((key) => key !== 'id')
214
+ .flatMap((key) => changedPaths(old[key], after[key], `${path}.${key}`));
215
+ }
216
+ if (Array.isArray(after) && Array.isArray(before) && after.length === before.length) {
217
+ return after.flatMap((row, i) => changedPaths(before[i], row, `${path}.${i}`));
218
+ }
219
+ return sameFieldValue(before, after) ? [] : [path];
220
+ }
221
+ /** A label for messages: the field's label, with the array row ("Links 2"). */
222
+ function changeLabel(regions, path) {
223
+ const found = regionFieldOf(regions, path);
224
+ if (!found)
225
+ return path;
226
+ const row = /\.(\d+)(?:\.|$)/.exec(path.slice(found.field.path.length));
227
+ return row ? `${found.field.label} ${Number(row[1]) + 1}` : found.field.label;
228
+ }
229
+ /**
230
+ * Saves changes of region fields as the request's user: a draft when the collection has drafts
231
+ * (Publish publishes it with the layout), the document otherwise. The document's write gate is
232
+ * held from the fresh read to the commit. Refused:
233
+ * - 403 when the user may not change the document or one of the fields;
234
+ * - 409 when a field changed since the editor read it (`conflicts`), or while the same user has the
235
+ * settings drawer open (its form holds an older copy of the fields and would save it back);
236
+ * - 423 when someone else holds Payload's document lock (the Edit view or the settings drawer).
237
+ */
238
+ export async function writeRegionFields(req, options) {
239
+ const { target, regions, changes, locale, runtime } = options;
240
+ const gate = options.gate ?? defaultWriteGate();
241
+ const locks = options.settingsLocks ?? defaultSettingsLocks();
242
+ const userId = req.user?.id;
243
+ if (!(await runtime.canUpdate(req, target.collection, target.id))) {
244
+ return { ok: false, status: 403, error: 'You are not allowed to change this document.' };
245
+ }
246
+ if ((typeof userId === 'string' || typeof userId === 'number') && locks.has(target.collection, target.id, userId)) {
247
+ return { ok: false, status: 409, error: 'Close the settings drawer first: it holds its own copy of these fields and would save it over this change.' };
248
+ }
249
+ const access = await (options.access ?? loadRegionAccess)(req, target, regions);
250
+ const refused = changes.filter((change) => !regionAccessAt(access, change.path).update);
251
+ if (refused.length > 0) {
252
+ return { ok: false, status: 403, error: `You are not allowed to change ${[...new Set(refused.map((c) => changeLabel(regions, c.path)))].join(', ')}.` };
253
+ }
254
+ const payload = api(req);
255
+ const read = (fallback) => payload.findByID({
256
+ collection: target.collection,
257
+ id: target.id,
258
+ depth: 0,
259
+ draft: target.drafts,
260
+ // The plugin's own read of values it writes back: siblings the user may not read must stay.
261
+ overrideAccess: true,
262
+ ...(locale ? { locale } : {}),
263
+ ...(fallback ? {} : { fallbackLocale: 'none' }),
264
+ });
265
+ return gate.run(writeKey(target.collection, target.id), req, async () => {
266
+ try {
267
+ // `shown`: what the user can see now, read as the user with Payload's locale fallback, as the
268
+ // editor got it. Bases compare with it, and conflicts return values from it only: a field the
269
+ // user may not read (also inside a group or an array row) is never in an answer.
270
+ // `stored`: every value of this locale (no access, no fallback). The save builds on it, so
271
+ // hidden fields stay and a fallback value never becomes a translation by itself.
272
+ const { values: shown } = await loadRegionValues(req, target, regions, locale);
273
+ const stored = await read(!locale);
274
+ const conflicts = [];
275
+ for (const change of changes) {
276
+ if (!('base' in change))
277
+ continue;
278
+ const now = valueAtDocPath(shown, change.path);
279
+ if (!sameFieldValue(now, change.base) && !sameFieldValue(now, change.value))
280
+ conflicts.push({ path: change.path, value: now ?? null });
281
+ }
282
+ if (conflicts.length > 0) {
283
+ const names = [...new Set(conflicts.map((c) => changeLabel(regions, c.path)))].join(', ');
284
+ return { ok: false, status: 409, error: `Not saved: someone else changed ${names} a moment ago. The page shows their version now.`, conflicts };
285
+ }
286
+ const denied = changes.flatMap((change) => changedPaths(valueAtDocPath(shown, change.path), change.value, change.path)).filter((path) => !regionAccessAt(access, path).update);
287
+ if (denied.length > 0) {
288
+ return { ok: false, status: 403, error: `You are not allowed to change ${[...new Set(denied.map((path) => changeLabel(regions, path)))].join(', ')}.` };
289
+ }
290
+ let next = stored;
291
+ const touched = new Set();
292
+ for (const change of changes) {
293
+ const value = keepHidden(valueAtDocPath(stored, change.path), change.value);
294
+ if (sameFieldValue(valueAtDocPath(next, change.path), value))
295
+ continue;
296
+ const result = setDocPath(next, change.path, value);
297
+ if (!result.ok) {
298
+ return { ok: false, status: 409, error: `Not saved: ${changeLabel(regions, change.path)} is gone. Someone removed it a moment ago.` };
299
+ }
300
+ next = result.value;
301
+ touched.add(change.path.split('.')[0]);
302
+ }
303
+ if (touched.size === 0) {
304
+ const { values, storedValues, updatedAt } = await loadRegionValues(req, target, regions, locale);
305
+ return { ok: true, values, storedValues, updatedAt, changed: false };
306
+ }
307
+ // Only the top-level fields that change. Payload merges them onto the newest version.
308
+ const data = Object.fromEntries([...touched].map((name) => [name, next[name]]));
309
+ await payload.update({
310
+ collection: target.collection,
311
+ id: target.id,
312
+ data,
313
+ depth: 0,
314
+ draft: target.drafts,
315
+ ...(target.drafts && target.autosave ? { autosave: true } : {}),
316
+ ...(locale ? { locale } : {}),
317
+ user: req.user,
318
+ // The same request: the save does not wait for the gate it already holds.
319
+ req,
320
+ overrideAccess: false,
321
+ // Someone else's lock (the Edit view, the settings drawer) refuses the save with 423.
322
+ overrideLock: false,
323
+ context: { [KEEP_LOCK_CONTEXT]: true, [REGION_SAVE_CONTEXT]: true },
324
+ });
325
+ const { values, storedValues, updatedAt } = await loadRegionValues(req, target, regions, locale);
326
+ return { ok: true, values, storedValues, updatedAt, changed: true };
327
+ }
328
+ catch (error) {
329
+ const status = statusOf(error);
330
+ if (status === 423) {
331
+ return { ok: false, status: 423, error: 'Not saved: someone else is editing this document’s settings right now. Try again when they finish.' };
332
+ }
333
+ const fields = payloadFieldErrors(error);
334
+ if (fields.length > 0) {
335
+ const errors = fields.map((e) => ({ path: e.path, message: `${changeLabel(regions, e.path)}: ${e.message}`, code: 'invalid' }));
336
+ return { ok: false, status: 400, error: `Not saved. ${payloadErrorMessage(error)}`, errors };
337
+ }
338
+ req.payload.logger.error({ err: error, msg: `[websiteBuilder] Could not save region fields of ${target.collection}:${String(target.id)}` });
339
+ return { ok: false, status: status >= 400 && status < 600 ? status : 500, error: `Not saved: ${payloadErrorMessage(error)}` };
340
+ }
341
+ });
342
+ }
343
+ export function regionEndpoints({ collections, runtime, gate, settingsLocks, access = loadRegionAccess }) {
344
+ const regionsOf = (target) => collections[target.collection]?.regions ?? [];
345
+ const read = {
346
+ path: `${LIVE_PATH}/:collection/:id/regions`,
347
+ method: 'get',
348
+ handler: async (req) => {
349
+ if (!req.user)
350
+ return json({ ok: false, error: 'Unauthorized' }, 401);
351
+ const target = targetOf(req, collections);
352
+ if (target instanceof Response)
353
+ return target;
354
+ const regions = regionsOf(target);
355
+ if (regions.length === 0)
356
+ return json({ ok: false, error: 'This collection has no regions.' }, 404);
357
+ const url = new URL(req.url ?? 'http://localhost');
358
+ try {
359
+ const [{ values, storedValues, updatedAt }, rights] = await Promise.all([
360
+ loadRegionValues(req, target, regions, localeOf(req, url.searchParams.get('locale'))),
361
+ access(req, target, regions),
362
+ ]);
363
+ return json({ ok: true, values, storedValues, access: rights, updatedAt });
364
+ }
365
+ catch (error) {
366
+ return json({ ok: false, error: 'Document not found or not readable' }, statusOf(error) === 403 ? 403 : 404);
367
+ }
368
+ },
369
+ };
370
+ const write = {
371
+ path: `${LIVE_PATH}/:collection/:id/fields`,
372
+ method: 'post',
373
+ handler: async (req) => {
374
+ if (!req.user)
375
+ return json({ ok: false, error: 'Unauthorized' }, 401);
376
+ const target = targetOf(req, collections);
377
+ if (target instanceof Response)
378
+ return target;
379
+ const regions = regionsOf(target);
380
+ if (regions.length === 0)
381
+ return json({ ok: false, error: 'This collection has no regions.' }, 404);
382
+ try {
383
+ await addDataAndFileToRequest(req);
384
+ }
385
+ catch {
386
+ return json({ ok: false, error: 'The body must be JSON' }, 400);
387
+ }
388
+ const changes = parseChanges(regions, req.data);
389
+ if (typeof changes === 'string')
390
+ return json({ ok: false, error: changes }, 400);
391
+ const locale = localeOf(req, req.data?.locale);
392
+ const result = await writeRegionFields(req, { target, regions, changes, locale, runtime, gate, settingsLocks, access });
393
+ if (!result.ok) {
394
+ const { status, ok: _ok, ...body } = result;
395
+ return json({ ok: false, ...body }, status);
396
+ }
397
+ return json({ ok: true, values: result.values, storedValues: result.storedValues, updatedAt: result.updatedAt });
398
+ },
399
+ };
400
+ return [read, write];
401
+ }
@@ -4,7 +4,7 @@ import { type SessionManager } from './session.js';
4
4
  * Checks that the request's user may update a document. The endpoints and the MCP tools call it
5
5
  * before a commit, because a commit changes the session at once and the draft is saved later.
6
6
  */
7
- export type UpdateAccessCheck = (req: PayloadRequest, collection: string, id: string) => Promise<boolean>;
7
+ export type UpdateAccessCheck = (req: PayloadRequest, collection: string, id: string | number) => Promise<boolean>;
8
8
  /** The document sessions and the access check. The endpoints, the save hook and the MCP tools share one. */
9
9
  export type LiveRuntime = {
10
10
  sessions: SessionManager;
@@ -1,11 +1,14 @@
1
1
  import { docAccessOperation } from 'payload';
2
2
  import { createSessionManager } from './session.js';
3
+ import { defaultWriteGate } from './writeGate.js';
3
4
  /** Key under `config.custom` where the plugin stores its runtime. */
4
5
  export const LIVE_RUNTIME_KEY = 'websiteBuilderLive';
5
6
  // v6: commits put locale operations in canonical form, sessions load every locale, and awareness
6
7
  // carries the editor's locale. A dev hot reload from an older runtime must not reuse its object.
7
8
  // v8: awareness carries the field the editor types in.
8
- const GLOBAL_KEY = Symbol.for('payload-canvas/live-runtime-v8');
9
+ // v9: the session's save holds the write gate, and a Payload blocks field has its codec.
10
+ // v10: sessions read the document's other fields again after every committed save (`currentDoc`).
11
+ const GLOBAL_KEY = Symbol.for('payload-canvas/live-runtime-v10');
9
12
  const ACCESS_TTL_MS = 30_000;
10
13
  /** Update access through Payload's own document access check, cached for 30 s per user and document. */
11
14
  export function createUpdateAccessCheck(ttlMs = ACCESS_TTL_MS) {
@@ -45,7 +48,7 @@ export function defaultLiveRuntime() {
45
48
  const store = globalThis;
46
49
  let runtime = store[GLOBAL_KEY];
47
50
  if (!runtime) {
48
- runtime = { sessions: createSessionManager(), canUpdate: createUpdateAccessCheck() };
51
+ runtime = { sessions: createSessionManager({ gate: defaultWriteGate() }), canUpdate: createUpdateAccessCheck() };
49
52
  store[GLOBAL_KEY] = runtime;
50
53
  }
51
54
  return runtime;