@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.
package/dist/index.js CHANGED
@@ -1,13 +1,16 @@
1
- import { readdirSync as re, statSync as se, readFileSync as ie } from "node:fs";
2
- import { join as ae } from "node:path";
3
- import { validateDoctype as te, parseDoctype as ne, isActionAllowedInState as ce, camelToSnake as D, pascalToSnake as le, getRecordIdField as de, resolveLinkRenderMode as ue } from "@stonecrop/schema";
4
- import { sideEffectWithPgClient as fe, loadOneWithPgClient as Z } from "@dataplan/pg";
5
- import { object as _, constant as ge, lambda as pe } from "postgraphile/grafast";
6
- import { gql as he, extendSchema as ye, wrapPlans as me } from "postgraphile/utils";
7
- import { PostGraphileAmberPreset as we } from "postgraphile/presets/amber";
8
- import { makePgService as Ge } from "postgraphile/adaptors/pg";
9
- const C = /* @__PURE__ */ new Map();
10
- class G extends Error {
1
+ import { readdirSync as Se, statSync as $e, readFileSync as ke } from "node:fs";
2
+ import { join as Ee } from "node:path";
3
+ import { flattenFields as z, validateDoctype as pe, parseDoctype as ge, isActionAllowedInState as be, pascalToSnake as ve, camelToSnake as R, linkDisplayFieldname as Re, getDisplayField as Ae, getRecordIdField as me, resolveLinkRenderMode as re } from "@stonecrop/schema";
4
+ import { sideEffectWithPgClient as Me, loadOneWithPgClient as ce } from "@dataplan/pg";
5
+ import { object as te, constant as Oe, lambda as Fe } from "postgraphile/grafast";
6
+ import { gql as xe, extendSchema as Te, wrapPlans as Le } from "postgraphile/utils";
7
+ import { PostGraphileAmberPreset as Ne } from "postgraphile/presets/amber";
8
+ import { makePgService as dt } from "postgraphile/adaptors/pg";
9
+ function Z(e) {
10
+ return z(e).filter((t) => t.kind === "field" && !t.computed);
11
+ }
12
+ const W = /* @__PURE__ */ new Map();
13
+ class ie extends Error {
11
14
  constructor(t, o) {
12
15
  const n = o.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
13
16
  `);
@@ -17,104 +20,126 @@ ${n}`), this.file = t, this.errors = o, this.name = "DoctypeValidationError";
17
20
  file;
18
21
  errors;
19
22
  }
20
- function Se(e, t = {}) {
21
- const o = re(e);
23
+ function De(e, t = {}) {
24
+ const o = Se(e);
22
25
  for (const n of o) {
23
- const r = ae(e, n);
24
- se(r).isDirectory() ? Se(r, t) : n.endsWith(".json") && $e(r, t);
26
+ const r = Ee(e, n);
27
+ $e(r).isDirectory() ? De(r, t) : n.endsWith(".json") && Ie(r, t);
25
28
  }
26
29
  }
27
- function $e(e, t) {
28
- const o = ie(e, "utf-8");
30
+ function Ie(e, t) {
31
+ const o = ke(e, "utf-8");
29
32
  let n;
30
33
  try {
31
34
  n = JSON.parse(o);
32
- } catch (l) {
33
- const d = {
35
+ } catch (a) {
36
+ const u = {
34
37
  path: [],
35
- message: `Invalid JSON: ${l instanceof Error ? l.message : String(l)}`
38
+ message: `Invalid JSON: ${a instanceof Error ? a.message : String(a)}`
36
39
  };
37
40
  if (t.continueOnError) {
38
- t.onError?.(e, [d]);
41
+ t.onError?.(e, [u]);
39
42
  return;
40
43
  }
41
- throw new G(e, [d]);
44
+ throw new ie(e, [u]);
42
45
  }
43
- const r = te(n);
46
+ const r = pe(n);
44
47
  if (!r.success) {
45
48
  if (t.continueOnError) {
46
49
  t.onError?.(e, r.errors);
47
50
  return;
48
51
  }
49
- throw new G(e, r.errors);
52
+ throw new ie(e, r.errors);
50
53
  }
51
- const i = ne(n);
52
- C.set(i.name, i);
54
+ const i = ge(n);
55
+ W.set(i.name, i);
53
56
  }
54
- function Le(e, t = {}) {
57
+ function et(e, t = {}) {
55
58
  for (const [o, n] of Object.entries(e)) {
56
- const r = { ...typeof n == "object" && n !== null ? n : {}, name: o }, i = te(r);
59
+ const r = { ...typeof n == "object" && n !== null ? n : {}, name: o }, i = pe(r);
57
60
  if (!i.success) {
58
61
  if (t.continueOnError) {
59
62
  t.onError?.(o, i.errors);
60
63
  continue;
61
64
  }
62
- throw new G(o, i.errors);
65
+ throw new ie(o, i.errors);
63
66
  }
64
- const l = ne(r);
65
- C.set(l.name, l);
67
+ const a = ge(r);
68
+ W.set(a.name, a);
66
69
  }
67
70
  }
68
- function M(e) {
69
- const t = C.get(e);
71
+ function L(e) {
72
+ const t = W.get(e);
70
73
  if (t) return t;
71
- for (const o of C.values())
74
+ for (const o of W.values())
72
75
  if (o.slug === e) return o;
73
76
  }
74
- function oe() {
75
- return Array.from(C.values());
77
+ function ye() {
78
+ return Array.from(W.values());
76
79
  }
77
- function Pe(e) {
78
- return C.has(e);
80
+ function tt(e) {
81
+ return W.has(e);
79
82
  }
80
- function We() {
81
- C.clear();
83
+ function nt() {
84
+ W.clear();
82
85
  }
83
- function ke() {
86
+ function Be() {
84
87
  const e = [];
85
- for (const t of C.values()) {
86
- t.inherits && M(t.inherits) === void 0 && e.push({
88
+ for (const t of W.values()) {
89
+ t.inherits && L(t.inherits) === void 0 && e.push({
87
90
  path: [t.name, "inherits"],
88
91
  message: `References unknown doctype: ${t.inherits}`
89
92
  });
90
- for (const o of t.fields) {
91
- if (o.kind !== "field") continue;
92
- const n = o.doctype;
93
- n !== void 0 && M(n) === void 0 && e.push({
94
- path: [t.name, "fields", o.fieldname, "doctype"],
95
- message: `Link references unknown doctype: ${n}`
93
+ const o = z(t.fields);
94
+ for (const n of o) {
95
+ if (n.kind !== "field") continue;
96
+ const r = n.doctype;
97
+ r !== void 0 && L(r) === void 0 && e.push({
98
+ path: [t.name, "fields", n.fieldname, "doctype"],
99
+ message: `Link references unknown doctype: ${r}`
96
100
  });
97
101
  }
98
- if (t.links)
99
- for (const [o, n] of Object.entries(t.links))
100
- M(n.target) === void 0 && e.push({
101
- path: [t.name, "links", o, "target"],
102
- message: `Link references unknown doctype: ${n.target}`
102
+ if (t.links) {
103
+ const n = new Set(o.map((i) => i.fieldname)), r = new Set(Z(t.fields).map((i) => i.fieldname));
104
+ for (const [i, a] of Object.entries(t.links)) {
105
+ if (L(a.target) === void 0 && e.push({
106
+ path: [t.name, "links", i, "target"],
107
+ message: `Link references unknown doctype: ${a.target}`
108
+ }), a.fetch?.method === "custom") continue;
109
+ if (a.cardinality === "noneOrMany" || a.cardinality === "atLeastOne") {
110
+ a.backlink || e.push({
111
+ path: [t.name, "links", i, "backlink"],
112
+ message: `Link "${i}" is ${a.cardinality} but names no \`backlink\`, so the runtime cannot find the target rows and drops the link with no error. Name the field on "${a.target}" that points back to this doctype.`
113
+ });
114
+ continue;
115
+ }
116
+ const u = a.fieldname ?? i;
117
+ r.has(u) || e.push({
118
+ // Point at whichever half actually carries the binding: the `fieldname`
119
+ // property when it is set, otherwise the key itself. Naming `target` here
120
+ // would send the reader to the one part that resolved correctly.
121
+ path: a.fieldname ? [t.name, "links", i, "fieldname"] : [t.name, "links", i],
122
+ // Two different repairs, so two different diagnoses: a name nothing declares
123
+ // is a typo, while a name that resolves to a column-less field is a binding
124
+ // pointed at the wrong one of several real fields.
125
+ message: n.has(u) ? `Link "${i}" binds to field "${u}", which has no database column of its own — it is computed, or a container rather than a value — so there is no foreign key to read and the record read fails on the missing column. Bind the link to the field holding the foreign key.` : `Link "${i}" binds to field "${u}", which this doctype does not declare, so it resolves to null with no error. Declare that field, or set \`fieldname\` to the field holding the foreign key. (A link's key is its fieldname unless \`fieldname\` overrides it.)`
103
126
  });
127
+ }
128
+ }
104
129
  }
105
130
  return e;
106
131
  }
107
- const K = /* @__PURE__ */ new Map();
108
- function qe(e, t) {
109
- K.set(e, t);
132
+ const ae = /* @__PURE__ */ new Map();
133
+ function ot(e, t) {
134
+ ae.set(e, t);
110
135
  }
111
- function Ee(e) {
112
- return K.get(e);
136
+ function je(e) {
137
+ return ae.get(e);
113
138
  }
114
- function He() {
115
- K.clear();
139
+ function rt() {
140
+ ae.clear();
116
141
  }
117
- async function be(e, t, o) {
142
+ async function Ce(e, t, o) {
118
143
  const n = e.label ?? "unknown", r = e.selfTransition === !0, i = r || e.nextState != null;
119
144
  if (!i && !t.runEffect)
120
145
  return {
@@ -128,18 +153,18 @@ async function be(e, t, o) {
128
153
  data: null,
129
154
  error: `Action "${n}" persists record data in place, which this backend does not support.`
130
155
  };
131
- const l = (e.allowedStates?.length ?? 0) > 0;
132
- let d;
133
- if (l || i) {
134
- const h = await t.readState();
135
- if (h === null) {
156
+ const a = (e.allowedStates?.length ?? 0) > 0;
157
+ let u;
158
+ if (a || i) {
159
+ const k = await t.readState();
160
+ if (k === null) {
136
161
  if (r && t.writeData) {
137
- const a = await t.writeData(o ?? {}, !1);
138
- return !a || Object.keys(a).length === 0 ? {
162
+ const E = await t.writeData(o ?? {}, !1);
163
+ return !E || Object.keys(E).length === 0 ? {
139
164
  success: !1,
140
165
  data: null,
141
166
  error: `Action "${n}" targets a record that does not exist, and the backend did not create it.`
142
- } : { success: !0, data: a, error: null };
167
+ } : { success: !0, data: E, error: null };
143
168
  }
144
169
  return {
145
170
  success: !1,
@@ -147,32 +172,84 @@ async function be(e, t, o) {
147
172
  error: `Action "${n}" targets a record that does not exist — nothing was executed.`
148
173
  };
149
174
  }
150
- d = h ?? "";
175
+ u = k ?? "";
151
176
  }
152
- if (!ce(e, d ?? ""))
177
+ if (!be(e, u ?? ""))
153
178
  return {
154
179
  success: !1,
155
180
  data: null,
156
- error: `Action not allowed from state: ${d || "(unknown)"}`
181
+ error: `Action not allowed from state: ${u || "(unknown)"}`
157
182
  };
158
- let S;
183
+ let $;
159
184
  if (t.runEffect)
160
185
  try {
161
- S = await t.runEffect(d);
162
- } catch (h) {
186
+ $ = await t.runEffect(u);
187
+ } catch (k) {
163
188
  return {
164
189
  success: !1,
165
190
  data: null,
166
- error: `Action "${n}" failed: ${h instanceof Error ? h.message : String(h)}`
191
+ error: `Action "${n}" failed: ${k instanceof Error ? k.message : String(k)}`
167
192
  };
168
193
  }
169
- return r ? { success: !0, data: (t.writeData ? await t.writeData(o ?? {}, !0) : S) ?? null, error: null } : e.nextState == null ? { success: !0, data: S ?? null, error: null } : (await t.writeState(e.nextState), {
194
+ return r ? { success: !0, data: (t.writeData ? await t.writeData(o ?? {}, !0) : $) ?? null, error: null } : e.nextState == null ? { success: !0, data: $ ?? null, error: null } : (await t.writeState(e.nextState), {
170
195
  success: !0,
171
- data: S ?? { state: e.nextState },
196
+ data: $ ?? { state: e.nextState },
172
197
  error: null
173
198
  });
174
199
  }
175
- const ve = he`
200
+ function P(e, t) {
201
+ const o = t?.[e] ?? ve(e), n = o.indexOf(".");
202
+ return n > 0 ? `"${o.slice(0, n)}"."${o.slice(n + 1)}"` : `"${o}"`;
203
+ }
204
+ function de(e) {
205
+ if (!(e == null || typeof e == "object")) {
206
+ if (typeof e == "string") return e === "" ? void 0 : e;
207
+ if (typeof e == "number" || typeof e == "boolean" || typeof e == "bigint")
208
+ return String(e);
209
+ }
210
+ }
211
+ function Pe(e, t) {
212
+ const o = [];
213
+ for (const n of z(e.fields)) {
214
+ if (n.kind !== "field" || !n.doctype) continue;
215
+ const r = L(n.doctype);
216
+ if (!r) continue;
217
+ const i = Ae(r.fields, r.displayField);
218
+ i && o.push({
219
+ fieldname: n.fieldname,
220
+ displayField: i.fieldname,
221
+ targetPkFieldname: me(r.fields),
222
+ targetTable: P(r.name, t)
223
+ });
224
+ }
225
+ return o;
226
+ }
227
+ async function ue(e, t, o, n, r) {
228
+ const i = Pe(t, n);
229
+ i.length === 0 || o.length === 0 || await Promise.all(
230
+ i.map(async (a) => {
231
+ const u = /* @__PURE__ */ new Set();
232
+ for (const y of o) {
233
+ const f = de(y[a.fieldname]);
234
+ f !== void 0 && u.add(f);
235
+ }
236
+ if (u.size === 0) return;
237
+ const $ = R(a.targetPkFieldname), k = R(a.displayField), E = k !== a.displayField ? `"${k}" AS "${a.displayField}"` : `"${a.displayField}"`, { rows: h } = await r(e, {
238
+ text: `SELECT "${$}" AS "${a.targetPkFieldname}", ${E} FROM ${a.targetTable} WHERE "${$}"::text = ANY($1::text[])`,
239
+ values: [Array.from(u)]
240
+ }), m = /* @__PURE__ */ new Map();
241
+ for (const y of h)
242
+ m.set(String(y[a.targetPkFieldname]), y[a.displayField]);
243
+ for (const y of o) {
244
+ const f = de(y[a.fieldname]);
245
+ if (f === void 0) continue;
246
+ const s = m.get(f);
247
+ s == null || s === "" || (y[Re(a.fieldname)] = s);
248
+ }
249
+ })
250
+ );
251
+ }
252
+ const We = xe`
176
253
  type StonecropFieldMeta {
177
254
  kind: String!
178
255
  fieldname: String!
@@ -216,6 +293,7 @@ const ve = he`
216
293
  type StonecropDoctypeMeta {
217
294
  name: String!
218
295
  slug: String
296
+ displayField: String
219
297
  fields: [StonecropFieldMeta!]!
220
298
  workflow: StonecropWorkflowMeta
221
299
  inherits: String
@@ -225,6 +303,13 @@ const ve = he`
225
303
  data: JSON
226
304
  doctype: String!
227
305
  unknownLinks: [String!]
306
+ """
307
+ Fields whose linked rows were cut short by a row cap, so data holds a prefix of the
308
+ relation rather than all of it. Null when nothing was truncated. A link cannot be paged,
309
+ so a client that sees a name here must not write that relation back — the rows it never
310
+ received would be deleted.
311
+ """
312
+ truncatedLinks: [String!]
228
313
  }
229
314
 
230
315
  type StonecropRecordsResult {
@@ -246,6 +331,14 @@ const ve = he`
246
331
  success: Boolean!
247
332
  data: JSON
248
333
  error: String
334
+ """
335
+ Keys the write discarded because the doctype declares no column for them, or because the
336
+ value was a nested relation rather than a column value. Null when everything sent was
337
+ stored. The action still succeeded — this is what it did not keep, and a client that
338
+ reports an unqualified success without checking it tells the user data was saved that
339
+ was not.
340
+ """
341
+ droppedFields: [String!]
249
342
  }
250
343
 
251
344
  extend type Query {
@@ -267,176 +360,191 @@ const ve = he`
267
360
  stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
268
361
  }
269
362
  `;
270
- class ee extends Error {
363
+ class fe extends Error {
271
364
  constructor(t) {
272
365
  super(t.error ?? "Action failed"), this.outcome = t, this.name = "ActionRolledBack";
273
366
  }
274
367
  outcome;
275
368
  }
276
- const Je = (e = {}) => {
277
- const t = e.debug ? (o, n) => (console.log(`[@stonecrop/graphql-middleware] ${n.text}`, n.values ?? []), o.query(n)) : (o, n) => o.query(n);
278
- return ye((o) => {
279
- const n = o.input?.pgRegistry?.pgExecutors, r = n ? Object.values(n)[0] : void 0;
280
- if (!r)
369
+ const he = "__stonecropLinkFk_", Q = "status", it = (e = {}) => {
370
+ const t = e.debug ? (n, r) => (console.log(`[@stonecrop/graphql-middleware] ${r.text}`, r.values ?? []), n.query(r)) : (n, r) => n.query(r), o = e.defaultRecordLimit === void 0 ? 200 : e.defaultRecordLimit;
371
+ return Te((n) => {
372
+ const r = n.input?.pgRegistry?.pgExecutors, i = r ? Object.values(r)[0] : void 0;
373
+ if (!i)
281
374
  throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
282
- return e.actionHandlers && Me(e.actionHandlers), Ae(), {
283
- typeDefs: ve,
375
+ return e.actionHandlers && qe(e.actionHandlers), Ue(), {
376
+ typeDefs: We,
284
377
  objects: {
285
378
  Query: {
286
379
  plans: {
287
- stonecropMeta(i, { $doctype: l }) {
288
- return pe(l, (d) => M(String(d)) ?? null);
380
+ stonecropMeta(a, { $doctype: u }) {
381
+ return Fe(u, ($) => L(String($)) ?? null);
289
382
  },
290
383
  stonecropAllMeta() {
291
- return ge(oe());
384
+ return Oe(ye());
292
385
  },
293
- stonecropRecord(i, { $doctype: l, $id: d, $options: S }) {
294
- return Z(
295
- r,
296
- _({ doctype: l, id: d, options: S }),
297
- async (h, a) => {
298
- const $ = /* @__PURE__ */ new Map();
299
- for (let y = 0; y < a.length; y++) {
300
- const s = String(a[y].doctype);
301
- $.has(s) || $.set(s, []), $.get(s).push(y);
386
+ stonecropRecord(a, { $doctype: u, $id: $, $options: k }) {
387
+ return ce(
388
+ i,
389
+ te({ doctype: u, id: $, options: k }),
390
+ async (E, h) => {
391
+ const m = /* @__PURE__ */ new Map();
392
+ for (let f = 0; f < h.length; f++) {
393
+ const s = String(h[f].doctype);
394
+ m.has(s) || m.set(s, []), m.get(s).push(f);
302
395
  }
303
- const R = Array.from({ length: a.length });
304
- for (const [y, s] of $) {
305
- const f = M(y);
306
- if (!f) {
307
- for (const w of s) R[w] = { data: null, doctype: y };
396
+ const y = Array.from({ length: h.length });
397
+ for (const [f, s] of m) {
398
+ const w = L(f);
399
+ if (!w) {
400
+ for (const c of s) y[c] = { data: null, doctype: f };
308
401
  continue;
309
402
  }
310
- const g = Q(f);
311
- if (!g) throw V(y);
312
- const T = D(g.fieldname), F = U(f), c = s.map((w) => String(a[w].id)), { rows: b } = await t(h, {
313
- text: `SELECT ${F} FROM ${B(f.name, e.tables)} WHERE "${T}"::text = ANY($1::text[])`,
314
- values: [c]
315
- }), k = new Map(b.map((w) => [String(w[g.fieldname]), w]));
316
- if (b.length !== k.size)
403
+ const g = ne(w);
404
+ if (!g) throw oe(f);
405
+ const I = R(g.fieldname), q = X(w), F = s.map((c) => String(h[c].id)), N = new Map(z(w.fields).map((c) => [c.fieldname, c])), T = [];
406
+ for (const [c, p] of Object.entries(w.links ?? {})) {
407
+ if (p.cardinality === "noneOrMany" || p.cardinality === "atLeastOne") continue;
408
+ const M = p.fieldname ?? c;
409
+ re(p, N.get(M)?.component) !== "inline" && T.push({ fieldname: M, alias: `${he}${M}` });
410
+ }
411
+ const U = [
412
+ q,
413
+ ...T.map(({ fieldname: c, alias: p }) => `"${R(c)}" AS "${p}"`)
414
+ ].filter(Boolean).join(", "), { rows: l } = await t(E, {
415
+ text: `SELECT ${U} FROM ${P(w.name, e.tables)} WHERE "${I}"::text = ANY($1::text[])`,
416
+ values: [F]
417
+ }), b = new Map(l.map((c) => [String(c[g.fieldname]), c]));
418
+ if (l.length !== b.size)
317
419
  throw new Error(
318
- `Doctype "${y}" declares "${g.fieldname}" as its identity, but that column is not unique in ${B(f.name, e.tables)} — ${b.length} rows matched ${k.size} distinct values, so a lookup cannot say which record it means. Declare a field that uniquely identifies a record, or add a unique constraint.`
420
+ `Doctype "${f}" declares "${g.fieldname}" as its identity, but that column is not unique in ${P(w.name, e.tables)} — ${l.length} rows matched ${b.size} distinct values, so a lookup cannot say which record it means. Declare a field that uniquely identifies a record, or add a unique constraint.`
319
421
  );
320
- for (const w of s) {
321
- const A = String(a[w].id), I = k.get(A);
322
- if (!I) {
323
- R[w] = { data: null, doctype: y };
422
+ const S = [];
423
+ for (const c of s) {
424
+ const p = String(h[c].id), M = b.get(p);
425
+ if (!M) {
426
+ y[c] = { data: null, doctype: f };
324
427
  continue;
325
428
  }
326
- const E = { ...I }, j = a[w].options ?? {}, H = j.includeNested === !0, O = Array.isArray(j.includeNested) ? new Set(j.includeNested) : null;
327
- if (f.links)
328
- for (const [u, m] of Object.entries(f.links)) {
329
- const v = m.fetch, N = m.cardinality === "noneOrMany" || m.cardinality === "atLeastOne", W = v?.method ?? (N ? "sync" : "lazy"), Y = v?.method === "sync" ? v.limit : N ? 50 : void 0;
330
- if (!(H || (O ? O.has(u) : W === "sync"))) continue;
331
- if (W === "custom" && v?.method === "custom") {
332
- const P = v.handler, x = Ee(P);
333
- x && (E[u] = await x(h, E, m));
429
+ const d = { ...M };
430
+ S.push(d);
431
+ const v = [], O = h[c].options ?? {}, A = O.includeNested === !0, x = Array.isArray(O.includeNested) ? new Set(O.includeNested) : null;
432
+ if (w.links)
433
+ for (const [B, D] of Object.entries(w.links)) {
434
+ const j = D.fieldname ?? B, K = D.fetch, ee = D.cardinality === "noneOrMany" || D.cardinality === "atLeastOne", se = K?.method ?? (ee ? "sync" : "lazy"), we = K?.method === "sync" ? K.limit : void 0, V = ee ? we ?? o : void 0;
435
+ if (!(A || (x ? x.has(B) : se === "sync"))) continue;
436
+ if (se === "custom" && K?.method === "custom") {
437
+ const J = K.handler, C = je(J);
438
+ C && (d[j] = await C(E, d, D));
334
439
  continue;
335
440
  }
336
- if (W !== "sync" && !O?.has(u)) continue;
337
- const L = M(m.target);
338
- if (!L) continue;
339
- const X = U(L);
340
- if (N) {
341
- if (!m.backlink) continue;
342
- const P = D(m.backlink);
343
- let x = `SELECT ${X} FROM ${B(L.name, e.tables)} WHERE "${P}"::text = $1`;
344
- const q = [A];
345
- Y != null && (x += " LIMIT $2", q.push(Y));
346
- const { rows: J } = await t(h, {
347
- text: x,
348
- values: q
441
+ if (re(D, N.get(j)?.component) === "inline") continue;
442
+ const _ = L(D.target);
443
+ if (!_) continue;
444
+ const le = X(_);
445
+ if (ee) {
446
+ if (!D.backlink) continue;
447
+ const J = R(D.backlink);
448
+ let C = `SELECT ${le} FROM ${P(_.name, e.tables)} WHERE "${J}"::text = $1`;
449
+ const Y = [p];
450
+ V != null && (C += " LIMIT $2", Y.push(V + 1));
451
+ const { rows: G } = await t(E, {
452
+ text: C,
453
+ values: Y
349
454
  });
350
- E[u] = J;
455
+ V != null && G.length > V ? (v.push(j), d[j] = G.slice(0, V)) : d[j] = G;
351
456
  } else {
352
- if (!m.fieldname) continue;
353
- const P = E[m.fieldname];
354
- if (P == null) {
355
- E[u] = null;
457
+ const J = d[`${he}${j}`];
458
+ if (J == null) {
459
+ d[j] = null;
356
460
  continue;
357
461
  }
358
- const x = Q(L);
359
- if (!x) throw V(L.name);
360
- const q = D(x.fieldname), { rows: J } = await t(h, {
361
- text: `SELECT ${X} FROM ${B(L.name, e.tables)} WHERE "${q}" = $1`,
362
- values: [P]
462
+ const C = ne(_);
463
+ if (!C) throw oe(_.name);
464
+ const Y = R(C.fieldname), { rows: G } = await t(E, {
465
+ text: `SELECT ${le} FROM ${P(_.name, e.tables)} WHERE "${Y}" = $1`,
466
+ values: [J]
363
467
  });
364
- E[u] = J[0] ?? null;
468
+ d[j] = G[0] ?? null;
365
469
  }
366
470
  }
367
- const p = O && f.links ? [...O].filter((u) => !(u in f.links)) : void 0;
368
- R[w] = {
369
- data: E,
370
- doctype: y,
371
- unknownLinks: p?.length ? p : void 0
471
+ for (const { alias: B } of T) delete d[B];
472
+ const H = x && w.links ? [...x].filter((B) => !(B in w.links)) : void 0;
473
+ y[c] = {
474
+ data: d,
475
+ doctype: f,
476
+ unknownLinks: H?.length ? H : void 0,
477
+ truncatedLinks: v.length ? v : void 0
372
478
  };
373
479
  }
480
+ await ue(E, w, S, e.tables, t);
374
481
  }
375
- return R;
482
+ return y;
376
483
  }
377
484
  );
378
485
  },
379
- stonecropRecords(i, { $doctype: l, $filters: d, $orderBy: S, $limit: h, $offset: a, $includeTotal: $ }) {
380
- return Z(
381
- r,
382
- _({
383
- doctype: l,
384
- filters: d,
385
- orderBy: S,
386
- limit: h,
387
- offset: a,
388
- includeTotal: $
486
+ stonecropRecords(a, { $doctype: u, $filters: $, $orderBy: k, $limit: E, $offset: h, $includeTotal: m }) {
487
+ return ce(
488
+ i,
489
+ te({
490
+ doctype: u,
491
+ filters: $,
492
+ orderBy: k,
493
+ limit: E,
494
+ offset: h,
495
+ includeTotal: m
389
496
  }),
390
- async (R, y) => await Promise.all(
391
- y.map(async (s) => {
392
- const f = String(s.doctype), g = M(f);
497
+ async (y, f) => await Promise.all(
498
+ f.map(async (s) => {
499
+ const w = String(s.doctype), g = L(w);
393
500
  if (!g)
394
- return { data: [], doctype: f, hasMore: !1, count: s.includeTotal === !0 ? 0 : null };
395
- const T = new Set(z(g.fields).map((p) => p.fieldname)), F = U(g), c = [], b = [];
501
+ return { data: [], doctype: w, hasMore: !1, count: s.includeTotal === !0 ? 0 : null };
502
+ const I = new Set(z(g.fields).map((d) => d.fieldname)), q = X(g), F = [], N = [];
396
503
  if (s.filters != null)
397
- for (const [p, u] of Object.entries(s.filters)) {
398
- if (!T.has(p))
399
- throw new Error(`Unknown filter field: ${p} for doctype ${g.name}`);
400
- c.push(u), b.push(`"${D(p)}" = $${c.length}`);
504
+ for (const [d, v] of Object.entries(s.filters)) {
505
+ if (!I.has(d))
506
+ throw new Error(`Unknown filter field: ${d} for doctype ${g.name}`);
507
+ F.push(v), N.push(`"${R(d)}" = $${F.length}`);
401
508
  }
402
- const k = b.length > 0 ? ` WHERE ${b.join(" AND ")}` : "";
403
- let w = "";
509
+ const T = N.length > 0 ? ` WHERE ${N.join(" AND ")}` : "";
510
+ let U = "";
404
511
  if (s.orderBy != null) {
405
512
  if (typeof s.orderBy != "string")
406
513
  throw new Error(`Invalid orderBy: expected string, got ${typeof s.orderBy}`);
407
- const p = s.orderBy, u = p.lastIndexOf("_");
408
- if (u <= 0)
409
- throw new Error(`Invalid orderBy format: "${p}". Expected FIELD_ASC or FIELD_DESC`);
410
- const m = p.slice(u + 1).toUpperCase();
411
- if (m !== "ASC" && m !== "DESC")
412
- throw new Error(`Invalid orderBy direction: "${m}". Must be ASC or DESC`);
413
- const v = p.slice(0, u);
414
- if (!T.has(v))
415
- throw new Error(`Unknown orderBy field: "${v}" for doctype ${g.name}`);
416
- w = ` ORDER BY "${D(v)}" ${m}`;
514
+ const d = s.orderBy, v = d.lastIndexOf("_");
515
+ if (v <= 0)
516
+ throw new Error(`Invalid orderBy format: "${d}". Expected FIELD_ASC or FIELD_DESC`);
517
+ const O = d.slice(v + 1).toUpperCase();
518
+ if (O !== "ASC" && O !== "DESC")
519
+ throw new Error(`Invalid orderBy direction: "${O}". Must be ASC or DESC`);
520
+ const A = d.slice(0, v);
521
+ if (!I.has(A))
522
+ throw new Error(`Unknown orderBy field: "${A}" for doctype ${g.name}`);
523
+ U = ` ORDER BY "${R(A)}" ${O}`;
417
524
  }
418
525
  if (s.limit != null && typeof s.limit != "number")
419
526
  throw new Error(`Invalid limit: expected number, got ${typeof s.limit}`);
420
- const A = s.limit ?? (e.defaultRecordLimit === void 0 ? 200 : e.defaultRecordLimit);
421
- let I = "";
422
- A != null && (c.push(A + 1), I += ` LIMIT $${c.length}`), s.offset != null && (c.push(s.offset), I += ` OFFSET $${c.length}`);
423
- const { rows: E } = await t(R, {
424
- text: `SELECT ${F} FROM ${B(g.name, e.tables)}${k}${w}${I}`,
425
- values: c
426
- }), j = A != null && E.length > A, H = j ? E.slice(0, A ?? E.length) : E;
427
- let O = null;
527
+ const l = s.limit ?? o;
528
+ let b = "";
529
+ l != null && (F.push(l + 1), b += ` LIMIT $${F.length}`), s.offset != null && (F.push(s.offset), b += ` OFFSET $${F.length}`);
530
+ const { rows: S } = await t(y, {
531
+ text: `SELECT ${q} FROM ${P(g.name, e.tables)}${T}${U}${b}`,
532
+ values: F
533
+ }), c = l != null && S.length > l, p = [...c ? S.slice(0, l ?? S.length) : S];
534
+ await ue(y, g, p, e.tables, t);
535
+ let M = null;
428
536
  if (s.includeTotal === !0) {
429
- const p = [], u = [];
537
+ const d = [], v = [];
430
538
  if (s.filters != null)
431
- for (const [N, W] of Object.entries(s.filters))
432
- T.has(N) && (p.push(W), u.push(`"${D(N)}" = $${p.length}`));
433
- const m = u.length > 0 ? ` WHERE ${u.join(" AND ")}` : "", { rows: v } = await t(R, {
434
- text: `SELECT COUNT(*) AS row_count FROM ${B(g.name, e.tables)}${m}`,
435
- values: p
539
+ for (const [x, H] of Object.entries(s.filters))
540
+ I.has(x) && (d.push(H), v.push(`"${R(x)}" = $${d.length}`));
541
+ const O = v.length > 0 ? ` WHERE ${v.join(" AND ")}` : "", { rows: A } = await t(y, {
542
+ text: `SELECT COUNT(*) AS row_count FROM ${P(g.name, e.tables)}${O}`,
543
+ values: d
436
544
  });
437
- O = parseInt(v[0]?.row_count ?? "0", 10);
545
+ M = parseInt(A[0]?.row_count ?? "0", 10);
438
546
  }
439
- return { data: H, doctype: f, hasMore: j, count: O };
547
+ return { data: p, doctype: w, hasMore: c, count: M };
440
548
  })
441
549
  )
442
550
  );
@@ -445,66 +553,125 @@ const Je = (e = {}) => {
445
553
  },
446
554
  Mutation: {
447
555
  plans: {
448
- stonecropAction(i, { $doctype: l, $action: d, $args: S }) {
449
- return fe(
450
- r,
451
- _({ doctype: l, action: d, actionArgs: S }),
452
- async (h, a) => {
453
- const $ = M(String(a.doctype));
454
- if (!$)
556
+ stonecropAction(a, { $doctype: u, $action: $, $args: k }) {
557
+ return Me(
558
+ i,
559
+ te({ doctype: u, action: $, actionArgs: k }),
560
+ async (E, h) => {
561
+ const m = L(String(h.doctype));
562
+ if (!m)
455
563
  return {
456
564
  success: !1,
457
565
  data: null,
458
- error: `Unknown doctype: ${a.doctype}`
566
+ error: `Unknown doctype: ${h.doctype}`
459
567
  };
460
- const R = $.workflow?.actions?.[a.action];
461
- if (!R)
568
+ const y = m.workflow?.actions?.[h.action];
569
+ if (!y)
462
570
  return {
463
571
  success: !1,
464
572
  data: null,
465
- error: `Unknown action: ${a.action} on ${a.doctype}`
573
+ error: `Unknown action: ${h.action} on ${h.doctype}`
466
574
  };
467
- const y = B($.name, e.tables), s = () => {
468
- const c = Q($);
469
- if (!c) throw V(String(a.doctype));
470
- return D(c.fieldname);
471
- }, f = Array.isArray(a.actionArgs) ? a.actionArgs : [], g = f[0]?.id, T = f[0]?.data ?? {}, F = e.actionHandlers?.[$.name]?.[String(a.action)];
575
+ const f = P(m.name, e.tables), s = () => {
576
+ const l = ne(m);
577
+ if (!l) throw oe(String(h.doctype));
578
+ return R(l.fieldname);
579
+ }, w = Array.isArray(h.actionArgs) ? h.actionArgs : [], g = w[0]?.id, I = w[0]?.data ?? {}, q = e.actionHandlers?.[m.name]?.[String(h.action)], F = new Map(
580
+ Z(m.fields).filter((l) => R(l.fieldname) !== Q).map((l) => [l.fieldname, l])
581
+ ), N = Z(m.fields).some(
582
+ (l) => R(l.fieldname) === Q
583
+ ), T = [], U = (l) => {
584
+ const b = [], S = [];
585
+ for (const [c, p] of Object.entries(l)) {
586
+ if (!F.has(c)) {
587
+ T.push(c);
588
+ continue;
589
+ }
590
+ if (p !== null && typeof p == "object") {
591
+ T.push(c);
592
+ continue;
593
+ }
594
+ b.push(R(c)), S.push(p);
595
+ }
596
+ return { cols: b, values: S };
597
+ };
472
598
  try {
473
- return await h.withTransaction(async (c) => {
474
- const b = await be(R, {
475
- readState: async () => {
476
- if (g == null) return null;
477
- const { rows: k } = await t(c, {
478
- text: `SELECT "status" FROM ${y} WHERE "${s()}"::text = $1 FOR UPDATE`,
479
- values: [String(g)]
480
- });
481
- return k.length === 0 ? null : k[0].status ?? void 0;
482
- },
483
- writeState: async (k) => {
484
- await t(c, {
485
- text: `UPDATE ${y} SET "status" = $1 WHERE "${s()}"::text = $2`,
486
- values: [k, String(g)]
487
- });
599
+ return await E.withTransaction(async (l) => {
600
+ const b = await Ce(
601
+ y,
602
+ {
603
+ readState: async () => {
604
+ if (g == null) return null;
605
+ const S = N ? `"${Q}"` : `"${s()}"`, { rows: c } = await t(l, {
606
+ text: `SELECT ${S} FROM ${f} WHERE "${s()}"::text = $1 FOR UPDATE`,
607
+ values: [String(g)]
608
+ });
609
+ if (c.length === 0) return null;
610
+ if (N)
611
+ return c[0][Q] ?? void 0;
612
+ },
613
+ writeState: async (S) => {
614
+ await t(l, {
615
+ text: `UPDATE ${f} SET "${Q}" = $1 WHERE "${s()}"::text = $2`,
616
+ values: [S, String(g)]
617
+ });
618
+ },
619
+ // The upsert, and the only write path for record data. `exists`
620
+ // comes from the guard's own read, so no second lookup decides it.
621
+ //
622
+ // Returns the same projection the read path selects, never
623
+ // `RETURNING *`: raw columns come back snake_case, and the client
624
+ // resolves identity by the *declared fieldname*. A doctype keyed
625
+ // `itemId` would receive `item_id`, find no identity, and file a
626
+ // created record nowhere — which is that exact bug, already once
627
+ // shipped and patched downstream.
628
+ writeData: async (S, c) => {
629
+ const { cols: p, values: M } = U(S), d = X(m);
630
+ if (!c) {
631
+ if (g != null)
632
+ throw new Error(
633
+ `Action "${y.label ?? h.action}" targets ${m.name} "${String(g)}", which no longer exists. Nothing was created — a record dispatched with an identity is an update, and creating one is what dispatching no identity means.`
634
+ );
635
+ const A = p.length ? `INSERT INTO ${f} (${p.map((H) => `"${H}"`).join(", ")}) VALUES (${p.map((H, B) => `$${B + 1}`).join(", ")}) RETURNING ${d}` : `INSERT INTO ${f} DEFAULT VALUES RETURNING ${d}`, { rows: x } = await t(l, { text: A, values: M });
636
+ return x[0] ?? {};
637
+ }
638
+ if (p.length === 0) {
639
+ const { rows: A } = await t(l, {
640
+ text: `SELECT ${d} FROM ${f} WHERE "${s()}"::text = $1`,
641
+ values: [String(g)]
642
+ });
643
+ return A[0] ?? {};
644
+ }
645
+ const v = p.map((A, x) => `"${A}" = $${x + 1}`).join(", "), { rows: O } = await t(l, {
646
+ text: `UPDATE ${f} SET ${v} WHERE "${s()}"::text = $${p.length + 1} RETURNING ${d}`,
647
+ values: [...M, String(g)]
648
+ });
649
+ return O[0] ?? {};
650
+ },
651
+ runEffect: q ? (S) => q({
652
+ pgClient: l,
653
+ doctype: String(h.doctype),
654
+ action: String(h.action),
655
+ meta: m,
656
+ recordId: g,
657
+ data: I,
658
+ args: w,
659
+ currentState: S
660
+ }) : void 0
488
661
  },
489
- runEffect: F ? (k) => F({
490
- pgClient: c,
491
- doctype: String(a.doctype),
492
- action: String(a.action),
493
- meta: $,
494
- recordId: g,
495
- data: T,
496
- args: f,
497
- currentState: k
498
- }) : void 0
499
- });
500
- if (!b.success) throw new ee(b);
501
- return b;
662
+ // The patch a self-transition persists. This adapter never passed it, which
663
+ // was moot while it had no `writeData` — nothing consumed it. Wiring the write
664
+ // without this argument saves an empty record and reports success.
665
+ I
666
+ );
667
+ if (!b.success) throw new fe(b);
668
+ return T.length ? { ...b, droppedFields: T } : b;
502
669
  });
503
- } catch (c) {
504
- return c instanceof ee ? c.outcome : {
670
+ } catch (l) {
671
+ return l instanceof fe ? l.outcome : {
505
672
  success: !1,
506
673
  data: null,
507
- error: c instanceof Error ? c.message : String(c)
674
+ error: l instanceof Error ? l.message : String(l)
508
675
  };
509
676
  }
510
677
  }
@@ -516,38 +683,31 @@ const Je = (e = {}) => {
516
683
  };
517
684
  });
518
685
  };
519
- function z(e) {
520
- const t = [];
521
- for (const o of e)
522
- o.kind === "fieldset" ? t.push(...z(o.schema)) : t.push(o);
523
- return t;
524
- }
525
- function Re(e, t) {
686
+ function He(e, t) {
526
687
  const o = [];
527
- for (const n of z(e)) {
528
- if (n.kind !== "field" || n.computed) continue;
688
+ for (const n of Z(e)) {
529
689
  const r = t.get(n.fieldname);
530
- if (r && ue(r, n.component) !== "inline") continue;
531
- const i = D(n.fieldname);
690
+ if (r && re(r, n.component) !== "inline") continue;
691
+ const i = R(n.fieldname);
532
692
  o.push(i !== n.fieldname ? `"${i}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
533
693
  }
534
694
  return o;
535
695
  }
536
- function U(e) {
696
+ function X(e) {
537
697
  const t = /* @__PURE__ */ new Map();
538
698
  if (e.links)
539
699
  for (const [o, n] of Object.entries(e.links))
540
700
  t.set(n.fieldname ?? o, n);
541
- return Re(e.fields, t).join(", ");
701
+ return He(e.fields, t).join(", ");
542
702
  }
543
- function Q(e) {
544
- const t = de(e.fields);
703
+ function ne(e) {
704
+ const t = me(e.fields);
545
705
  return e.fields.find((o) => o.kind === "field" && o.fieldname === t);
546
706
  }
547
- function Me(e) {
707
+ function qe(e) {
548
708
  const t = Object.entries(e);
549
709
  if (t.length === 0) return;
550
- if (oe().length === 0) {
710
+ if (ye().length === 0) {
551
711
  console.warn(
552
712
  "[@stonecrop/graphql-middleware] Schema built with no doctypes registered, so the `actionHandlers` map could not be verified. Load doctypes before building the schema to have stale handler keys reported."
553
713
  );
@@ -555,7 +715,7 @@ function Me(e) {
555
715
  }
556
716
  const o = [];
557
717
  for (const [n, r] of t) {
558
- const i = M(n);
718
+ const i = L(n);
559
719
  if (!i) {
560
720
  o.push(`"${n}": no doctype by that name is registered`);
561
721
  continue;
@@ -566,9 +726,9 @@ function Me(e) {
566
726
  );
567
727
  continue;
568
728
  }
569
- const l = i.workflow?.actions ?? {};
570
- for (const d of Object.keys(r))
571
- d in l || o.push(`"${n}.${d}": the doctype declares no action by that key`);
729
+ const a = i.workflow?.actions ?? {};
730
+ for (const u of Object.keys(r))
731
+ u in a || o.push(`"${n}.${u}": the doctype declares no action by that key`);
572
732
  }
573
733
  if (o.length > 0)
574
734
  throw new Error(
@@ -577,8 +737,8 @@ function Me(e) {
577
737
  `)}`
578
738
  );
579
739
  }
580
- function Ae() {
581
- const e = ke();
740
+ function Ue() {
741
+ const e = Be();
582
742
  if (e.length !== 0)
583
743
  throw new Error(
584
744
  `StonecropPlugin: ${e.length} doctype reference${e.length === 1 ? "" : "s"} cannot be resolved and would silently drop the relation:
@@ -586,26 +746,22 @@ function Ae() {
586
746
  `)
587
747
  );
588
748
  }
589
- function V(e) {
749
+ function oe(e) {
590
750
  return new Error(
591
751
  `Doctype "${e}" has no identity field: it declares no field with \`primaryKey: true\` and no field named \`id\`. Declare one of the two — records cannot be fetched or acted on until then.`
592
752
  );
593
753
  }
594
- function B(e, t) {
595
- const o = t?.[e] ?? le(e), n = o.indexOf(".");
596
- return n > 0 ? `"${o.slice(0, n)}"."${o.slice(n + 1)}"` : `"${o}"`;
597
- }
598
- const _e = (e = {}) => {
754
+ const at = (e = {}) => {
599
755
  const { logPlans: t = !0, logTiming: o = !1 } = e, n = (r, i) => ({
600
- plan: (l) => {
756
+ plan: (a) => {
601
757
  t && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${i}`);
602
- const d = o ? Date.now() : 0, S = l();
758
+ const u = o ? Date.now() : 0, $ = a();
603
759
  return o && console.log(
604
- `[@stonecrop/graphql-middleware] Plan built for ${r}.${i} in ${Date.now() - d}ms`
605
- ), S;
760
+ `[@stonecrop/graphql-middleware] Plan built for ${r}.${i} in ${Date.now() - u}ms`
761
+ ), $;
606
762
  }
607
763
  });
608
- return me({
764
+ return Le({
609
765
  Query: {
610
766
  stonecropRecord: n("Query", "stonecropRecord"),
611
767
  stonecropRecords: n("Query", "stonecropRecords"),
@@ -616,7 +772,7 @@ const _e = (e = {}) => {
616
772
  stonecropAction: n("Mutation", "stonecropAction")
617
773
  }
618
774
  });
619
- }, Oe = {
775
+ }, _e = {
620
776
  name: "StonecropFieldCasingPlugin",
621
777
  version: "0.0.0",
622
778
  inflection: {
@@ -626,27 +782,27 @@ const _e = (e = {}) => {
626
782
  }
627
783
  }
628
784
  }
629
- }, xe = (e) => ({
630
- extends: [we],
631
- plugins: e?.fieldCasing === "pascal" ? [Oe] : []
632
- }), Ue = xe();
785
+ }, Je = (e) => ({
786
+ extends: [Ne],
787
+ plugins: e?.fieldCasing === "pascal" ? [_e] : []
788
+ }), st = Je();
633
789
  export {
634
- G as DoctypeValidationError,
635
- Ue as StonecropPreset,
636
- be as applyGuardedTransition,
637
- He as clearFetchHandlers,
638
- We as clearRegistry,
639
- _e as createDebugPlugin,
640
- Je as createStonecropPlugin,
641
- xe as createStonecropPreset,
642
- oe as getAllMeta,
643
- Ee as getFetchHandler,
644
- M as getMeta,
645
- Pe as hasMeta,
646
- Se as loadDoctypes,
647
- Le as loadDoctypesFromObject,
648
- Ge as makePgService,
649
- qe as registerFetchHandler,
650
- ve as typeDefs
790
+ ie as DoctypeValidationError,
791
+ st as StonecropPreset,
792
+ Ce as applyGuardedTransition,
793
+ rt as clearFetchHandlers,
794
+ nt as clearRegistry,
795
+ at as createDebugPlugin,
796
+ it as createStonecropPlugin,
797
+ Je as createStonecropPreset,
798
+ ye as getAllMeta,
799
+ je as getFetchHandler,
800
+ L as getMeta,
801
+ tt as hasMeta,
802
+ De as loadDoctypes,
803
+ et as loadDoctypesFromObject,
804
+ dt as makePgService,
805
+ ot as registerFetchHandler,
806
+ We as typeDefs
651
807
  };
652
808
  //# sourceMappingURL=index.js.map