@stonecrop/graphql-middleware 0.13.0 → 0.13.1

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,133 +1,133 @@
1
- import { readdirSync as G, statSync as K, readFileSync as X } from "node:fs";
2
- import { join as Z } from "node:path";
3
- import { validateDoctype as V, parseDoctype as Y } from "@stonecrop/schema";
4
- import { sideEffectWithPgClient as ee, loadOneWithPgClient as U } from "@dataplan/pg";
5
- import { object as J, constant as te, lambda as ne } from "postgraphile/grafast";
6
- import { gql as oe, extendSchema as re, wrapPlans as ie } from "postgraphile/utils";
7
- import { PostGraphileAmberPreset as se } from "postgraphile/presets/amber";
8
- import { makePgService as qe } from "postgraphile/adaptors/pg";
9
- const b = /* @__PURE__ */ new Map();
10
- class T extends Error {
1
+ import { readdirSync as te, statSync as ne, readFileSync as oe } from "node:fs";
2
+ import { join as re } from "node:path";
3
+ import { validateDoctype as Z, parseDoctype as ee, camelToSnake as x, pascalToSnake as ie } from "@stonecrop/schema";
4
+ import { sideEffectWithPgClient as se, loadOneWithPgClient as K } from "@dataplan/pg";
5
+ import { object as Q, constant as ce, lambda as ae } from "postgraphile/grafast";
6
+ import { gql as le, extendSchema as de, wrapPlans as fe } from "postgraphile/utils";
7
+ import { PostGraphileAmberPreset as ue } from "postgraphile/presets/amber";
8
+ import { makePgService as ze } from "postgraphile/adaptors/pg";
9
+ const S = /* @__PURE__ */ new Map();
10
+ class V extends Error {
11
11
  constructor(e, n) {
12
- const i = n.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
12
+ const o = n.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
13
13
  `);
14
14
  super(`Invalid doctype definition in ${e}:
15
- ${i}`), this.file = e, this.errors = n, this.name = "DoctypeValidationError";
15
+ ${o}`), this.file = e, this.errors = n, this.name = "DoctypeValidationError";
16
16
  }
17
17
  file;
18
18
  errors;
19
19
  }
