@stonecrop/graphql-middleware 0.25.0 → 0.27.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,15 +1,15 @@
1
- import { readdirSync as $e, statSync as ke, readFileSync as Ee } from "node:fs";
2
- import { join as be } from "node:path";
3
- import { flattenFields as Y, validateDoctype as ge, parseDoctype as me, isActionAllowedInState as ve, pascalToSnake as Re, camelToSnake as E, getDisplayField as Ae, getRecordIdField as ye, resolveLinkRenderMode as ae } from "@stonecrop/schema";
4
- import { sideEffectWithPgClient as Me, loadOneWithPgClient as ue } from "@dataplan/pg";
5
- import { object as re, constant as Oe, lambda as xe } from "postgraphile/grafast";
6
- import { gql as Fe, 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";
1
+ import { readdirSync as be, statSync as Ee, readFileSync as Re } from "node:fs";
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";
9
9
  function te(e) {
10
- return Y(e).filter((t) => t.kind === "field" && !t.computed);
10
+ return K(e).filter((t) => t.kind === "field" && !t.computed);
11
11
  }
12
- const H = /* @__PURE__ */ new Map();
12
+ const W = /* @__PURE__ */ new Map();
13
13
  class se extends Error {
14
14
  constructor(t, o) {
15
15
  const n = o.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
@@ -20,15 +20,15 @@ ${n}`), this.file = t, this.errors = o, this.name = "DoctypeValidationError";
20
20
  file;
21
21
  errors;
22
22
  }
23
- function De(e, t = {}) {
24
- const o = $e(e);
23
+ function Ce(e, t = {}) {
24
+ const o = be(e);
25
25
  for (const n of o) {
26
- const r = be(e, n);
27
- ke(r).isDirectory() ? De(r, t) : n.endsWith(".json") && Be(r, t);
26
+ const r = ve(e, n);
27
+ Ee(r).isDirectory() ? Ce(r, t) : n.endsWith(".json") && Be(r, t);
28
28
  }
29
29
  }
30
30
  function Be(e, t) {
31
- const o = Ee(e, "utf-8");
31
+ const o = Re(e, "utf-8");
32
32
  let n;
33
33
  try {
34
34
  n = JSON.parse(o);
@@ -43,7 +43,7 @@ function Be(e, t) {
43
43
  }
44
44
  throw new se(e, [u]);
45
45
  }
46
- const r = ge(n);
46
+ const r = ye(n);
47
47
  if (!r.success) {
48
48
  if (t.continueOnError) {
49
49
  t.onError?.(e, r.errors);
@@ -51,12 +51,12 @@ function Be(e, t) {
51
51
  }
52
52
  throw new se(e, r.errors);
53
53
  }
54
- const i = me(n);
55
- H.set(i.name, i);
54
+ const i = we(n);
55
+ W.set(i.name, i);
56
56
  }
57
- function et(e, t = {}) {
57
+ function nt(e, t = {}) {
58
58
  for (const [o, n] of Object.entries(e)) {
59
- const r = { ...typeof n == "object" && n !== null ? n : {}, name: o }, i = ge(r);
59
+ const r = { ...typeof n == "object" && n !== null ? n : {}, name: o }, i = ye(r);
60
60
  if (!i.success) {
61
61
  if (t.continueOnError) {
62
62
  t.onError?.(o, i.errors);
@@ -64,37 +64,37 @@ function et(e, t = {}) {
64
64
  }
65
65
  throw new se(o, i.errors);
66
66
  }
67
- const a = me(r);
68
- H.set(a.name, a);
67
+ const a = we(r);
68
+ W.set(a.name, a);
69
69
  }
70
70
  }
71
- function L(e) {
72
- const t = H.get(e);
71
+ function T(e) {
72
+ const t = W.get(e);
73
73
  if (t) return t;
74
- for (const o of H.values())
74
+ for (const o of W.values())
75
75
  if (o.slug === e) return o;
76
76
  }
77
- function we() {
78
- return Array.from(H.values());
77
+ function $e() {
78
+ return Array.from(W.values());
79
79
  }
80
- function tt(e) {
81
- return H.has(e);
80
+ function ot(e) {
81
+ return W.has(e);
82
82
  }
83
- function nt() {
84
- H.clear();
83
+ function rt() {
84
+ W.clear();
85
85
  }
86
- function Ie() {
86
+ function Pe() {
87
87
  const e = [];
88
- for (const t of H.values()) {
89
- t.inherits && L(t.inherits) === void 0 && e.push({
88
+ for (const t of W.values()) {
89
+ t.inherits && T(t.inherits) === void 0 && e.push({
90
90
  path: [t.name, "inherits"],
91
91
  message: `References unknown doctype: ${t.inherits}`
92
92
  });
93
- const o = Y(t.fields);
93
+ const o = K(t.fields);
94
94
  for (const n of o) {
95
95
  if (n.kind !== "field") continue;
96
96
  const r = n.doctype;
97
- r !== void 0 && L(r) === void 0 && e.push({
97
+ r !== void 0 && T(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 Ie() {
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 (L(a.target) === void 0 && e.push({
105
+ if (T(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;
@@ -129,17 +129,17 @@ function Ie() {
129
129
  }
130
130
  return e;
131
131
  }
132
- const le = /* @__PURE__ */ new Map();
133
- function ot(e, t) {
134
- le.set(e, t);
132
+ const ce = /* @__PURE__ */ new Map();
133
+ function it(e, t) {
134
+ ce.set(e, t);
135
135
  }
136
- function Ce(e) {
137
- return le.get(e);
136
+ function je(e) {
137
+ return ce.get(e);
138
138
  }
139
- function rt() {
140
- le.clear();
139
+ function at() {
140
+ ce.clear();
141
141
  }
142
- async function je(e, t, o) {
142
+ async function _e(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 {
@@ -159,12 +159,12 @@ async function je(e, t, o) {
159
159
  const k = await t.readState();
160
160
  if (k === null) {
161
161
  if (r && t.writeData) {
162
- const b = await t.writeData(o ?? {}, !1);
163
- return !b || Object.keys(b).length === 0 ? {
162
+ const E = await t.writeData(o ?? {}, !1);
163
+ return !E || Object.keys(E).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: b, error: null };
167
+ } : { success: !0, data: E, error: null };
168
168
  }
169
169
  return {
170
170
  success: !1,
@@ -174,7 +174,7 @@ async function je(e, t, o) {
174
174
  }
175
175
  u = k ?? "";
176
176
  }
177
- if (!ve(e, u ?? ""))
177
+ if (!Ae(e, u ?? ""))
178
178
  return {
179
179
  success: !1,
180
180
  data: null,
@@ -197,8 +197,8 @@ async function je(e, t, o) {
197
197
  error: null
198
198
  });
199
199
  }
200
- function W(e, t) {
201
- const o = t?.[e] ?? Re(e), n = o.indexOf(".");
200
+ function _(e, t) {
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
  }
204
204
  function Z(e) {
@@ -208,24 +208,24 @@ function Z(e) {
208
208
  return String(e);
209
209
  }
210
210
  }
211
- function Pe(e, t) {
211
+ function We(e, t) {
212
212
  const o = [];
213
- for (const n of Y(e.fields)) {
213
+ for (const n of K(e.fields)) {
214
214
  if (n.kind !== "field" || !n.doctype) continue;
215
- const r = L(n.doctype);
215
+ const r = T(n.doctype);
216
216
  if (!r) continue;
217
- const i = Ae(r.fields, r.displayField);
217
+ const i = Oe(r.fields, r.displayField);
218
218
  i && o.push({
219
219
  fieldname: n.fieldname,
220
220
  displayField: i.fieldname,
221
- targetPkFieldname: ye(r.fields),
222
- targetTable: W(r.name, t)
221
+ targetPkFieldname: Se(r.fields),
222
+ targetTable: _(r.name, t)
223
223
  });
224
224
  }
225
225
  return o;
226
226
  }
227
227
  async function fe(e, t, o, n, r) {
228
- const i = Pe(t, n);
228
+ const i = We(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();
@@ -234,8 +234,8 @@ async function fe(e, t, o, n, r) {
234
234
  f !== void 0 && u.add(f);
235
235
  }
236
236
  if (u.size === 0) return;
237
- const $ = E(a.targetPkFieldname), k = E(a.displayField), b = k !== a.displayField ? `"${k}" AS "${a.displayField}"` : `"${a.displayField}"`, { rows: h } = await r(e, {
238
- text: `SELECT "${$}" AS "${a.targetPkFieldname}", ${b} FROM ${a.targetTable} WHERE "${$}"::text = ANY($1::text[])`,
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[])`,
239
239
  values: [Array.from(u)]
240
240
  }), y = /* @__PURE__ */ new Map();
241
241
  for (const w of h) {
@@ -251,7 +251,7 @@ async function fe(e, t, o, n, r) {
251
251
  })
252
252
  );
