@stonecrop/graphql-middleware 0.17.0 → 0.19.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,7 +1,10 @@
1
- import { camelToSnake, getRecordIdField, pascalToSnake, resolveLinkRenderMode } from '@stonecrop/schema';
1
+ import { camelToSnake, getRecordIdField, 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';
6
+ import { enrichLinkDisplayFields } from '../link-display';
7
+ import { resolveTableName } from '../tables';
5
8
  import { getFetchHandler } from '../registry/fetchHandlers';
6
9
  import { getMeta, getAllMeta, validateReferences } from '../registry/doctypes';
7
10
  import { applyGuardedTransition } from '../dispatch/transition';
@@ -22,6 +25,22 @@ class ActionRolledBack extends Error {
22
25
  this.name = 'ActionRolledBack';
23
26
  }
24
27
  }
28
+ /**
29
+ * Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can
30
+ * read it. An *expanding* link is a relation in the payload rather than a scalar, so `getSqlColumns`
31
+ * omits its FK column by design — but the expansion needs the value to find the target. Aliasing
32
+ * keeps that need from changing the payload: every alias is stripped before the record is returned.
33
+ */
34
+ const LINK_FK_ALIAS = '__stonecropLinkFk_';
35
+ /**
36
+ * The column this adapter keeps a record's workflow state in.
37
+ *
38
+ * Named once because three statements depend on agreeing about it: the guard's `FOR UPDATE` read,
39
+ * the transition's write, and the data write that must refuse to touch it. A patch that could set
40
+ * this column would let any client walk past `allowedStates` by writing the very value the guard
41
+ * reads.
42
+ */
43
+ const STATE_COLUMN = 'status';
25
44
  /**
26
45
  * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
27
46
  *
@@ -45,6 +64,10 @@ export const createStonecropPlugin = (options = {}) => {
45
64
  return pgClient.query(query);
46
65
  }
47
66
  : (pgClient, query) => pgClient.query(query);
67
+ // Resolved once, for both read paths. `undefined` means "not configured" and `null` means
68
+ // "configured off", which is a distinction `??` cannot make — and the two paths disagreeing
69
+ // about it is exactly how a link came to be capped by a different number than a list.
70
+ const defaultRowLimit = options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit;
48
71
  return extendSchema(build => {
49
72
  // Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.
50
73
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- build.input.pgRegistry is a PostGraphile internal not in the public Build type
@@ -98,11 +121,37 @@ export const createStonecropPlugin = (options = {}) => {
98
121
  const pkColumn = camelToSnake(pkMeta.fieldname);
99
122
  const columns = getSqlColumns(meta);
100
123
  const ids = indices.map(i => String(specs[i].id));
124
+ // Resolved once per doctype: how each link renders, and which foreign keys the
125
+ // SELECT must carry for the expansion below to work at all.
126
+ //
127
+ // `resolveLinkRenderMode` needs the linked field's own component, so the fields
128
+ // are indexed by name — flattened, because a link's field may sit inside a
129
+ // fieldset and `getSqlColumns` already descends to select it.
130
+ const fieldByName = new Map(flattenFields(meta.fields).map(f => [f.fieldname, f]));
131
+ const linkFkAliases = [];
132
+ for (const [linkName, link] of Object.entries(meta.links ?? {})) {
133
+ // Many-side links find their rows by a column on the *target*; only a one-side
134
+ // link reads a foreign key off this row.
135
+ if (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne')
136
+ continue;
137
+ const fieldname = link.fieldname ?? linkName;
138
+ // An inline link keeps its FK as a scalar, so `getSqlColumns` already selected
139
+ // it under its own name and no alias is needed.
140
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline')
141
+ continue;
142
+ linkFkAliases.push({ fieldname, alias: `${LINK_FK_ALIAS}${fieldname}` });
143
+ }
144
+ const selectList = [
145
+ columns,
146
+ ...linkFkAliases.map(({ fieldname, alias }) => `"${camelToSnake(fieldname)}" AS "${alias}"`),
147
+ ]
148
+ .filter(Boolean)
149
+ .join(', ');
101
150
  // TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;
102
151
  // requires refactoring the grouped-by-doctype loop to collect promises before resolving results
103
152
  // oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above
104
153
  const { rows } = await debugSql(pgClient, {
105
- text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
154
+ text: `SELECT ${selectList} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
106
155
  values: [ids],
107
156
  });
108
157
  // Use String() so integer PKs (e.g. serial) match the string ids from GraphQL
@@ -122,6 +171,11 @@ export const createStonecropPlugin = (options = {}) => {
122
171
  `matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. ` +
123
172
  `Declare a field that uniquely identifies a record, or add a unique constraint.`);
124
173
  }
174
+ // Collected across the batch so the display lookup runs once for all of them.
175
+ // Called per row inside this loop it issued one query per record per link field,
176
+ // which is the N+1 this batched loader exists to avoid — and silently, since the
177
+ // enriched rows come out identical either way.
178
+ const enrichedRows = [];
125
179
  for (const i of indices) {
126
180
  const specId = String(specs[i].id);
127
181
  const row = rowByPk.get(specId);
@@ -130,6 +184,10 @@ export const createStonecropPlugin = (options = {}) => {
130
184
  continue;
131
185
  }
132
186
  const rowData = { ...row };
187
+ enrichedRows.push(rowData);
188
+ // Per record, not per doctype: two records of one doctype can differ in whether
189
+ // a relation overflowed, and a shared list would report the wrong one truncated.
190
+ const truncatedLinks = [];
133
191
  const recordOptions = (specs[i].options ?? {});
134
192
  const includeAll = recordOptions.includeNested === true;
135
193
  const includeSet = Array.isArray(recordOptions.includeNested)
@@ -138,10 +196,30 @@ export const createStonecropPlugin = (options = {}) => {
138
196
  // FetchStrategy dispatch over link declarations
139
197
  if (meta.links) {
140
198
  for (const [linkName, link] of Object.entries(meta.links)) {
199
+ // The payload key is the *resolved* fieldname, not the map key: the client
200
+ // binds a link to the field named `link.fieldname ?? key` and reads the
201
+ // nested data off that field, so writing under the bare key put the result
202
+ // somewhere nothing looks whenever a declaration named its own `fieldname`.
203
+ // Identical for every declaration that omits `fieldname`, which is all of them
204
+ // in this repo — hence latent until now.
205
+ const fieldname = link.fieldname ?? linkName;
141
206
  const fetch = link.fetch;
142
207
  const isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne';
143
208
  const effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy');
144
- const effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined;
209
+ // Two questions, kept apart. `method === 'sync'` is a *type narrowing* — only
210
+ // `SyncFetch` carries a `limit` — and the server default used to hang off its
211
+ // `else`, so declaring the method a many-side link already defaults to removed
212
+ // the cap entirely. "Did the author write a limit?" and "did the author write
213
+ // the word sync?" are now asked separately.
214
+ const declaredLimit = fetch?.method === 'sync' ? fetch.limit : undefined;
215
+ const effectiveLimit = isMany ? (declaredLimit ?? defaultRowLimit) : undefined;
216
+ // The one gate. It used to be followed by a second test that re-asked the
217
+ // same question using only `includeSet` — `null` for the boolean form — so
218
+ // `includeNested: true` admitted every link here and then silently dropped
219
+ // each non-`sync` one, handing back a partial record with no way to tell.
220
+ // That test was redundant wherever it was correct: with a name list this gate
221
+ // has already required membership, and without one it has already required
222
+ // `sync`, so it could only ever fire in the boolean case it got wrong.
145
223
  const shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync');
146
224
  if (!shouldInclude)
147
225
  continue;
@@ -151,11 +229,16 @@ export const createStonecropPlugin = (options = {}) => {
151
229
  if (handler) {
152
230
  // TODO(perf): custom link handlers per-row could run in parallel; needs collecting all custom handlers before await
153
231
  // oxlint-disable-next-line eslint/no-await-in-loop -- custom handler per link; see TODO above
154
- rowData[linkName] = await handler(pgClient, rowData, link);
232
+ rowData[fieldname] = await handler(pgClient, rowData, link);
155
233
  }
156
234
  continue;
157
235
  }
158
- if (effectiveMethod !== 'sync' && !includeSet?.has(linkName))
236
+ // `resolveLinkRenderMode` is the single definition of whether a link expands,
237
+ // and this loop was the one caller that never asked it. An `inline` link is a
238
+ // picker: the field holds its own id and the client resolves display text
239
+ // separately, so expanding it here overwrote that id with the whole target
240
+ // record and left the picker with an object it cannot render.
241
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline')
159
242
  continue;
160
243
  const targetMeta = getMeta(link.target);
161
244
  if (!targetMeta)
@@ -168,8 +251,10 @@ export const createStonecropPlugin = (options = {}) => {
168
251
  let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
169
252
  const linkValues = [specId];
170
253
  if (effectiveLimit != null) {
254
+ // One row more than the cap, same probe the list path uses: its presence
255
+ // is the whole truncation answer and costs no second query.
171
256
  sql += ` LIMIT $2`;
172
- linkValues.push(effectiveLimit);
257
+ linkValues.push(effectiveLimit + 1);
173
258
  }
174
259
  // TODO(perf): many-side link queries per row could be parallelized; needs collecting across links before await
175
260
  // oxlint-disable-next-line eslint/no-await-in-loop -- one SQL per backlink per row; see TODO above
@@ -177,14 +262,26 @@ export const createStonecropPlugin = (options = {}) => {
177
262
  text: sql,
178
263
  values: linkValues,
179
264
  });
180
- rowData[linkName] = linked;
265
+ // A truncated relation that says nothing is how a read-modify-write deletes
266
+ // the tail: the client cannot tell 50 rows from all of them, so it writes
267
+ // back what it was given. Reported for every source of truncation, the
268
+ // author's `fetch.limit` included — that one is just as silent.
269
+ if (effectiveLimit != null && linked.length > effectiveLimit) {
270
+ truncatedLinks.push(fieldname);
271
+ rowData[fieldname] = linked.slice(0, effectiveLimit);
272
+ }
273
+ else {
274
+ rowData[fieldname] = linked;
275
+ }
181
276
  }
182
277
  else {
183
- if (!link.fieldname)
184
- continue;
185
- const fkValue = rowData[link.fieldname];
278
+ // Read from the reserved alias, never the fieldname: an expanding link's FK
279
+ // column is deliberately absent from `getSqlColumns`, so the plain read found
280
+ // `undefined` on every record and answered `null` — a relation that looked
281
+ // permanently empty rather than one nobody had asked the right question for.
282
+ const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
186
283
  if (fkValue == null) {
187
- rowData[linkName] = null;
284
+ rowData[fieldname] = null;
188
285
  continue;
189
286
  }
190
287
  // `continue` here would drop the link from the payload, which reads to the
@@ -200,18 +297,28 @@ export const createStonecropPlugin = (options = {}) => {
200
297
  text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
201
298
  values: [fkValue],
202
299
  });
203
- rowData[linkName] = linked[0] ?? null;
300
+ rowData[fieldname] = linked[0] ?? null;
204
301
  }
205
302
  }
206
303
  }
304
+ // The aliases are a read channel for this loop, not part of the record. Stripped
305
+ // unconditionally so a link that was never expanded cannot leak its raw FK into a
306
+ // payload that has otherwise always described that relation as a nested object.
307
+ for (const { alias } of linkFkAliases)
308
+ delete rowData[alias];
207
309
  // Names in includeNested that don't correspond to any link
208
310
  const unknownLinks = includeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links)) : undefined;
209
311
  results[i] = {
210
312
  data: rowData,
211
313
  doctype,
212
314
  unknownLinks: unknownLinks?.length ? unknownLinks : undefined,
315
+ truncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,
213
316
  };
214
317
  }
318
+ // After the expansion loop, not before it: a link that expanded has replaced its
319
+ // scalar FK with an object, and enrichment skips those. Running first stamped a
320
+ // display value beside a relation that no longer had an id to display.
321
+ await enrichLinkDisplayFields(pgClient, meta, enrichedRows, options.tables, debugSql);
215
322
  }
216
323
  return results;
217
324
  });
@@ -280,7 +387,7 @@ export const createStonecropPlugin = (options = {}) => {
280
387
  if (spec.limit != null && typeof spec.limit !== 'number') {
281
388
  throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
282
389
  }
283
- const effectiveLimit = spec.limit ?? (options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit);
390
+ const effectiveLimit = spec.limit ?? defaultRowLimit;
284
391
  let pagingClause = '';
285
392
  if (effectiveLimit != null) {
286
393
  // One more row than asked for. Its presence is the whole `hasMore` answer, and
@@ -301,7 +408,8 @@ export const createStonecropPlugin = (options = {}) => {
301
408
  // a capped page distinguishable from a complete table; trim it before anything
302
409
  // downstream can mistake it for a record.
303
410
  const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
304
- const data = hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows;
411
+ const data = [...(hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows)];
412
+ await enrichLinkDisplayFields(pgClient, meta, data, options.tables, debugSql);
305
413
  // Total matching the filters, independent of LIMIT/OFFSET, and opt-in.
306
414
  //
307
415
  // Explicitly requested rather than inferred from whether `count` was selected:
@@ -373,6 +481,46 @@ export const createStonecropPlugin = (options = {}) => {
373
481
  // by the doctype's canonical name so a slug-resolved lookup above cannot
374
482
  // silently miss it.
375
483
  const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
484
+ // What a data write is allowed to set. Column identifiers come from the
485
+ // doctype and never from the request — `args` is an opaque JSON scalar, so
486
+ // every key in `data` is browser-supplied — which is what makes it safe to
487
+ // build SQL from a patch at all.
488
+ //
489
+ // The same derivation the read path uses, so what a record exposes is what a
490
+ // record accepts. `status` is removed because state is the workflow's to
491
+ // move, never the patch's.
492
+ const writable = new Map(columnBackedFields(meta.fields)
493
+ .filter(f => camelToSnake(f.fieldname) !== STATE_COLUMN)
494
+ .map(f => [f.fieldname, f]));
495
+ // Whether this doctype has a workflow state to read at all. Derived from the
496
+ // same declarations, so the guard cannot look for a column the doctype's own
497
+ // API surface does not describe.
498
+ const declaresState = columnBackedFields(meta.fields).some(f => camelToSnake(f.fieldname) === STATE_COLUMN);
499
+ // Reported on the result rather than logged: a dropped key is data the user
500
+ // believes was saved, which is the same data-loss signal `truncatedLinks`
501
+ // carries for a truncated read.
502
+ const droppedFields = [];
503
+ const partitionPatch = (patch) => {
504
+ const cols = [];
505
+ const values = [];
506
+ for (const [key, value] of Object.entries(patch)) {
507
+ if (!writable.has(key)) {
508
+ droppedFields.push(key);
509
+ continue;
510
+ }
511
+ // An expanding link reads back as a nested record while its column
512
+ // holds a scalar foreign key, so a read-modify-write hands this loop
513
+ // an object bound for a uuid column. The name resolving is not
514
+ // enough; the shape has to match a column value too.
515
+ if (value !== null && typeof value === 'object') {
516
+ droppedFields.push(key);
517
+ continue;
518
+ }
519
+ cols.push(camelToSnake(key));
520
+ values.push(value);
521
+ }
522
+ return { cols, values };
523
+ };
376
524
  // One transaction spans the guard read, the effect and the state write, so an
377
525
  // action either lands whole or not at all. `withTransaction` issues `begin` at
378
526
  // the top level and a `savepoint` if something upstream already opened one, so
@@ -389,25 +537,93 @@ export const createStonecropPlugin = (options = {}) => {
389
537
  // the same answer as a lookup that misses: `null`, not `undefined`.
390
538
  if (recordId == null)
391
539
  return null;
540
+ // Selecting `status` unconditionally made this read fail outright on
541
+ // any table without that column — and a self-transition reaches here
542
+ // not to read a state but to learn whether the row exists, which is
543
+ // what decides create vs. update. So the projection follows the
544
+ // doctype: a doctype that declares no state field has none to read,
545
+ // and the honest answer for a row it finds is "exists, no state".
546
+ // (Measured: 24 of FAB's 35 guarded tables have no `status` column.)
547
+ const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
392
548
  // FOR UPDATE holds the row until this transaction ends, so a second
393
549
  // action on the same record waits rather than reading the same state
394
550
  // and acting on it too. Without it the guard is a check-then-act
395
551
  // race: two concurrent approvals both read PENDING and both proceed.
396
552
  const { rows } = await debugSql(tx, {
397
- text: `SELECT "status" FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
553
+ text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
398
554
  values: [String(recordId)],
399
555
  });
400
556
  // No row at all vs. a row whose `status` is NULL — see GuardedTransitionIO.
401
557
  if (rows.length === 0)
402
558
  return null;
403
- return rows[0].status ?? undefined;
559
+ if (!declaresState)
560
+ return undefined;
561
+ return rows[0][STATE_COLUMN] ?? undefined;
404
562
  },
405
563
  writeState: async (nextState) => {
406
564
  await debugSql(tx, {
407
- text: `UPDATE ${table} SET "status" = $1 WHERE "${pkColumn()}"::text = $2`,
565
+ text: `UPDATE ${table} SET "${STATE_COLUMN}" = $1 WHERE "${pkColumn()}"::text = $2`,
408
566
  values: [nextState, String(recordId)],
409
567
  });
410
568
  },
569
+ // The upsert, and the only write path for record data. `exists`
570
+ // comes from the guard's own read, so no second lookup decides it.
571
+ //
572
+ // Returns the same projection the read path selects, never
573
+ // `RETURNING *`: raw columns come back snake_case, and the client
574
+ // resolves identity by the *declared fieldname*. A doctype keyed
575
+ // `itemId` would receive `item_id`, find no identity, and file a
576
+ // created record nowhere — which is that exact bug, already once
577
+ // shipped and patched downstream.
578
+ writeData: async (patch, exists) => {
579
+ const { cols, values } = partitionPatch(patch);
580
+ const returning = getSqlColumns(meta);
581
+ if (!exists) {
582
+ // Creating is what the *absence* of an id means. An id that was
583
+ // dispatched and matched nothing is a record that has gone away
584
+ // since the client read it, and treating that as a create mints a
585
+ // second row under a new identity while the client believes it
586
+ // updated the first — a lost update that reports success.
587
+ //
588
+ // The dispatcher cannot make this call: it never receives the id,
589
+ // deliberately, since identity is the backend's business. So the
590
+ // distinction its `readState` contract collapses is restored here,
591
+ // where the id is in scope.
592
+ if (recordId != null) {
593
+ throw new Error(`Action "${actionDef.label ?? spec.action}" targets ${meta.name} "${String(recordId)}", ` +
594
+ `which no longer exists. Nothing was created — a record dispatched with an ` +
595
+ `identity is an update, and creating one is what dispatching no identity means.`);
596
+ }
597
+ // No identity is minted here. A declared key present in the
598
+ // patch is a natural key the user filled in and passes
599
+ // through the whitelist like any other column; absent, the
600
+ // column default supplies it. Either way the row states its
601
+ // own identity back.
602
+ const text = cols.length
603
+ ? `INSERT INTO ${table} (${cols.map(c => `"${c}"`).join(', ')}) VALUES (${cols.map((_col, i) => `$${i + 1}`).join(', ')}) RETURNING ${returning}`
604
+ : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning}`;
605
+ const { rows } = await debugSql(tx, { text, values });
606
+ return rows[0] ?? {};
607
+ }
608
+ // Nothing writable survived the patch. `SET` with no assignments
609
+ // is a syntax error, and reporting failure would be wrong — the
610
+ // record is fine, it just has no new data. Read it back so the
611
+ // client still gets the record, with `droppedFields` saying why
612
+ // nothing changed.
613
+ if (cols.length === 0) {
614
+ const { rows } = await debugSql(tx, {
615
+ text: `SELECT ${returning} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
616
+ values: [String(recordId)],
617
+ });
618
+ return rows[0] ?? {};
619
+ }
620
+ const assignments = cols.map((c, i) => `"${c}" = $${i + 1}`).join(', ');
621
+ const { rows } = await debugSql(tx, {
622
+ text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning}`,
623
+ values: [...values, String(recordId)],
624
+ });
625
+ return rows[0] ?? {};
626
+ },
411
627
  runEffect: handler
412
628
  ? (currentState) => handler({
413
629
  pgClient: tx,
@@ -420,7 +636,11 @@ export const createStonecropPlugin = (options = {}) => {
420
636
  currentState,
421
637
  })
422
638
  : undefined,
423
- });
639
+ },
640
+ // The patch a self-transition persists. This adapter never passed it, which
641
+ // was moot while it had no `writeData` — nothing consumed it. Wiring the write
642
+ // without this argument saves an empty record and reports success.
643
+ recordData);
424
644
  // `applyGuardedTransition` REPORTS failure, it does not throw — a refused
425
645
  // guard and a handler that blew up both come back as `{ success: false }`.
426
646
  // Returning that normally would commit the transaction, so a handler that
@@ -429,7 +649,11 @@ export const createStonecropPlugin = (options = {}) => {
429
649
  // caller still gets `success: false` rather than a GraphQL error.
430
650
  if (!outcome.success)
431
651
  throw new ActionRolledBack(outcome);
432
- return outcome;
652
+ // Attached here rather than carried through `applyGuardedTransition`:
653
+ // which keys a backend can store is a storage question, and the
654
+ // dispatcher is deliberately storage-agnostic. A failed action wrote
655
+ // nothing, so the list is only meaningful on success.
656
+ return droppedFields.length ? { ...outcome, droppedFields } : outcome;
433
657
  });
434
658
  }
435
659
  catch (err) {
@@ -452,23 +676,6 @@ export const createStonecropPlugin = (options = {}) => {
452
676
  // ===========================================================================
453
677
  // SQL column helpers
454
678
  // ===========================================================================
455
- /**
456
- * Recursively flatten Fieldset containers into a flat array of non-container fields.
457
- * Fieldset entries are replaced by their children; all other fields pass through.
458
- * Used by getSqlColumns (for SELECT) and knownFields (for filter/orderBy validation).
459
- */
460
- function flattenFields(fields) {
461
- const result = [];
462
- for (const f of fields) {
463
- if (f.kind === 'fieldset') {
464
- result.push(...flattenFields(f.schema));
465
- }
466
- else {
467
- result.push(f);
468
- }
469
- }
470
- return result;
471
- }
472
679
  /**
473
680
  * Derive quoted SQL column entries from a flat field array.
474
681
  * Skips non-scalar fields (kind !== 'field'), `computed` fields
@@ -477,12 +684,7 @@ function flattenFields(fields) {
477
684
  */