20
- function ce(t, e = {}) {
21
- const n = G(t);
22
- for (const i of n) {
23
- const r = Z(t, i);
24
- K(r).isDirectory() ? ce(r, e) : i.endsWith(".json") && ae(r, e);
20
+ function pe(t, e = {}) {
21
+ const n = te(t);
22
+ for (const o of n) {
23
+ const r = re(t, o);
24
+ ne(r).isDirectory() ? pe(r, e) : o.endsWith(".json") && ye(r, e);
25
25
  }
26
26
  }
27
- function ae(t, e) {
28
- const n = X(t, "utf-8");
29
- let i;
27
+ function ye(t, e) {
28
+ const n = oe(t, "utf-8");
29
+ let o;
30
30
  try {
31
- i = JSON.parse(n);
32
- } catch (a) {
33
- const c = {
31
+ o = JSON.parse(n);
32
+ } catch (c) {
33
+ const a = {
34
34
  path: [],
35
- message: `Invalid JSON: ${a instanceof Error ? a.message : String(a)}`
35
+ message: `Invalid JSON: ${c instanceof Error ? c.message : String(c)}`
36
36
  };
37
37
  if (e.continueOnError) {
38
- e.onError?.(t, [c]);
38
+ e.onError?.(t, [a]);
39
39
  return;
40
40
  }
41
- throw new T(t, [c]);
41
+ throw new V(t, [a]);
42
42
  }
43
- const r = V(i);
43
+ const r = Z(o);
44
44
  if (!r.success) {
45
45
  if (e.continueOnError) {
46
46
  e.onError?.(t, r.errors);
47
47
  return;
48
48
  }
49
- throw new T(t, r.errors);
49
+ throw new V(t, r.errors);
50
50
  }
51
- const o = Y(i);
52
- b.set(o.name, o);
51
+ const s = ee(o);
52
+ S.set(s.name, s);
53
53
  }
54
- function xe(t, e = {}) {
55
- for (const [n, i] of Object.entries(t)) {
56
- const r = { ...i, name: n }, o = V(r);
57
- if (!o.success) {
54
+ function Ie(t, e = {}) {
55
+ for (const [n, o] of Object.entries(t)) {
56
+ const r = { ...o, name: n }, s = Z(r);
57
+ if (!s.success) {
58
58
  if (e.continueOnError) {
59
- e.onError?.(n, o.errors);
59
+ e.onError?.(n, s.errors);
60
60
  continue;
61
61
  }
62
- throw new T(n, o.errors);
62
+ throw new V(n, s.errors);
63
63
  }
64
- const a = Y(r);
65
- b.set(a.name, a);
64
+ const c = ee(r);
65
+ S.set(c.name, c);
66
66
  }
67
67
  }
68
- function v(t) {
69
- const e = b.get(t);
68
+ function j(t) {
69
+ const e = S.get(t);
70
70
  if (e) return e;
71
- for (const n of b.values())
71
+ for (const n of S.values())
72
72
  if (n.slug === t) return n;
73
73
  }
74
- function le() {
75
- return Array.from(b.values());
74
+ function ge() {
75
+ return Array.from(S.values());
76
76
  }
77
- function Ae(t) {
78
- return b.has(t);
77
+ function Be(t) {
78
+ return S.has(t);
79
79
  }
80
- function Fe() {
81
- b.clear();
80
+ function Le() {
81
+ S.clear();
82
82
  }
83
- function ve() {
83
+ function Pe() {
84
84
  const t = [];
85
- for (const e of b.values()) {
86
- e.inherits && !b.has(e.inherits) && t.push({
85
+ for (const e of S.values()) {
86
+ e.inherits && !S.has(e.inherits) && t.push({
87
87
  path: [e.name, "inherits"],
88
88
  message: `References unknown doctype: ${e.inherits}`
89
89
  });
90
90
  for (const n of e.fields)
91
- n.fieldtype === "Link" && typeof n.options == "string" && (b.has(n.options) || t.push({
91
+ n.fieldtype === "Link" && typeof n.options == "string" && (S.has(n.options) || t.push({
92
92
  path: [e.name, "fields", n.fieldname, "options"],
93
93
  message: `Link references unknown doctype: ${n.options}`
94
94
  }));
95
95
  }
96
96
  return t;
97
97
  }
98
- const I = /* @__PURE__ */ new Map();
99
- function de(t, e) {
100
- I.set(t, e);
98
+ const H = /* @__PURE__ */ new Map();
99
+ function me(t, e) {
100
+ H.set(t, e);
101
101
  }
102
- function fe(t) {
103
- return I.get(t);
102
+ function he(t) {
103
+ return H.get(t);
104
104
  }
105
- function Ce(t) {
106
- return I.has(t);
105
+ function Te(t) {
106
+ return H.has(t);
107
107
  }
108
- function je() {
109
- I.clear();
108
+ function He() {
109
+ H.clear();
110
110
  }
111
- const ue = async (t, e) => {
112
- const [n] = t, { doctype: i } = e, r = [];
113
- for (const o of i.fields)
114
- o.required && (n[o.fieldname] === void 0 || n[o.fieldname] === null) && r.push(o.label ?? o.fieldname);
111
+ const Se = async (t, e) => {
112
+ const [n] = t, { doctype: o } = e, r = [];
113
+ for (const s of o.fields)
114
+ s.required && (n[s.fieldname] === void 0 || n[s.fieldname] === null) && r.push(s.label ?? s.fieldname);
115
115
  if (r.length > 0)
116
116
  throw new Error(`Missing required fields: ${r.join(", ")}`);
117
117
  return { valid: !0 };
118
- }, pe = async (t, e) => {
119
- const [n] = t, { doctype: i } = e, r = [];
120
- for (const o of i.fields) {
121
- const a = n[o.fieldname];
122
- if (a == null) continue;
123
- const c = ye(o, a);
124
- c && r.push(c);
118
+ }, $e = async (t, e) => {
119
+ const [n] = t, { doctype: o } = e, r = [];
120
+ for (const s of o.fields) {
121
+ const c = n[s.fieldname];
122
+ if (c == null) continue;
123
+ const a = we(s, c);
124
+ a && r.push(a);
125
125
  }
126
- if (i.links)
127
- for (const [o, a] of Object.entries(i.links)) {
128
- const c = n[o];
129
- if (c == null) continue;
130
- a.cardinality === "noneOrMany" || a.cardinality === "atLeastOne" ? Array.isArray(c) || r.push(`${o}: expected array, got ${typeof c}`) : (typeof c != "object" || Array.isArray(c)) && r.push(`${o}: expected object, got ${typeof c}`);
126
+ if (o.links)
127
+ for (const [s, c] of Object.entries(o.links)) {
128
+ const a = n[s];
129
+ if (a == null) continue;
130
+ c.cardinality === "noneOrMany" || c.cardinality === "atLeastOne" ? Array.isArray(a) || r.push(`${s}: expected array, got ${typeof a}`) : (typeof a != "object" || Array.isArray(a)) && r.push(`${s}: expected object, got ${typeof a}`);
131
131
  }
132
132
  if (r.length > 0)
133
133
  throw new Error(`Field type validation failed:
@@ -135,9 +135,9 @@ ${r.join(`
135
135
  `)}`);
136
136
  return { valid: !0 };
137
137
  };
138
- function ye(t, e) {
139
- const { fieldname: n, fieldtype: i } = t;
140
- switch (i) {
138
+ function we(t, e) {
139
+ const { fieldname: n, fieldtype: o } = t;
140
+ switch (o) {
141
141
  case "Int":
142
142
  if (typeof e != "number" || !Number.isInteger(e))
143
143
  return `${n}: expected integer, got ${typeof e}`;
@@ -173,26 +173,26 @@ function ye(t, e) {
173
173
  }
174
174
  return null;
175
175
  }
176
- const ge = async () => ({ ok: !0 }), me = {
177
- validateRequiredFields: ue,
178
- validateFieldTypes: pe,
179
- noop: ge
176
+ const ke = async () => ({ ok: !0 }), Ee = {
177
+ validateRequiredFields: Se,
178
+ validateFieldTypes: $e,
179
+ noop: ke
180
180
  };
181
- function Ie() {
182
- for (const [t, e] of Object.entries(me))
183
- de(t, e);
181
+ function Je() {
182
+ for (const [t, e] of Object.entries(Ee))
183
+ me(t, e);
184
184
  }
185
- const q = /* @__PURE__ */ new Map();
186
- function Be(t, e) {
187
- q.set(t, e);
185
+ const Y = /* @__PURE__ */ new Map();
186
+ function We(t, e) {
187
+ Y.set(t, e);
188
188
  }
189
- function he(t) {
190
- return q.get(t);
189
+ function be(t) {
190
+ return Y.get(t);
191
191
  }
192
- function Le() {
193
- q.clear();
192
+ function qe() {
193
+ Y.clear();
194
194
  }
195
- const Se = oe`
195
+ const Me = le`
196
196
  type StonecropFieldMeta {
197
197
  fieldname: String!
198
198
  fieldtype: String!
@@ -230,7 +230,6 @@ const Se = oe`
230
230
  type StonecropDoctypeMeta {
231
231
  name: String!
232
232
  slug: String
233
- tableName: String
234
233
  fields: [StonecropFieldMeta!]!
235
234
  workflow: StonecropWorkflowMeta
236
235
  inherits: String
@@ -271,155 +270,163 @@ const Se = oe`
271
270
  extend type Mutation {
272
271
  stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
273
272
  }
274
- `, Pe = (t = {}) => {
275
- const e = t.pkField ?? "id", n = t.debug ? (i, r) => (console.log(`[@stonecrop/graphql-middleware] ${r.text}`, r.values ?? []), i.query(r)) : (i, r) => i.query(r);
276
- return re((i) => {
277
- const r = i.input?.pgRegistry?.pgExecutors, o = r ? Object.values(r)[0] : void 0;
278
- if (!o)
273
+ `, _e = (t = {}) => {
274
+ const e = t.debug ? (n, o) => (console.log(`[@stonecrop/graphql-middleware] ${o.text}`, o.values ?? []), n.query(o)) : (n, o) => n.query(o);
275
+ return de((n) => {
276
+ const o = n.input?.pgRegistry?.pgExecutors, r = o ? Object.values(o)[0] : void 0;
277
+ if (!r)
279
278
  throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
280
279
  return {
281
- typeDefs: Se,
280
+ typeDefs: Me,
282
281
  objects: {
283
282
  Query: {
284
283
  plans: {
285
- stonecropMeta(a, { $doctype: c }) {
286
- return ne(c, ($) => v($) ?? null);
284
+ stonecropMeta(s, { $doctype: c }) {
285
+ return ae(c, (a) => j(a) ?? null);
287
286
  },
288
287
  stonecropAllMeta() {
289
- return te(le());
288
+ return ce(ge());
290
289
  },
291
- stonecropRecord(a, { $doctype: c, $id: $, $options: D }) {
292
- return U(
293
- o,
294
- J({ doctype: c, id: $, options: D }),
295
- async (M, u) => {
290
+ stonecropRecord(s, { $doctype: c, $id: a, $options: $ }) {
291
+ return K(
292
+ r,
293
+ Q({ doctype: c, id: a, options: $ }),
294
+ async (E, y) => {
296
295
  const g = /* @__PURE__ */ new Map();
297
- for (let s = 0; s < u.length; s++) {
298
- const d = u[s].doctype;
299
- g.has(d) || g.set(d, []), g.get(d).push(s);
296
+ for (let i = 0; i < y.length; i++) {
297
+ const l = y[i].doctype;
298
+ g.has(l) || g.set(l, []), g.get(l).push(i);
300
299
  }
301
- const w = new Array(u.length);
302
- for (const [s, d] of g) {
303
- const f = v(s);
304
- if (!f?.tableName) {
305
- for (const p of d) w[p] = { data: null, doctype: s };
300
+ const m = new Array(y.length);
301
+ for (const [i, l] of g) {
302
+ const d = j(i);
303
+ if (!d) {
304
+ for (const p of l) m[p] = { data: null, doctype: i };
306
305
  continue;
307
306
  }
308
- const B = W(f, e), E = d.map((p) => u[p].id), { rows: A } = await n(M, {
309
- text: `SELECT ${B} FROM "${f.tableName}" WHERE "${e}"::text = ANY($1::text[])`,
310
- values: [E]
311
- }), L = new Map(A.map((p) => [String(p[e]), p]));
312
- for (const p of d) {
313
- const x = u[p].id, F = L.get(x);
314
- if (!F) {
315
- w[p] = { data: null, doctype: s };
307
+ const D = X(d);
308
+ if (!D) {
309
+ for (const p of l) m[p] = { data: null, doctype: i };
310
+ continue;
311
+ }
312
+ const w = x(D.fieldname), C = U(d), J = l.map((p) => y[p].id), { rows: B } = await e(E, {
313
+ text: `SELECT ${C} FROM ${I(d.name, t.tables)} WHERE "${w}"::text = ANY($1::text[])`,
314
+ values: [J]
315
+ }), v = new Map(B.map((p) => [String(p[D.fieldname]), p]));
316
+ for (const p of l) {
317
+ const F = y[p].id, f = v.get(F);
318
+ if (!f) {
319
+ m[p] = { data: null, doctype: i };
316
320
  continue;
317
321
  }
318
- const k = { ...F }, l = u[p].options ?? {}, m = l.includeNested === !0, y = Array.isArray(l.includeNested) ? new Set(l.includeNested) : null;
319
- if (f.links)
320
- for (const [h, S] of Object.entries(f.links)) {
321
- const C = S.fetch, P = S.cardinality === "noneOrMany" || S.cardinality === "atLeastOne", H = C?.method ?? (P ? "sync" : "lazy"), _ = C?.method === "sync" ? C.limit : P ? 50 : void 0;
322
- if (!(m || (y ? y.has(h) : H === "sync"))) continue;
323
- if (H === "custom") {
324
- const R = C.handler, N = he(R);
325
- N && (k[h] = await N(M, k, S));
322
+ const u = { ...f }, h = y[p].options ?? {}, R = h.includeNested === !0, b = Array.isArray(h.includeNested) ? new Set(h.includeNested) : null;
323
+ if (d.links)
324
+ for (const [M, k] of Object.entries(d.links)) {
325
+ const P = k.fetch, W = k.cardinality === "noneOrMany" || k.cardinality === "atLeastOne", q = P?.method ?? (W ? "sync" : "lazy"), z = P?.method === "sync" ? P.limit : W ? 50 : void 0;
326
+ if (!(R || (b ? b.has(M) : q === "sync"))) continue;
327
+ if (q === "custom") {
328
+ const A = P.handler, O = be(A);
329
+ O && (u[M] = await O(E, u, k));
326
330
  continue;
327
331
  }
328
- if (H !== "sync" && !y?.has(h)) continue;
329
- const j = v(S.target);
330
- if (!j?.tableName) continue;
331
- const Q = W(j, e);
332
- if (P) {
333
- if (!S.backlink) continue;
334
- let R = `SELECT ${Q} FROM "${j.tableName}" WHERE "${S.backlink}"::text = $1`;
335
- const N = [x];
336
- _ != null && (R += " LIMIT $2", N.push(_));
337
- const { rows: z } = await n(M, {
338
- text: R,
339
- values: N
332
+ if (q !== "sync" && !b?.has(M)) continue;
333
+ const N = j(k.target);
334
+ if (!N) continue;
335
+ const G = U(N);
336
+ if (W) {
337
+ if (!k.backlink) continue;
338
+ const A = x(k.backlink);
339
+ let O = `SELECT ${G} FROM ${I(N.name, t.tables)} WHERE "${A}"::text = $1`;
340
+ const T = [F];
341
+ z != null && (O += " LIMIT $2", T.push(z));
342
+ const { rows: _ } = await e(E, {
343
+ text: O,
344
+ values: T
340
345
  });
341
- k[h] = z;
346
+ u[M] = _;
342
347
  } else {
343
- if (!S.fieldname) continue;
344
- const R = k[S.fieldname];
345
- if (R == null) {
346
- k[h] = null;
348
+ if (!k.fieldname) continue;
349
+ const A = u[k.fieldname];
350
+ if (A == null) {
351
+ u[M] = null;
347
352
  continue;
348
353
  }
349
- const { rows: N } = await n(M, {
350
- text: `SELECT ${Q} FROM "${j.tableName}" WHERE "${e}" = $1`,
351
- values: [R]
354
+ const O = X(N);
355
+ if (!O) continue;
356
+ const T = x(O.fieldname), { rows: _ } = await e(E, {
357
+ text: `SELECT ${G} FROM ${I(N.name, t.tables)} WHERE "${T}" = $1`,
358
+ values: [A]
352
359
  });
353
- k[h] = N[0] ?? null;
360
+ u[M] = _[0] ?? null;
354
361
  }
355
362
  }
356
- const O = y && f.links ? [...y].filter((h) => !(h in f.links)) : void 0;
357
- w[p] = {
358
- data: k,
359
- doctype: s,
360
- unknownLinks: O?.length ? O : void 0
363
+ const L = b && d.links ? [...b].filter((M) => !(M in d.links)) : void 0;
364
+ m[p] = {
365
+ data: u,
366
+ doctype: i,
367
+ unknownLinks: L?.length ? L : void 0
361
368
  };
362
369
  }
363
370
  }
364
- return w;
371
+ return m;
365
372
  }
366
373
  );
367
374
  },
368
- stonecropRecords(a, { $doctype: c, $filters: $, $orderBy: D, $limit: M, $offset: u }) {
369
- return U(
370
- o,
371
- J({
375
+ stonecropRecords(s, { $doctype: c, $filters: a, $orderBy: $, $limit: E, $offset: y }) {
376
+ return K(
377
+ r,
378
+ Q({
372
379
  doctype: c,
373
- filters: $,
374
- orderBy: D,
375
- limit: M,
376
- offset: u
380
+ filters: a,
381
+ orderBy: $,
382
+ limit: E,
383
+ offset: y
377
384
  }),
378
- async (g, w) => await Promise.all(
379
- w.map(async (s) => {
380
- const d = v(s.doctype);
381
- if (!d?.tableName)
382
- return { data: [], doctype: s.doctype, count: 0 };
383
- const f = new Set(d.fields.map((l) => l.fieldname)), B = W(d, e), E = [], A = [];
384
- if (s.filters != null)
385
- for (const [l, m] of Object.entries(s.filters)) {
386
- if (!f.has(l))
387
- throw new Error(`Unknown filter field: ${l} for doctype ${d.name}`);
388
- E.push(m), A.push(`"${l}" = $${E.length}`);
385
+ async (g, m) => await Promise.all(
386
+ m.map(async (i) => {
387
+ const l = j(i.doctype);
388
+ if (!l)
389
+ return { data: [], doctype: i.doctype, count: 0 };
390
+ const d = new Set(l.fields.map((f) => f.fieldname)), D = U(l), w = [], C = [];
391
+ if (i.filters != null)
392
+ for (const [f, u] of Object.entries(i.filters)) {
393
+ if (!d.has(f))
394
+ throw new Error(`Unknown filter field: ${f} for doctype ${l.name}`);
395
+ w.push(u), C.push(`"${x(f)}" = $${w.length}`);
389
396
  }
390
- const L = A.length > 0 ? ` WHERE ${A.join(" AND ")}` : "";
391
- let p = "";
392
- if (s.orderBy != null) {
393
- const l = s.orderBy, m = l.lastIndexOf("_");
394
- if (m <= 0)
395
- throw new Error(`Invalid orderBy format: "${l}". Expected FIELD_ASC or FIELD_DESC`);
396
- const y = l.slice(m + 1).toUpperCase();
397
- if (y !== "ASC" && y !== "DESC")
398
- throw new Error(`Invalid orderBy direction: "${y}". Must be ASC or DESC`);
399
- const O = l.slice(0, m);
400
- if (!f.has(O))
401
- throw new Error(`Unknown orderBy field: "${O}" for doctype ${d.name}`);
402
- p = ` ORDER BY "${O}" ${y}`;
397
+ const J = C.length > 0 ? ` WHERE ${C.join(" AND ")}` : "";
398
+ let B = "";
399
+ if (i.orderBy != null) {
400
+ const f = i.orderBy, u = f.lastIndexOf("_");
401
+ if (u <= 0)
402
+ throw new Error(`Invalid orderBy format: "${f}". Expected FIELD_ASC or FIELD_DESC`);
403
+ const h = f.slice(u + 1).toUpperCase();
404
+ if (h !== "ASC" && h !== "DESC")
405
+ throw new Error(`Invalid orderBy direction: "${h}". Must be ASC or DESC`);
406
+ const R = f.slice(0, u);
407
+ if (!d.has(R))
408
+ throw new Error(`Unknown orderBy field: "${R}" for doctype ${l.name}`);
409
+ B = ` ORDER BY "${x(R)}" ${h}`;
403
410
  }
404
- let x = "";
405
- s.limit != null && (E.push(s.limit), x += ` LIMIT $${E.length}`), s.offset != null && (E.push(s.offset), x += ` OFFSET $${E.length}`);
406
- const { rows: F } = await n(g, {
407
- text: `SELECT ${B} FROM "${d.tableName}"${L}${p}${x}`,
408
- values: E
411
+ let v = "";
412
+ i.limit != null && (w.push(i.limit), v += ` LIMIT $${w.length}`), i.offset != null && (w.push(i.offset), v += ` OFFSET $${w.length}`);
413
+ const { rows: p } = await e(g, {
414
+ text: `SELECT ${D} FROM ${I(l.name, t.tables)}${J}${B}${v}`,
415
+ values: w
409
416
  });
410
- let k = F.length;
411
- if (s.limit != null || s.offset != null) {
412
- const l = [], m = [];
413
- if (s.filters != null)
414
- for (const [h, S] of Object.entries(s.filters))
415
- f.has(h) && (l.push(S), m.push(`"${h}" = $${l.length}`));
416
- const y = m.length > 0 ? ` WHERE ${m.join(" AND ")}` : "", { rows: O } = await n(g, {
417
- text: `SELECT COUNT(*) AS __count FROM "${d.tableName}"${y}`,
418
- values: l
417
+ let F = p.length;
418
+ if (i.limit != null || i.offset != null) {
419
+ const f = [], u = [];
420
+ if (i.filters != null)
421
+ for (const [b, L] of Object.entries(i.filters))
422
+ d.has(b) && (f.push(L), u.push(`"${x(b)}" = $${f.length}`));
423
+ const h = u.length > 0 ? ` WHERE ${u.join(" AND ")}` : "", { rows: R } = await e(g, {
424
+ text: `SELECT COUNT(*) AS __count FROM ${I(l.name, t.tables)}${h}`,
425
+ values: f
419
426
  });
420
- k = parseInt(O[0]?.__count ?? "0", 10);
427
+ F = parseInt(R[0]?.__count ?? "0", 10);
421
428
  }
422
- return { data: F, doctype: s.doctype, count: k };
429
+ return { data: p, doctype: i.doctype, count: F };
423
430
  })
424
431
  )
425
432
  );
@@ -428,40 +435,40 @@ const Se = oe`
428
435
  },
429
436
  Mutation: {
430
437
  plans: {
431
- stonecropAction(a, { $doctype: c, $action: $, $args: D }) {
432
- return ee(
433
- o,
434
- J({ doctype: c, action: $, actionArgs: D }),
435
- async (M, u) => {
436
- const g = v(u.doctype);
438
+ stonecropAction(s, { $doctype: c, $action: a, $args: $ }) {
439
+ return se(
440
+ r,
441
+ Q({ doctype: c, action: a, actionArgs: $ }),
442
+ async (E, y) => {
443
+ const g = j(y.doctype);
437
444
  if (!g)
438
445
  return {
439
446
  success: !1,
440
447
  data: null,
441
- error: `Unknown doctype: ${u.doctype}`
448
+ error: `Unknown doctype: ${y.doctype}`
442
449
  };
443
- const w = g.workflow?.actions?.[u.action];
444
- if (!w)
450
+ const m = g.workflow?.actions?.[y.action];
451
+ if (!m)
445
452
  return {
446
453
  success: !1,
447
454
  data: null,
448
- error: `Unknown action: ${u.action} on ${u.doctype}`
455
+ error: `Unknown action: ${y.action} on ${y.doctype}`
449
456
  };
450
- const s = fe(w.handler);
451
- if (!s)
457
+ const i = he(m.handler);
458
+ if (!i)
452
459
  return {
453
460
  success: !1,
454
461
  data: null,
455
- error: `Handler not registered: ${w.handler}`
462
+ error: `Handler not registered: ${m.handler}`
456
463
  };
457
- const d = { doctype: g, pgClient: M };
464
+ const l = { doctype: g, pgClient: E };
458
465
  try {
459
- return { success: !0, data: await s(u.actionArgs ?? [], d), error: null };
460
- } catch (f) {
466
+ return { success: !0, data: await i(y.actionArgs ?? [], l), error: null };
467
+ } catch (d) {
461
468
  return {
462
469
  success: !1,
463
470
  data: null,
464
- error: f instanceof Error ? f.message : String(f)
471
+ error: d instanceof Error ? d.message : String(d)
465
472
  };
466
473
  }
467
474
  }
@@ -473,39 +480,48 @@ const Se = oe`
473
480
  };
474
481
  });
475
482
  };
476
- function W(t, e) {
477
- const n = /* @__PURE__ */ new Set();
483
+ function U(t) {
484
+ const e = /* @__PURE__ */ new Set();
478
485
  if (t.links)
479
- for (const [o, a] of Object.entries(t.links))
480
- n.add(a.fieldname ?? o);
481
- const i = [];
482
- t.fields.some((o) => o.fieldname === e) || i.push(`"${e}"`);
483
- for (const o of t.fields)
484
- o.fieldtype !== "Display" && (o.fieldtype === "Link" && n.has(o.fieldname) || i.push(`"${o.fieldname}"`));
485
- return i.join(", ");
486
+ for (const [o, r] of Object.entries(t.links))
487
+ e.add(r.fieldname ?? o);
488
+ const n = [];
489
+ for (const o of t.fields) {
490
+ if (o.fieldtype === "Display" || o.fieldtype === "Link" && e.has(o.fieldname)) continue;
491
+ const r = x(o.fieldname);
492
+ n.push(r !== o.fieldname ? `"${r}" AS "${o.fieldname}"` : `"${o.fieldname}"`);
493
+ }
494
+ return n.join(", ");
495
+ }
496
+ function X(t) {
497
+ return t.fields.find((e) => e.fieldtype === "PrimaryKey");
498
+ }
499
+ function I(t, e) {
500
+ const n = e?.[t] ?? ie(t), o = n.indexOf(".");
501
+ return o > 0 ? `"${n.slice(0, o)}"."${n.slice(o + 1)}"` : `"${n}"`;
486
502
  }
487
- const He = (t = {}) => {
488
- const { logPlans: e = !0, logTiming: n = !1 } = t, i = (r, o) => ({
489
- plan: (a) => {
490
- e && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${o}`);
491
- const c = n ? Date.now() : 0, $ = a();
503
+ const Qe = (t = {}) => {
504
+ const { logPlans: e = !0, logTiming: n = !1 } = t, o = (r, s) => ({
505
+ plan: (c) => {
506
+ e && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${s}`);
507
+ const a = n ? Date.now() : 0, $ = c();
492
508
  return n && console.log(
493
- `[@stonecrop/graphql-middleware] Plan built for ${r}.${o} in ${Date.now() - c}ms`
509
+ `[@stonecrop/graphql-middleware] Plan built for ${r}.${s} in ${Date.now() - a}ms`
494
510
  ), $;
495
511
  }
496
512
  });
497
- return ie({
513
+ return fe({
498
514
  Query: {
499
- stonecropRecord: i("Query", "stonecropRecord"),
500
- stonecropRecords: i("Query", "stonecropRecords"),
501
- stonecropMeta: i("Query", "stonecropMeta"),
502
- stonecropAllMeta: i("Query", "stonecropAllMeta")
515
+ stonecropRecord: o("Query", "stonecropRecord"),
516
+ stonecropRecords: o("Query", "stonecropRecords"),
517
+ stonecropMeta: o("Query", "stonecropMeta"),
518
+ stonecropAllMeta: o("Query", "stonecropAllMeta")
503
519
  },
504
520
  Mutation: {
505
- stonecropAction: i("Mutation", "stonecropAction")
521
+ stonecropAction: o("Mutation", "stonecropAction")
506
522
  }
507
523
  });
508
- }, $e = {
524
+ }, Oe = {
509
525
  name: "StonecropFieldCasingPlugin",
510
526
  version: "0.0.0",
511
527
  inflection: {
@@ -515,33 +531,33 @@ const He = (t = {}) => {
515
531
  }
516
532
  }
517
533
  }
518
- }, we = (t) => ({
519
- extends: [se],
520
- plugins: t?.fieldCasing === "pascal" ? [$e] : []
521
- }), Je = we();
534
+ }, Re = (t) => ({
535
+ extends: [ue],
536
+ plugins: t?.fieldCasing === "pascal" ? [Oe] : []
537
+ }), Ue = Re();
522
538
  export {
523
- T as DoctypeValidationError,
524
- Je as StonecropPreset,
525
- me as builtinHandlers,
526
- Le as clearFetchHandlers,
527
- je as clearHandlers,
528
- Fe as clearRegistry,
529
- He as createDebugPlugin,
530
- Pe as createStonecropPlugin,
531
- we as createStonecropPreset,
532
- le as getAllMeta,
533
- he as getFetchHandler,
534
- fe as getHandler,
535
- v as getMeta,
536
- Ce as hasHandler,
537
- Ae as hasMeta,
538
- ce as loadDoctypes,
539
- xe as loadDoctypesFromObject,
540
- qe as makePgService,
541
- Ie as registerBuiltinHandlers,
542
- Be as registerFetchHandler,
543
- de as registerHandler,
544
- Se as typeDefs,
545
- ve as validateReferences
539
+ V as DoctypeValidationError,
540
+ Ue as StonecropPreset,
541
+ Ee as builtinHandlers,
542
+ qe as clearFetchHandlers,
543
+ He as clearHandlers,
544
+ Le as clearRegistry,
545
+ Qe as createDebugPlugin,
546
+ _e as createStonecropPlugin,
547
+ Re as createStonecropPreset,
548
+ ge as getAllMeta,
549
+ be as getFetchHandler,
550
+ he as getHandler,
551
+ j as getMeta,
552
+ Te as hasHandler,
553
+ Be as hasMeta,
554
+ pe as loadDoctypes,
555
+ Ie as loadDoctypesFromObject,
556
+ ze as makePgService,
557
+ Je as registerBuiltinHandlers,
558
+ We as registerFetchHandler,
559
+ me as registerHandler,
560
+ Me as typeDefs,
561
+ Pe as validateReferences
546
562
  };
547
563
  //# sourceMappingURL=index.js.map