253
253
  }
254
- const We = Fe`
254
+ const He = Te`
255
255
  type StonecropFieldMeta {
256
256
  kind: String!
257
257
  fieldname: String!
@@ -262,6 +262,7 @@ const We = Fe`
262
262
  doctype: String
263
263
  label: String
264
264
  width: String
265
+ height: String
265
266
  align: String
266
267
  edit: Boolean
267
268
  mask: String
@@ -368,28 +369,28 @@ class he extends Error {
368
369
  }
369
370
  outcome;
370
371
  }
371
- const pe = "__stonecropLinkFk_", Q = "status", it = (e = {}) => {
372
+ const pe = "__stonecropLinkFk_", V = "status", st = (e = {}) => {
372
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;
373
- return Te((n) => {
374
+ return Le((n) => {
374
375
  const r = n.input?.pgRegistry?.pgExecutors, i = r ? Object.values(r)[0] : void 0;
375
376
  if (!i)
376
377
  throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
377
- return e.actionHandlers && qe(e.actionHandlers), Ue(), {
378
- typeDefs: We,
378
+ return e.actionHandlers && Ue(e.actionHandlers), Je(), {
379
+ typeDefs: He,
379
380
  objects: {
380
381
  Query: {
381
382
  plans: {
382
383
  stonecropMeta(a, { $doctype: u }) {
383
- return xe(u, ($) => L(String($)) ?? null);
384
+ return Ne(u, ($) => T(String($)) ?? null);
384
385
  },
385
386
  stonecropAllMeta() {
386
- return Oe(we());
387
+ return Fe($e());
387
388
  },
388
389
  stonecropRecord(a, { $doctype: u, $id: $, $options: k }) {
389
390
  return ue(
390
391
  i,
391
392
  re({ doctype: u, id: $, options: k }),
392
- async (b, h) => {
393
+ async (E, h) => {
393
394
  const y = /* @__PURE__ */ new Map();
394
395
  for (let f = 0; f < h.length; f++) {
395
396
  const s = String(h[f].doctype);
@@ -397,156 +398,156 @@ const pe = "__stonecropLinkFk_", Q = "status", it = (e = {}) => {
397
398
  }
398
399
  const w = Array.from({ length: h.length });
399
400
  for (const [f, s] of y) {
400
- const p = L(f);
401
+ const p = T(f);
401
402
  if (!p) {
402
403
  for (const d of s) w[d] = { data: null, doctype: f };
403
404
  continue;
404
405
  }
405
- const g = V(p);
406
+ const g = Y(p);
406
407
  if (!g) throw ie(f);
407
- const I = E(g.fieldname), _ = ee(p), x = s.map((d) => String(h[d].id)), N = new Map(Y(p.fields).map((d) => [d.fieldname, d])), T = [];
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 = [];
408
409
  for (const [d, m] of Object.entries(p.links ?? {})) {
409
410
  if (m.cardinality === "noneOrMany" || m.cardinality === "atLeastOne") continue;
410
411
  const M = m.fieldname ?? d;
411
- ae(m, N.get(M)?.component) !== "inline" && T.push({ fieldname: M, alias: `${pe}${M}` });
412
+ ae(m, L.get(M)?.component) !== "inline" && N.push({ fieldname: M, alias: `${pe}${M}` });
412
413
  }
413
- const C = [
414
- _,
415
- ...T.map(({ fieldname: d, alias: m }) => `"${E(d)}" AS "${m}"`)
416
- ].filter(Boolean).join(", "), { rows: l } = await t(b, {
417
- text: `SELECT ${C} FROM ${W(p.name, e.tables)} WHERE "${I}"::text = ANY($1::text[])`,
414
+ const B = [
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[])`,
418
419
  values: [x]
419
- }), v = new Map(l.map((d) => [String(d[g.fieldname]), d]));
420
- if (l.length !== v.size)
420
+ }), R = new Map(c.map((d) => [String(d[g.fieldname]), d]));
421
+ if (c.length !== R.size)
421
422
  throw new Error(
422
- `Doctype "${f}" declares "${g.fieldname}" as its identity, but that column is not unique in ${W(p.name, e.tables)} — ${l.length} rows matched ${v.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 "${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
424
  );
424
425
  const S = [];
425
426
  for (const d of s) {
426
- const m = String(h[d].id), M = v.get(m);
427
+ const m = String(h[d].id), M = R.get(m);
427
428
  if (!M) {
428
429
  w[d] = { data: null, doctype: f };
429
430
  continue;
430
431
  }
431
- const c = { ...M };
432
- S.push(c);
433
- const R = [], O = h[d].options ?? {}, A = O.includeNested === !0, F = Array.isArray(O.includeNested) ? new Set(O.includeNested) : null;
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;
434
435
  if (p.links)
435
- for (const [j, D] of Object.entries(p.links)) {
436
- const P = D.fieldname ?? j, K = D.fetch, ne = D.cardinality === "noneOrMany" || D.cardinality === "atLeastOne", ce = K?.method ?? (ne ? "sync" : "lazy"), Se = K?.method === "sync" ? K.limit : void 0, G = ne ? Se ?? o : void 0;
437
- if (!(A || (F ? F.has(j) : ce === "sync"))) continue;
438
- if (ce === "custom" && K?.method === "custom") {
439
- const J = K.handler, B = Ce(J);
440
- B && (c[P] = await B(b, c, D));
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));
441
442
  continue;
442
443
  }
443
- if (ae(D, N.get(P)?.component) === "inline") continue;
444
- const U = L(D.target);
445
- if (!U) continue;
446
- const de = ee(U);
444
+ if (ae(I, L.get(j)?.component) === "inline") continue;
445
+ const q = T(I.target);
446
+ if (!q) continue;
447
+ const de = ee(q);
447
448
  if (ne) {
448
- if (!D.backlink) continue;
449
- const J = E(D.backlink);
450
- let B = `SELECT ${de} FROM ${W(U.name, e.tables)} WHERE "${J}"::text = $1`;
451
- const z = [m], X = V(U);
452
- X && (B += ` ORDER BY "${E(X.fieldname)}" ASC`), G != null && (B += " LIMIT $2", z.push(G + 1));
453
- const { rows: oe } = await t(b, {
454
- text: B,
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,
455
456
  values: z
456
457
  });
457
- G != null && oe.length > G ? (R.push(P), c[P] = oe.slice(0, G)) : c[P] = oe;
458
+ Q != null && oe.length > Q ? (v.push(j), l[j] = oe.slice(0, Q)) : l[j] = oe;
458
459
  } else {
459
- const J = c[`${pe}${P}`];
460
+ const J = l[`${pe}${j}`];
460
461
  if (J == null) {
461
- c[P] = null;
462
+ l[j] = null;
462
463
  continue;
463
464
  }
464
- const B = V(U);
465
- if (!B) throw ie(U.name);
466
- const z = E(B.fieldname), { rows: X } = await t(b, {
467
- text: `SELECT ${de} FROM ${W(U.name, e.tables)} WHERE "${z}" = $1`,
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`,
468
469
  values: [J]
469
470
  });
