payload-canvas 0.1.1 → 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 +187 -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
@@ -0,0 +1,478 @@
1
+ // One save at a time per builder document.
2
+ //
3
+ // Payload's update reads the newest version, merges the request's data onto it and writes the
4
+ // whole version back. Two saves of one document that overlap therefore lose a change: the live
5
+ // session saves only the layout, the settings drawer's autosave saves the other fields, and the
6
+ // one that read first writes the other's fields back with their old values. The write gate makes
7
+ // every update of a builder document wait until the update before it has ended. A bulk update
8
+ // (`where`) is refused with a 409: Payload reads every document it updates before it writes any,
9
+ // so no wait per document could keep it from writing over a save that commits in between.
10
+ //
11
+ // When a save ends comes from the database's own answer, never from a guess:
12
+ // - With a transaction: when the adapter's `commitTransaction` or `rollbackTransaction` for that
13
+ // transaction settles. `installTransactionSignals` wraps the two methods of `payload.db` once (the
14
+ // plugin's `onInit`, and the first gated update, for runs without `onInit` such as
15
+ // `payload migrate`) and tells the gate the outcome: committed, or not.
16
+ // - Without a transaction (an adapter without them): the write is stored when the operation
17
+ // succeeds, so its `afterOperation` ends it. A failed REST request ends it in `afterError`. A
18
+ // failed Local API call has no hook, so `installLocalApiBoundary` wraps `payload.update` (the
19
+ // plugin's `onInit`): the call runs in its own async context (`AsyncLocalStorage`), every update
20
+ // it runs registers with it (the innermost call, also for nested calls and for parallel calls
21
+ // that share one `req`), and when the call's promise settles, its own updates that never reached
22
+ // `afterOperation` failed: their holds end at once. Retrying with the same `req`
23
+ // works as in Payload. A failed GraphQL request ends in the config's `afterError` (`failRequest`).
24
+ // Only a request abandoned with neither signal ends when it is garbage collected (a
25
+ // `FinalizationRegistry`), which can only happen after its operation is over; the gate keeps no
26
+ // strong reference to a request for that reason. A save with a transaction never ends that way:
27
+ // the transaction may outlive its request objects, and only the adapter's answer ends it (a
28
+ // transaction nobody commits or rolls back keeps its documents' gates, as it keeps its locks).
29
+ // Nothing ends a hold by time. A save that waits gives up after a while with a 409 ("another save
30
+ // of this document is still running"): the waiter fails clearly, the owner keeps the gate.
31
+ //
32
+ // One request may hold the gates of several documents (a hook that saves another document with the
33
+ // same `req`, in the same transaction). An update joins a hold only within the same active
34
+ // transaction (also from another request object that carries that transaction), or the same
35
+ // running operation without one, or inside `run`; a later update on a reused request takes the
36
+ // gate again. A wait that would close a cycle is refused at once (409).
37
+ //
38
+ // `afterCommit` queues work on the operation that runs it: with a transaction it runs when that
39
+ // transaction committed, never after a rollback or a failed commit; without one, when the
40
+ // operation succeeded. The events that tell editors a save happened use it, so nobody reloads
41
+ // values that are not stored.
42
+ //
43
+ // In-process only, like the live sessions (one server process; see docs/architecture.md section 12).
44
+ import { AsyncLocalStorage } from 'node:async_hooks';
45
+ import { APIError } from 'payload';
46
+ /** How long a save waits for the gate before it gives up with a 409. */
47
+ const WAIT_MS = 30_000;
48
+ /** The gate key of a document. Number and text ids of one document share a key. */
49
+ export const writeKey = (collection, id) => `${collection}:${String(id)}`;
50
+ /** A transaction id, or null for none (Payload leaves a Promise there when the adapter began none). */
51
+ const transactionOf = (req) => {
52
+ const value = req?.transactionID;
53
+ return value === undefined || value === null || value instanceof Promise ? null : value;
54
+ };
55
+ /**
56
+ * The function that opens a gate again. Made outside the function that waits for the gate: V8
57
+ * closures of one function share one context, and the waiting closures hold the request. A
58
+ * `release` made there would keep every request alive, and no request could ever be collected.
59
+ */
60
+ function releaser(tails, key, tail, open) {
61
+ return () => {
62
+ open();
63
+ if (tails.get(key) === tail)
64
+ tails.delete(key);
65
+ };
66
+ }
67
+ /** The document of a version (`restoreVersion` gets the version's id), or undefined. */
68
+ async function versionParent(req, collection, versionId) {
69
+ if (typeof versionId !== 'string' && typeof versionId !== 'number')
70
+ return undefined;
71
+ const db = req.payload?.db;
72
+ if (!db?.findVersions)
73
+ return undefined;
74
+ const { docs } = await db.findVersions({ collection, where: { id: { equals: versionId } }, limit: 1, pagination: false, req });
75
+ const parent = docs[0]?.parent;
76
+ return parent !== null && typeof parent === 'object' ? parent.id : parent;
77
+ }
78
+ /** The answer when a save cannot get the document's gate. */
79
+ function busy(key, why) {
80
+ return new APIError(`Not saved: another save of this document is still running (${why}). Try again in a moment.`, 409, { key }, true);
81
+ }
82
+ /**
83
+ * True when Payload runs an update as an update by id. Its Local API runs the bulk update unless
84
+ * `options.id` is truthy (an id of `0` or `''` runs the bulk update); REST and GraphQL send an id
85
+ * only to the update by id. An update with `where` is refused too, whatever its id.
86
+ */
87
+ const isUpdateByID = (args) => args.where === undefined && (typeof args.id === 'string' || typeof args.id === 'number') && Boolean(args.id);
88
+ /**
89
+ * The answer to a bulk update (`where`) of a builder document. It reads every document before it
90
+ * writes any, so no gate can keep it from writing over a save that commits in between.
91
+ */
92
+ function bulkRefused(collection) {
93
+ return new APIError(`Not saved: bulk updates of "${collection}" are not supported, because they can overwrite other saves of a document. Update each document by ID.`, 409, { collection }, true);
94
+ }
95
+ export function createWriteGate(options = {}) {
96
+ const waitMs = options.waitMs ?? WAIT_MS;
97
+ const tails = new Map();
98
+ /** The hold of each key. */
99
+ const holders = new Map();
100
+ /** The live holds of each request, by key. */
101
+ const byReq = new WeakMap();
102
+ /** The key a request waits for. */
103
+ const waiting = new WeakMap();
104
+ /** The running operations of each request, by key, innermost last. */
105
+ const running = new WeakMap();
106
+ /** The Local API call an update runs in: the innermost `localCall` around it. */
107
+ const calls = new AsyncLocalStorage();
108
+ /** Operations by their `args` (Payload passes the same object to `afterOperation`). */
109
+ const byArgs = new WeakMap();
110
+ /** Per open transaction: its holds, its running operations, and the work of its finished ones. */
111
+ const transactions = new Map();
112
+ /**
113
+ * A request collected while it held a gate without a transaction: its save is over (a failed
114
+ * Local API call). Holds with a transaction are never registered here.
115
+ */
116
+ const collected = new FinalizationRegistry((hold) => finish(hold));
117
+ const runAll = (callbacks) => {
118
+ for (const fn of callbacks.splice(0)) {
119
+ try {
120
+ fn();
121
+ }
122
+ catch (error) {
123
+ options.logger?.error?.('[websiteBuilder] An after-commit task failed.', error);
124
+ }
125
+ }
126
+ };
127
+ function finish(hold) {
128
+ if (hold.released)
129
+ return;
130
+ hold.released = true;
131
+ collected.unregister(hold);
132
+ const req = hold.req.deref();
133
+ const held = req ? byReq.get(req) : undefined;
134
+ if (held?.get(hold.key) === hold)
135
+ held.delete(hold.key);
136
+ if (holders.get(hold.key) === hold)
137
+ holders.delete(hold.key);
138
+ hold.release();
139
+ }
140
+ const transactionRecord = (transaction) => {
141
+ let record = transactions.get(transaction);
142
+ if (!record) {
143
+ record = { holds: new Set(), ops: new Set(), callbacks: [] };
144
+ transactions.set(transaction, record);
145
+ }
146
+ return record;
147
+ };
148
+ /** Takes an operation off its request's running list. */
149
+ const leave = (op) => {
150
+ op.ended = true;
151
+ const req = op.req.deref();
152
+ const list = req ? running.get(req)?.get(op.key) : undefined;
153
+ const index = list ? list.lastIndexOf(op) : -1;
154
+ if (list && index !== -1)
155
+ list.splice(index, 1);
156
+ };
157
+ /** An operation that ended without reaching afterOperation: no work, and without a transaction its hold ends. */
158
+ const fail = (op) => {
159
+ if (op.ended)
160
+ return;
161
+ op.callbacks.length = 0;
162
+ leave(op);
163
+ if (op.transaction === null && op.hold.owner === op)
164
+ finish(op.hold);
165
+ };
166
+ /** True when `req` waiting for `key` would close a cycle of waits. */
167
+ const wouldDeadlock = (req, key) => {
168
+ const seen = new Set();
169
+ for (let holder = holders.get(key); holder;) {
170
+ const owner = holder.req.deref();
171
+ if (!owner)
172
+ return false;
173
+ if (owner === req)
174
+ return true;
175
+ if (seen.has(owner))
176
+ return false;
177
+ seen.add(owner);
178
+ const next = waiting.get(owner);
179
+ holder = next ? holders.get(next) : undefined;
180
+ }
181
+ return false;
182
+ };
183
+ /** Waits for the gate of `key`, as `req`. Resolves with the hold; rejects with a 409 when it stays busy. */
184
+ const take = (key, req, transaction, kind) => {
185
+ if (wouldDeadlock(req, key))
186
+ return Promise.reject(busy(key, 'it waits for a document this save holds'));
187
+ const previous = tails.get(key) ?? Promise.resolve();
188
+ let open;
189
+ const mine = new Promise((resolve) => {
190
+ open = resolve;
191
+ });
192
+ const tail = previous.then(() => mine);
193
+ tails.set(key, tail);
194
+ const release = releaser(tails, key, tail, open);
195
+ let gaveUp = false;
196
+ waiting.set(req, key);
197
+ return new Promise((resolve, reject) => {
198
+ const timer = setTimeout(() => {
199
+ gaveUp = true;
200
+ if (waiting.get(req) === key)
201
+ waiting.delete(req);
202
+ reject(busy(key, `waited ${Math.round(waitMs / 1000)} s`));
203
+ }, waitMs);
204
+ timer.unref?.();
205
+ void previous.then(() => {
206
+ clearTimeout(timer);
207
+ // A waiter that gave up lets the next one go at once.
208
+ if (gaveUp) {
209
+ release();
210
+ return;
211
+ }
212
+ if (waiting.get(req) === key)
213
+ waiting.delete(req);
214
+ const hold = { key, req: new WeakRef(req), transaction, kind, owner: null, released: false, release };
215
+ holders.set(key, hold);
216
+ const held = byReq.get(req) ?? new Map();
217
+ held.set(key, hold);
218
+ byReq.set(req, held);
219
+ // Only a save without a transaction ends when its request is collected. A transaction can
220
+ // outlive every request object that carried it (`req: { transactionID }` per call): only the
221
+ // adapter's commit or rollback ends its holds.
222
+ if (kind === 'op' && transaction === null)
223
+ collected.register(req, hold, hold);
224
+ if (transaction !== null)
225
+ transactionRecord(transaction).holds.add(hold);
226
+ resolve(hold);
227
+ });
228
+ });
229
+ };
230
+ /**
231
+ * The live hold an update of `key` may join: the request's own hold in the same transaction, the
232
+ * same running operation, or `run`; or the hold of another request in the same open transaction
233
+ * (Payload's `req: { transactionID }` pattern: a new request object per call, one transaction).
234
+ * Its writes are that transaction's, and the hold ends with its commit or rollback.
235
+ */
236
+ const joinable = (req, key, transaction) => {
237
+ const hold = byReq.get(req)?.get(key);
238
+ if (hold && !hold.released) {
239
+ if (hold.kind === 'run')
240
+ return hold;
241
+ if (transaction !== null && hold.transaction === transaction)
242
+ return hold;
243
+ if (transaction === null && hold.transaction === null && hold.owner !== null && !hold.owner.ended)
244
+ return hold;
245
+ }
246
+ if (transaction === null)
247
+ return null;
248
+ const holder = holders.get(key);
249
+ return holder && !holder.released && holder.transaction === transaction ? holder : null;
250
+ };
251
+ /** Records that `req` takes part in `hold` (it joined the hold of another request). */
252
+ const remember = (req, hold) => {
253
+ const held = byReq.get(req) ?? new Map();
254
+ held.set(hold.key, hold);
255
+ byReq.set(req, held);
256
+ };
257
+ /**
258
+ * Wraps the adapter's commit and rollback and `payload.update` (both once per instance), from
259
+ * the first gated update on. The plugin's `onInit` does it too, but `payload migrate` runs
260
+ * without `onInit` (`disableOnInit`), and migrations on connect run before it: their commits
261
+ * must end their holds as well.
262
+ */
263
+ const learnFrom = (req) => {
264
+ const payload = req.payload;
265
+ if (payload?.db && typeof payload.db === 'object')
266
+ installTransactionSignals(payload.db, gate);
267
+ if (payload && typeof payload.update === 'function')
268
+ installLocalApiBoundary(payload, gate);
269
+ };
270
+ const gate = {
271
+ async run(key, req, task) {
272
+ if (joinable(req, key, transactionOf(req)))
273
+ return task();
274
+ const hold = await take(key, req, null, 'run');
275
+ try {
276
+ return await task();
277
+ }
278
+ finally {
279
+ finish(hold);
280
+ }
281
+ },
282
+ holds: (req) => [...(byReq.get(req)?.values() ?? [])].some((hold) => !hold.released),
283
+ afterCommit(req, key, fn) {
284
+ const op = running.get(req)?.get(key)?.at(-1);
285
+ if (op && !op.ended) {
286
+ op.callbacks.push(fn);
287
+ return;
288
+ }
289
+ // An operation the gate does not run (none of its updates): still never before the commit
290
+ // of the request's transaction.
291
+ const transaction = transactionOf(req);
292
+ if (transaction !== null) {
293
+ transactionRecord(transaction).callbacks.push(fn);
294
+ return;
295
+ }
296
+ fn();
297
+ },
298
+ transactionEnded(transaction, committed) {
299
+ const record = transactions.get(transaction);
300
+ if (!record)
301
+ return;
302
+ transactions.delete(transaction);
303
+ // Operations that never reached afterOperation failed: their work goes.
304
+ for (const op of record.ops) {
305
+ op.callbacks.length = 0;
306
+ leave(op);
307
+ }
308
+ const callbacks = record.callbacks.splice(0);
309
+ if (committed)
310
+ runAll(callbacks);
311
+ for (const hold of record.holds)
312
+ finish(hold);
313
+ },
314
+ failRequest(req) {
315
+ for (const ops of running.get(req)?.values() ?? []) {
316
+ for (const op of ops.slice())
317
+ if (op.transaction === null)
318
+ fail(op);
319
+ }
320
+ },
321
+ async localCall(call) {
322
+ const record = { ops: [] };
323
+ try {
324
+ return await calls.run(record, call);
325
+ }
326
+ finally {
327
+ // Saves with a transaction end with its commit or rollback; the others end here.
328
+ for (const op of record.ops)
329
+ if (op.transaction === null)
330
+ fail(op);
331
+ }
332
+ },
333
+ hooks(collection) {
334
+ return {
335
+ beforeOperation: async ({ args, operation, req }) => {
336
+ if (operation !== 'update' && operation !== 'restoreVersion')
337
+ return args;
338
+ // A bulk update is refused before it reads or writes anything (also with overrideAccess).
339
+ if (operation === 'update' && !isUpdateByID(args))
340
+ throw bulkRefused(collection);
341
+ let id = args.id;
342
+ // Restoring a version writes its document: its gate, by the version's parent.
343
+ if (operation === 'restoreVersion')
344
+ id = await versionParent(req, collection, id);
345
+ if (typeof id !== 'string' && typeof id !== 'number')
346
+ return args;
347
+ learnFrom(req);
348
+ const key = writeKey(collection, id);
349
+ const transaction = transactionOf(req);
350
+ const joined = joinable(req, key, transaction);
351
+ if (joined)
352
+ remember(req, joined);
353
+ const hold = joined ?? (await take(key, req, transaction, 'op'));
354
+ const op = { key, req: new WeakRef(req), hold, transaction, ended: false, callbacks: [] };
355
+ if (hold.kind === 'op' && hold.owner === null)
356
+ hold.owner = op;
357
+ if (transaction !== null)
358
+ transactionRecord(transaction).ops.add(op);
359
+ const ops = running.get(req) ?? new Map();
360
+ ops.set(key, [...(ops.get(key) ?? []), op]);
361
+ running.set(req, ops);
362
+ calls.getStore()?.ops.push(op);
363
+ byArgs.set(args, op);
364
+ return args;
365
+ },
366
+ afterOperation: ({ args, result }) => {
367
+ const op = byArgs.get(args);
368
+ if (!op)
369
+ return result;
370
+ byArgs.delete(args);
371
+ leave(op);
372
+ if (op.transaction === null) {
373
+ // Stored now: there is no commit to wait for.
374
+ runAll(op.callbacks);
375
+ if (op.hold.owner === op)
376
+ finish(op.hold);
377
+ return result;
378
+ }
379
+ // The commit follows: the work waits for the adapter's answer.
380
+ const record = transactions.get(op.transaction);
381
+ if (record) {
382
+ record.ops.delete(op);
383
+ record.callbacks.push(...op.callbacks.splice(0));
384
+ }
385
+ return result;
386
+ },
387
+ afterError: ({ req }) => {
388
+ // A failed REST request. Saves with a transaction end with its rollback.
389
+ for (const ops of running.get(req)?.values() ?? []) {
390
+ for (const op of ops.slice())
391
+ if (op.transaction === null)
392
+ fail(op);
393
+ }
394
+ },
395
+ };
396
+ },
397
+ size: () => tails.size,
398
+ };
399
+ return gate;
400
+ }
401
+ const WRAPPED = Symbol.for('payload-canvas/transaction-signals');
402
+ /**
403
+ * Tells the gate when the adapter committed or rolled back a transaction, from the adapter's own
404
+ * answer: wraps `commitTransaction` and `rollbackTransaction` of `payload.db` once. A commit that
405
+ * throws counts as not committed.
406
+ */
407
+ export function installTransactionSignals(db, gate) {
408
+ const target = db;
409
+ if (target[WRAPPED])
410
+ return;
411
+ target[WRAPPED] = true;
412
+ const commit = db.commitTransaction?.bind(db);
413
+ const rollback = db.rollbackTransaction?.bind(db);
414
+ if (commit) {
415
+ db.commitTransaction = (async (id) => {
416
+ let committed = false;
417
+ try {
418
+ const result = await commit(id);
419
+ committed = true;
420
+ return result;
421
+ }
422
+ finally {
423
+ gate.transactionEnded(id, committed);
424
+ }
425
+ });
426
+ }
427
+ if (rollback) {
428
+ db.rollbackTransaction = (async (id) => {
429
+ try {
430
+ return await rollback(id);
431
+ }
432
+ finally {
433
+ gate.transactionEnded(id, false);
434
+ }
435
+ });
436
+ }
437
+ }
438
+ const BOUNDARY = Symbol.for('payload-canvas/local-api-boundary');
439
+ /** Gives the gate the end of every Local API update: wraps `payload.update` once. The call itself is unchanged. */
440
+ export function installLocalApiBoundary(payload, gate) {
441
+ const target = payload;
442
+ if (target[BOUNDARY])
443
+ return;
444
+ target[BOUNDARY] = true;
445
+ const update = payload.update.bind(payload);
446
+ payload.update = (options) => gate.localCall(() => update(options));
447
+ }
448
+ /**
449
+ * Payload's `config.db` with the gate's signals installed as soon as the adapter exists. Payload
450
+ * calls `config.db.init({ payload })` first thing in `payload.init`, before the adapter's own
451
+ * `init` and `connect`, before migrations (`payload migrate` runs without `onInit`, and migrations
452
+ * on connect run before it) and before any operation. So the adapter's commit and rollback, and
453
+ * `payload.update` (failed Local API saves without a transaction), report to the gate from the
454
+ * first save on. The adapter object itself is returned unchanged; the plugin's `onInit` and the
455
+ * gate's first update install the same signals again as fallbacks (each install runs once).
456
+ */
457
+ export function withGateSignals(db, gate) {
458
+ const init = db.init;
459
+ return {
460
+ ...db,
461
+ init: (args) => {
462
+ const adapter = init.call(db, args);
463
+ if (adapter && typeof adapter === 'object')
464
+ installTransactionSignals(adapter, gate);
465
+ const payload = args?.payload;
466
+ if (payload && typeof payload.update === 'function')
467
+ installLocalApiBoundary(payload, gate);
468
+ return adapter;
469
+ },
470
+ };
471
+ }
472
+ const GATE_KEY = Symbol.for('payload-canvas/write-gate-v4');
473
+ /** The process-wide write gate. Kept on `globalThis`, so a dev hot reload keeps it. */
474
+ export function defaultWriteGate() {
475
+ const store = globalThis;
476
+ store[GATE_KEY] ??= createWriteGate({ logger: { error: (message, error) => console.error(message, error) } });
477
+ return store[GATE_KEY];
478
+ }
package/dist/mcp/index.js CHANGED
@@ -19,6 +19,8 @@ import { validateLayout } from '../core/validate.js';
19
19
  import { actorFromUser, splitLayoutErrors, userLabel } from '../live/apply.js';