478
685
  function collectColumns(fields, links) {
479
686
  const columns = [];
480
- for (const f of flattenFields(fields)) {
481
- if (f.kind !== 'field')
482
- continue;
483
- // A computed field has no backing DB column.
484
- if (f.computed)
485
- continue;
687
+ for (const f of columnBackedFields(fields)) {
486
688
  // Only an *expanding* link is a relation rather than a column. An inline link (a picker)
487
689
  // keeps its FK on this table and must still be selected — `resolveLinkRenderMode` is the
488
690
  // shared rule, also used by the client resolver; never re-derive it here.
@@ -626,11 +828,3 @@ function unresolvableIdentityError(doctype) {
626
828
  * Schema-qualified names (e.g. "orpin.plan") are emitted as "schema"."table".
627
829
  * Values must be bare identifiers or schema.table pairs — not SQL fragments.
628
830
  */
629
- function resolveTableName(name, tables) {
630
- const target = tables?.[name] ?? pascalToSnake(name);
631
- const dotIndex = target.indexOf('.');
632
- if (dotIndex > 0) {
633
- return `"${target.slice(0, dotIndex)}"."${target.slice(dotIndex + 1)}"`;
634
- }
635
- return `"${target}"`;
636
- }
@@ -61,7 +61,8 @@ export declare function hasMeta(name: string): boolean;
61
61
  */
62
62
  export declare function clearRegistry(): void;
63
63
  /**
64
- * Validate cross-doctype references (link targets, `inherits`) against what is loaded.
64
+ * Validate doctype references — link targets, `inherits`, and each link's binding — against what
65
+ * is loaded.
65
66
  *
66
67
  * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by
67
68
  * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as
@@ -74,6 +75,16 @@ export declare function clearRegistry(): void;
74
75
  * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the
75
76
  * permissive direction.
76
77
  *
78
+ * The **binding** checks are the same defect class as an unresolvable target, one step further in:
79
+ * a link whose target resolves can still name no way to reach the rows, and the reader's answer for
80
+ * that is `continue` or a `null` — indistinguishable on the wire from a relation that is genuinely
81
+ * empty. Both halves of a declaration are `.optional()` in the schema because which one is required
82
+ * depends on cardinality, which Zod cannot express here; this is where that dependency is enforced.
83
+ *
84
+ * Only what the runtime actually consults is required. A `backlink` naming a column the target
85
+ * table does not have already fails loudly — Postgres rejects the SELECT — so it is left alone;
86
+ * the check exists for the silent cases, not to restate the database's own errors.
87
+ *
77
88
  * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that
78
89
  * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only
79
90
  * meaningful after this module's own loaders have run.
@@ -1 +1 @@
1
- {"version":3,"file":"doctypes.d.ts","sourceRoot":"","sources":["../../../src/registry/doctypes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAIrE;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAE/C,4DAA4D;aAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;aACtB,MAAM,EAAE,eAAe,EAAE;;IAHzC,4DAA4D;IAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;IACtB,MAAM,EAAE,eAAe,EAAE;CAM1C;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IACnC,2DAA2D;IAC3D,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,kEAAkE;IAClE,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,KAAK,IAAI,CAAA;CAC3D;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAajF;AAsCD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAgBjH;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAQ7D;AAED;;;GAGG;AACH,wBAAgB,UAAU,IAAI,WAAW,EAAE,CAE1C;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE7C;AAED;;;GAGG;AACH,wBAAgB,aAAa,IAAI,IAAI,CAEpC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,kBAAkB,IAAI,eAAe,EAAE,CAsCtD"}
1
+ {"version":3,"file":"doctypes.d.ts","sourceRoot":"","sources":["../../../src/registry/doctypes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAMrE;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAE/C,4DAA4D;aAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;aACtB,MAAM,EAAE,eAAe,EAAE;;IAHzC,4DAA4D;IAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;IACtB,MAAM,EAAE,eAAe,EAAE;CAM1C;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IACnC,2DAA2D;IAC3D,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,kEAAkE;IAClE,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,KAAK,IAAI,CAAA;CAC3D;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAajF;AAsCD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAgBjH;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAQ7D;AAED;;;GAGG;AACH,wBAAgB,UAAU,IAAI,WAAW,EAAE,CAE1C;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE7C;AAED;;;GAGG;AACH,wBAAgB,aAAa,IAAI,IAAI,CAEpC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,kBAAkB,IAAI,eAAe,EAAE,CA8FtD"}
@@ -1,6 +1,7 @@
1
1
  import { readFileSync, readdirSync, statSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { parseDoctype, validateDoctype } from '@stonecrop/schema';
4
+ import { columnBackedFields, flattenFields } from '../fields';
4
5
  const doctypeRegistry = new Map();
5
6
  /**
6
7
  * Error thrown when a doctype definition fails validation
@@ -131,7 +132,8 @@ export function clearRegistry() {
131
132
  doctypeRegistry.clear();
132
133
  }
133
134
  /**
134
- * Validate cross-doctype references (link targets, `inherits`) against what is loaded.
135
+ * Validate doctype references — link targets, `inherits`, and each link's binding — against what
136
+ * is loaded.
135
137
  *
136
138
  * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by
137
139
  * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as
@@ -144,6 +146,16 @@ export function clearRegistry() {
144
146
  * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the
145
147
  * permissive direction.
146
148
  *
149
+ * The **binding** checks are the same defect class as an unresolvable target, one step further in:
150
+ * a link whose target resolves can still name no way to reach the rows, and the reader's answer for
151
+ * that is `continue` or a `null` — indistinguishable on the wire from a relation that is genuinely
152
+ * empty. Both halves of a declaration are `.optional()` in the schema because which one is required
153
+ * depends on cardinality, which Zod cannot express here; this is where that dependency is enforced.
154
+ *
155
+ * Only what the runtime actually consults is required. A `backlink` naming a column the target
156
+ * table does not have already fails loudly — Postgres rejects the SELECT — so it is left alone;
157
+ * the check exists for the silent cases, not to restate the database's own errors.
158
+ *
147
159
  * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that
148
160
  * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only
149
161
  * meaningful after this module's own loaders have run.
@@ -160,8 +172,9 @@ export function validateReferences() {
160
172
  message: `References unknown doctype: ${doctype.inherits}`,
161
173
  });
162
174
  }
175
+ const fields = flattenFields(doctype.fields);
163
176
  // Check link field targets — `doctype` is both the link marker and its target.
164
- for (const field of doctype.fields) {
177
+ for (const field of fields) {
165
178
  if (field.kind !== 'field')
166
179
  continue;
167
180
  const target = field.doctype;
@@ -174,6 +187,11 @@ export function validateReferences() {
174
187
  }
175
188
  // Check link-declaration targets (component-primary links live in the `links` map)
176
189
  if (doctype.links) {
190
+ const declared = new Set(fields.map(f => f.fieldname));
191
+ // A foreign key is read from a column, so a link can only bind to a field that has one.
192
+ // The rule itself lives in one place — see `columnBackedFields` — because the read path,
193
+ // the write path and this check all have to answer it the same way.
194
+ const columnBacked = new Set(columnBackedFields(doctype.fields).map(f => f.fieldname));
177
195
  for (const [key, link] of Object.entries(doctype.links)) {
178
196
  if (getMeta(link.target) === undefined) {
179
197
  errors.push({
@@ -181,6 +199,51 @@ export function validateReferences() {
181
199
  message: `Link references unknown doctype: ${link.target}`,
182
200
  });
183
201
  }
202
+ // A custom fetch strategy hands the whole read to its handler, which is given the
203
+ // row and the declaration and finds the target however it likes. The runtime returns
204
+ // before consulting either binding below, so requiring one would refuse a link that
205
+ // works.
206
+ if (link.fetch?.method === 'custom')
207
+ continue;
208
+ // The two cardinalities bind through different halves of the declaration, so the
209
+ // check has to split the same way the reader does.
210
+ if (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne') {
211
+ // Many-side: the target rows are found by a column on the *target* table, so
212
+ // this doctype needs no field of its own — and the in-repo hosts disagree on
213
+ // whether one exists, which is why only `backlink` can be required here.
214
+ if (!link.backlink) {
215
+ errors.push({
216
+ path: [doctype.name, 'links', key, 'backlink'],
217
+ message: `Link "${key}" is ${link.cardinality} but names no \`backlink\`, so the runtime cannot ` +
218
+ `find the target rows and drops the link with no error. Name the field on "${link.target}" ` +
219
+ `that points back to this doctype.`,
220
+ });
221
+ }
222
+ continue;
223
+ }
224
+ // One-side: the foreign key is a column on *this* table, read as
225
+ // `link.fieldname ?? key`. A name matching no declared field is not selected, so the
226
+ // link resolves to null forever and reads as "this record has no such relation".
227
+ const fieldname = link.fieldname ?? key;
228
+ if (!columnBacked.has(fieldname)) {
229
+ errors.push({
230
+ // Point at whichever half actually carries the binding: the `fieldname`
231
+ // property when it is set, otherwise the key itself. Naming `target` here
232
+ // would send the reader to the one part that resolved correctly.
233
+ path: link.fieldname ? [doctype.name, 'links', key, 'fieldname'] : [doctype.name, 'links', key],
234
+ // Two different repairs, so two different diagnoses: a name nothing declares
235
+ // is a typo, while a name that resolves to a column-less field is a binding
236
+ // pointed at the wrong one of several real fields.
237
+ message: declared.has(fieldname)
238
+ ? `Link "${key}" binds to field "${fieldname}", which has no database column of its own — ` +
239
+ `it is computed, or a container rather than a value — so there is no foreign key to read ` +
240
+ `and the record read fails on the missing column. Bind the link to the field holding the ` +
241
+ `foreign key.`
242
+ : `Link "${key}" binds to field "${fieldname}", which this doctype does not declare, so it ` +
243
+ `resolves to null with no error. Declare that field, or set \`fieldname\` to the field ` +
244
+ `holding the foreign key. (A link's key is its fieldname unless \`fieldname\` overrides it.)`,
245
+ });
246
+ }
184
247
  }
185
248
  }
186
249
  }