470
- c[P] = X[0] ?? null;
471
+ l[j] = X[0] ?? null;
471
472
  }
472
473
  }
473
- for (const { alias: j } of T) delete c[j];
474
- const q = F && p.links ? [...F].filter((j) => !(j in p.links)) : void 0;
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;
475
476
  w[d] = {
476
- data: c,
477
+ data: l,
477
478
  doctype: f,
478
- unknownLinks: q?.length ? q : void 0,
479
- truncatedLinks: R.length ? R : void 0
479
+ unknownLinks: H?.length ? H : void 0,
480
+ truncatedLinks: v.length ? v : void 0
480
481
  };
481
482
  }
482
- await fe(b, p, S, e.tables, t);
483
+ await fe(E, p, S, e.tables, t);
483
484
  }
484
485
  return w;
485
486
  }
486
487
  );
487
488
  },
488
- stonecropRecords(a, { $doctype: u, $filters: $, $orderBy: k, $limit: b, $offset: h, $includeTotal: y }) {
489
+ stonecropRecords(a, { $doctype: u, $filters: $, $orderBy: k, $limit: E, $offset: h, $includeTotal: y }) {
489
490
  return ue(
490
491
  i,
491
492
  re({
492
493
  doctype: u,
493
494
  filters: $,
494
495
  orderBy: k,
495
- limit: b,
496
+ limit: E,
496
497
  offset: h,
497
498
  includeTotal: y
498
499
  }),
499
500
  async (w, f) => await Promise.all(
500
501
  f.map(async (s) => {
501
- const p = String(s.doctype), g = L(p);
502
+ const p = String(s.doctype), g = T(p);
502
503
  if (!g)
503
504
  return { data: [], doctype: p, hasMore: !1, count: s.includeTotal === !0 ? 0 : null };
504
- const I = new Set(Y(g.fields).map((c) => c.fieldname)), _ = ee(g), x = [], N = [];
505
+ const C = new Set(K(g.fields).map((l) => l.fieldname)), U = ee(g), x = [], L = [];
505
506
  if (s.filters != null)
506
- for (const [c, R] of Object.entries(s.filters)) {
507
- if (!I.has(c))
508
- throw new Error(`Unknown filter field: ${c} for doctype ${g.name}`);
509
- x.push(R), N.push(`"${E(c)}" = $${x.length}`);
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}`);
510
511
  }
511
- const T = N.length > 0 ? ` WHERE ${N.join(" AND ")}` : "";
512
- let C = "";
512
+ const N = L.length > 0 ? ` WHERE ${L.join(" AND ")}` : "";
513
+ let B = "";
513
514
  if (s.orderBy != null) {
514
515
  if (typeof s.orderBy != "string")
515
516
  throw new Error(`Invalid orderBy: expected string, got ${typeof s.orderBy}`);
516
- const c = s.orderBy, R = c.lastIndexOf("_");
517
- if (R <= 0)
518
- throw new Error(`Invalid orderBy format: "${c}". Expected FIELD_ASC or FIELD_DESC`);
519
- const O = c.slice(R + 1).toUpperCase();
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();
520
521
  if (O !== "ASC" && O !== "DESC")
521
522
  throw new Error(`Invalid orderBy direction: "${O}". Must be ASC or DESC`);
522
- const A = c.slice(0, R);
523
- if (!I.has(A))
523
+ const A = l.slice(0, v);
524
+ if (!C.has(A))
524
525
  throw new Error(`Unknown orderBy field: "${A}" for doctype ${g.name}`);
525
- C = ` ORDER BY "${E(A)}" ${O}`;
526
+ B = ` ORDER BY "${b(A)}" ${O}`;
526
527
  }
527
- if (C === "") {
528
- const c = V(g);
529
- c && (C = ` ORDER BY "${E(c.fieldname)}" ASC`);
528
+ if (B === "") {
529
+ const l = Y(g);
530
+ l && (B = ` ORDER BY "${b(l.fieldname)}" ASC`);
530
531
  }
531
532
  if (s.limit != null && typeof s.limit != "number")
532
533
  throw new Error(`Invalid limit: expected number, got ${typeof s.limit}`);
533
- const l = s.limit ?? o;
534
- let v = "";
535
- l != null && (x.push(l + 1), v += ` LIMIT $${x.length}`), s.offset != null && (x.push(s.offset), v += ` OFFSET $${x.length}`);
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}`);
536
537
  const { rows: S } = await t(w, {
537
- text: `SELECT ${_} FROM ${W(g.name, e.tables)}${T}${C}${v}`,
538
+ text: `SELECT ${U} FROM ${_(g.name, e.tables)}${N}${B}${R}`,
538
539
  values: x
539
- }), d = l != null && S.length > l, m = [...d ? S.slice(0, l ?? S.length) : S];
540
+ }), d = c != null && S.length > c, m = [...d ? S.slice(0, c ?? S.length) : S];
540
541
  await fe(w, g, m, e.tables, t);
541
542
  let M = null;
542
543
  if (s.includeTotal === !0) {
543
- const c = [], R = [];
544
+ const l = [], v = [];
544
545
  if (s.filters != null)
545
- for (const [F, q] of Object.entries(s.filters))
546
- I.has(F) && (c.push(q), R.push(`"${E(F)}" = $${c.length}`));
547
- const O = R.length > 0 ? ` WHERE ${R.join(" AND ")}` : "", { rows: A } = await t(w, {
548
- text: `SELECT COUNT(*) AS row_count FROM ${W(g.name, e.tables)}${O}`,
549
- values: c
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
550
551
  });
551
552
  M = parseInt(A[0]?.row_count ?? "0", 10);
552
553
  }
@@ -560,11 +561,11 @@ const pe = "__stonecropLinkFk_", Q = "status", it = (e = {}) => {
560
561
  Mutation: {
561
562
  plans: {
562
563
  stonecropAction(a, { $doctype: u, $action: $, $args: k }) {
563
- return Me(
564
+ return xe(
564
565
  i,
565
566
  re({ doctype: u, action: $, actionArgs: k }),
566
- async (b, h) => {
567
- const y = L(String(h.doctype));
567
+ async (E, h) => {
568
+ const y = T(String(h.doctype));
568
569
  if (!y)
569
570
  return {
570
571
  success: !1,
@@ -578,47 +579,47 @@ const pe = "__stonecropLinkFk_", Q = "status", it = (e = {}) => {
578
579
  data: null,
579
580
  error: `Unknown action: ${h.action} on ${h.doctype}`
580
581
  };
581
- const f = W(y.name, e.tables), s = () => {
582
- const l = V(y);
583
- if (!l) throw ie(String(h.doctype));
584
- return E(l.fieldname);
585
- }, p = Array.isArray(h.actionArgs) ? h.actionArgs : [], g = p[0]?.id, I = p[0]?.data ?? {}, _ = e.actionHandlers?.[y.name]?.[String(h.action)], x = new Map(
586
- te(y.fields).filter((l) => E(l.fieldname) !== Q).map((l) => [l.fieldname, l])
587
- ), N = te(y.fields).some(
588
- (l) => E(l.fieldname) === Q
589
- ), T = [], C = (l) => {
590
- const v = [], S = [];
591
- for (const [d, m] of Object.entries(l)) {
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)) {
592
593
  if (!x.has(d)) {
593
- T.push(d);
594
+ N.push(d);
594
595
  continue;
595
596
  }
596
597
  if (m !== null && typeof m == "object") {
597
- T.push(d);
598
+ N.push(d);
598
599
  continue;
599
600
  }
600
- v.push(E(d)), S.push(m);
601
+ R.push(b(d)), S.push(m);
601
602
  }
602
- return { cols: v, values: S };
603
+ return { cols: R, values: S };
603
604
  };
604
605
  try {
605
- return await b.withTransaction(async (l) => {
606
- const v = await je(
606
+ return await E.withTransaction(async (c) => {
607
+ const R = await _e(
607
608
  w,
608
609
  {
609
610
  readState: async () => {
610
611
  if (g == null) return null;
611
- const S = N ? `"${Q}"` : `"${s()}"`, { rows: d } = await t(l, {
612
+ const S = L ? `"${V}"` : `"${s()}"`, { rows: d } = await t(c, {
612
613
  text: `SELECT ${S} FROM ${f} WHERE "${s()}"::text = $1 FOR UPDATE`,
613
614
  values: [String(g)]
614
615
  });
615
616
  if (d.length === 0) return null;
616
- if (N)
617
- return d[0][Q] ?? void 0;
617
+ if (L)
618
+ return d[0][V] ?? void 0;
618
619
  },
619
620
  writeState: async (S) => {
620
- await t(l, {
621
- text: `UPDATE ${f} SET "${Q}" = $1 WHERE "${s()}"::text = $2`,
621
+ await t(c, {
622
+ text: `UPDATE ${f} SET "${V}" = $1 WHERE "${s()}"::text = $2`,
622
623
  values: [S, String(g)]
623
624
  });
624
625
  },
@@ -632,35 +633,35 @@ const pe = "__stonecropLinkFk_", Q = "status", it = (e = {}) => {
632
633
  // created record nowhere — which is that exact bug, already once
633
634
  // shipped and patched downstream.
634
635
  writeData: async (S, d) => {
635
- const { cols: m, values: M } = C(S), c = ee(y);
636
+ const { cols: m, values: M } = B(S), l = ee(y);
636
637
  if (!d) {
637
638
  if (g != null)
638
639
  throw new Error(
639
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.`
640
641
  );
641
- const A = m.length ? `INSERT INTO ${f} (${m.map((q) => `"${q}"`).join(", ")}) VALUES (${m.map((q, j) => `$${j + 1}`).join(", ")}) RETURNING ${c}` : `INSERT INTO ${f} DEFAULT VALUES RETURNING ${c}`, { rows: F } = await t(l, { text: A, values: M });
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 });
642
643
  return F[0] ?? {};
643
644
  }
644
645
  if (m.length === 0) {
645
- const { rows: A } = await t(l, {
646
- text: `SELECT ${c} FROM ${f} WHERE "${s()}"::text = $1`,
646
+ const { rows: A } = await t(c, {
647
+ text: `SELECT ${l} FROM ${f} WHERE "${s()}"::text = $1`,
647
648
  values: [String(g)]
648
649
  });
649
650
  return A[0] ?? {};
650
651
  }
651
- const R = m.map((A, F) => `"${A}" = $${F + 1}`).join(", "), { rows: O } = await t(l, {
652
- text: `UPDATE ${f} SET ${R} WHERE "${s()}"::text = $${m.length + 1} RETURNING ${c}`,
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}`,
653
654
  values: [...M, String(g)]
654
655
  });
655
656
  return O[0] ?? {};
656
657
  },
657
- runEffect: _ ? (S) => _({
658
- pgClient: l,
658
+ runEffect: U ? (S) => U({
659
+ pgClient: c,
659
660
  doctype: String(h.doctype),
660
661
  action: String(h.action),
661
662
  meta: y,
662
663
  recordId: g,
663
- data: I,
664
+ data: C,
664
665
  args: p,
665
666
  currentState: S
666
667
  }) : void 0
@@ -668,16 +669,16 @@ const pe = "__stonecropLinkFk_", Q = "status", it = (e = {}) => {
668
669
  // The patch a self-transition persists. This adapter never passed it, which
669
670
  // was moot while it had no `writeData` — nothing consumed it. Wiring the write
670
671
  // without this argument saves an empty record and reports success.
671
- I
672
+ C
672
673
  );
673
- if (!v.success) throw new he(v);
674
- return T.length ? { ...v, droppedFields: T } : v;
674
+ if (!R.success) throw new he(R);
675
+ return N.length ? { ...R, droppedFields: N } : R;
675
676
  });
676
- } catch (l) {
677
- return l instanceof he ? l.outcome : {
677
+ } catch (c) {
678
+ return c instanceof he ? c.outcome : {
678
679
  success: !1,
679
680
  data: null,
680
- error: l instanceof Error ? l.message : String(l)
681
+ error: c instanceof Error ? c.message : String(c)
681
682
  };
682
683
  }
683
684
  }
@@ -689,12 +690,12 @@ const pe = "__stonecropLinkFk_", Q = "status", it = (e = {}) => {
689
690
  };
690
691
  });
691
692
  };
692
- function He(e, t) {
693
+ function qe(e, t) {
693
694
  const o = [];
694
695
  for (const n of te(e)) {
695
696
  const r = t.get(n.fieldname);
696
697
  if (r && ae(r, n.component) !== "inline") continue;
697
- const i = E(n.fieldname);
698
+ const i = b(n.fieldname);
698
699
  o.push(i !== n.fieldname ? `"${i}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
699
700
  }
700
701
  return o;
@@ -704,16 +705,16 @@ function ee(e) {
704
705
  if (e.links)
705
706
  for (const [o, n] of Object.entries(e.links))
706
707
  t.set(n.fieldname ?? o, n);
707
- return He(e.fields, t).join(", ");
708
+ return qe(e.fields, t).join(", ");
708
709
  }
709
- function V(e) {
710
- const t = ye(e.fields);
711
- return e.fields.find((o) => o.kind === "field" && o.fieldname === t);
710
+ function Y(e) {
711
+ const t = Se(e.fields);
712
+ return K(e.fields).find((o) => o.kind === "field" && o.fieldname === t);
712
713
  }
713
- function qe(e) {
714
+ function Ue(e) {
714
715
  const t = Object.entries(e);
715
716
  if (t.length === 0) return;
716
- if (we().length === 0) {
717
+ if ($e().length === 0) {
717
718
  console.warn(
718
719
  "[@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."
719
720
  );
@@ -721,7 +722,7 @@ function qe(e) {
721
722
  }
722
723
  const o = [];
723
724
  for (const [n, r] of t) {
724
- const i = L(n);
725
+ const i = T(n);
725
726
  if (!i) {
726
727
  o.push(`"${n}": no doctype by that name is registered`);
727
728
  continue;
@@ -743,8 +744,8 @@ function qe(e) {
743
744
  `)}`
744
745
  );
745
746
  }
746
- function Ue() {
747
- const e = Ie();
747
+ function Je() {
748
+ const e = Pe();
748
749
  if (e.length !== 0)
749
750
  throw new Error(
750
751
  `StonecropPlugin: ${e.length} doctype reference${e.length === 1 ? "" : "s"} cannot be resolved and would silently drop the relation:
@@ -757,7 +758,7 @@ function ie(e) {
757
758
  `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.`
758
759
  );
759
760
  }
760
- const at = (e = {}) => {
761
+ const ct = (e = {}) => {
761
762
  const { logPlans: t = !0, logTiming: o = !1 } = e, n = (r, i) => ({
762
763
  plan: (a) => {
763
764
  t && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${i}`);
@@ -767,7 +768,7 @@ const at = (e = {}) => {
767
768
  ), $;
768
769
  }
769
770
  });
770
- return Le({
771
+ return Ie({
771
772
  Query: {
772
773
  stonecropRecord: n("Query", "stonecropRecord"),
773
774
  stonecropRecords: n("Query", "stonecropRecords"),
@@ -778,7 +779,40 @@ const at = (e = {}) => {
778
779
  stonecropAction: n("Mutation", "stonecropAction")
779
780
  }
780
781
  });
781
- }, _e = {
782
+ }, ge = {
783
+ name: "StonecropNaturalIdPlugin",
784
+ version: "0.0.0",
785
+ after: ["PgAttributesPlugin"],
786
+ inflection: {
787
+ replace: {
788
+ // Move Relay's global identifier off `id`...
789
+ nodeIdFieldName() {
790
+ return "nodeId";
791
+ },
792
+ // ...so the real column can keep its own name.
793
+ _attributeName(e, t, o) {
794
+ const n = e?.(o) ?? o.attributeName;
795
+ if (!o.skipRowId && n === "row_id") {
796
+ const { codec: r, attributeName: i } = o, a = r.attributes[i]?.extensions?.tags?.name ?? i;
797
+ if (typeof a == "string" && a.toLowerCase() === "id" && !r.isAnonymous)
798
+ return "id";
799
+ }
800
+ return n;
801
+ }
802
+ }
803
+ }
804
+ }, me = {
805
+ name: "StonecropOwnedRelationsPlugin",
806
+ version: "0.0.0",
807
+ gather: {
808
+ hooks: {
809
+ pgRelations_relation(e, t) {
810
+ const { relation: o, pgConstraint: n } = t;
811
+ o.isReferencee && n.confdeltype === "c" && (o.extensions ??= {}, o.extensions.tags ??= {}, o.extensions.tags.behavior = "+manyRelation:resource:connection");
812
+ }
813
+ }
814
+ }
815
+ }, Ke = {
782
816
  name: "StonecropFieldCasingPlugin",
783
817
  version: "0.0.0",
784
818
  inflection: {
@@ -788,27 +822,27 @@ const at = (e = {}) => {
788
822
  }
789
823
  }
790
824
  }
791
- }, Je = (e) => ({
792
- extends: [Ne],
793
- plugins: e?.fieldCasing === "pascal" ? [_e] : []
794
- }), st = Je();
825
+ }, Ge = (e) => ({
826
+ extends: [De],
827
+ plugins: e?.fieldCasing === "pascal" ? [ge, me, Ke] : [ge, me]
828
+ }), lt = Ge();
795
829
  export {
796
830
  se as DoctypeValidationError,
797
- st as StonecropPreset,
798
- je as applyGuardedTransition,
799
- rt as clearFetchHandlers,
800
- nt as clearRegistry,
801
- at as createDebugPlugin,
802
- it as createStonecropPlugin,
803
- Je as createStonecropPreset,
804
- we as getAllMeta,
805
- Ce as getFetchHandler,
806
- L as getMeta,
807
- tt as hasMeta,
808
- De as loadDoctypes,
809
- et as loadDoctypesFromObject,
810
- dt as makePgService,
811
- ot as registerFetchHandler,
812
- We as typeDefs
831
+ lt as StonecropPreset,
832
+ _e as applyGuardedTransition,
833
+ at as clearFetchHandlers,
834
+ rt as clearRegistry,
835
+ ct as createDebugPlugin,
836
+ st as createStonecropPlugin,
837
+ Ge as createStonecropPreset,
838
+ $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
813
847
  };
814
848
  //# sourceMappingURL=index.js.map