@stonecrop/graphql-middleware 0.16.6 → 0.18.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.
@@ -1,11 +1,44 @@
1
- import { camelToSnake, getPrimaryKeyField, pascalToSnake, resolveLinkRenderMode } from '@stonecrop/schema';
1
+ import { camelToSnake, getRecordIdField, pascalToSnake, resolveLinkRenderMode } from '@stonecrop/schema';
2
2
  import { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg';
3
3
  import { constant, lambda, object } from 'postgraphile/grafast';
4
4
  import { extendSchema } from 'postgraphile/utils';
5
+ import { columnBackedFields, flattenFields } from '../fields';
5
6
  import { getFetchHandler } from '../registry/fetchHandlers';
6
- import { getMeta, getAllMeta } from '../registry/doctypes';
7
+ import { getMeta, getAllMeta, validateReferences } from '../registry/doctypes';
7
8
  import { applyGuardedTransition } from '../dispatch/transition';
8
9
  import { typeDefs } from '../typeDefs';
10
+ /**
11
+ * Carries a reported failure out through a `throw`, purely so the transaction rolls back.
12
+ *
13
+ * `applyGuardedTransition` reports every failure as a return value, and a value returned from
14
+ * inside `withTransaction` commits. This is the adapter between "the action failed" and "undo it"
15
+ * that does not also turn a refused guard into a GraphQL error: the dispatcher unwraps it and
16
+ * answers with the original envelope.
17
+ */
18
+ class ActionRolledBack extends Error {
19
+ outcome;
20
+ constructor(outcome) {
21
+ super(outcome.error ?? 'Action failed');
22
+ this.outcome = outcome;
23
+ this.name = 'ActionRolledBack';
24
+ }
25
+ }
26
+ /**
27
+ * Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can
28
+ * read it. An *expanding* link is a relation in the payload rather than a scalar, so `getSqlColumns`
29
+ * omits its FK column by design — but the expansion needs the value to find the target. Aliasing
30
+ * keeps that need from changing the payload: every alias is stripped before the record is returned.
31
+ */
32
+ const LINK_FK_ALIAS = '__stonecropLinkFk_';
33
+ /**
34
+ * The column this adapter keeps a record's workflow state in.
35
+ *
36
+ * Named once because three statements depend on agreeing about it: the guard's `FOR UPDATE` read,
37
+ * the transition's write, and the data write that must refuse to touch it. A patch that could set
38
+ * this column would let any client walk past `allowedStates` by writing the very value the guard
39
+ * reads.
40
+ */
41
+ const STATE_COLUMN = 'status';
9
42
  /**
10
43
  * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
11
44
  *
@@ -29,6 +62,10 @@ export const createStonecropPlugin = (options = {}) => {
29
62
  return pgClient.query(query);
30
63
  }
31
64
  : (pgClient, query) => pgClient.query(query);
65
+ // Resolved once, for both read paths. `undefined` means "not configured" and `null` means
66
+ // "configured off", which is a distinction `??` cannot make — and the two paths disagreeing
67
+ // about it is exactly how a link came to be capped by a different number than a list.
68
+ const defaultRowLimit = options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit;
32
69
  return extendSchema(build => {
33
70
  // Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.
34
71
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- build.input.pgRegistry is a PostGraphile internal not in the public Build type
@@ -37,6 +74,11 @@ export const createStonecropPlugin = (options = {}) => {
37
74
  if (!executor) {
38
75
  throw new Error('StonecropPlugin: no pgExecutors found — ensure pgServices is configured');
39
76
  }
77
+ // Schema build is the one point where both the registry and the plugin's options are in
78
+ // hand, so it is where a stale registration can be caught before it silently no-ops.
79
+ if (options.actionHandlers)
80
+ assertActionHandlersResolve(options.actionHandlers);
81
+ assertReferencesResolve();
40
82
  return {
41
83
  typeDefs,
42
84
  objects: {
@@ -69,24 +111,64 @@ export const createStonecropPlugin = (options = {}) => {
69
111
  results[i] = { data: null, doctype };
70
112
  continue;
71
113
  }
114
+ // Not `data: null` — that is the answer for a record that does not exist, and a
115
+ // doctype nobody can look up is a misconfiguration, not an empty result.
72
116
  const pkMeta = getPkMeta(meta);
73
- if (!pkMeta) {
74
- for (const i of indices)
75
- results[i] = { data: null, doctype };
76
- continue;
77
- }
117
+ if (!pkMeta)
118
+ throw unresolvableIdentityError(doctype);
78
119
  const pkColumn = camelToSnake(pkMeta.fieldname);
79
120
  const columns = getSqlColumns(meta);
80
121
  const ids = indices.map(i => String(specs[i].id));
122
+ // Resolved once per doctype: how each link renders, and which foreign keys the
123
+ // SELECT must carry for the expansion below to work at all.
124
+ //
125
+ // `resolveLinkRenderMode` needs the linked field's own component, so the fields
126
+ // are indexed by name — flattened, because a link's field may sit inside a
127
+ // fieldset and `getSqlColumns` already descends to select it.
128
+ const fieldByName = new Map(flattenFields(meta.fields).map(f => [f.fieldname, f]));
129
+ const linkFkAliases = [];
130
+ for (const [linkName, link] of Object.entries(meta.links ?? {})) {
131
+ // Many-side links find their rows by a column on the *target*; only a one-side
132
+ // link reads a foreign key off this row.
133
+ if (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne')
134
+ continue;
135
+ const fieldname = link.fieldname ?? linkName;
136
+ // An inline link keeps its FK as a scalar, so `getSqlColumns` already selected
137
+ // it under its own name and no alias is needed.
138
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline')
139
+ continue;
140
+ linkFkAliases.push({ fieldname, alias: `${LINK_FK_ALIAS}${fieldname}` });
141
+ }
142
+ const selectList = [
143
+ columns,
144
+ ...linkFkAliases.map(({ fieldname, alias }) => `"${camelToSnake(fieldname)}" AS "${alias}"`),
145
+ ]
146
+ .filter(Boolean)
147
+ .join(', ');
81
148
  // TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;
82
149
  // requires refactoring the grouped-by-doctype loop to collect promises before resolving results
83
150
  // oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above
84
151
  const { rows } = await debugSql(pgClient, {
85
- text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
152
+ text: `SELECT ${selectList} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
86
153
  values: [ids],
87
154
  });
88
155
  // Use String() so integer PKs (e.g. serial) match the string ids from GraphQL
89
156
  const rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]));
157
+ // A declared key the database does not actually enforce as unique collapses several
158
+ // rows into that Map, and it keeps whichever came last — one arbitrary record,
159
+ // returned as though it were *the* record, with nothing to say so. Refuse instead.
160
+ //
161
+ // This is exact rather than a proxy for the problem: `ANY` matches each requested id
162
+ // once, so a shortfall here means two distinct rows genuinely share a key value. A
163
+ // `pg_index` check would instead ask whether a unique constraint exists, which is the
164
+ // cause rather than the harm — and would flag a column that is unique in practice but
165
+ // unconstrained, which is a real and common shape.
166
+ if (rows.length !== rowByPk.size) {
167
+ throw new Error(`Doctype "${doctype}" declares "${pkMeta.fieldname}" as its identity, but that column ` +
168
+ `is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows ` +
169
+ `matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. ` +
170
+ `Declare a field that uniquely identifies a record, or add a unique constraint.`);
171
+ }
90
172
  for (const i of indices) {
91
173
  const specId = String(specs[i].id);
92
174
  const row = rowByPk.get(specId);
@@ -95,6 +177,9 @@ export const createStonecropPlugin = (options = {}) => {
95
177
  continue;
96
178
  }
97
179
  const rowData = { ...row };
180
+ // Per record, not per doctype: two records of one doctype can differ in whether
181
+ // a relation overflowed, and a shared list would report the wrong one truncated.
182
+ const truncatedLinks = [];
98
183
  const recordOptions = (specs[i].options ?? {});
99
184
  const includeAll = recordOptions.includeNested === true;
100
185
  const includeSet = Array.isArray(recordOptions.includeNested)
@@ -103,10 +188,30 @@ export const createStonecropPlugin = (options = {}) => {
103
188
  // FetchStrategy dispatch over link declarations
104
189
  if (meta.links) {
105
190
  for (const [linkName, link] of Object.entries(meta.links)) {
191
+ // The payload key is the *resolved* fieldname, not the map key: the client
192
+ // binds a link to the field named `link.fieldname ?? key` and reads the
193
+ // nested data off that field, so writing under the bare key put the result
194
+ // somewhere nothing looks whenever a declaration named its own `fieldname`.
195
+ // Identical for every declaration that omits `fieldname`, which is all of them
196
+ // in this repo — hence latent until now.
197
+ const fieldname = link.fieldname ?? linkName;
106
198
  const fetch = link.fetch;
107
199
  const isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne';
108
200
  const effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy');
109
- const effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined;
201
+ // Two questions, kept apart. `method === 'sync'` is a *type narrowing* — only
202
+ // `SyncFetch` carries a `limit` — and the server default used to hang off its
203
+ // `else`, so declaring the method a many-side link already defaults to removed
204
+ // the cap entirely. "Did the author write a limit?" and "did the author write
205
+ // the word sync?" are now asked separately.
206
+ const declaredLimit = fetch?.method === 'sync' ? fetch.limit : undefined;
207
+ const effectiveLimit = isMany ? (declaredLimit ?? defaultRowLimit) : undefined;
208
+ // The one gate. It used to be followed by a second test that re-asked the
209
+ // same question using only `includeSet` — `null` for the boolean form — so
210
+ // `includeNested: true` admitted every link here and then silently dropped
211
+ // each non-`sync` one, handing back a partial record with no way to tell.
212
+ // That test was redundant wherever it was correct: with a name list this gate
213
+ // has already required membership, and without one it has already required
214
+ // `sync`, so it could only ever fire in the boolean case it got wrong.
110
215
  const shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync');
111
216
  if (!shouldInclude)
112
217
  continue;
@@ -116,11 +221,16 @@ export const createStonecropPlugin = (options = {}) => {
116
221
  if (handler) {
117
222
  // TODO(perf): custom link handlers per-row could run in parallel; needs collecting all custom handlers before await
118
223
  // oxlint-disable-next-line eslint/no-await-in-loop -- custom handler per link; see TODO above
119
- rowData[linkName] = await handler(pgClient, rowData, link);
224
+ rowData[fieldname] = await handler(pgClient, rowData, link);
120
225
  }
121
226
  continue;
122
227
  }
123
- if (effectiveMethod !== 'sync' && !includeSet?.has(linkName))
228
+ // `resolveLinkRenderMode` is the single definition of whether a link expands,
229
+ // and this loop was the one caller that never asked it. An `inline` link is a
230
+ // picker: the field holds its own id and the client resolves display text
231
+ // separately, so expanding it here overwrote that id with the whole target
232
+ // record and left the picker with an object it cannot render.
233
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline')
124
234
  continue;
125
235
  const targetMeta = getMeta(link.target);
126
236
  if (!targetMeta)
@@ -133,8 +243,10 @@ export const createStonecropPlugin = (options = {}) => {
133
243
  let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
134
244
  const linkValues = [specId];
135
245
  if (effectiveLimit != null) {
246
+ // One row more than the cap, same probe the list path uses: its presence
247
+ // is the whole truncation answer and costs no second query.
136
248
  sql += ` LIMIT $2`;
137
- linkValues.push(effectiveLimit);
249
+ linkValues.push(effectiveLimit + 1);
138
250
  }
139
251
  // TODO(perf): many-side link queries per row could be parallelized; needs collecting across links before await
140
252
  // oxlint-disable-next-line eslint/no-await-in-loop -- one SQL per backlink per row; see TODO above
@@ -142,19 +254,34 @@ export const createStonecropPlugin = (options = {}) => {
142
254
  text: sql,
143
255
  values: linkValues,
144
256
  });
145
- rowData[linkName] = linked;
257
+ // A truncated relation that says nothing is how a read-modify-write deletes
258
+ // the tail: the client cannot tell 50 rows from all of them, so it writes
259
+ // back what it was given. Reported for every source of truncation, the
260
+ // author's `fetch.limit` included — that one is just as silent.
261
+ if (effectiveLimit != null && linked.length > effectiveLimit) {
262
+ truncatedLinks.push(fieldname);
263
+ rowData[fieldname] = linked.slice(0, effectiveLimit);
264
+ }
265
+ else {
266
+ rowData[fieldname] = linked;
267
+ }
146
268
  }
147
269
  else {
148
- if (!link.fieldname)
149
- continue;
150
- const fkValue = rowData[link.fieldname];
270
+ // Read from the reserved alias, never the fieldname: an expanding link's FK
271
+ // column is deliberately absent from `getSqlColumns`, so the plain read found
272
+ // `undefined` on every record and answered `null` — a relation that looked
273
+ // permanently empty rather than one nobody had asked the right question for.
274
+ const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
151
275
  if (fkValue == null) {
152
- rowData[linkName] = null;
276
+ rowData[fieldname] = null;
153
277
  continue;
154
278
  }
279
+ // `continue` here would drop the link from the payload, which reads to the
280
+ // client as "this record has no such relation" rather than "its target
281
+ // cannot be identified".
155
282
  const targetPkMeta = getPkMeta(targetMeta);
156
283
  if (!targetPkMeta)
157
- continue;
284
+ throw unresolvableIdentityError(targetMeta.name);
158
285
  const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
159
286
  // TODO(perf): one-side link FK lookups per row could be parallelized; needs collecting across links before await
160
287
  // oxlint-disable-next-line eslint/no-await-in-loop -- one FK lookup per link per row; see TODO above
@@ -162,35 +289,46 @@ export const createStonecropPlugin = (options = {}) => {
162
289
  text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
163
290
  values: [fkValue],
164
291
  });
165
- rowData[linkName] = linked[0] ?? null;
292
+ rowData[fieldname] = linked[0] ?? null;
166
293
  }
167
294
  }
168
295
  }
296
+ // The aliases are a read channel for this loop, not part of the record. Stripped
297
+ // unconditionally so a link that was never expanded cannot leak its raw FK into a
298
+ // payload that has otherwise always described that relation as a nested object.
299
+ for (const { alias } of linkFkAliases)
300
+ delete rowData[alias];
169
301
  // Names in includeNested that don't correspond to any link
170
302
  const unknownLinks = includeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links)) : undefined;
171
303
  results[i] = {
172
304
  data: rowData,
173
305
  doctype,
174
306
  unknownLinks: unknownLinks?.length ? unknownLinks : undefined,
307
+ truncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,
175
308
  };
176
309
  }
177
310
  }
178
311
  return results;
179
312
  });
180
313
  },
181
- stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset }) {
314
+ stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
182
315
  return loadOneWithPgClient(executor, object({
183
316
  doctype: $doctype,
184
317
  filters: $filters,
185
318
  orderBy: $orderBy,
186
319
  limit: $limit,
187
320
  offset: $offset,
321
+ includeTotal: $includeTotal,
188
322
  }), async (pgClient, specs) => {
189
323
  return await Promise.all(specs.map(async (spec) => {
190
324
  const doctype = String(spec.doctype);
191
325
  const meta = getMeta(doctype);
192
326
  if (!meta) {
193
- return { data: [], doctype, count: 0 };
327
+ // An unknown doctype answers "no records" rather than erroring, so a caller
328
+ // who asked for a total gets 0. Returning null here would make null mean
329
+ // two things — "you did not ask" and "I could not say" — and a client
330
+ // cannot tell those apart.
331
+ return { data: [], doctype, hasMore: false, count: spec.includeTotal === true ? 0 : null };
194
332
  }
195
333
  const knownFields = new Set(flattenFields(meta.fields).map(f => f.fieldname));
196
334
  const columns = getSqlColumns(meta);
@@ -228,10 +366,22 @@ export const createStonecropPlugin = (options = {}) => {
228
366
  }
229
367
  orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
230
368
  }
231
- // LIMIT / OFFSET
369
+ // LIMIT / OFFSET. A caller that names no limit gets the configured default rather
370
+ // than the whole table: omission is how an unbounded scan used to happen, and the
371
+ // only guard against it lived in the scaffold's fetch helper, which is neither the
372
+ // right layer nor present in a host that wrote its own.
373
+ // Grafast passes arguments through as loosely-typed runtime values, so narrow
374
+ // before doing arithmetic on this — same reason orderBy is validated above.
375
+ if (spec.limit != null && typeof spec.limit !== 'number') {
376
+ throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
377
+ }
378
+ const effectiveLimit = spec.limit ?? defaultRowLimit;
232
379
  let pagingClause = '';
233
- if (spec.limit != null) {
234
- values.push(spec.limit);
380
+ if (effectiveLimit != null) {
381
+ // One more row than asked for. Its presence is the whole `hasMore` answer, and
382
+ // it is discarded below — this is why knowing a list is truncated costs no
383
+ // second query, where a COUNT(*) would be a full scan on every list read.
384
+ values.push(effectiveLimit + 1);
235
385
  pagingClause += ` LIMIT $${values.length}`;
236
386
  }
237
387
  if (spec.offset != null) {
@@ -242,9 +392,19 @@ export const createStonecropPlugin = (options = {}) => {
242
392
  text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)}${whereClause}${orderByClause}${pagingClause}`,
243
393
  values,
244
394
  });
245
- // Total count matching filters (independent of LIMIT/OFFSET)
246
- let count = rows.length;
247
- if (spec.limit != null || spec.offset != null) {
395
+ // The extra row requested above is a probe, not data. Its presence is what makes
396
+ // a capped page distinguishable from a complete table; trim it before anything
397
+ // downstream can mistake it for a record.
398
+ const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
399
+ const data = hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows;
400
+ // Total matching the filters, independent of LIMIT/OFFSET, and opt-in.
401
+ //
402
+ // Explicitly requested rather than inferred from whether `count` was selected:
403
+ // this resolver is a Grafast plan step and receives only its arguments, never the
404
+ // selection set, and making the plan vary by selection is what Grafast optimises
405
+ // against. An argument also puts the cost in the query the client wrote.
406
+ let count = null;
407
+ if (spec.includeTotal === true) {
248
408
  const countValues = [];
249
409
  const countWhere = [];
250
410
  if (spec.filters != null) {
@@ -263,7 +423,7 @@ export const createStonecropPlugin = (options = {}) => {
263
423
  });
264
424
  count = parseInt(countRows[0]?.row_count ?? '0', 10);
265
425
  }
266
- return { data: rows, doctype, count };
426
+ return { data, doctype, hasMore, count };
267
427
  }));
268
428
  });
269
429
  },
@@ -289,40 +449,203 @@ export const createStonecropPlugin = (options = {}) => {
289
449
  error: `Unknown action: ${spec.action} on ${spec.doctype}`,
290
450
  };
291
451
  }
292
- const pkMeta = getPkMeta(meta);
293
- if (!pkMeta) {
294
- return {
295
- success: false,
296
- data: null,
297
- error: `No primary key for doctype: ${spec.doctype}`,
298
- };
299
- }
300
- const pkColumn = camelToSnake(pkMeta.fieldname);
301
452
  const table = resolveTableName(meta.name, options.tables);
453
+ // Resolved lazily: only a state read or write needs the key column. A
454
+ // record-less command reaches its handler on a doctype that declares no
455
+ // primary key, which an eager check would refuse for no reason.
456
+ const pkColumn = () => {
457
+ const pkMeta = getPkMeta(meta);
458
+ if (!pkMeta)
459
+ throw unresolvableIdentityError(String(spec.doctype));
460
+ return camelToSnake(pkMeta.fieldname);
461
+ };
302
462
  // Record envelope: [{ id, data }] — the transition keys off the record id.
303
463
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.actionArgs is a Grafast runtime value; record envelope shape is the dispatch contract
304
464
  const argList = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []);
305
465
  const recordId = argList[0]?.id;
466
+ const recordData = argList[0]?.data ?? {};
467
+ // The database author's effect for this action, if one is registered. Keyed
468
+ // by the doctype's canonical name so a slug-resolved lookup above cannot
469
+ // silently miss it.
470
+ const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
471
+ // What a data write is allowed to set. Column identifiers come from the
472
+ // doctype and never from the request — `args` is an opaque JSON scalar, so
473
+ // every key in `data` is browser-supplied — which is what makes it safe to
474
+ // build SQL from a patch at all.
475
+ //
476
+ // The same derivation the read path uses, so what a record exposes is what a
477
+ // record accepts. `status` is removed because state is the workflow's to
478
+ // move, never the patch's.
479
+ const writable = new Map(columnBackedFields(meta.fields)
480
+ .filter(f => camelToSnake(f.fieldname) !== STATE_COLUMN)
481
+ .map(f => [f.fieldname, f]));
482
+ // Whether this doctype has a workflow state to read at all. Derived from the
483
+ // same declarations, so the guard cannot look for a column the doctype's own
484
+ // API surface does not describe.
485
+ const declaresState = columnBackedFields(meta.fields).some(f => camelToSnake(f.fieldname) === STATE_COLUMN);
486
+ // Reported on the result rather than logged: a dropped key is data the user
487
+ // believes was saved, which is the same data-loss signal `truncatedLinks`
488
+ // carries for a truncated read.
489
+ const droppedFields = [];
490
+ const partitionPatch = (patch) => {
491
+ const cols = [];
492
+ const values = [];
493
+ for (const [key, value] of Object.entries(patch)) {
494
+ if (!writable.has(key)) {
495
+ droppedFields.push(key);
496
+ continue;
497
+ }
498
+ // An expanding link reads back as a nested record while its column
499
+ // holds a scalar foreign key, so a read-modify-write hands this loop
500
+ // an object bound for a uuid column. The name resolving is not
501
+ // enough; the shape has to match a column value too.
502
+ if (value !== null && typeof value === 'object') {
503
+ droppedFields.push(key);
504
+ continue;
505
+ }
506
+ cols.push(camelToSnake(key));
507
+ values.push(value);
508
+ }
509
+ return { cols, values };
510
+ };
511
+ // One transaction spans the guard read, the effect and the state write, so an
512
+ // action either lands whole or not at all. `withTransaction` issues `begin` at
513
+ // the top level and a `savepoint` if something upstream already opened one, so
514
+ // nesting is safe rather than something callers must avoid.
515
+ //
516
+ // Every statement below runs on `tx`, not on the outer client. Work sent to the
517
+ // outer client — or to a connection a handler opens itself — is outside this
518
+ // transaction and would survive a rollback.
306
519
  try {
307
- return await applyGuardedTransition(actionDef, {
308
- readState: async () => {
309
- if (recordId == null)
310
- return undefined;
311
- const { rows } = await debugSql(pgClient, {
312
- text: `SELECT "status" FROM ${table} WHERE "${pkColumn}"::text = $1`,
313
- values: [String(recordId)],
314
- });
315
- return rows[0]?.status == null ? undefined : rows[0].status;
316
- },
317
- writeState: async (nextState) => {
318
- await debugSql(pgClient, {
319
- text: `UPDATE ${table} SET "status" = $1 WHERE "${pkColumn}"::text = $2`,
320
- values: [nextState, String(recordId)],
321
- });
322
- },
520
+ return await pgClient.withTransaction(async (tx) => {
521
+ const outcome = await applyGuardedTransition(actionDef, {
522
+ readState: async () => {
523
+ // No id in the envelope means no record was targeted at all, which is
524
+ // the same answer as a lookup that misses: `null`, not `undefined`.
525
+ if (recordId == null)
526
+ return null;
527
+ // Selecting `status` unconditionally made this read fail outright on
528
+ // any table without that column — and a self-transition reaches here
529
+ // not to read a state but to learn whether the row exists, which is
530
+ // what decides create vs. update. So the projection follows the
531
+ // doctype: a doctype that declares no state field has none to read,
532
+ // and the honest answer for a row it finds is "exists, no state".
533
+ // (Measured: 24 of FAB's 35 guarded tables have no `status` column.)
534
+ const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
535
+ // FOR UPDATE holds the row until this transaction ends, so a second
536
+ // action on the same record waits rather than reading the same state
537
+ // and acting on it too. Without it the guard is a check-then-act
538
+ // race: two concurrent approvals both read PENDING and both proceed.
539
+ const { rows } = await debugSql(tx, {
540
+ text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
541
+ values: [String(recordId)],
542
+ });
543
+ // No row at all vs. a row whose `status` is NULL — see GuardedTransitionIO.
544
+ if (rows.length === 0)
545
+ return null;
546
+ if (!declaresState)
547
+ return undefined;
548
+ return rows[0][STATE_COLUMN] ?? undefined;
549
+ },
550
+ writeState: async (nextState) => {
551
+ await debugSql(tx, {
552
+ text: `UPDATE ${table} SET "${STATE_COLUMN}" = $1 WHERE "${pkColumn()}"::text = $2`,
553
+ values: [nextState, String(recordId)],
554
+ });
555
+ },
556
+ // The upsert, and the only write path for record data. `exists`
557
+ // comes from the guard's own read, so no second lookup decides it.
558
+ //
559
+ // Returns the same projection the read path selects, never
560
+ // `RETURNING *`: raw columns come back snake_case, and the client
561
+ // resolves identity by the *declared fieldname*. A doctype keyed
562
+ // `itemId` would receive `item_id`, find no identity, and file a
563
+ // created record nowhere — which is that exact bug, already once
564
+ // shipped and patched downstream.
565
+ writeData: async (patch, exists) => {
566
+ const { cols, values } = partitionPatch(patch);
567
+ const returning = getSqlColumns(meta);
568
+ if (!exists) {
569
+ // Creating is what the *absence* of an id means. An id that was
570
+ // dispatched and matched nothing is a record that has gone away
571
+ // since the client read it, and treating that as a create mints a
572
+ // second row under a new identity while the client believes it
573
+ // updated the first — a lost update that reports success.
574
+ //
575
+ // The dispatcher cannot make this call: it never receives the id,
576
+ // deliberately, since identity is the backend's business. So the
577
+ // distinction its `readState` contract collapses is restored here,
578
+ // where the id is in scope.
579
+ if (recordId != null) {
580
+ throw new Error(`Action "${actionDef.label ?? spec.action}" targets ${meta.name} "${String(recordId)}", ` +
581
+ `which no longer exists. Nothing was created — a record dispatched with an ` +
582
+ `identity is an update, and creating one is what dispatching no identity means.`);
583
+ }
584
+ // No identity is minted here. A declared key present in the
585
+ // patch is a natural key the user filled in and passes
586
+ // through the whitelist like any other column; absent, the
587
+ // column default supplies it. Either way the row states its
588
+ // own identity back.
589
+ const text = cols.length
590
+ ? `INSERT INTO ${table} (${cols.map(c => `"${c}"`).join(', ')}) VALUES (${cols.map((_col, i) => `$${i + 1}`).join(', ')}) RETURNING ${returning}`
591
+ : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning}`;
592
+ const { rows } = await debugSql(tx, { text, values });
593
+ return rows[0] ?? {};
594
+ }
595
+ // Nothing writable survived the patch. `SET` with no assignments
596
+ // is a syntax error, and reporting failure would be wrong — the
597
+ // record is fine, it just has no new data. Read it back so the
598
+ // client still gets the record, with `droppedFields` saying why
599
+ // nothing changed.
600
+ if (cols.length === 0) {
601
+ const { rows } = await debugSql(tx, {
602
+ text: `SELECT ${returning} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
603
+ values: [String(recordId)],
604
+ });
605
+ return rows[0] ?? {};
606
+ }
607
+ const assignments = cols.map((c, i) => `"${c}" = $${i + 1}`).join(', ');
608
+ const { rows } = await debugSql(tx, {
609
+ text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning}`,
610
+ values: [...values, String(recordId)],
611
+ });
612
+ return rows[0] ?? {};
613
+ },
614
+ runEffect: handler
615
+ ? (currentState) => handler({
616
+ pgClient: tx,
617
+ doctype: String(spec.doctype),
618
+ action: String(spec.action),
619
+ meta,
620
+ recordId,
621
+ data: recordData,
622
+ args: argList,
623
+ currentState,
624
+ })
625
+ : undefined,
626
+ },
627
+ // The patch a self-transition persists. This adapter never passed it, which
628
+ // was moot while it had no `writeData` — nothing consumed it. Wiring the write
629
+ // without this argument saves an empty record and reports success.
630
+ recordData);
631
+ // `applyGuardedTransition` REPORTS failure, it does not throw — a refused
632
+ // guard and a handler that blew up both come back as `{ success: false }`.
633
+ // Returning that normally would commit the transaction, so a handler that
634
+ // wrote three rows and then threw would keep all three. Throwing here is
635
+ // what makes the rollback happen; the envelope is carried across so the
636
+ // caller still gets `success: false` rather than a GraphQL error.
637
+ if (!outcome.success)
638
+ throw new ActionRolledBack(outcome);
639
+ // Attached here rather than carried through `applyGuardedTransition`:
640
+ // which keys a backend can store is a storage question, and the
641
+ // dispatcher is deliberately storage-agnostic. A failed action wrote
642
+ // nothing, so the list is only meaningful on success.
643
+ return droppedFields.length ? { ...outcome, droppedFields } : outcome;
323
644
  });
324
645
  }
325
646
  catch (err) {
647
+ if (err instanceof ActionRolledBack)
648
+ return err.outcome;
326
649
  return {
327
650
  success: false,
328
651
  data: null,
@@ -340,23 +663,6 @@ export const createStonecropPlugin = (options = {}) => {
340
663
  // ===========================================================================
341
664
  // SQL column helpers
342
665
  // ===========================================================================
343
- /**
344
- * Recursively flatten Fieldset containers into a flat array of non-container fields.
345
- * Fieldset entries are replaced by their children; all other fields pass through.
346
- * Used by getSqlColumns (for SELECT) and knownFields (for filter/orderBy validation).
347
- */
348
- function flattenFields(fields) {
349
- const result = [];
350
- for (const f of fields) {
351
- if (f.kind === 'fieldset') {
352
- result.push(...flattenFields(f.schema));
353
- }
354
- else {
355
- result.push(f);
356
- }
357
- }
358
- return result;
359
- }
360
666
  /**
361
667
  * Derive quoted SQL column entries from a flat field array.
362
668
  * Skips non-scalar fields (kind !== 'field'), `computed` fields
@@ -365,12 +671,7 @@ function flattenFields(fields) {
365
671
  */
366
672
  function collectColumns(fields, links) {
367
673
  const columns = [];
368
- for (const f of flattenFields(fields)) {
369
- if (f.kind !== 'field')
370
- continue;
371
- // A computed field has no backing DB column.
372
- if (f.computed)
373
- continue;
674
+ for (const f of columnBackedFields(fields)) {
374
675
  // Only an *expanding* link is a relation rather than a column. An inline link (a picker)
375
676
  // keeps its FK on this table and must still be selected — `resolveLinkRenderMode` is the
376
677
  // shared rule, also used by the client resolver; never re-derive it here.
@@ -402,14 +703,111 @@ export function getSqlColumns(meta) {
402
703
  return collectColumns(meta.fields, links).join(', ');
403
704
  }
404
705
  /**
405
- * Find the field marked `primaryKey` in the doctype.
406
- * Returns undefined when none is marked (PK-less doctypes).
706
+ * Resolve the declared field this doctype's records are looked up by.
707
+ *
708
+ * Delegates the *rule* to `@stonecrop/schema` so the server's SQL identity predicate and the
709
+ * client's record keying name the same field — including the `id` fallback, whose absence here
710
+ * used to make the two disagree: a doctype declaring no `primaryKey` was keyed by `id` on the
711
+ * client and refused outright by this adapter, so every fetch answered `null` and looked exactly
712
+ * like a record that does not exist.
407
713
  *
408
- * Delegates to `@stonecrop/schema` so the server's identity predicate and the client's record
409
- * keying resolve the same field — this used to be a private re-implementation of that rule.
714
+ * Returns `undefined` only when the resolved name is not a declared top-level field — a doctype
715
+ * with no `primaryKey` and no `id`. That case cannot be served: `getSqlColumns` selects declared
716
+ * fields only, so the row map would key on a column the SELECT never returned and every lookup
717
+ * would miss silently. Callers must say so rather than answer `null`.
410
718
  */
411
719
  function getPkMeta(meta) {
412
- return getPrimaryKeyField(meta.fields);
720
+ const fieldname = getRecordIdField(meta.fields);
721
+ return meta.fields.find((f) => f.kind === 'field' && f.fieldname === fieldname);
722
+ }
723
+ /**
724
+ * Assert that every registered action handler names a doctype and an action that exist.
725
+ *
726
+ * An unregistered action is fine — a transition needs no effect. The reverse is not: a handler
727
+ * registered under a key nothing resolves to can never run, and **nothing says so at dispatch**.
728
+ * `applyGuardedTransition` fails loudly only when the action also has no state outcome; when it
729
+ * has one, the missing effect is skipped and the state write still reports success. So renaming a
730
+ * doctype leaves `approve` moving records to APPROVED while its ledger posting quietly stops.
731
+ *
732
+ * Two ways a key fails to resolve, and the second is the trap. `getMeta` falls back to matching a
733
+ * slug, but dispatch looks handlers up by `meta.name`, so a slug-keyed registration resolves to a
734
+ * real doctype here and still never fires. It is reported as its own case rather than as "unknown
735
+ * doctype", because the repair is different.
736
+ *
737
+ * Throws rather than warns: there is no legitimate reason to register a handler for an action that
738
+ * does not exist, and the alternative is a silent half-executed workflow. Every offender is
739
+ * collected so a consumer with several fixes them in one pass.
740
+ */
741
+ function assertActionHandlersResolve(actionHandlers) {
742
+ // Nothing registered, nothing to check.
743
+ const registered = Object.entries(actionHandlers);
744
+ if (registered.length === 0)
745
+ return;
746
+ // An empty registry cannot tell "this key is stale" from "doctypes have not loaded yet" — a
747
+ // host is free to build the schema before its loader runs. Warn on that ambiguity rather than
748
+ // failing a boot that is merely early.
749
+ if (getAllMeta().length === 0) {
750
+ // oxlint-disable-next-line no-console
751
+ console.warn('[@stonecrop/graphql-middleware] Schema built with no doctypes registered, so the ' +
752
+ '`actionHandlers` map could not be verified. Load doctypes before building the schema to ' +
753
+ 'have stale handler keys reported.');
754
+ return;
755
+ }
756
+ const orphans = [];
757
+ for (const [doctypeKey, handlers] of registered) {
758
+ const meta = getMeta(doctypeKey);
759
+ if (!meta) {
760
+ orphans.push(`"${doctypeKey}": no doctype by that name is registered`);
761
+ continue;
762
+ }
763
+ if (meta.name !== doctypeKey) {
764
+ orphans.push(`"${doctypeKey}": matches the doctype named "${meta.name}" by slug, but handlers are looked up by name — key it "${meta.name}"`);
765
+ continue;
766
+ }
767
+ const actions = meta.workflow?.actions ?? {};
768
+ for (const actionKey of Object.keys(handlers)) {
769
+ if (!(actionKey in actions)) {
770
+ orphans.push(`"${doctypeKey}.${actionKey}": the doctype declares no action by that key`);
771
+ }
772
+ }
773
+ }
774
+ if (orphans.length > 0) {
775
+ throw new Error(`StonecropPlugin: ${orphans.length} registered action handler${orphans.length === 1 ? '' : 's'} ` +
776
+ `cannot be reached and would never run:\n ${orphans.join('\n ')}`);
777
+ }
778
+ }
779
+ /**
780
+ * Refuse a doctype set whose links or `inherits` name a doctype nobody registered.
781
+ *
782
+ * What it prevents is silent: the link read does `const targetMeta = getMeta(link.target)` followed
783
+ * by `if (!targetMeta) continue`, so an unresolvable target drops the relation from the response
784
+ * with no error. On the wire that is indistinguishable from "this record has no such relation", and
785
+ * a typo in a target reads as a legitimately empty link forever.
786
+ *
787
+ * Throws rather than warns, like the handler check above: a link pointing at a doctype that does not
788
+ * exist has no correct reading. Every offender is collected so a consumer fixes them in one pass.
789
+ *
790
+ * Deliberately no empty-registry warning, unlike `assertActionHandlersResolve`. That one warns
791
+ * because a registered handler map is evidence the host meant to be checked; here there is no such
792
+ * evidence, so warning would fire on every host that loads doctypes after building its schema —
793
+ * and an advisory that fires on a correct setup is worse than none. An empty registry simply
794
+ * reports nothing, because the loop has nothing to walk.
795
+ */
796
+ function assertReferencesResolve() {
797
+ const broken = validateReferences();
798
+ if (broken.length === 0)
799
+ return;
800
+ throw new Error(`StonecropPlugin: ${broken.length} doctype reference${broken.length === 1 ? '' : 's'} ` +
801
+ `cannot be resolved and would silently drop the relation:\n ` +
802
+ broken.map(e => `${e.path.join('.')}: ${e.message}`).join('\n '));
803
+ }
804
+ /**
805
+ * The error a caller raises when `getPkMeta` cannot resolve an identity field, naming the doctype
806
+ * and both repairs. Shared so the three lookup sites report one diagnosis.
807
+ */
808
+ function unresolvableIdentityError(doctype) {
809
+ return new Error(`Doctype "${doctype}" has no identity field: it declares no field with \`primaryKey: true\` ` +
810
+ `and no field named \`id\`. Declare one of the two — records cannot be fetched or acted on until then.`);
413
811
  }
414
812
  /**
415
813
  * Resolve the PostgreSQL FROM clause target for a doctype.