20
20
  import { fieldRegistryOf, propAccessCheck } from '../live/fieldChecks.js';
21
21
  import { builderConfigOf } from '../live/document.js';
22
+ import { DRAFT_NOT_READABLE_MESSAGE, liveReadProblem, withLiveReadCheck } from '../live/draftAccess.js';
23
+ import { blocksAccessProblem, codecOf, withBlocksReadCheck } from '../live/storage.js';
22
24
  import { liveRuntimeOf } from '../live/runtime.js';
23
25
  import { storedLayout } from '../plugin/hook.js';
24
26
  import { builderViewPath, documentPath, draftPreviewPath } from '../plugin/links.js';
@@ -226,30 +228,43 @@ export function builderMcpTools(options) {
226
228
  if (!(await runtime.canUpdate(req, collection, id))) {
227
229
  return { ok: false, status: 403, error: 'Not allowed to edit this document (or it does not exist).', seq: 0 };
228
230
  }
229
- return runtime.sessions.commit({
230
- target: {
231
- collection,
232
- id,
233
- field: fieldOf(collection),
234
- drafts: Boolean(drafts),
235
- autosave: typeof drafts === 'object' && Boolean(drafts.autosave),
236
- },
231
+ const target = {
232
+ collection,
233
+ id,
234
+ field: fieldOf(collection),
235
+ drafts: Boolean(drafts),
236
+ autosave: typeof drafts === 'object' && Boolean(drafts.autosave),
237
+ // The collection's own Payload blocks field keeps its codec (live/storage.ts).
238
+ codec: codecOf(builderConfigOf(req.payload)?.collections[collection]),
239
+ };
240
+ // A Payload blocks field: only users who may read all of it and update it use the session.
241
+ // The session holds the document as a draft: only users who may read it so change it.
242
+ const stale = await liveReadProblem(req, target).catch(() => DRAFT_NOT_READABLE_MESSAGE);
243
+ if (stale)
244
+ return { ok: false, status: 403, error: stale, seq: 0 };
245
+ const denied = await blocksAccessProblem(req, target, { write: true, layouts: [runtime.sessions.peek(collection, id)?.layout] });
246
+ if (denied)
247
+ return { ok: false, status: 403, error: denied, seq: 0 };
248
+ const result = await runtime.sessions.commit({
249
+ target,
237
250
  store: req.payload,
238
251
  user: req.user,
239
252
  actor: await aiActor(req),
240
253
  ops,
241
254
  blocks,
242
255
  localization: localizationOf(req, collection),
243
- // Field access of block props, as for people's edits.
244
- access: propAccessCheck(req, {
256
+ // As for people's edits, inside the commit: the user may still read the draft; field access
257
+ // of block props; a Payload blocks field: and no value the user may not read, in any state.
258
+ access: withLiveReadCheck(req, target, withBlocksReadCheck(req, target, propAccessCheck(req, {
245
259
  blocks,
246
260
  registry: fieldRegistryOf(req.payload),
247
261
  collection,
248
262
  id,
249
263
  field: fieldOf(collection),
250
264
  localization: localizationOf(req, collection),
251
- }),
265
+ }))),
252
266
  });
267
+ return result;
253
268
  };
254
269
  /** The app's sections, then the saved sections the request's user can read (when turned on). */
255
270
  const allSections = async (req) => {
@@ -261,9 +276,26 @@ export function builderMcpTools(options) {
261
276
  * locale): the draft read gives one locale's view, so a localized layout comes from the database.
262
277
  */
263
278
  const currentLayout = async (req, collection, doc) => {
279
+ const codec = codecOf(builderConfigOf(req.payload)?.collections[collection]);
264
280
  const open = liveRuntimeOf(req.payload).sessions.peek(collection, String(doc.id));
281
+ // The session holds the document as a draft: a user who may read only other versions gets nothing from it.
282
+ if (open) {
283
+ const target = { collection, id: doc.id, field: fieldOf(collection), drafts: hasDrafts(req, collection) };
284
+ const stale = await liveReadProblem(req, target).catch(() => DRAFT_NOT_READABLE_MESSAGE);
285
+ if (stale)
286
+ throw new Error(stale);
287
+ }
288
+ // A Payload blocks field: the session holds every value, also ones this user may not read.
289
+ if (codec.kind === 'payload-blocks') {
290
+ const target = { collection, id: doc.id, field: fieldOf(collection), drafts: hasDrafts(req, collection), codec };
291
+ const unreadable = await blocksAccessProblem(req, target, { write: false, layouts: [open?.layout] });
292
+ if (unreadable)
293
+ throw new Error(unreadable);
294
+ }
265
295
  if (open)
266
296
  return { layout: open.layout, seq: open.seq };
297
+ if (codec.kind === 'payload-blocks')
298
+ return { layout: codec.decode(doc[fieldOf(collection)]) };
267
299
  const config = collectionConfig(req, collection);
268
300
  const stored = localizationOf(req, collection) && config && doc.id !== undefined ? await storedLayout(req, config, doc.id, fieldOf(collection)) : null;
269
301
  return { layout: stored ?? normalizeLayout(doc[fieldOf(collection)]) };
@@ -393,7 +425,13 @@ export function builderMcpTools(options) {
393
425
  return fail(errorMessage(error));
394
426
  }
395
427
  const titleField = collectionConfig(req, collection)?.admin?.useAsTitle;
396
- const current = await currentLayout(req, collection, doc);
428
+ let current;
429
+ try {
430
+ current = await currentLayout(req, collection, doc);
431
+ }
432
+ catch (error) {
433
+ return fail(errorMessage(error));
434
+ }
397
435
  const { settings } = at;
398
436
  let localized = {};
399
437
  if (settings) {
@@ -505,6 +543,12 @@ export function builderMcpTools(options) {
505
543
  }
506
544
  const localization = localizationOf(req, String(args.collection));
507
545
  const { blocking, warnings } = splitLayoutErrors(withoutBoundRequired(validateLayout(layout, blocks, { localization }), layout));
546
+ // A Payload blocks field refuses what it cannot store (classes, animations, other block types).
547
+ const codec = codecOf(builderConfigOf(req.payload)?.collections[String(args.collection)]);
548
+ if (blocking.length === 0) {
549
+ for (const message of codec.problems(normalizeLayout(layout)))
550
+ blocking.push({ path: '', message, code: 'invalid' });
551
+ }
508
552
  // The props' own `validate` functions (publish only, so they are warnings), on a layout that
509
553
  // has the right shape.
510
554
  if (blocking.length === 0) {