@stonecrop/graphql-middleware 0.28.0 → 0.30.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,16 +1,16 @@
1
1
  import { readdirSync as be, statSync as Ee, readFileSync as Re } from "node:fs";
2
2
  import { join as ve } from "node:path";
3
- import { flattenFields as K, validateDoctype as ye, parseDoctype as we, isActionAllowedInState as Ae, pascalToSnake as Me, camelToSnake as b, getDisplayField as Oe, getRecordIdField as Se, resolveLinkRenderMode as ae } from "@stonecrop/schema";
4
- import { sideEffectWithPgClient as xe, loadOneWithPgClient as ue } from "@dataplan/pg";
5
- import { object as re, constant as Fe, lambda as Ne } from "postgraphile/grafast";
6
- import { gql as Te, extendSchema as Le, wrapPlans as Ie } from "postgraphile/utils";
7
- import { PostGraphileAmberPreset as De } from "postgraphile/presets/amber";
8
- import { makePgService as ft } from "postgraphile/adaptors/pg";
3
+ import { flattenFields as K, validateDoctype as ye, parseDoctype as we, isActionAllowedInState as Ae, pascalToSnake as Me, camelToSnake as R, getDisplayField as Oe, getRecordIdField as Se, unwrapInlineLinks as xe, resolveLinkRenderMode as se } from "@stonecrop/schema";
4
+ import { sideEffectWithPgClient as Fe, loadOneWithPgClient as fe } from "@dataplan/pg";
5
+ import { object as re, constant as Ne, lambda as Te } from "postgraphile/grafast";
6
+ import { gql as Le, extendSchema as Ie, wrapPlans as De } from "postgraphile/utils";
7
+ import { PostGraphileAmberPreset as Ce } from "postgraphile/presets/amber";
8
+ import { makePgService as ht } from "postgraphile/adaptors/pg";
9
9
  function te(e) {
10
10
  return K(e).filter((t) => t.kind === "field" && !t.computed);
11
11
  }
