@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.
@@ -61,9 +61,35 @@ export declare function hasMeta(name: string): boolean;
61
61
  */
62
62
  export declare function clearRegistry(): void;
63
63
  /**
64
- * Validate cross-doctype references (Link fields, inherits, etc.)
65
- * Call after all doctypes are loaded.
66
- * @public
64
+ * Validate doctype references — link targets, `inherits`, and each link's binding — against what
65
+ * is loaded.
66
+ *
67
+ * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by
68
+ * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as
69
+ * one, and every doctype in this repo writes one), so a raw `.has()` reports a broken reference for
70
+ * every correct link — measured at 12 of 12 across the two in-repo hosts before this was fixed.
71
+ * `getMeta` is also what the plugin resolves a link with at fetch time, so this asks the same
72
+ * question the runtime asks.
73
+ *
74
+ * `inherits` is checked the same way even though nothing resolves it at runtime (both resolvers
75
+ * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the
76
+ * permissive direction.
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
+ *
88
+ * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that
89
+ * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only
90
+ * meaningful after this module's own loaders have run.
91
+ *
92
+ * @internal
67
93
  */
68
94
  export declare function validateReferences(): ValidationError[];
69
95
  //# sourceMappingURL=doctypes.d.ts.map
@@ -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;;;;GAIG;AACH,wBAAgB,kBAAkB,IAAI,eAAe,EAAE,CAsCtD"}
1
+ {"version":3,"file":"doctypes.d.ts","sourceRoot":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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,26 +132,53 @@ export function clearRegistry() {
131
132
  doctypeRegistry.clear();
132
133
  }
133
134
  /**
134
- * Validate cross-doctype references (Link fields, inherits, etc.)
135
- * Call after all doctypes are loaded.
136
- * @public
135
+ * Validate doctype references — link targets, `inherits`, and each link's binding — against what
136
+ * is loaded.
137
+ *
138
+ * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by
139
+ * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as
140
+ * one, and every doctype in this repo writes one), so a raw `.has()` reports a broken reference for
141
+ * every correct link — measured at 12 of 12 across the two in-repo hosts before this was fixed.
142
+ * `getMeta` is also what the plugin resolves a link with at fetch time, so this asks the same
143
+ * question the runtime asks.
144
+ *
145
+ * `inherits` is checked the same way even though nothing resolves it at runtime (both resolvers
146
+ * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the
147
+ * permissive direction.
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
+ *
159
+ * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that
160
+ * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only
161
+ * meaningful after this module's own loaders have run.
162
+ *
163
+ * @internal
137
164
  */
138
165
  export function validateReferences() {
139
166
  const errors = [];
140
167
  for (const doctype of doctypeRegistry.values()) {
141
168
  // Check inherits reference
142
- if (doctype.inherits && !doctypeRegistry.has(doctype.inherits)) {
169
+ if (doctype.inherits && getMeta(doctype.inherits) === undefined) {
143
170
  errors.push({
144
171
  path: [doctype.name, 'inherits'],
145
172
  message: `References unknown doctype: ${doctype.inherits}`,
146
173
  });
147
174
  }
175
+ const fields = flattenFields(doctype.fields);
148
176
  // Check link field targets — `doctype` is both the link marker and its target.
149
- for (const field of doctype.fields) {
177
+ for (const field of fields) {
150
178
  if (field.kind !== 'field')
151
179
  continue;
152
180
  const target = field.doctype;
153
- if (target !== undefined && !doctypeRegistry.has(target)) {
181
+ if (target !== undefined && getMeta(target) === undefined) {
154
182
  errors.push({
155
183
  path: [doctype.name, 'fields', field.fieldname, 'doctype'],
156
184
  message: `Link references unknown doctype: ${target}`,
@@ -159,13 +187,63 @@ export function validateReferences() {
159
187
  }
160
188
  // Check link-declaration targets (component-primary links live in the `links` map)
161
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));
162
195
  for (const [key, link] of Object.entries(doctype.links)) {
163
- if (!doctypeRegistry.has(link.target)) {
196
+ if (getMeta(link.target) === undefined) {
164
197
  errors.push({
165
198
  path: [doctype.name, 'links', key, 'target'],
166
199
  message: `Link references unknown doctype: ${link.target}`,
167
200
  });
168
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
+ }
169
247
  }
170
248
  }
171
249
  }
@@ -1 +1 @@
1
- {"version":3,"file":"typeDefs.d.ts","sourceRoot":"","sources":["../../src/typeDefs.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,eAAO,MAAM,QAAQ,gCAoFpB,CAAA"}
1
+ {"version":3,"file":"typeDefs.d.ts","sourceRoot":"","sources":["../../src/typeDefs.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,eAAO,MAAM,QAAQ,gCA6GpB,CAAA"}
@@ -57,18 +57,42 @@ export const typeDefs = gql `
57
57
  data: JSON
58
58
  doctype: String!
59
59
  unknownLinks: [String!]
60
+ """
61
+ Fields whose linked rows were cut short by a row cap, so data holds a prefix of the
62
+ relation rather than all of it. Null when nothing was truncated. A link cannot be paged,
63
+ so a client that sees a name here must not write that relation back — the rows it never
64
+ received would be deleted.
65
+ """
66
+ truncatedLinks: [String!]
60
67
  }
61
68
 
62
69
  type StonecropRecordsResult {
63
70
  data: [JSON!]!
64
71
  doctype: String!
65
- count: Int!
72
+ """
73
+ Whether further records exist beyond this page. Always answered — it is read from the
74
+ page itself (one extra row is requested and discarded), so it costs no second query.
75
+ """
76
+ hasMore: Boolean!
77
+ """
78
+ Total matching the filters, ignoring limit/offset. Null unless the query asked for it
79
+ with includeTotal, because counting is a full scan on most backends.
80
+ """
81
+ count: Int
66
82
  }
67
83
 
68
84
  type StonecropActionResult {
69
85
  success: Boolean!
70
86
  data: JSON
71
87
  error: String
88
+ """
89
+ Keys the write discarded because the doctype declares no column for them, or because the
90
+ value was a nested relation rather than a column value. Null when everything sent was
91
+ stored. The action still succeeded — this is what it did not keep, and a client that
92
+ reports an unqualified success without checking it tells the user data was saved that
93
+ was not.
94
+ """
95
+ droppedFields: [String!]
72
96
  }
73
97
 
74
98
  extend type Query {
@@ -81,6 +105,7 @@ export const typeDefs = gql `
81
105
  orderBy: String
82
106
  limit: Int
83
107
  offset: Int
108
+ includeTotal: Boolean
84
109
  options: JSON
85
110
  ): StonecropRecordsResult
86
111
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stonecrop/graphql-middleware",
3
- "version": "0.16.6",
3
+ "version": "0.18.0",
4
4
  "description": "GraphQL middleware for PostGraphile and Stonecrop schema",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,7 +23,7 @@
23
23
  "graphql": "^16.14.0",
24
24
  "pluralize": "^8.0.0",
25
25
  "postgraphile": "^5.0.3",
26
- "@stonecrop/schema": "0.16.6"
26
+ "@stonecrop/schema": "0.18.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@electric-sql/pglite": "^0.4.5",