12
- const W = /* @__PURE__ */ new Map();
13
- class se extends Error {
12
+ const H = /* @__PURE__ */ new Map();
13
+ class le extends Error {
14
14
  constructor(t, o) {
15
15
  const n = o.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
16
16
  `);
@@ -20,14 +20,14 @@ ${n}`), this.file = t, this.errors = o, this.name = "DoctypeValidationError";
20
20
  file;
21
21
  errors;
22
22
  }
23
- function Ce(e, t = {}) {
23
+ function Be(e, t = {}) {
24
24
  const o = be(e);
25
25
  for (const n of o) {
26
26
  const r = ve(e, n);
27
- Ee(r).isDirectory() ? Ce(r, t) : n.endsWith(".json") && Be(r, t);
27
+ Ee(r).isDirectory() ? Be(r, t) : n.endsWith(".json") && Pe(r, t);
28
28
  }
29
29
  }
30
- function Be(e, t) {
30
+ function Pe(e, t) {
31
31
  const o = Re(e, "utf-8");
32
32
  let n;
33
33
  try {
@@ -41,7 +41,7 @@ function Be(e, t) {
41
41
  t.onError?.(e, [u]);
42
42
  return;
43
43
  }
44
- throw new se(e, [u]);
44
+ throw new le(e, [u]);
45
45
  }
46
46
  const r = ye(n);
47
47
  if (!r.success) {
@@ -49,12 +49,12 @@ function Be(e, t) {
49
49
  t.onError?.(e, r.errors);
50
50
  return;
51
51
  }
52
- throw new se(e, r.errors);
52
+ throw new le(e, r.errors);
53
53
  }
54
54
  const i = we(n);
55
- W.set(i.name, i);
55
+ H.set(i.name, i);
56
56
  }
57
- function nt(e, t = {}) {
57
+ function ot(e, t = {}) {
58
58
  for (const [o, n] of Object.entries(e)) {
59
59
  const r = { ...typeof n == "object" && n !== null ? n : {}, name: o }, i = ye(r);
60
60
  if (!i.success) {
@@ -62,31 +62,31 @@ function nt(e, t = {}) {
62
62
  t.onError?.(o, i.errors);
63
63
  continue;
64
64
  }
65
- throw new se(o, i.errors);
65
+ throw new le(o, i.errors);
66
66
  }
67
67
  const a = we(r);
68
- W.set(a.name, a);
68
+ H.set(a.name, a);
69
69
  }
70
70
  }
71
- function T(e) {
72
- const t = W.get(e);
71
+ function L(e) {
72
+ const t = H.get(e);
73
73
  if (t) return t;
74
- for (const o of W.values())
74
+ for (const o of H.values())
75
75
  if (o.slug === e) return o;
76
76
  }
77
77
  function $e() {
78
- return Array.from(W.values());
78
+ return Array.from(H.values());
79
79
  }
80
- function ot(e) {
81
- return W.has(e);
80
+ function rt(e) {
81
+ return H.has(e);
82
82
  }
83
- function rt() {
84
- W.clear();
83
+ function it() {
84
+ H.clear();
85
85
  }
86
- function Pe() {
86
+ function je() {
87
87
  const e = [];
88
- for (const t of W.values()) {
89
- t.inherits && T(t.inherits) === void 0 && e.push({
88
+ for (const t of H.values()) {
89
+ t.inherits && L(t.inherits) === void 0 && e.push({
90
90
  path: [t.name, "inherits"],
91
91
  message: `References unknown doctype: ${t.inherits}`
92
92
  });
@@ -94,7 +94,7 @@ function Pe() {
94
94
  for (const n of o) {
95
95
  if (n.kind !== "field") continue;
96
96
  const r = n.doctype;
97
- r !== void 0 && T(r) === void 0 && e.push({
97
+ r !== void 0 && L(r) === void 0 && e.push({
98
98
  path: [t.name, "fields", n.fieldname, "doctype"],
99
99
  message: `Link references unknown doctype: ${r}`
100
100
  });
@@ -102,7 +102,7 @@ function Pe() {
102
102
  if (t.links) {
103
103
  const n = new Set(o.map((i) => i.fieldname)), r = new Set(te(t.fields).map((i) => i.fieldname));
104
104
  for (const [i, a] of Object.entries(t.links)) {
105
- if (T(a.target) === void 0 && e.push({
105
+ if (L(a.target) === void 0 && e.push({
106
106
  path: [t.name, "links", i, "target"],
107
107
  message: `Link references unknown doctype: ${a.target}`
108
108
  }), a.fetch?.method === "custom") continue;
@@ -130,16 +130,16 @@ function Pe() {
130
130
  return e;
131
131
  }
132
132
  const ce = /* @__PURE__ */ new Map();
133
- function it(e, t) {
133
+ function at(e, t) {
134
134
  ce.set(e, t);
135
135
  }
136
- function je(e) {
136
+ function _e(e) {
137
137
  return ce.get(e);
138
138
  }
139
- function at() {
139
+ function st() {
140
140
  ce.clear();
141
141
  }
142
- async function _e(e, t, o) {
142
+ async function We(e, t, o) {
143
143
  const n = e.label ?? "unknown", r = e.selfTransition === !0, i = r || e.nextState != null;
144
144
  if (!i && !t.runEffect)
145
145
  return {
@@ -156,15 +156,15 @@ async function _e(e, t, o) {
156
156
  const a = (e.allowedStates?.length ?? 0) > 0;
157
157
  let u;
158
158
  if (a || i) {
159
- const k = await t.readState();
160
- if (k === null) {
159
+ const E = await t.readState();
160
+ if (E === null) {
161
161
  if (r && t.writeData) {
162
- const E = await t.writeData(o ?? {}, !1);
163
- return !E || Object.keys(E).length === 0 ? {
162
+ const v = await t.writeData(o ?? {}, !1);
163
+ return !v || Object.keys(v).length === 0 ? {
164
164
  success: !1,
165
165
  data: null,
166
166
  error: `Action "${n}" targets a record that does not exist, and the backend did not create it.`
167
- } : { success: !0, data: E, error: null };
167
+ } : { success: !0, data: v, error: null };
168
168
  }
169
169
  return {
170
170
  success: !1,
@@ -172,7 +172,7 @@ async function _e(e, t, o) {
172
172
  error: `Action "${n}" targets a record that does not exist — nothing was executed.`
173
173
  };
174
174
  }
175
- u = k ?? "";
175
+ u = E ?? "";
176
176
  }
177
177
  if (!Ae(e, u ?? ""))
178
178
  return {
@@ -180,24 +180,24 @@ async function _e(e, t, o) {
180
180
  data: null,
181
181
  error: `Action not allowed from state: ${u || "(unknown)"}`
182
182
  };
183
- let $;
183
+ let b;
184
184
  if (t.runEffect)
185
185
  try {
186
- $ = await t.runEffect(u);
187
- } catch (k) {
186
+ b = await t.runEffect(u);
187
+ } catch (E) {
188
188
  return {
189
189
  success: !1,
190
190
  data: null,
191
- error: `Action "${n}" failed: ${k instanceof Error ? k.message : String(k)}`
191
+ error: `Action "${n}" failed: ${E instanceof Error ? E.message : String(E)}`
192
192
  };
193
193
  }
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), {
194
+ return r ? { success: !0, data: (t.writeData ? await t.writeData(o ?? {}, !0) : b) ?? null, error: null } : e.nextState == null ? { success: !0, data: b ?? null, error: null } : (await t.writeState(e.nextState), {
195
195
  success: !0,
196
- data: $ ?? { state: e.nextState },
196
+ data: b ?? { state: e.nextState },
197
197
  error: null
198
198
  });
199
199
  }
200
- function _(e, t) {
200
+ function W(e, t) {
201
201
  const o = t?.[e] ?? Me(e), n = o.indexOf(".");
202
202
  return n > 0 ? `"${o.slice(0, n)}"."${o.slice(n + 1)}"` : `"${o}"`;
203
203
  }
@@ -208,50 +208,50 @@ function Z(e) {
208
208
  return String(e);
209
209
  }
210
210
  }
211
- function We(e, t) {
211
+ function He(e, t) {
212
212
  const o = [];
213
213
  for (const n of K(e.fields)) {
214
214
  if (n.kind !== "field" || !n.doctype) continue;
215
- const r = T(n.doctype);
215
+ const r = L(n.doctype);
216
216
  if (!r) continue;
217
217
  const i = Oe(r.fields, r.displayField);
218
218
  i && o.push({
219
219
  fieldname: n.fieldname,
220
220
  displayField: i.fieldname,
221
221
  targetPkFieldname: Se(r.fields),
222
- targetTable: _(r.name, t)
222
+ targetTable: W(r.name, t)
223
223
  });
224
224
  }
225
225
  return o;
226
226
  }
227
- async function fe(e, t, o, n, r) {
228
- const i = We(t, n);
227
+ async function ie(e, t, o, n, r) {
228
+ const i = He(t, n);
229
229
  i.length === 0 || o.length === 0 || await Promise.all(
230
230
  i.map(async (a) => {
231
231
  const u = /* @__PURE__ */ new Set();
232
- for (const w of o) {
233
- const f = Z(w[a.fieldname]);
232
+ for (const y of o) {
233
+ const f = Z(y[a.fieldname]);
234
234
  f !== void 0 && u.add(f);
235
235
  }
236
236
  if (u.size === 0) return;
237
- const $ = b(a.targetPkFieldname), k = b(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[])`,
237
+ const b = R(a.targetPkFieldname), E = R(a.displayField), v = E !== a.displayField ? `"${E}" AS "${a.displayField}"` : `"${a.displayField}"`, { rows: p } = await r(e, {
238
+ text: `SELECT "${b}" AS "${a.targetPkFieldname}", ${v} FROM ${a.targetTable} WHERE "${b}"::text = ANY($1::text[])`,
239
239
  values: [Array.from(u)]
240
- }), y = /* @__PURE__ */ new Map();
241
- for (const w of h) {
242
- const f = Z(w[a.targetPkFieldname]), s = Z(w[a.displayField]);
243
- f === void 0 || s === void 0 || y.set(f, s);
240
+ }), g = /* @__PURE__ */ new Map();
241
+ for (const y of p) {
242
+ const f = Z(y[a.targetPkFieldname]), l = Z(y[a.displayField]);
243
+ f === void 0 || l === void 0 || g.set(f, l);
244
244
  }
245
- for (const w of o) {
246
- const f = w[a.fieldname], s = Z(f);
247
- if (s === void 0) continue;
248
- const p = y.get(s);
249
- p !== void 0 && (w[a.fieldname] = { id: f, displayText: p });
245
+ for (const y of o) {
246
+ const f = y[a.fieldname], l = Z(f);
247
+ if (l === void 0) continue;
248
+ const w = g.get(l);
249
+ w !== void 0 && (y[a.fieldname] = { id: f, displayText: w });
250
250
  }
251
251
  })
252
252
  );
253
253
  }
254
- const He = Te`
254
+ const qe = Le`
255
255
  type StonecropFieldMeta {
256
256
  kind: String!
257
257
  fieldname: String!
@@ -369,189 +369,189 @@ class he extends Error {
369
369
  }
370
370
  outcome;
371
371
  }
372
- const pe = "__stonecropLinkFk_", V = "status", st = (e = {}) => {
372
+ const pe = "__stonecropLinkFk_", V = "status", lt = (e = {}) => {
373
373
  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;
374
- return Le((n) => {
374
+ return Ie((n) => {
375
375
  const r = n.input?.pgRegistry?.pgExecutors, i = r ? Object.values(r)[0] : void 0;
376
376
  if (!i)
377
377
  throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
378
- return e.actionHandlers && Ue(e.actionHandlers), Je(), {
379
- typeDefs: He,
378
+ return e.actionHandlers && Je(e.actionHandlers), Ke(), {
379
+ typeDefs: qe,
380
380
  objects: {
381
381
  Query: {
382
382
  plans: {
383
383
  stonecropMeta(a, { $doctype: u }) {
384
- return Ne(u, ($) => T(String($)) ?? null);
384
+ return Te(u, (b) => L(String(b)) ?? null);
385
385
  },
386
386
  stonecropAllMeta() {
387
- return Fe($e());
387
+ return Ne($e());
388
388
  },
389
- stonecropRecord(a, { $doctype: u, $id: $, $options: k }) {
390
- return ue(
389
+ stonecropRecord(a, { $doctype: u, $id: b, $options: E }) {
390
+ return fe(
391
391
  i,
392
- re({ doctype: u, id: $, options: k }),
393
- async (E, h) => {
394
- const y = /* @__PURE__ */ new Map();
395
- for (let f = 0; f < h.length; f++) {
396
- const s = String(h[f].doctype);
397
- y.has(s) || y.set(s, []), y.get(s).push(f);
392
+ re({ doctype: u, id: b, options: E }),
393
+ async (v, p) => {
394
+ const g = /* @__PURE__ */ new Map();
395
+ for (let f = 0; f < p.length; f++) {
396
+ const l = String(p[f].doctype);
397
+ g.has(l) || g.set(l, []), g.get(l).push(f);
398
398
  }
399
- const w = Array.from({ length: h.length });
400
- for (const [f, s] of y) {
401
- const p = T(f);
402
- if (!p) {
403
- for (const d of s) w[d] = { data: null, doctype: f };
399
+ const y = Array.from({ length: p.length });
400
+ for (const [f, l] of g) {
401
+ const w = L(f);
402
+ if (!w) {
403
+ for (const c of l) y[c] = { data: null, doctype: f };
404
404
  continue;
405
405
  }
406
- const g = Y(p);
407
- if (!g) throw ie(f);
408
- const C = b(g.fieldname), U = ee(p), x = s.map((d) => String(h[d].id)), L = new Map(K(p.fields).map((d) => [d.fieldname, d])), N = [];
409
- for (const [d, m] of Object.entries(p.links ?? {})) {
410
- if (m.cardinality === "noneOrMany" || m.cardinality === "atLeastOne") continue;
411
- const M = m.fieldname ?? d;
412
- ae(m, L.get(M)?.component) !== "inline" && N.push({ fieldname: M, alias: `${pe}${M}` });
406
+ const $ = Y(w);
407
+ if (!$) throw ae(f);
408
+ const A = R($.fieldname), U = ee(w), O = l.map((c) => String(p[c].id)), B = new Map(K(w.fields).map((c) => [c.fieldname, c])), P = [];
409
+ for (const [c, h] of Object.entries(w.links ?? {})) {
410
+ if (h.cardinality === "noneOrMany" || h.cardinality === "atLeastOne") continue;
411
+ const S = h.fieldname ?? c;
412
+ se(h, B.get(S)?.component) !== "inline" && P.push({ fieldname: S, alias: `${pe}${S}` });
413
413
  }
414
- const B = [
414
+ const F = [
415
415
  U,
416
- ...N.map(({ fieldname: d, alias: m }) => `"${b(d)}" AS "${m}"`)
417
- ].filter(Boolean).join(", "), { rows: c } = await t(E, {
418
- text: `SELECT ${B} FROM ${_(p.name, e.tables)} WHERE "${C}"::text = ANY($1::text[])`,
419
- values: [x]
420
- }), R = new Map(c.map((d) => [String(d[g.fieldname]), d]));
421
- if (c.length !== R.size)
416
+ ...P.map(({ fieldname: c, alias: h }) => `"${R(c)}" AS "${h}"`)
417
+ ].filter(Boolean).join(", "), { rows: N } = await t(v, {
418
+ text: `SELECT ${F} FROM ${W(w.name, e.tables)} WHERE "${A}"::text = ANY($1::text[])`,
419
+ values: [O]
420
+ }), s = new Map(N.map((c) => [String(c[$.fieldname]), c]));
421
+ if (N.length !== s.size)
422
422
  throw new Error(
423
- `Doctype "${f}" declares "${g.fieldname}" as its identity, but that column is not unique in ${_(p.name, e.tables)} — ${c.length} rows matched ${R.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.`
423
+ `Doctype "${f}" declares "${$.fieldname}" as its identity, but that column is not unique in ${W(w.name, e.tables)} — ${N.length} rows matched ${s.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.`
424
424
  );
425
- const S = [];
426
- for (const d of s) {
427
- const m = String(h[d].id), M = R.get(m);
428
- if (!M) {
429
- w[d] = { data: null, doctype: f };
425
+ const m = [];
426
+ for (const c of l) {
427
+ const h = String(p[c].id), S = s.get(h);
428
+ if (!S) {
429
+ y[c] = { data: null, doctype: f };
430
430
  continue;
431
431
  }
432
- const l = { ...M };
433
- S.push(l);
434
- const v = [], O = h[d].options ?? {}, A = O.includeNested === !0, F = Array.isArray(O.includeNested) ? new Set(O.includeNested) : null;
435
- if (p.links)
436
- for (const [P, I] of Object.entries(p.links)) {
437
- const j = I.fieldname ?? P, G = I.fetch, ne = I.cardinality === "noneOrMany" || I.cardinality === "atLeastOne", le = G?.method ?? (ne ? "sync" : "lazy"), ke = G?.method === "sync" ? G.limit : void 0, Q = ne ? ke ?? o : void 0;
438
- if (!(A || (F ? F.has(P) : le === "sync"))) continue;
439
- if (le === "custom" && G?.method === "custom") {
440
- const J = G.handler, D = je(J);
441
- D && (l[j] = await D(E, l, I));
432
+ const d = { ...S };
433
+ m.push(d);
434
+ const k = [], x = p[c].options ?? {}, I = x.includeNested === !0, M = Array.isArray(x.includeNested) ? new Set(x.includeNested) : null;
435
+ if (w.links)
436
+ for (const [D, T] of Object.entries(w.links)) {
437
+ const _ = T.fieldname ?? D, G = T.fetch, ne = T.cardinality === "noneOrMany" || T.cardinality === "atLeastOne", de = G?.method ?? (ne ? "sync" : "lazy"), ke = G?.method === "sync" ? G.limit : void 0, Q = ne ? ke ?? o : void 0;
438
+ if (!(I || (M ? M.has(D) : de === "sync"))) continue;
439
+ if (de === "custom" && G?.method === "custom") {
440
+ const J = G.handler, C = _e(J);
441
+ C && (d[_] = await C(v, d, T));
442
442
  continue;
443
443
  }
444
- if (ae(I, L.get(j)?.component) === "inline") continue;
445
- const q = T(I.target);
444
+ if (se(T, B.get(_)?.component) === "inline") continue;
445
+ const q = L(T.target);
446
446
  if (!q) continue;
447
- const de = ee(q);
447
+ const ue = ee(q);
448
448
  if (ne) {
449
- if (!I.backlink) continue;
450
- const J = b(I.backlink);
451
- let D = `SELECT ${de} FROM ${_(q.name, e.tables)} WHERE "${J}"::text = $1`;
452
- const z = [m], X = Y(q);
453
- X && (D += ` ORDER BY "${b(X.fieldname)}" ASC`), Q != null && (D += " LIMIT $2", z.push(Q + 1));
454
- const { rows: oe } = await t(E, {
455
- text: D,
449
+ if (!T.backlink) continue;
450
+ const J = R(T.backlink);
451
+ let C = `SELECT ${ue} FROM ${W(q.name, e.tables)} WHERE "${J}"::text = $1`;
452
+ const z = [h], X = Y(q);
453
+ X && (C += ` ORDER BY "${R(X.fieldname)}" ASC`), Q != null && (C += " LIMIT $2", z.push(Q + 1));
454
+ const { rows: oe } = await t(v, {
455
+ text: C,
456
456
  values: z
457
457
  });
458
- Q != null && oe.length > Q ? (v.push(j), l[j] = oe.slice(0, Q)) : l[j] = oe;
458
+ Q != null && oe.length > Q ? (k.push(_), d[_] = oe.slice(0, Q)) : d[_] = oe;
459
459
  } else {
460
- const J = l[`${pe}${j}`];
460
+ const J = d[`${pe}${_}`];
461
461
  if (J == null) {
462
- l[j] = null;
462
+ d[_] = null;
463
463
  continue;
464
464
  }
465
- const D = Y(q);
466
- if (!D) throw ie(q.name);
467
- const z = b(D.fieldname), { rows: X } = await t(E, {
468
- text: `SELECT ${de} FROM ${_(q.name, e.tables)} WHERE "${z}" = $1`,
465
+ const C = Y(q);
466
+ if (!C) throw ae(q.name);
467
+ const z = R(C.fieldname), { rows: X } = await t(v, {
468
+ text: `SELECT ${ue} FROM ${W(q.name, e.tables)} WHERE "${z}" = $1`,
469
469
  values: [J]
470
470
  });
471
- l[j] = X[0] ?? null;
471
+ d[_] = X[0] ?? null;
472
472
  }
473
473
  }
474
- for (const { alias: P } of N) delete l[P];
475
- const H = F && p.links ? [...F].filter((P) => !(P in p.links)) : void 0;
476
- w[d] = {
477
- data: l,
474
+ for (const { alias: D } of P) delete d[D];
475
+ const j = M && w.links ? [...M].filter((D) => !(D in w.links)) : void 0;
476
+ y[c] = {
477
+ data: d,
478
478
  doctype: f,
479
- unknownLinks: H?.length ? H : void 0,
480
- truncatedLinks: v.length ? v : void 0
479
+ unknownLinks: j?.length ? j : void 0,
480
+ truncatedLinks: k.length ? k : void 0
481
481
  };
482
482
  }
483
- await fe(E, p, S, e.tables, t);
483
+ await ie(v, w, m, e.tables, t);
484
484
  }
485
- return w;
485
+ return y;
486
486
  }
487
487
  );
488
488
  },
489
- stonecropRecords(a, { $doctype: u, $filters: $, $orderBy: k, $limit: E, $offset: h, $includeTotal: y }) {
490
- return ue(
489
+ stonecropRecords(a, { $doctype: u, $filters: b, $orderBy: E, $limit: v, $offset: p, $includeTotal: g }) {
490
+ return fe(
491
491
  i,
492
492
  re({
493
493
  doctype: u,
494
- filters: $,
495
- orderBy: k,
496
- limit: E,
497
- offset: h,
498
- includeTotal: y
494
+ filters: b,
495
+ orderBy: E,
496
+ limit: v,
497
+ offset: p,
498
+ includeTotal: g
499
499
  }),
500
- async (w, f) => await Promise.all(
501
- f.map(async (s) => {
502
- const p = String(s.doctype), g = T(p);
503
- if (!g)
504
- return { data: [], doctype: p, hasMore: !1, count: s.includeTotal === !0 ? 0 : null };
505
- const C = new Set(K(g.fields).map((l) => l.fieldname)), U = ee(g), x = [], L = [];
506
- if (s.filters != null)
507
- for (const [l, v] of Object.entries(s.filters)) {
508
- if (!C.has(l))
509
- throw new Error(`Unknown filter field: ${l} for doctype ${g.name}`);
510
- x.push(v), L.push(`"${b(l)}" = $${x.length}`);
500
+ async (y, f) => await Promise.all(
501
+ f.map(async (l) => {
502
+ const w = String(l.doctype), $ = L(w);
503
+ if (!$)
504
+ return { data: [], doctype: w, hasMore: !1, count: l.includeTotal === !0 ? 0 : null };
505
+ const A = new Set(K($.fields).map((d) => d.fieldname)), U = ee($), O = [], B = [];
506
+ if (l.filters != null)
507
+ for (const [d, k] of Object.entries(l.filters)) {
508
+ if (!A.has(d))
509
+ throw new Error(`Unknown filter field: ${d} for doctype ${$.name}`);
510
+ O.push(k), B.push(`"${R(d)}" = $${O.length}`);
511
511
  }
512
- const N = L.length > 0 ? ` WHERE ${L.join(" AND ")}` : "";
513
- let B = "";
514
- if (s.orderBy != null) {
515
- if (typeof s.orderBy != "string")
516
- throw new Error(`Invalid orderBy: expected string, got ${typeof s.orderBy}`);
517
- const l = s.orderBy, v = l.lastIndexOf("_");
518
- if (v <= 0)
519
- throw new Error(`Invalid orderBy format: "${l}". Expected FIELD_ASC or FIELD_DESC`);
520
- const O = l.slice(v + 1).toUpperCase();
521
- if (O !== "ASC" && O !== "DESC")
522
- throw new Error(`Invalid orderBy direction: "${O}". Must be ASC or DESC`);
523
- const A = l.slice(0, v);
524
- if (!C.has(A))
525
- throw new Error(`Unknown orderBy field: "${A}" for doctype ${g.name}`);
526
- B = ` ORDER BY "${b(A)}" ${O}`;
512
+ const P = B.length > 0 ? ` WHERE ${B.join(" AND ")}` : "";
513
+ let F = "";
514
+ if (l.orderBy != null) {
515
+ if (typeof l.orderBy != "string")
516
+ throw new Error(`Invalid orderBy: expected string, got ${typeof l.orderBy}`);
517
+ const d = l.orderBy, k = d.lastIndexOf("_");
518
+ if (k <= 0)
519
+ throw new Error(`Invalid orderBy format: "${d}". Expected FIELD_ASC or FIELD_DESC`);
520
+ const x = d.slice(k + 1).toUpperCase();
521
+ if (x !== "ASC" && x !== "DESC")
522
+ throw new Error(`Invalid orderBy direction: "${x}". Must be ASC or DESC`);
523
+ const I = d.slice(0, k);
524
+ if (!A.has(I))
525
+ throw new Error(`Unknown orderBy field: "${I}" for doctype ${$.name}`);
526
+ F = ` ORDER BY "${R(I)}" ${x}`;
527
527
  }
528
- if (B === "") {
529
- const l = Y(g);
530
- l && (B = ` ORDER BY "${b(l.fieldname)}" ASC`);
528
+ if (F === "") {
529
+ const d = Y($);
530
+ d && (F = ` ORDER BY "${R(d.fieldname)}" ASC`);
531
531
  }
532
- if (s.limit != null && typeof s.limit != "number")
533
- throw new Error(`Invalid limit: expected number, got ${typeof s.limit}`);
534
- const c = s.limit ?? o;
535
- let R = "";
536
- c != null && (x.push(c + 1), R += ` LIMIT $${x.length}`), s.offset != null && (x.push(s.offset), R += ` OFFSET $${x.length}`);
537
- const { rows: S } = await t(w, {
538
- text: `SELECT ${U} FROM ${_(g.name, e.tables)}${N}${B}${R}`,
539
- values: x
540
- }), d = c != null && S.length > c, m = [...d ? S.slice(0, c ?? S.length) : S];
541
- await fe(w, g, m, e.tables, t);
542
- let M = null;
543
- if (s.includeTotal === !0) {
544
- const l = [], v = [];
545
- if (s.filters != null)
546
- for (const [F, H] of Object.entries(s.filters))
547
- C.has(F) && (l.push(H), v.push(`"${b(F)}" = $${l.length}`));
548
- const O = v.length > 0 ? ` WHERE ${v.join(" AND ")}` : "", { rows: A } = await t(w, {
549
- text: `SELECT COUNT(*) AS row_count FROM ${_(g.name, e.tables)}${O}`,
550
- values: l
532
+ if (l.limit != null && typeof l.limit != "number")
533
+ throw new Error(`Invalid limit: expected number, got ${typeof l.limit}`);
534
+ const N = l.limit ?? o;
535
+ let s = "";
536
+ N != null && (O.push(N + 1), s += ` LIMIT $${O.length}`), l.offset != null && (O.push(l.offset), s += ` OFFSET $${O.length}`);
537
+ const { rows: m } = await t(y, {
538
+ text: `SELECT ${U} FROM ${W($.name, e.tables)}${P}${F}${s}`,
539
+ values: O
540
+ }), c = N != null && m.length > N, h = [...c ? m.slice(0, N ?? m.length) : m];
541
+ await ie(y, $, h, e.tables, t);
542
+ let S = null;
543
+ if (l.includeTotal === !0) {
544
+ const d = [], k = [];
545
+ if (l.filters != null)
546
+ for (const [M, j] of Object.entries(l.filters))
547
+ A.has(M) && (d.push(j), k.push(`"${R(M)}" = $${d.length}`));
548
+ const x = k.length > 0 ? ` WHERE ${k.join(" AND ")}` : "", { rows: I } = await t(y, {
549
+ text: `SELECT COUNT(*) AS row_count FROM ${W($.name, e.tables)}${x}`,
550
+ values: d
551
551
  });
552
- M = parseInt(A[0]?.row_count ?? "0", 10);
552
+ S = parseInt(I[0]?.row_count ?? "0", 10);
553
553
  }
554
- return { data: m, doctype: p, hasMore: d, count: M };
554
+ return { data: h, doctype: w, hasMore: c, count: S };
555
555
  })
556
556
  )
557
557
  );
@@ -560,67 +560,69 @@ const pe = "__stonecropLinkFk_", V = "status", st = (e = {}) => {
560
560
  },
561
561
  Mutation: {
562
562
  plans: {
563
- stonecropAction(a, { $doctype: u, $action: $, $args: k }) {
564
- return xe(
563
+ stonecropAction(a, { $doctype: u, $action: b, $args: E }) {
564
+ return Fe(
565
565
  i,
566
- re({ doctype: u, action: $, actionArgs: k }),
567
- async (E, h) => {
568
- const y = T(String(h.doctype));
569
- if (!y)
566
+ re({ doctype: u, action: b, actionArgs: E }),
567
+ async (v, p) => {
568
+ const g = L(String(p.doctype));
569
+ if (!g)
570
570
  return {
571
571
  success: !1,
572
572
  data: null,
573
- error: `Unknown doctype: ${h.doctype}`
573
+ error: `Unknown doctype: ${p.doctype}`
574
574
  };
575
- const w = y.workflow?.actions?.[h.action];
576
- if (!w)
575
+ const y = g.workflow?.actions?.[p.action];
576
+ if (!y)
577
577
  return {
578
578
  success: !1,
579
579
  data: null,
580
- error: `Unknown action: ${h.action} on ${h.doctype}`
580
+ error: `Unknown action: ${p.action} on ${p.doctype}`
581
581
  };
582
- const f = _(y.name, e.tables), s = () => {
583
- const c = Y(y);
584
- if (!c) throw ie(String(h.doctype));
585
- return b(c.fieldname);
586
- }, p = Array.isArray(h.actionArgs) ? h.actionArgs : [], g = p[0]?.id, C = p[0]?.data ?? {}, U = e.actionHandlers?.[y.name]?.[String(h.action)], x = new Map(
587
- te(y.fields).filter((c) => b(c.fieldname) !== V).map((c) => [c.fieldname, c])
588
- ), L = te(y.fields).some(
589
- (c) => b(c.fieldname) === V
590
- ), N = [], B = (c) => {
591
- const R = [], S = [];
592
- for (const [d, m] of Object.entries(c)) {
593
- if (!x.has(d)) {
594
- N.push(d);
582
+ const f = W(g.name, e.tables), l = () => {
583
+ const s = Y(g);
584
+ if (!s) throw ae(String(p.doctype));
585
+ return R(s.fieldname);
586
+ }, $ = (Array.isArray(p.actionArgs) ? p.actionArgs : []).map(
587
+ (s) => s?.data ? { ...s, data: xe(g.fields, s.data) } : s
588
+ ), A = $[0]?.id, U = $[0]?.data ?? {}, O = e.actionHandlers?.[g.name]?.[String(p.action)], B = new Map(
589
+ te(g.fields).filter((s) => R(s.fieldname) !== V).map((s) => [s.fieldname, s])
590
+ ), P = te(g.fields).some(
591
+ (s) => R(s.fieldname) === V
592
+ ), F = [], N = (s) => {
593
+ const m = [], c = [];
594
+ for (const [h, S] of Object.entries(s)) {
595
+ if (!B.has(h)) {
596
+ F.push(h);
595
597
  continue;
596
598
  }
597
- if (m !== null && typeof m == "object") {
598
- N.push(d);
599
+ if (S !== null && typeof S == "object") {
600
+ F.push(h);
599
601
  continue;
600
602
  }
601
- R.push(b(d)), S.push(m);
603
+ m.push(R(h)), c.push(S);
602
604
  }
603
- return { cols: R, values: S };
605
+ return { cols: m, values: c };
604
606
  };
605
607
  try {
606
- return await E.withTransaction(async (c) => {
607
- const R = await _e(
608
- w,
608
+ return await v.withTransaction(async (s) => {
609
+ const m = await We(
610
+ y,
609
611
  {
610
612
  readState: async () => {
611
- if (g == null) return null;
612
- const S = L ? `"${V}"` : `"${s()}"`, { rows: d } = await t(c, {
613
- text: `SELECT ${S} FROM ${f} WHERE "${s()}"::text = $1 FOR UPDATE`,
614
- values: [String(g)]
613
+ if (A == null) return null;
614
+ const c = P ? `"${V}"` : `"${l()}"`, { rows: h } = await t(s, {
615
+ text: `SELECT ${c} FROM ${f} WHERE "${l()}"::text = $1 FOR UPDATE`,
616
+ values: [String(A)]
615
617
  });
616
- if (d.length === 0) return null;
617
- if (L)
618
- return d[0][V] ?? void 0;
618
+ if (h.length === 0) return null;
619
+ if (P)
620
+ return h[0][V] ?? void 0;
619
621
  },
620
- writeState: async (S) => {
621
- await t(c, {
622
- text: `UPDATE ${f} SET "${V}" = $1 WHERE "${s()}"::text = $2`,
623
- values: [S, String(g)]
622
+ writeState: async (c) => {
623
+ await t(s, {
624
+ text: `UPDATE ${f} SET "${V}" = $1 WHERE "${l()}"::text = $2`,
625
+ values: [c, String(A)]
624
626
  });
625
627
  },
626
628
  // The upsert, and the only write path for record data. `exists`
@@ -632,53 +634,59 @@ const pe = "__stonecropLinkFk_", V = "status", st = (e = {}) => {
632
634
  // `itemId` would receive `item_id`, find no identity, and file a
633
635
  // created record nowhere — which is that exact bug, already once
634
636
  // shipped and patched downstream.
635
- writeData: async (S, d) => {
636
- const { cols: m, values: M } = B(S), l = ee(y);
637
- if (!d) {
638
- if (g != null)
637
+ writeData: async (c, h) => {
638
+ const { cols: S, values: d } = N(c), k = ee(g);
639
+ if (!h) {
640
+ if (A != null)
639
641
  throw new Error(
640
- `Action "${w.label ?? h.action}" targets ${y.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.`
642
+ `Action "${y.label ?? p.action}" targets ${g.name} "${String(A)}", 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.`
641
643
  );
642
- const A = m.length ? `INSERT INTO ${f} (${m.map((H) => `"${H}"`).join(", ")}) VALUES (${m.map((H, P) => `$${P + 1}`).join(", ")}) RETURNING ${l}` : `INSERT INTO ${f} DEFAULT VALUES RETURNING ${l}`, { rows: F } = await t(c, { text: A, values: M });
643
- return F[0] ?? {};
644
+ const M = S.length ? `INSERT INTO ${f} (${S.map((D) => `"${D}"`).join(", ")}) VALUES (${S.map((D, T) => `$${T + 1}`).join(", ")}) RETURNING ${k}` : `INSERT INTO ${f} DEFAULT VALUES RETURNING ${k}`, { rows: j } = await t(s, { text: M, values: d });
645
+ return j[0] ?? {};
644
646
  }
645
- if (m.length === 0) {
646
- const { rows: A } = await t(c, {
647
- text: `SELECT ${l} FROM ${f} WHERE "${s()}"::text = $1`,
648
- values: [String(g)]
647
+ if (S.length === 0) {
648
+ const { rows: M } = await t(s, {
649
+ text: `SELECT ${k} FROM ${f} WHERE "${l()}"::text = $1`,
650
+ values: [String(A)]
649
651
  });
650
- return A[0] ?? {};
652
+ return M[0] ?? {};
651
653
  }
652
- const v = m.map((A, F) => `"${A}" = $${F + 1}`).join(", "), { rows: O } = await t(c, {
653
- text: `UPDATE ${f} SET ${v} WHERE "${s()}"::text = $${m.length + 1} RETURNING ${l}`,
654
- values: [...M, String(g)]
654
+ const x = S.map((M, j) => `"${M}" = $${j + 1}`).join(", "), { rows: I } = await t(s, {
655
+ text: `UPDATE ${f} SET ${x} WHERE "${l()}"::text = $${S.length + 1} RETURNING ${k}`,
656
+ values: [...d, String(A)]
655
657
  });
656
- return O[0] ?? {};
658
+ return I[0] ?? {};
657
659
  },
658
- runEffect: U ? (S) => U({
659
- pgClient: c,
660
- doctype: String(h.doctype),
661
- action: String(h.action),
662
- meta: y,
663
- recordId: g,
664
- data: C,
665
- args: p,
666
- currentState: S
660
+ runEffect: O ? (c) => O({
661
+ pgClient: s,
662
+ doctype: String(p.doctype),
663
+ action: String(p.action),
664
+ meta: g,
665
+ recordId: A,
666
+ data: U,
667
+ args: $,
668
+ currentState: c
667
669
  }) : void 0
668
670
  },
669
671
  // The patch a self-transition persists. This adapter never passed it, which
670
672
  // was moot while it had no `writeData` — nothing consumed it. Wiring the write
671
673
  // without this argument saves an empty record and reports success.
672
- C
674
+ U
673
675
  );
674
- if (!R.success) throw new he(R);
675
- return N.length ? { ...R, droppedFields: N } : R;
676
+ if (!m.success) throw new he(m);
677
+ if (m.success && m.data !== null && typeof m.data == "object") {
678
+ const c = (Array.isArray(m.data) ? m.data : [m.data]).filter(
679
+ (h) => h !== null && typeof h == "object"
680
+ );
681
+ await ie(s, g, c, e.tables, t);
682
+ }
683
+ return F.length ? { ...m, droppedFields: F } : m;
676
684
  });
677
- } catch (c) {
678
- return c instanceof he ? c.outcome : {
685
+ } catch (s) {
686
+ return s instanceof he ? s.outcome : {
679
687
  success: !1,
680
688
  data: null,
681
- error: c instanceof Error ? c.message : String(c)
689
+ error: s instanceof Error ? s.message : String(s)
682
690
  };
683
691
  }
684
692
  }
@@ -690,12 +698,12 @@ const pe = "__stonecropLinkFk_", V = "status", st = (e = {}) => {
690
698
  };
691
699
  });
692
700
  };
693
- function qe(e, t) {
701
+ function Ue(e, t) {
694
702
  const o = [];
695
703
  for (const n of te(e)) {
696
704
  const r = t.get(n.fieldname);
697
- if (r && ae(r, n.component) !== "inline") continue;
698
- const i = b(n.fieldname);
705
+ if (r && se(r, n.component) !== "inline") continue;
706
+ const i = R(n.fieldname);
699
707
  o.push(i !== n.fieldname ? `"${i}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
700
708
  }
701
709
  return o;
@@ -705,13 +713,13 @@ function ee(e) {
705
713
  if (e.links)
706
714
  for (const [o, n] of Object.entries(e.links))
707
715
  t.set(n.fieldname ?? o, n);
708
- return qe(e.fields, t).join(", ");
716
+ return Ue(e.fields, t).join(", ");
709
717
  }
710
718
  function Y(e) {
711
719
  const t = Se(e.fields);
712
720
  return K(e.fields).find((o) => o.kind === "field" && o.fieldname === t);
713
721
  }
714
- function Ue(e) {
722
+ function Je(e) {
715
723
  const t = Object.entries(e);
716
724
  if (t.length === 0) return;
717
725
  if ($e().length === 0) {
@@ -722,7 +730,7 @@ function Ue(e) {
722
730
  }
723
731
  const o = [];
724
732
  for (const [n, r] of t) {
725
- const i = T(n);
733
+ const i = L(n);
726
734
  if (!i) {
727
735
  o.push(`"${n}": no doctype by that name is registered`);
728
736
  continue;
@@ -744,8 +752,8 @@ function Ue(e) {
744
752
  `)}`
745
753
  );
746
754
  }
747
- function Je() {
748
- const e = Pe();
755
+ function Ke() {
756
+ const e = je();
749
757
  if (e.length !== 0)
750
758
  throw new Error(
751
759
  `StonecropPlugin: ${e.length} doctype reference${e.length === 1 ? "" : "s"} cannot be resolved and would silently drop the relation:
@@ -753,7 +761,7 @@ function Je() {
753
761
  `)
754
762
  );
755
763
  }
756
- function ie(e) {
764
+ function ae(e) {
757
765
  return new Error(
758
766
  `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.`
759
767
  );
@@ -762,13 +770,13 @@ const ct = (e = {}) => {
762
770
  const { logPlans: t = !0, logTiming: o = !1 } = e, n = (r, i) => ({
763
771
  plan: (a) => {
764
772
  t && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${i}`);
765
- const u = o ? Date.now() : 0, $ = a();
773
+ const u = o ? Date.now() : 0, b = a();
766
774
  return o && console.log(
767
775
  `[@stonecrop/graphql-middleware] Plan built for ${r}.${i} in ${Date.now() - u}ms`
768
- ), $;
776
+ ), b;
769
777
  }
770
778
  });
771
- return Ie({
779
+ return De({
772
780
  Query: {
773
781
  stonecropRecord: n("Query", "stonecropRecord"),
774
782
  stonecropRecords: n("Query", "stonecropRecords"),
@@ -812,7 +820,7 @@ const ct = (e = {}) => {
812
820
  }
813
821
  }
814
822
  }
815
- }, Ke = {
823
+ }, Ge = {
816
824
  name: "StonecropFieldCasingPlugin",
817
825
  version: "0.0.0",
818
826
  inflection: {
@@ -822,27 +830,27 @@ const ct = (e = {}) => {
822
830
  }
823
831
  }
824
832
  }
825
- }, Ge = (e) => ({
826
- extends: [De],
827
- plugins: e?.fieldCasing === "pascal" ? [ge, me, Ke] : [ge, me]
828
- }), lt = Ge();
833
+ }, Qe = (e) => ({
834
+ extends: [Ce],
835
+ plugins: e?.fieldCasing === "pascal" ? [ge, me, Ge] : [ge, me]
836
+ }), dt = Qe();
829
837
  export {
830
- se as DoctypeValidationError,
831
- lt as StonecropPreset,
832
- _e as applyGuardedTransition,
833
- at as clearFetchHandlers,
834
- rt as clearRegistry,
838
+ le as DoctypeValidationError,
839
+ dt as StonecropPreset,
840
+ We as applyGuardedTransition,
841
+ st as clearFetchHandlers,
842
+ it as clearRegistry,
835
843
  ct as createDebugPlugin,
836
- st as createStonecropPlugin,
837
- Ge as createStonecropPreset,
844
+ lt as createStonecropPlugin,
845
+ Qe as createStonecropPreset,
838
846
  $e as getAllMeta,
839
- je as getFetchHandler,
840
- T as getMeta,
841
- ot as hasMeta,
842
- Ce as loadDoctypes,
843
- nt as loadDoctypesFromObject,
844
- ft as makePgService,
845
- it as registerFetchHandler,
846
- He as typeDefs
847
+ _e as getFetchHandler,
848
+ L as getMeta,
849
+ rt as hasMeta,
850
+ Be as loadDoctypes,
851
+ ot as loadDoctypesFromObject,
852
+ ht as makePgService,
853
+ at as registerFetchHandler,
854
+ qe as typeDefs
847
855
  };
848
856
  //# sourceMappingURL=index.js.map