@stonecrop/graphql-middleware 0.30.0 → 0.32.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.
Files changed (38) hide show
  1. package/dist/index.js +1188 -720
  2. package/dist/index.js.map +1 -1
  3. package/dist/tsdoc-metadata.json +1 -1
  4. package/package.json +33 -14
  5. package/dist/graphql_client.tsbuildinfo +0 -1
  6. package/dist/src/debug.d.ts +0 -31
  7. package/dist/src/debug.d.ts.map +0 -1
  8. package/dist/src/debug.js +0 -49
  9. package/dist/src/dispatch/transition.d.ts +0 -107
  10. package/dist/src/dispatch/transition.d.ts.map +0 -1
  11. package/dist/src/dispatch/transition.js +0 -152
  12. package/dist/src/fields.d.ts +0 -23
  13. package/dist/src/fields.d.ts.map +0 -1
  14. package/dist/src/fields.js +0 -28
  15. package/dist/src/index.d.ts +0 -16
  16. package/dist/src/index.d.ts.map +0 -1
  17. package/dist/src/index.js +0 -14
  18. package/dist/src/link-display.d.ts +0 -19
  19. package/dist/src/link-display.d.ts.map +0 -1
  20. package/dist/src/link-display.js +0 -93
  21. package/dist/src/plugin/postgraphile.d.ts +0 -174
  22. package/dist/src/plugin/postgraphile.d.ts.map +0 -1
  23. package/dist/src/plugin/postgraphile.js +0 -882
  24. package/dist/src/preset.d.ts +0 -53
  25. package/dist/src/preset.d.ts.map +0 -1
  26. package/dist/src/preset.js +0 -148
  27. package/dist/src/registry/doctypes.d.ts +0 -95
  28. package/dist/src/registry/doctypes.d.ts.map +0 -1
  29. package/dist/src/registry/doctypes.js +0 -251
  30. package/dist/src/registry/fetchHandlers.d.ts +0 -31
  31. package/dist/src/registry/fetchHandlers.d.ts.map +0 -1
  32. package/dist/src/registry/fetchHandlers.js +0 -24
  33. package/dist/src/tables.d.ts +0 -14
  34. package/dist/src/tables.d.ts.map +0 -1
  35. package/dist/src/tables.js +0 -21
  36. package/dist/src/typeDefs.d.ts +0 -7
  37. package/dist/src/typeDefs.d.ts.map +0 -1
  38. package/dist/src/typeDefs.js +0 -118
package/dist/index.js CHANGED
@@ -1,257 +1,487 @@
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 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
- function te(e) {
10
- return K(e).filter((t) => t.kind === "field" && !t.computed);
1
+ import { readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { camelToSnake, flattenFields, flattenFields as flattenFields$1, getDisplayField, getRecordIdField, isActionAllowedInState, parseDoctype, pascalToSnake, resolveLinkRenderMode, unwrapInlineLinks, validateDoctype } from "@stonecrop/schema";
4
+ import { loadOneWithPgClient, sideEffectWithPgClient } from "@dataplan/pg";
5
+ import { constant, lambda, object } from "postgraphile/grafast";
6
+ import { extendSchema, gql, wrapPlans } from "postgraphile/utils";
7
+ import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
8
+ import { makePgService } from "postgraphile/adaptors/pg";
9
+ //#region src/fields.ts
10
+ /**
11
+ * The fields that have a database column of their own — the one definition of that question.
12
+ *
13
+ * Two properties disqualify a field, and both are the field saying so itself: a `computed` field is
14
+ * declared precisely to state it has no column, and a container (a table field) is a relation
15
+ * rather than a value. Everything else names a column.
16
+ *
17
+ * This is deliberately **not** the same question as "does this column belong in a record payload".
18
+ * An *expanding* link's foreign key has a real column that this returns, while `collectColumns`
19
+ * omits it from the SELECT on purpose because the relation is fetched separately. Conflating the
20
+ * two is how the read path came to drop the very column its expansion needed. Callers wanting the
21
+ * payload projection filter this further by render mode; callers asking whether a column exists —
22
+ * link validation, and the write path deciding what it may set — want it unfiltered.
23
+ *
24
+ * Extracted because the rule had grown three statements across two modules, one of them a comment
25
+ * reading "mirrors `collectColumns`". A rule that has to be mirrored by hand is one edit away from
26
+ * the read path and the validator disagreeing about what a doctype declares.
27
+ */
28
+ function columnBackedFields(fields) {
29
+ return flattenFields$1(fields).filter((f) => f.kind === "field" && !f.computed);
11
30
  }
12
- const H = /* @__PURE__ */ new Map();
13
- class le extends Error {
14
- constructor(t, o) {
15
- const n = o.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
16
- `);
17
- super(`Invalid doctype definition in ${t}:
18
- ${n}`), this.file = t, this.errors = o, this.name = "DoctypeValidationError";
19
- }
20
- file;
21
- errors;
22
- }
23
- function Be(e, t = {}) {
24
- const o = be(e);
25
- for (const n of o) {
26
- const r = ve(e, n);
27
- Ee(r).isDirectory() ? Be(r, t) : n.endsWith(".json") && Pe(r, t);
28
- }
31
+ //#endregion
32
+ //#region src/registry/doctypes.ts
33
+ var doctypeRegistry = /* @__PURE__ */ new Map();
34
+ /**
35
+ * Error thrown when a doctype definition fails validation
36
+ * @public
37
+ */
38
+ var DoctypeValidationError = class extends Error {
39
+ file;
40
+ errors;
41
+ constructor(file, errors) {
42
+ const errorMessages = errors.map((e) => ` ${e.path.join(".")}: ${e.message}`).join("\n");
43
+ super(`Invalid doctype definition in ${file}:\n${errorMessages}`);
44
+ this.file = file;
45
+ this.errors = errors;
46
+ this.name = "DoctypeValidationError";
47
+ }
48
+ };
49
+ /**
50
+ * Load doctype definitions from a directory of JSON files
51
+ * @param dir - Directory path containing doctype JSON files
52
+ * @param options - Options for loading doctypes (continueOnError, onError callback)
53
+ * @public
54
+ */
55
+ function loadDoctypes(dir, options = {}) {
56
+ const entries = readdirSync(dir);
57
+ for (const entry of entries) {
58
+ const fullPath = join(dir, entry);
59
+ if (statSync(fullPath).isDirectory()) loadDoctypes(fullPath, options);
60
+ else if (entry.endsWith(".json")) loadDoctypeFile(fullPath, options);
61
+ }
29
62
  }
30
- function Pe(e, t) {
31
- const o = Re(e, "utf-8");
32
- let n;
33
- try {
34
- n = JSON.parse(o);
35
- } catch (a) {
36
- const u = {
37
- path: [],
38
- message: `Invalid JSON: ${a instanceof Error ? a.message : String(a)}`
39
- };
40
- if (t.continueOnError) {
41
- t.onError?.(e, [u]);
42
- return;
43
- }
44
- throw new le(e, [u]);
45
- }
46
- const r = ye(n);
47
- if (!r.success) {
48
- if (t.continueOnError) {
49
- t.onError?.(e, r.errors);
50
- return;
51
- }
52
- throw new le(e, r.errors);
53
- }
54
- const i = we(n);
55
- H.set(i.name, i);
63
+ /**
64
+ * Load and validate a single doctype file
65
+ */
66
+ function loadDoctypeFile(filePath, options) {
67
+ const content = readFileSync(filePath, "utf-8");
68
+ let data;
69
+ try {
70
+ data = JSON.parse(content);
71
+ } catch (err) {
72
+ const parseError = {
73
+ path: [],
74
+ message: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`
75
+ };
76
+ if (options.continueOnError) {
77
+ options.onError?.(filePath, [parseError]);
78
+ return;
79
+ }
80
+ throw new DoctypeValidationError(filePath, [parseError]);
81
+ }
82
+ const result = validateDoctype(data);
83
+ if (!result.success) {
84
+ if (options.continueOnError) {
85
+ options.onError?.(filePath, result.errors);
86
+ return;
87
+ }
88
+ throw new DoctypeValidationError(filePath, result.errors);
89
+ }
90
+ const doctype = parseDoctype(data);
91
+ doctypeRegistry.set(doctype.name, doctype);
56
92
  }
57
- function ot(e, t = {}) {
58
- for (const [o, n] of Object.entries(e)) {
59
- const r = { ...typeof n == "object" && n !== null ? n : {}, name: o }, i = ye(r);
60
- if (!i.success) {
61
- if (t.continueOnError) {
62
- t.onError?.(o, i.errors);
63
- continue;
64
- }
65
- throw new le(o, i.errors);
66
- }
67
- const a = we(r);
68
- H.set(a.name, a);
69
- }
93
+ /**
94
+ * Load doctypes from an object (for programmatic use)
95
+ * @param doctypes - Object mapping doctype names to doctype definitions
96
+ * @param options - Options for loading doctypes (continueOnError, onError callback)
97
+ * @public
98
+ */
99
+ function loadDoctypesFromObject(doctypes, options = {}) {
100
+ for (const [name, data] of Object.entries(doctypes)) {
101
+ const withName = {
102
+ ...typeof data === "object" && data !== null ? data : {},
103
+ name
104
+ };
105
+ const result = validateDoctype(withName);
106
+ if (!result.success) {
107
+ if (options.continueOnError) {
108
+ options.onError?.(name, result.errors);
109
+ continue;
110
+ }
111
+ throw new DoctypeValidationError(name, result.errors);
112
+ }
113
+ const doctype = parseDoctype(withName);
114
+ doctypeRegistry.set(doctype.name, doctype);
115
+ }
70
116
  }
71
- function L(e) {
72
- const t = H.get(e);
73
- if (t) return t;
74
- for (const o of H.values())
75
- if (o.slug === e) return o;
117
+ /**
118
+ * Get a doctype by name
119
+ * @param name - Name of the doctype to retrieve
120
+ * @public
121
+ */
122
+ function getMeta(name) {
123
+ const direct = doctypeRegistry.get(name);
124
+ if (direct) return direct;
125
+ for (const doctype of doctypeRegistry.values()) if (doctype.slug === name) return doctype;
76
126
  }
77
- function $e() {
78
- return Array.from(H.values());
127
+ /**
128
+ * Get all loaded doctypes
129
+ * @public
130
+ */
131
+ function getAllMeta() {
132
+ return Array.from(doctypeRegistry.values());
79
133
  }
80
- function rt(e) {
81
- return H.has(e);
134
+ /**
135
+ * Check if a doctype is registered
136
+ * @param name - Name of the doctype to check
137
+ * @public
138
+ */
139
+ function hasMeta(name) {
140
+ return doctypeRegistry.has(name);
82
141
  }
83
- function it() {
84
- H.clear();
142
+ /**
143
+ * Clear all registered doctypes
144
+ * @public
145
+ */
146
+ function clearRegistry() {
147
+ doctypeRegistry.clear();
85
148
  }
86
- function je() {
87
- const e = [];
88
- for (const t of H.values()) {
89
- t.inherits && L(t.inherits) === void 0 && e.push({
90
- path: [t.name, "inherits"],
91
- message: `References unknown doctype: ${t.inherits}`
92
- });
93
- const o = K(t.fields);
94
- for (const n of o) {
95
- if (n.kind !== "field") continue;
96
- const r = n.doctype;
97
- r !== void 0 && L(r) === void 0 && e.push({
98
- path: [t.name, "fields", n.fieldname, "doctype"],
99
- message: `Link references unknown doctype: ${r}`
100
- });
101
- }
102
- if (t.links) {
103
- const n = new Set(o.map((i) => i.fieldname)), r = new Set(te(t.fields).map((i) => i.fieldname));
104
- for (const [i, a] of Object.entries(t.links)) {
105
- if (L(a.target) === void 0 && e.push({
106
- path: [t.name, "links", i, "target"],
107
- message: `Link references unknown doctype: ${a.target}`
108
- }), a.fetch?.method === "custom") continue;
109
- if (a.cardinality === "noneOrMany" || a.cardinality === "atLeastOne") {
110
- a.backlink || e.push({
111
- path: [t.name, "links", i, "backlink"],
112
- message: `Link "${i}" is ${a.cardinality} but names no \`backlink\`, so the runtime cannot find the target rows and drops the link with no error. Name the field on "${a.target}" that points back to this doctype.`
113
- });
114
- continue;
115
- }
116
- const u = a.fieldname ?? i;
117
- r.has(u) || e.push({
118
- // Point at whichever half actually carries the binding: the `fieldname`
119
- // property when it is set, otherwise the key itself. Naming `target` here
120
- // would send the reader to the one part that resolved correctly.
121
- path: a.fieldname ? [t.name, "links", i, "fieldname"] : [t.name, "links", i],
122
- // Two different repairs, so two different diagnoses: a name nothing declares
123
- // is a typo, while a name that resolves to a column-less field is a binding
124
- // pointed at the wrong one of several real fields.
125
- message: n.has(u) ? `Link "${i}" binds to field "${u}", which has no database column of its own — it is computed, or a container rather than a value — so there is no foreign key to read and the record read fails on the missing column. Bind the link to the field holding the foreign key.` : `Link "${i}" binds to field "${u}", which this doctype does not declare, so it resolves to null with no error. Declare that field, or set \`fieldname\` to the field holding the foreign key. (A link's key is its fieldname unless \`fieldname\` overrides it.)`
126
- });
127
- }
128
- }
129
- }
130
- return e;
149
+ /**
150
+ * Validate doctype references — link targets, `inherits`, and each link's binding — against what
151
+ * is loaded.
152
+ *
153
+ * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by
154
+ * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as
155
+ * one, and every doctype in this repo writes one), so a raw `.has()` reports a broken reference for
156
+ * every correct link — measured at 12 of 12 across the two in-repo hosts before this was fixed.
157
+ * `getMeta` is also what the plugin resolves a link with at fetch time, so this asks the same
158
+ * question the runtime asks.
159
+ *
160
+ * `inherits` is checked the same way even though nothing resolves it at runtime (both resolvers
161
+ * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the
162
+ * permissive direction.
163
+ *
164
+ * The **binding** checks are the same defect class as an unresolvable target, one step further in:
165
+ * a link whose target resolves can still name no way to reach the rows, and the reader's answer for
166
+ * that is `continue` or a `null` — indistinguishable on the wire from a relation that is genuinely
167
+ * empty. Both halves of a declaration are `.optional()` in the schema because which one is required
168
+ * depends on cardinality, which Zod cannot express here; this is where that dependency is enforced.
169
+ *
170
+ * Only what the runtime actually consults is required. A `backlink` naming a column the target
171
+ * table does not have already fails loudly — Postgres rejects the SELECT — so it is left alone;
172
+ * the check exists for the silent cases, not to restate the database's own errors.
173
+ *
174
+ * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that
175
+ * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only
176
+ * meaningful after this module's own loaders have run.
177
+ *
178
+ * @internal
179
+ */
180
+ function validateReferences() {
181
+ const errors = [];
182
+ for (const doctype of doctypeRegistry.values()) {
183
+ if (doctype.inherits && getMeta(doctype.inherits) === void 0) errors.push({
184
+ path: [doctype.name, "inherits"],
185
+ message: `References unknown doctype: ${doctype.inherits}`
186
+ });
187
+ const fields = flattenFields$1(doctype.fields);
188
+ for (const field of fields) {
189
+ if (field.kind !== "field") continue;
190
+ const target = field.doctype;
191
+ if (target !== void 0 && getMeta(target) === void 0) errors.push({
192
+ path: [
193
+ doctype.name,
194
+ "fields",
195
+ field.fieldname,
196
+ "doctype"
197
+ ],
198
+ message: `Link references unknown doctype: ${target}`
199
+ });
200
+ }
201
+ if (doctype.links) {
202
+ const declared = new Set(fields.map((f) => f.fieldname));
203
+ const columnBacked = new Set(columnBackedFields(doctype.fields).map((f) => f.fieldname));
204
+ for (const [key, link] of Object.entries(doctype.links)) {
205
+ if (getMeta(link.target) === void 0) errors.push({
206
+ path: [
207
+ doctype.name,
208
+ "links",
209
+ key,
210
+ "target"
211
+ ],
212
+ message: `Link references unknown doctype: ${link.target}`
213
+ });
214
+ if (link.fetch?.method === "custom") continue;
215
+ if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") {
216
+ if (!link.backlink) errors.push({
217
+ path: [
218
+ doctype.name,
219
+ "links",
220
+ key,
221
+ "backlink"
222
+ ],
223
+ message: `Link "${key}" is ${link.cardinality} but names no \`backlink\`, so the runtime cannot find the target rows and drops the link with no error. Name the field on "${link.target}" that points back to this doctype.`
224
+ });
225
+ continue;
226
+ }
227
+ const fieldname = link.fieldname ?? key;
228
+ if (!columnBacked.has(fieldname)) errors.push({
229
+ path: link.fieldname ? [
230
+ doctype.name,
231
+ "links",
232
+ key,
233
+ "fieldname"
234
+ ] : [
235
+ doctype.name,
236
+ "links",
237
+ key
238
+ ],
239
+ message: declared.has(fieldname) ? `Link "${key}" binds to field "${fieldname}", which has no database column of its own — it is computed, or a container rather than a value — so there is no foreign key to read and the record read fails on the missing column. Bind the link to the field holding the foreign key.` : `Link "${key}" binds to field "${fieldname}", which this doctype does not declare, so it resolves to null with no error. Declare that field, or set \`fieldname\` to the field holding the foreign key. (A link's key is its fieldname unless \`fieldname\` overrides it.)`
240
+ });
241
+ }
242
+ }
243
+ }
244
+ return errors;
131
245
  }
132
- const ce = /* @__PURE__ */ new Map();
133
- function at(e, t) {
134
- ce.set(e, t);
246
+ //#endregion
247
+ //#region src/registry/fetchHandlers.ts
248
+ var registry = /* @__PURE__ */ new Map();
249
+ /**
250
+ * Register a custom fetch handler by name.
251
+ * The name must match the `handler` field on a `CustomFetch` strategy declaration.
252
+ * @public
253
+ */
254
+ function registerFetchHandler(name, handler) {
255
+ registry.set(name, handler);
135
256
  }
136
- function _e(e) {
137
- return ce.get(e);
257
+ /**
258
+ * Retrieve a registered fetch handler by name.
259
+ * Returns `undefined` if no handler has been registered under that name.
260
+ * @public
261
+ */
262
+ function getFetchHandler(name) {
263
+ return registry.get(name);
138
264
  }
139
- function st() {
140
- ce.clear();
265
+ /**
266
+ * Remove all registered fetch handlers. Primarily for test isolation.
267
+ * @public
268
+ */
269
+ function clearFetchHandlers() {
270
+ registry.clear();
141
271
  }
142
- async function We(e, t, o) {
143
- const n = e.label ?? "unknown", r = e.selfTransition === !0, i = r || e.nextState != null;
144
- if (!i && !t.runEffect)
145
- return {
146
- success: !1,
147
- data: null,
148
- error: `Action "${n}" has no workflow transition and no server-side effect is wired — nothing was executed. Give it a nextState or selfTransition in the doctype, or register a server-side handler for it on the adapter.`
149
- };
150
- if (r && !t.writeData && !t.runEffect)
151
- return {
152
- success: !1,
153
- data: null,
154
- error: `Action "${n}" persists record data in place, which this backend does not support.`
155
- };
156
- const a = (e.allowedStates?.length ?? 0) > 0;
157
- let u;
158
- if (a || i) {
159
- const E = await t.readState();
160
- if (E === null) {
161
- if (r && t.writeData) {
162
- const v = await t.writeData(o ?? {}, !1);
163
- return !v || Object.keys(v).length === 0 ? {
164
- success: !1,
165
- data: null,
166
- error: `Action "${n}" targets a record that does not exist, and the backend did not create it.`
167
- } : { success: !0, data: v, error: null };
168
- }
169
- return {
170
- success: !1,
171
- data: null,
172
- error: `Action "${n}" targets a record that does not exist — nothing was executed.`
173
- };
174
- }
175
- u = E ?? "";
176
- }
177
- if (!Ae(e, u ?? ""))
178
- return {
179
- success: !1,
180
- data: null,
181
- error: `Action not allowed from state: ${u || "(unknown)"}`
182
- };
183
- let b;
184
- if (t.runEffect)
185
- try {
186
- b = await t.runEffect(u);
187
- } catch (E) {
188
- return {
189
- success: !1,
190
- data: null,
191
- error: `Action "${n}" failed: ${E instanceof Error ? E.message : String(E)}`
192
- };
193
- }
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
- success: !0,
196
- data: b ?? { state: e.nextState },
197
- error: null
198
- });
272
+ //#endregion
273
+ //#region src/dispatch/transition.ts
274
+ /**
275
+ * Apply a workflow action on the server, enforcing `allowedStates`.
276
+ *
277
+ * The server owns the transition: it reads the record's authoritative current state,
278
+ * rejects the action when `isActionAllowedInState` denies it, then applies the outcome.
279
+ * Storage access is injected via `io` so this one guard serves every backend and can never
280
+ * disagree with the frontend's `getAvailableTransitions`, which shares the same predicate.
281
+ *
282
+ * **The doctype decides whether an action may run and what state results; the adapter decides
283
+ * what actually happens.** `allowedStates`, `nextState` and `selfTransition` are authored in the
284
+ * doctype (in DocBuilder, by whoever models the workflow); the effect is registered by whoever
285
+ * owns the database. Neither names the other: an action never carries a handler name, and a
286
+ * handler never overrides the guard.
287
+ *
288
+ * There are four action shapes this distinguishes:
289
+ * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.
290
+ * - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current
291
+ * state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.
292
+ * When the target record does not exist the same write creates it — saving a record is one
293
+ * request whether or not the row is there yet, so there is no separate create action, no create
294
+ * mutation, and no second write path for it.
295
+ * - A **stateless command** (neither of the above) with an `io.runEffect`: the handler is the whole
296
+ * outcome. Still guarded by `allowedStates`, and still forbidden from moving the record.
297
+ * - Anything else — no `nextState`, no `selfTransition`, no registered effect — is either a genuine
298
+ * authoring mistake or a command whose handler was never wired. It fails loudly before touching
299
+ * the backend rather than reporting a false success.
300
+ *
301
+ * @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`
302
+ * @param io - Backend read/write closures, plus the optional adapter-owned effect
303
+ * @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)
304
+ * @returns Action result envelope — the freshest record the backend produced, or the resulting state
305
+ * @public
306
+ */
307
+ async function applyGuardedTransition(actionDef, io, data) {
308
+ const label = actionDef.label ?? "unknown";
309
+ const isSelfTransition = actionDef.selfTransition === true;
310
+ const hasStateOutcome = isSelfTransition || actionDef.nextState != null;
311
+ if (!hasStateOutcome && !io.runEffect) return {
312
+ success: false,
313
+ data: null,
314
+ error: `Action "${label}" has no workflow transition and no server-side effect is wired — nothing was executed. Give it a nextState or selfTransition in the doctype, or register a server-side handler for it on the adapter.`
315
+ };
316
+ if (isSelfTransition && !io.writeData && !io.runEffect) return {
317
+ success: false,
318
+ data: null,
319
+ error: `Action "${label}" persists record data in place, which this backend does not support.`
320
+ };
321
+ const isGuarded = (actionDef.allowedStates?.length ?? 0) > 0;
322
+ let currentState;
323
+ if (isGuarded || hasStateOutcome) {
324
+ const state = await io.readState();
325
+ if (state === null) {
326
+ if (isSelfTransition && io.writeData) {
327
+ const created = await io.writeData(data ?? {}, false);
328
+ if (!created || Object.keys(created).length === 0) return {
329
+ success: false,
330
+ data: null,
331
+ error: `Action "${label}" targets a record that does not exist, and the backend did not create it.`
332
+ };
333
+ return {
334
+ success: true,
335
+ data: created,
336
+ error: null
337
+ };
338
+ }
339
+ return {
340
+ success: false,
341
+ data: null,
342
+ error: `Action "${label}" targets a record that does not exist — nothing was executed.`
343
+ };
344
+ }
345
+ currentState = state ?? "";
346
+ }
347
+ if (!isActionAllowedInState(actionDef, currentState ?? "")) return {
348
+ success: false,
349
+ data: null,
350
+ error: `Action not allowed from state: ${currentState || "(unknown)"}`
351
+ };
352
+ let effectResult;
353
+ if (io.runEffect) try {
354
+ effectResult = await io.runEffect(currentState);
355
+ } catch (err) {
356
+ return {
357
+ success: false,
358
+ data: null,
359
+ error: `Action "${label}" failed: ${err instanceof Error ? err.message : String(err)}`
360
+ };
361
+ }
362
+ if (isSelfTransition) return {
363
+ success: true,
364
+ data: (io.writeData ? await io.writeData(data ?? {}, true) : effectResult) ?? null,
365
+ error: null
366
+ };
367
+ if (actionDef.nextState == null) return {
368
+ success: true,
369
+ data: effectResult ?? null,
370
+ error: null
371
+ };
372
+ await io.writeState(actionDef.nextState);
373
+ return {
374
+ success: true,
375
+ data: effectResult ?? { state: actionDef.nextState },
376
+ error: null
377
+ };
199
378
  }
200
- function W(e, t) {
201
- const o = t?.[e] ?? Me(e), n = o.indexOf(".");
202
- return n > 0 ? `"${o.slice(0, n)}"."${o.slice(n + 1)}"` : `"${o}"`;
379
+ //#endregion
380
+ //#region src/tables.ts
381
+ /**
382
+ * The quoted SQL table a doctype reads from: the `tables` override when the adapter supplies one,
383
+ * otherwise the doctype name snake-cased.
384
+ *
385
+ * The one definition of that mapping. It lives in its own module rather than beside either caller
386
+ * because the plugin imports the link-display enrichment, so the enrichment cannot import back —
387
+ * and the copy it made instead was byte-identical, which is the state a mapping is in right before
388
+ * one side learns about schema-qualified names and the other does not.
389
+ *
390
+ * A dotted override is read as `schema.table` and quoted in two parts, so a table in a non-default
391
+ * Postgres schema survives quoting instead of becoming one identifier containing a dot.
392
+ */
393
+ function resolveTableName(name, tables) {
394
+ const target = tables?.[name] ?? pascalToSnake(name);
395
+ const dotIndex = target.indexOf(".");
396
+ if (dotIndex > 0) return `"${target.slice(0, dotIndex)}"."${target.slice(dotIndex + 1)}"`;
397
+ return `"${target}"`;
203
398
  }
204
- function Z(e) {
205
- if (!(e == null || typeof e == "object")) {
206
- if (typeof e == "string") return e === "" ? void 0 : e;
207
- if (typeof e == "number" || typeof e == "boolean" || typeof e == "bigint")
208
- return String(e);
209
- }
399
+ //#endregion
400
+ //#region src/link-display.ts
401
+ /**
402
+ * Normalize a scalar SQL cell value to a non-empty string, or nothing.
403
+ *
404
+ * One rule for the three reads that all need it — the FK a lookup keys on, the target's own key
405
+ * in the result, and the display text stamped into the payload. Rejecting objects is what each
406
+ * of those wants: an object FK is a link that was already expanded, and an object display column
407
+ * is the `[object Object]` a bare `String()` would otherwise write into the payload as though it
408
+ * were the record's name. Falling back to the raw id is visibly unhelpful; that is not.
409
+ */
410
+ function scalarText(value) {
411
+ if (value == null || typeof value === "object") return void 0;
412
+ if (typeof value === "string") return value === "" ? void 0 : value;
413
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
210
414
  }
211
- function He(e, t) {
212
- const o = [];
213
- for (const n of K(e.fields)) {
214
- if (n.kind !== "field" || !n.doctype) continue;
215
- const r = L(n.doctype);
216
- if (!r) continue;
217
- const i = Oe(r.fields, r.displayField);
218
- i && o.push({
219
- fieldname: n.fieldname,
220
- displayField: i.fieldname,
221
- targetPkFieldname: Se(r.fields),
222
- targetTable: W(r.name, t)
223
- });
224
- }
225
- return o;
415
+ function collectLinkDisplaySpecs(meta, tables) {
416
+ const specs = [];
417
+ for (const field of flattenFields(meta.fields)) {
418
+ if (field.kind !== "field" || !field.doctype) continue;
419
+ const targetMeta = getMeta(field.doctype);
420
+ if (!targetMeta) continue;
421
+ const displayField = getDisplayField(targetMeta.fields, targetMeta.displayField);
422
+ if (!displayField) continue;
423
+ specs.push({
424
+ fieldname: field.fieldname,
425
+ displayField: displayField.fieldname,
426
+ targetPkFieldname: getRecordIdField(targetMeta.fields),
427
+ targetTable: resolveTableName(targetMeta.name, tables)
428
+ });
429
+ }
430
+ return specs;
226
431
  }
227
- async function ie(e, t, o, n, r) {
228
- const i = He(t, n);
229
- i.length === 0 || o.length === 0 || await Promise.all(
230
- i.map(async (a) => {
231
- const u = /* @__PURE__ */ new Set();
232
- for (const y of o) {
233
- const f = Z(y[a.fieldname]);
234
- f !== void 0 && u.add(f);
235
- }
236
- if (u.size === 0) return;
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
- values: [Array.from(u)]
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
- }
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
- }
251
- })
252
- );
432
+ /**
433
+ * Replace inline link FK scalars with `{ id, displayText }` when the target doctype declares a
434
+ * `displayField`. Expanded relations (object values) are skipped.
435
+ *
436
+ * Takes every row at once and issues one lookup per FK field, not per row. Callers holding a batch
437
+ * must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the
438
+ * loader exists to prevent, and does so invisibly, since the result is identical either way.
439
+ */
440
+ async function enrichLinkDisplayFields(pgClient, meta, rows, tables, debugSql) {
441
+ const specs = collectLinkDisplaySpecs(meta, tables);
442
+ if (specs.length === 0 || rows.length === 0) return;
443
+ await Promise.all(specs.map(async (spec) => {
444
+ const ids = /* @__PURE__ */ new Set();
445
+ for (const row of rows) {
446
+ const id = scalarText(row[spec.fieldname]);
447
+ if (id !== void 0) ids.add(id);
448
+ }
449
+ if (ids.size === 0) return;
450
+ const pkColumn = camelToSnake(spec.targetPkFieldname);
451
+ const displayColumn = camelToSnake(spec.displayField);
452
+ const displayAlias = displayColumn !== spec.displayField ? `"${displayColumn}" AS "${spec.displayField}"` : `"${spec.displayField}"`;
453
+ const { rows: displayRows } = await debugSql(pgClient, {
454
+ text: `SELECT "${pkColumn}" AS "${spec.targetPkFieldname}", ${displayAlias} FROM ${spec.targetTable} WHERE "${pkColumn}"::text = ANY($1::text[])`,
455
+ values: [Array.from(ids)]
456
+ });
457
+ const displayById = /* @__PURE__ */ new Map();
458
+ for (const displayRow of displayRows) {
459
+ const key = scalarText(displayRow[spec.targetPkFieldname]);
460
+ const text = scalarText(displayRow[spec.displayField]);
461
+ if (key === void 0 || text === void 0) continue;
462
+ displayById.set(key, text);
463
+ }
464
+ for (const row of rows) {
465
+ const rawId = row[spec.fieldname];
466
+ const idKey = scalarText(rawId);
467
+ if (idKey === void 0) continue;
468
+ const displayText = displayById.get(idKey);
469
+ if (displayText === void 0) continue;
470
+ row[spec.fieldname] = {
471
+ id: rawId,
472
+ displayText
473
+ };
474
+ }
475
+ }));
253
476
  }
254
- const qe = Le`
477
+ //#endregion
478
+ //#region src/typeDefs.ts
479
+ /**
480
+ * GraphQL type definitions for Stonecrop's middleware API.
481
+ * Includes stonecropMeta, stonecropRecord, stonecropRecords, stonecropAction, and related types.
482
+ * @public
483
+ */
484
+ var typeDefs = gql`
255
485
  type StonecropFieldMeta {
256
486
  kind: String!
257
487
  fieldname: String!
@@ -363,494 +593,732 @@ const qe = Le`
363
593
  stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
364
594
  }
365
595
  `;
366
- class he extends Error {
367
- constructor(t) {
368
- super(t.error ?? "Action failed"), this.outcome = t, this.name = "ActionRolledBack";
369
- }
370
- outcome;
371
- }
372
- const pe = "__stonecropLinkFk_", V = "status", lt = (e = {}) => {
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 Ie((n) => {
375
- const r = n.input?.pgRegistry?.pgExecutors, i = r ? Object.values(r)[0] : void 0;
376
- if (!i)
377
- throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
378
- return e.actionHandlers && Je(e.actionHandlers), Ke(), {
379
- typeDefs: qe,
380
- objects: {
381
- Query: {
382
- plans: {
383
- stonecropMeta(a, { $doctype: u }) {
384
- return Te(u, (b) => L(String(b)) ?? null);
385
- },
386
- stonecropAllMeta() {
387
- return Ne($e());
388
- },
389
- stonecropRecord(a, { $doctype: u, $id: b, $options: E }) {
390
- return fe(
391
- i,
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
- }
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
- continue;
405
- }
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
- }
414
- const F = [
415
- U,
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
- throw new Error(
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
- );
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
- continue;
431
- }
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
- continue;
443
- }
444
- if (se(T, B.get(_)?.component) === "inline") continue;
445
- const q = L(T.target);
446
- if (!q) continue;
447
- const ue = ee(q);
448
- if (ne) {
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
- values: z
457
- });
458
- Q != null && oe.length > Q ? (k.push(_), d[_] = oe.slice(0, Q)) : d[_] = oe;
459
- } else {
460
- const J = d[`${pe}${_}`];
461
- if (J == null) {
462
- d[_] = null;
463
- continue;
464
- }
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
- values: [J]
470
- });
471
- d[_] = X[0] ?? null;
472
- }
473
- }
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
- doctype: f,
479
- unknownLinks: j?.length ? j : void 0,
480
- truncatedLinks: k.length ? k : void 0
481
- };
482
- }
483
- await ie(v, w, m, e.tables, t);
484
- }
485
- return y;
486
- }
487
- );
488
- },
489
- stonecropRecords(a, { $doctype: u, $filters: b, $orderBy: E, $limit: v, $offset: p, $includeTotal: g }) {
490
- return fe(
491
- i,
492
- re({
493
- doctype: u,
494
- filters: b,
495
- orderBy: E,
496
- limit: v,
497
- offset: p,
498
- includeTotal: g
499
- }),
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
- }
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
- }
528
- if (F === "") {
529
- const d = Y($);
530
- d && (F = ` ORDER BY "${R(d.fieldname)}" ASC`);
531
- }
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
- });
552
- S = parseInt(I[0]?.row_count ?? "0", 10);
553
- }
554
- return { data: h, doctype: w, hasMore: c, count: S };
555
- })
556
- )
557
- );
558
- }
559
- }
560
- },
561
- Mutation: {
562
- plans: {
563
- stonecropAction(a, { $doctype: u, $action: b, $args: E }) {
564
- return Fe(
565
- i,
566
- re({ doctype: u, action: b, actionArgs: E }),
567
- async (v, p) => {
568
- const g = L(String(p.doctype));
569
- if (!g)
570
- return {
571
- success: !1,
572
- data: null,
573
- error: `Unknown doctype: ${p.doctype}`
574
- };
575
- const y = g.workflow?.actions?.[p.action];
576
- if (!y)
577
- return {
578
- success: !1,
579
- data: null,
580
- error: `Unknown action: ${p.action} on ${p.doctype}`
581
- };
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);
597
- continue;
598
- }
599
- if (S !== null && typeof S == "object") {
600
- F.push(h);
601
- continue;
602
- }
603
- m.push(R(h)), c.push(S);
604
- }
605
- return { cols: m, values: c };
606
- };
607
- try {
608
- return await v.withTransaction(async (s) => {
609
- const m = await We(
610
- y,
611
- {
612
- readState: async () => {
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)]
617
- });
618
- if (h.length === 0) return null;
619
- if (P)
620
- return h[0][V] ?? void 0;
621
- },
622
- writeState: async (c) => {
623
- await t(s, {
624
- text: `UPDATE ${f} SET "${V}" = $1 WHERE "${l()}"::text = $2`,
625
- values: [c, String(A)]
626
- });
627
- },
628
- // The upsert, and the only write path for record data. `exists`
629
- // comes from the guard's own read, so no second lookup decides it.
630
- //
631
- // Returns the same projection the read path selects, never
632
- // `RETURNING *`: raw columns come back snake_case, and the client
633
- // resolves identity by the *declared fieldname*. A doctype keyed
634
- // `itemId` would receive `item_id`, find no identity, and file a
635
- // created record nowhere — which is that exact bug, already once
636
- // shipped and patched downstream.
637
- writeData: async (c, h) => {
638
- const { cols: S, values: d } = N(c), k = ee(g);
639
- if (!h) {
640
- if (A != null)
641
- throw new Error(
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.`
643
- );
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] ?? {};
646
- }
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)]
651
- });
652
- return M[0] ?? {};
653
- }
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)]
657
- });
658
- return I[0] ?? {};
659
- },
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
669
- }) : void 0
670
- },
671
- // The patch a self-transition persists. This adapter never passed it, which
672
- // was moot while it had no `writeData` — nothing consumed it. Wiring the write
673
- // without this argument saves an empty record and reports success.
674
- U
675
- );
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;
684
- });
685
- } catch (s) {
686
- return s instanceof he ? s.outcome : {
687
- success: !1,
688
- data: null,
689
- error: s instanceof Error ? s.message : String(s)
690
- };
691
- }
692
- }
693
- );
694
- }
695
- }
696
- }
697
- }
698
- };
699
- });
596
+ //#endregion
597
+ //#region src/plugin/postgraphile.ts
598
+ /**
599
+ * Carries a reported failure out through a `throw`, purely so the transaction rolls back.
600
+ *
601
+ * `applyGuardedTransition` reports every failure as a return value, and a value returned from
602
+ * inside `withTransaction` commits. This is the adapter between "the action failed" and "undo it"
603
+ * that does not also turn a refused guard into a GraphQL error: the dispatcher unwraps it and
604
+ * answers with the original envelope.
605
+ */
606
+ var ActionRolledBack = class extends Error {
607
+ outcome;
608
+ constructor(outcome) {
609
+ super(outcome.error ?? "Action failed");
610
+ this.outcome = outcome;
611
+ this.name = "ActionRolledBack";
612
+ }
613
+ };
614
+ /**
615
+ * Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can
616
+ * read it. An *expanding* link is a relation in the payload rather than a scalar, so `getSqlColumns`
617
+ * omits its FK column by design — but the expansion needs the value to find the target. Aliasing
618
+ * keeps that need from changing the payload: every alias is stripped before the record is returned.
619
+ */
620
+ var LINK_FK_ALIAS = "__stonecropLinkFk_";
621
+ /**
622
+ * The column this adapter keeps a record's workflow state in.
623
+ *
624
+ * Named once because three statements depend on agreeing about it: the guard's `FOR UPDATE` read,
625
+ * the transition's write, and the data write that must refuse to touch it. A patch that could set
626
+ * this column would let any client walk past `allowedStates` by writing the very value the guard
627
+ * reads.
628
+ */
629
+ var STATE_COLUMN = "status";
630
+ /**
631
+ * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
632
+ *
633
+ * The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`
634
+ * during schema construction — it does not need to be supplied by the caller.
635
+ *
636
+ * @param options - Optional plugin configuration
637
+ * @returns A PostGraphile plugin
638
+ * @public
639
+ */
640
+ var createStonecropPlugin = (options = {}) => {
641
+ /**
642
+ * SQL debug helper — mirrors PostGraphile's `@dataplan/pg:PgExecutor` logging
643
+ * for queries that run inside custom loadOneWithPgClient callbacks, which
644
+ * bypass the executor's native instrumentation.
645
+ */
646
+ const debugSql = options.debug ? (pgClient, query) => {
647
+ console.log(`[@stonecrop/graphql-middleware] ${query.text}`, query.values ?? []);
648
+ return pgClient.query(query);
649
+ } : (pgClient, query) => pgClient.query(query);
650
+ const defaultRowLimit = options.defaultRecordLimit === void 0 ? 200 : options.defaultRecordLimit;
651
+ return extendSchema((build) => {
652
+ const pgExecutors = build.input?.pgRegistry?.pgExecutors;
653
+ const executor = pgExecutors ? Object.values(pgExecutors)[0] : void 0;
654
+ if (!executor) throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
655
+ if (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers);
656
+ assertReferencesResolve();
657
+ return {
658
+ typeDefs,
659
+ objects: {
660
+ Query: { plans: {
661
+ stonecropMeta(_, { $doctype }) {
662
+ return lambda($doctype, (doctype) => {
663
+ return getMeta(String(doctype)) ?? null;
664
+ });
665
+ },
666
+ stonecropAllMeta() {
667
+ return constant(getAllMeta());
668
+ },
669
+ stonecropRecord(_, { $doctype, $id, $options }) {
670
+ return loadOneWithPgClient(executor, object({
671
+ doctype: $doctype,
672
+ id: $id,
673
+ options: $options
674
+ }), async (pgClient, specs) => {
675
+ const byDoctype = /* @__PURE__ */ new Map();
676
+ for (let i = 0; i < specs.length; i++) {
677
+ const d = String(specs[i].doctype);
678
+ if (!byDoctype.has(d)) byDoctype.set(d, []);
679
+ byDoctype.get(d).push(i);
680
+ }
681
+ const results = Array.from({ length: specs.length });
682
+ for (const [doctype, indices] of byDoctype) {
683
+ const meta = getMeta(doctype);
684
+ if (!meta) {
685
+ for (const i of indices) results[i] = {
686
+ data: null,
687
+ doctype
688
+ };
689
+ continue;
690
+ }
691
+ const pkMeta = getPkMeta(meta);
692
+ if (!pkMeta) throw unresolvableIdentityError(doctype);
693
+ const pkColumn = camelToSnake(pkMeta.fieldname);
694
+ const columns = getSqlColumns(meta);
695
+ const ids = indices.map((i) => String(specs[i].id));
696
+ const fieldByName = new Map(flattenFields$1(meta.fields).map((f) => [f.fieldname, f]));
697
+ const linkFkAliases = [];
698
+ for (const [linkName, link] of Object.entries(meta.links ?? {})) {
699
+ if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") continue;
700
+ const fieldname = link.fieldname ?? linkName;
701
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
702
+ linkFkAliases.push({
703
+ fieldname,
704
+ alias: `${LINK_FK_ALIAS}${fieldname}`
705
+ });
706
+ }
707
+ const selectList = [columns, ...linkFkAliases.map(({ fieldname, alias }) => `"${camelToSnake(fieldname)}" AS "${alias}"`)].filter(Boolean).join(", ");
708
+ const { rows } = await debugSql(pgClient, {
709
+ text: `SELECT ${selectList} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
710
+ values: [ids]
711
+ });
712
+ const rowByPk = new Map(rows.map((r) => [String(r[pkMeta.fieldname]), r]));
713
+ if (rows.length !== rowByPk.size) throw new Error(`Doctype "${doctype}" declares "${pkMeta.fieldname}" as its identity, but that column is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows matched ${rowByPk.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.`);
714
+ const enrichedRows = [];
715
+ for (const i of indices) {
716
+ const specId = String(specs[i].id);
717
+ const row = rowByPk.get(specId);
718
+ if (!row) {
719
+ results[i] = {
720
+ data: null,
721
+ doctype
722
+ };
723
+ continue;
724
+ }
725
+ const rowData = { ...row };
726
+ enrichedRows.push(rowData);
727
+ const truncatedLinks = [];
728
+ const recordOptions = specs[i].options ?? {};
729
+ const includeAll = recordOptions.includeNested === true;
730
+ const includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null;
731
+ if (meta.links) for (const [linkName, link] of Object.entries(meta.links)) {
732
+ const fieldname = link.fieldname ?? linkName;
733
+ const fetch = link.fetch;
734
+ const isMany = link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne";
735
+ const effectiveMethod = fetch?.method ?? (isMany ? "sync" : "lazy");
736
+ const declaredLimit = fetch?.method === "sync" ? fetch.limit : void 0;
737
+ const effectiveLimit = isMany ? declaredLimit ?? defaultRowLimit : void 0;
738
+ if (!(includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === "sync"))) continue;
739
+ if (effectiveMethod === "custom" && fetch?.method === "custom") {
740
+ const handlerName = fetch.handler;
741
+ const handler = getFetchHandler(handlerName);
742
+ if (handler) rowData[fieldname] = await handler(pgClient, rowData, link);
743
+ continue;
744
+ }
745
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
746
+ const targetMeta = getMeta(link.target);
747
+ if (!targetMeta) continue;
748
+ const targetColumns = getSqlColumns(targetMeta);
749
+ if (isMany) {
750
+ if (!link.backlink) continue;
751
+ const backlinkCol = camelToSnake(link.backlink);
752
+ let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
753
+ const linkValues = [specId];
754
+ const linkPkMeta = getPkMeta(targetMeta);
755
+ if (linkPkMeta) sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
756
+ if (effectiveLimit != null) {
757
+ sql += ` LIMIT $2`;
758
+ linkValues.push(effectiveLimit + 1);
759
+ }
760
+ const { rows: linked } = await debugSql(pgClient, {
761
+ text: sql,
762
+ values: linkValues
763
+ });
764
+ if (effectiveLimit != null && linked.length > effectiveLimit) {
765
+ truncatedLinks.push(fieldname);
766
+ rowData[fieldname] = linked.slice(0, effectiveLimit);
767
+ } else rowData[fieldname] = linked;
768
+ } else {
769
+ const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
770
+ if (fkValue == null) {
771
+ rowData[fieldname] = null;
772
+ continue;
773
+ }
774
+ const targetPkMeta = getPkMeta(targetMeta);
775
+ if (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name);
776
+ const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
777
+ const { rows: linked } = await debugSql(pgClient, {
778
+ text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
779
+ values: [fkValue]
780
+ });
781
+ rowData[fieldname] = linked[0] ?? null;
782
+ }
783
+ }
784
+ for (const { alias } of linkFkAliases) delete rowData[alias];
785
+ const unknownLinks = includeSet && meta.links ? [...includeSet].filter((name) => !(name in meta.links)) : void 0;
786
+ results[i] = {
787
+ data: rowData,
788
+ doctype,
789
+ unknownLinks: unknownLinks?.length ? unknownLinks : void 0,
790
+ truncatedLinks: truncatedLinks.length ? truncatedLinks : void 0
791
+ };
792
+ }
793
+ await enrichLinkDisplayFields(pgClient, meta, enrichedRows, options.tables, debugSql);
794
+ }
795
+ return results;
796
+ });
797
+ },
798
+ stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
799
+ return loadOneWithPgClient(executor, object({
800
+ doctype: $doctype,
801
+ filters: $filters,
802
+ orderBy: $orderBy,
803
+ limit: $limit,
804
+ offset: $offset,
805
+ includeTotal: $includeTotal
806
+ }), async (pgClient, specs) => {
807
+ return await Promise.all(specs.map(async (spec) => {
808
+ const doctype = String(spec.doctype);
809
+ const meta = getMeta(doctype);
810
+ if (!meta) return {
811
+ data: [],
812
+ doctype,
813
+ hasMore: false,
814
+ count: spec.includeTotal === true ? 0 : null
815
+ };
816
+ const knownFields = new Set(flattenFields$1(meta.fields).map((f) => f.fieldname));
817
+ const columns = getSqlColumns(meta);
818
+ const values = [];
819
+ const whereClauses = [];
820
+ if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
821
+ if (!knownFields.has(field)) throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
822
+ values.push(value);
823
+ whereClauses.push(`"${camelToSnake(field)}" = $${values.length}`);
824
+ }
825
+ const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(" AND ")}` : "";
826
+ let orderByClause = "";
827
+ if (spec.orderBy != null) {
828
+ if (typeof spec.orderBy !== "string") throw new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`);
829
+ const orderByStr = spec.orderBy;
830
+ const lastUnder = orderByStr.lastIndexOf("_");
831
+ if (lastUnder <= 0) throw new Error(`Invalid orderBy format: "${orderByStr}". Expected FIELD_ASC or FIELD_DESC`);
832
+ const dir = orderByStr.slice(lastUnder + 1).toUpperCase();
833
+ if (dir !== "ASC" && dir !== "DESC") throw new Error(`Invalid orderBy direction: "${dir}". Must be ASC or DESC`);
834
+ const fieldName = orderByStr.slice(0, lastUnder);
835
+ if (!knownFields.has(fieldName)) throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
836
+ orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
837
+ }
838
+ if (orderByClause === "") {
839
+ const listPkMeta = getPkMeta(meta);
840
+ if (listPkMeta) orderByClause = ` ORDER BY "${camelToSnake(listPkMeta.fieldname)}" ASC`;
841
+ }
842
+ if (spec.limit != null && typeof spec.limit !== "number") throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
843
+ const effectiveLimit = spec.limit ?? defaultRowLimit;
844
+ let pagingClause = "";
845
+ if (effectiveLimit != null) {
846
+ values.push(effectiveLimit + 1);
847
+ pagingClause += ` LIMIT $${values.length}`;
848
+ }
849
+ if (spec.offset != null) {
850
+ values.push(spec.offset);
851
+ pagingClause += ` OFFSET $${values.length}`;
852
+ }
853
+ const { rows } = await debugSql(pgClient, {
854
+ text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)}${whereClause}${orderByClause}${pagingClause}`,
855
+ values
856
+ });
857
+ const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
858
+ const data = [...hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows];
859
+ await enrichLinkDisplayFields(pgClient, meta, data, options.tables, debugSql);
860
+ let count = null;
861
+ if (spec.includeTotal === true) {
862
+ const countValues = [];
863
+ const countWhere = [];
864
+ if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
865
+ if (!knownFields.has(field)) continue;
866
+ countValues.push(value);
867
+ countWhere.push(`"${camelToSnake(field)}" = $${countValues.length}`);
868
+ }
869
+ const countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(" AND ")}` : "";
870
+ const { rows: countRows } = await debugSql(pgClient, {
871
+ text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${countWhereClause}`,
872
+ values: countValues
873
+ });
874
+ count = parseInt(countRows[0]?.row_count ?? "0", 10);
875
+ }
876
+ return {
877
+ data,
878
+ doctype,
879
+ hasMore,
880
+ count
881
+ };
882
+ }));
883
+ });
884
+ }
885
+ } },
886
+ Mutation: { plans: { stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
887
+ return sideEffectWithPgClient(executor, object({
888
+ doctype: $doctype,
889
+ action: $action,
890
+ actionArgs: $actionArgs
891
+ }), async (pgClient, spec) => {
892
+ const meta = getMeta(String(spec.doctype));
893
+ if (!meta) return {
894
+ success: false,
895
+ data: null,
896
+ error: `Unknown doctype: ${spec.doctype}`
897
+ };
898
+ const actionDef = meta.workflow?.actions?.[spec.action];
899
+ if (!actionDef) return {
900
+ success: false,
901
+ data: null,
902
+ error: `Unknown action: ${spec.action} on ${spec.doctype}`
903
+ };
904
+ const table = resolveTableName(meta.name, options.tables);
905
+ const pkColumn = () => {
906
+ const pkMeta = getPkMeta(meta);
907
+ if (!pkMeta) throw unresolvableIdentityError(String(spec.doctype));
908
+ return camelToSnake(pkMeta.fieldname);
909
+ };
910
+ const argList = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []).map((entry) => entry?.data ? {
911
+ ...entry,
912
+ data: unwrapInlineLinks(meta.fields, entry.data)
913
+ } : entry);
914
+ const recordId = argList[0]?.id;
915
+ const recordData = argList[0]?.data ?? {};
916
+ const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
917
+ const writable = new Map(columnBackedFields(meta.fields).filter((f) => camelToSnake(f.fieldname) !== STATE_COLUMN).map((f) => [f.fieldname, f]));
918
+ const declaresState = columnBackedFields(meta.fields).some((f) => camelToSnake(f.fieldname) === STATE_COLUMN);
919
+ const droppedFields = [];
920
+ const partitionPatch = (patch) => {
921
+ const cols = [];
922
+ const values = [];
923
+ for (const [key, value] of Object.entries(patch)) {
924
+ if (!writable.has(key)) {
925
+ droppedFields.push(key);
926
+ continue;
927
+ }
928
+ if (value !== null && typeof value === "object") {
929
+ droppedFields.push(key);
930
+ continue;
931
+ }
932
+ cols.push(camelToSnake(key));
933
+ values.push(value);
934
+ }
935
+ return {
936
+ cols,
937
+ values
938
+ };
939
+ };
940
+ try {
941
+ return await pgClient.withTransaction(async (tx) => {
942
+ const outcome = await applyGuardedTransition(actionDef, {
943
+ readState: async () => {
944
+ if (recordId == null) return null;
945
+ const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
946
+ const { rows } = await debugSql(tx, {
947
+ text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
948
+ values: [String(recordId)]
949
+ });
950
+ if (rows.length === 0) return null;
951
+ if (!declaresState) return void 0;
952
+ return rows[0][STATE_COLUMN] ?? void 0;
953
+ },
954
+ writeState: async (nextState) => {
955
+ await debugSql(tx, {
956
+ text: `UPDATE ${table} SET "${STATE_COLUMN}" = $1 WHERE "${pkColumn()}"::text = $2`,
957
+ values: [nextState, String(recordId)]
958
+ });
959
+ },
960
+ writeData: async (patch, exists) => {
961
+ const { cols, values } = partitionPatch(patch);
962
+ const returning = getSqlColumns(meta);
963
+ if (!exists) {
964
+ if (recordId != null) throw new Error(`Action "${actionDef.label ?? spec.action}" targets ${meta.name} "${String(recordId)}", 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.`);
965
+ const text = cols.length ? `INSERT INTO ${table} (${cols.map((c) => `"${c}"`).join(", ")}) VALUES (${cols.map((_col, i) => `$${i + 1}`).join(", ")}) RETURNING ${returning}` : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning}`;
966
+ const { rows } = await debugSql(tx, {
967
+ text,
968
+ values
969
+ });
970
+ return rows[0] ?? {};
971
+ }
972
+ if (cols.length === 0) {
973
+ const { rows } = await debugSql(tx, {
974
+ text: `SELECT ${returning} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
975
+ values: [String(recordId)]
976
+ });
977
+ return rows[0] ?? {};
978
+ }
979
+ const assignments = cols.map((c, i) => `"${c}" = $${i + 1}`).join(", ");
980
+ const { rows } = await debugSql(tx, {
981
+ text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning}`,
982
+ values: [...values, String(recordId)]
983
+ });
984
+ return rows[0] ?? {};
985
+ },
986
+ runEffect: handler ? (currentState) => handler({
987
+ pgClient: tx,
988
+ doctype: String(spec.doctype),
989
+ action: String(spec.action),
990
+ meta,
991
+ recordId,
992
+ data: recordData,
993
+ args: argList,
994
+ currentState
995
+ }) : void 0
996
+ }, recordData);
997
+ if (!outcome.success) throw new ActionRolledBack(outcome);
998
+ if (outcome.success && outcome.data !== null && typeof outcome.data === "object") {
999
+ const written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter((row) => row !== null && typeof row === "object");
1000
+ await enrichLinkDisplayFields(tx, meta, written, options.tables, debugSql);
1001
+ }
1002
+ return droppedFields.length ? {
1003
+ ...outcome,
1004
+ droppedFields
1005
+ } : outcome;
1006
+ });
1007
+ } catch (err) {
1008
+ if (err instanceof ActionRolledBack) return err.outcome;
1009
+ return {
1010
+ success: false,
1011
+ data: null,
1012
+ error: err instanceof Error ? err.message : String(err)
1013
+ };
1014
+ }
1015
+ });
1016
+ } } }
1017
+ }
1018
+ };
1019
+ });
700
1020
  };
701
- function Ue(e, t) {
702
- const o = [];
703
- for (const n of te(e)) {
704
- const r = t.get(n.fieldname);
705
- if (r && se(r, n.component) !== "inline") continue;
706
- const i = R(n.fieldname);
707
- o.push(i !== n.fieldname ? `"${i}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
708
- }
709
- return o;
1021
+ /**
1022
+ * Derive quoted SQL column entries from a flat field array.
1023
+ * Skips non-scalar fields (kind !== 'field'), `computed` fields
1024
+ * (no backing DB column), and *expanding* links
1025
+ * (relations fetched separately, not scalar columns on this table).
1026
+ */
1027
+ function collectColumns(fields, links) {
1028
+ const columns = [];
1029
+ for (const f of columnBackedFields(fields)) {
1030
+ const link = links.get(f.fieldname);
1031
+ if (link && resolveLinkRenderMode(link, f.component) !== "inline") continue;
1032
+ const col = camelToSnake(f.fieldname);
1033
+ columns.push(col !== f.fieldname ? `"${col}" AS "${f.fieldname}"` : `"${f.fieldname}"`);
1034
+ }
1035
+ return columns;
710
1036
  }
711
- function ee(e) {
712
- const t = /* @__PURE__ */ new Map();
713
- if (e.links)
714
- for (const [o, n] of Object.entries(e.links))
715
- t.set(n.fieldname ?? o, n);
716
- return Ue(e.fields, t).join(", ");
1037
+ /**
1038
+ * Derive a quoted SQL column list from doctype field definitions.
1039
+ * Applies camelToSnake to each fieldname to get the DB column name, then
1040
+ * aliases it back to the fieldname so result rows carry API-layer keys.
1041
+ * Excludes `computed` fields (no backing DB column), Fieldset
1042
+ * containers (recursing into their children instead), and *expanding* links
1043
+ * (relations fetched separately). An inline link keeps its FK column here.
1044
+ *
1045
+ * Exported for unit testing (not re-exported from the package index).
1046
+ */
1047
+ function getSqlColumns(meta) {
1048
+ const links = /* @__PURE__ */ new Map();
1049
+ if (meta.links) for (const [key, link] of Object.entries(meta.links)) links.set(link.fieldname ?? key, link);
1050
+ return collectColumns(meta.fields, links).join(", ");
717
1051
  }
718
- function Y(e) {
719
- const t = Se(e.fields);
720
- return K(e.fields).find((o) => o.kind === "field" && o.fieldname === t);
1052
+ /**
1053
+ * Resolve the declared field this doctype's records are looked up by.
1054
+ *
1055
+ * Delegates the *rule* to `@stonecrop/schema` so the server's SQL identity predicate and the
1056
+ * client's record keying name the same field — including the `id` fallback, whose absence here
1057
+ * used to make the two disagree: a doctype declaring no `primaryKey` was keyed by `id` on the
1058
+ * client and refused outright by this adapter, so every fetch answered `null` and looked exactly
1059
+ * like a record that does not exist.
1060
+ *
1061
+ * Returns `undefined` only when the resolved name is not a declared field — a doctype with no
1062
+ * `primaryKey` and no `id`. That case cannot be served: `getSqlColumns` selects declared fields
1063
+ * only, so the row map would key on a column the SELECT never returned and every lookup would miss
1064
+ * silently. Callers must say so rather than answer `null`.
1065
+ *
1066
+ * Descends into fieldsets, because both halves of the question already do — `getSqlColumns` selects
1067
+ * a fieldset's children, and `getRecordIdField` resolves a key declared among them. While this
1068
+ * scanned top level only it could refuse a name that helper had just resolved, so a doctype whose
1069
+ * SELECT carried its own key column had no identity to look that column up by.
1070
+ */
1071
+ function getPkMeta(meta) {
1072
+ const fieldname = getRecordIdField(meta.fields);
1073
+ return flattenFields$1(meta.fields).find((f) => f.kind === "field" && f.fieldname === fieldname);
721
1074
  }
722
- function Je(e) {
723
- const t = Object.entries(e);
724
- if (t.length === 0) return;
725
- if ($e().length === 0) {
726
- console.warn(
727
- "[@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."
728
- );
729
- return;
730
- }
731
- const o = [];
732
- for (const [n, r] of t) {
733
- const i = L(n);
734
- if (!i) {
735
- o.push(`"${n}": no doctype by that name is registered`);
736
- continue;
737
- }
738
- if (i.name !== n) {
739
- o.push(
740
- `"${n}": matches the doctype named "${i.name}" by slug, but handlers are looked up by name — key it "${i.name}"`
741
- );
742
- continue;
743
- }
744
- const a = i.workflow?.actions ?? {};
745
- for (const u of Object.keys(r))
746
- u in a || o.push(`"${n}.${u}": the doctype declares no action by that key`);
747
- }
748
- if (o.length > 0)
749
- throw new Error(
750
- `StonecropPlugin: ${o.length} registered action handler${o.length === 1 ? "" : "s"} cannot be reached and would never run:
751
- ${o.join(`
752
- `)}`
753
- );
1075
+ /**
1076
+ * Assert that every registered action handler names a doctype and an action that exist.
1077
+ *
1078
+ * An unregistered action is fine — a transition needs no effect. The reverse is not: a handler
1079
+ * registered under a key nothing resolves to can never run, and **nothing says so at dispatch**.
1080
+ * `applyGuardedTransition` fails loudly only when the action also has no state outcome; when it
1081
+ * has one, the missing effect is skipped and the state write still reports success. So renaming a
1082
+ * doctype leaves `approve` moving records to APPROVED while its ledger posting quietly stops.
1083
+ *
1084
+ * Two ways a key fails to resolve, and the second is the trap. `getMeta` falls back to matching a
1085
+ * slug, but dispatch looks handlers up by `meta.name`, so a slug-keyed registration resolves to a
1086
+ * real doctype here and still never fires. It is reported as its own case rather than as "unknown
1087
+ * doctype", because the repair is different.
1088
+ *
1089
+ * Throws rather than warns: there is no legitimate reason to register a handler for an action that
1090
+ * does not exist, and the alternative is a silent half-executed workflow. Every offender is
1091
+ * collected so a consumer with several fixes them in one pass.
1092
+ */
1093
+ function assertActionHandlersResolve(actionHandlers) {
1094
+ const registered = Object.entries(actionHandlers);
1095
+ if (registered.length === 0) return;
1096
+ if (getAllMeta().length === 0) {
1097
+ console.warn("[@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.");
1098
+ return;
1099
+ }
1100
+ const orphans = [];
1101
+ for (const [doctypeKey, handlers] of registered) {
1102
+ const meta = getMeta(doctypeKey);
1103
+ if (!meta) {
1104
+ orphans.push(`"${doctypeKey}": no doctype by that name is registered`);
1105
+ continue;
1106
+ }
1107
+ if (meta.name !== doctypeKey) {
1108
+ orphans.push(`"${doctypeKey}": matches the doctype named "${meta.name}" by slug, but handlers are looked up by name — key it "${meta.name}"`);
1109
+ continue;
1110
+ }
1111
+ const actions = meta.workflow?.actions ?? {};
1112
+ for (const actionKey of Object.keys(handlers)) if (!(actionKey in actions)) orphans.push(`"${doctypeKey}.${actionKey}": the doctype declares no action by that key`);
1113
+ }
1114
+ if (orphans.length > 0) throw new Error(`StonecropPlugin: ${orphans.length} registered action handler${orphans.length === 1 ? "" : "s"} cannot be reached and would never run:\n ${orphans.join("\n ")}`);
754
1115
  }
755
- function Ke() {
756
- const e = je();
757
- if (e.length !== 0)
758
- throw new Error(
759
- `StonecropPlugin: ${e.length} doctype reference${e.length === 1 ? "" : "s"} cannot be resolved and would silently drop the relation:
760
- ` + e.map((t) => `${t.path.join(".")}: ${t.message}`).join(`
761
- `)
762
- );
1116
+ /**
1117
+ * Refuse a doctype set whose links or `inherits` name a doctype nobody registered.
1118
+ *
1119
+ * What it prevents is silent: the link read does `const targetMeta = getMeta(link.target)` followed
1120
+ * by `if (!targetMeta) continue`, so an unresolvable target drops the relation from the response
1121
+ * with no error. On the wire that is indistinguishable from "this record has no such relation", and
1122
+ * a typo in a target reads as a legitimately empty link forever.
1123
+ *
1124
+ * Throws rather than warns, like the handler check above: a link pointing at a doctype that does not
1125
+ * exist has no correct reading. Every offender is collected so a consumer fixes them in one pass.
1126
+ *
1127
+ * Deliberately no empty-registry warning, unlike `assertActionHandlersResolve`. That one warns
1128
+ * because a registered handler map is evidence the host meant to be checked; here there is no such
1129
+ * evidence, so warning would fire on every host that loads doctypes after building its schema —
1130
+ * and an advisory that fires on a correct setup is worse than none. An empty registry simply
1131
+ * reports nothing, because the loop has nothing to walk.
1132
+ */
1133
+ function assertReferencesResolve() {
1134
+ const broken = validateReferences();
1135
+ if (broken.length === 0) return;
1136
+ throw new Error(`StonecropPlugin: ${broken.length} doctype reference${broken.length === 1 ? "" : "s"} cannot be resolved and would silently drop the relation:\n ` + broken.map((e) => `${e.path.join(".")}: ${e.message}`).join("\n "));
763
1137
  }
764
- function ae(e) {
765
- return new Error(
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.`
767
- );
1138
+ /**
1139
+ * The error a caller raises when `getPkMeta` cannot resolve an identity field, naming the doctype
1140
+ * and both repairs. Shared so the three lookup sites report one diagnosis.
1141
+ */
1142
+ function unresolvableIdentityError(doctype) {
1143
+ return /* @__PURE__ */ new Error(`Doctype "${doctype}" 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.`);
768
1144
  }
769
- const ct = (e = {}) => {
770
- const { logPlans: t = !0, logTiming: o = !1 } = e, n = (r, i) => ({
771
- plan: (a) => {
772
- t && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${i}`);
773
- const u = o ? Date.now() : 0, b = a();
774
- return o && console.log(
775
- `[@stonecrop/graphql-middleware] Plan built for ${r}.${i} in ${Date.now() - u}ms`
776
- ), b;
777
- }
778
- });
779
- return De({
780
- Query: {
781
- stonecropRecord: n("Query", "stonecropRecord"),
782
- stonecropRecords: n("Query", "stonecropRecords"),
783
- stonecropMeta: n("Query", "stonecropMeta"),
784
- stonecropAllMeta: n("Query", "stonecropAllMeta")
785
- },
786
- Mutation: {
787
- stonecropAction: n("Mutation", "stonecropAction")
788
- }
789
- });
790
- }, ge = {
791
- name: "StonecropNaturalIdPlugin",
792
- version: "0.0.0",
793
- after: ["PgAttributesPlugin"],
794
- inflection: {
795
- replace: {
796
- // Move Relay's global identifier off `id`...
797
- nodeIdFieldName() {
798
- return "nodeId";
799
- },
800
- // ...so the real column can keep its own name.
801
- _attributeName(e, t, o) {
802
- const n = e?.(o) ?? o.attributeName;
803
- if (!o.skipRowId && n === "row_id") {
804
- const { codec: r, attributeName: i } = o, a = r.attributes[i]?.extensions?.tags?.name ?? i;
805
- if (typeof a == "string" && a.toLowerCase() === "id" && !r.isAnonymous)
806
- return "id";
807
- }
808
- return n;
809
- }
810
- }
811
- }
812
- }, me = {
813
- name: "StonecropOwnedRelationsPlugin",
814
- version: "0.0.0",
815
- gather: {
816
- hooks: {
817
- pgRelations_relation(e, t) {
818
- const { relation: o, pgConstraint: n } = t;
819
- o.isReferencee && n.confdeltype === "c" && (o.extensions ??= {}, o.extensions.tags ??= {}, o.extensions.tags.behavior = "+manyRelation:resource:connection");
820
- }
821
- }
822
- }
823
- }, Ge = {
824
- name: "StonecropFieldCasingPlugin",
825
- version: "0.0.0",
826
- inflection: {
827
- replace: {
828
- attribute(e, t, o) {
829
- return this.upperCamelCase(this._attributeName(o));
830
- }
831
- }
832
- }
833
- }, Qe = (e) => ({
834
- extends: [Ce],
835
- plugins: e?.fieldCasing === "pascal" ? [ge, me, Ge] : [ge, me]
836
- }), dt = Qe();
837
- export {
838
- le as DoctypeValidationError,
839
- dt as StonecropPreset,
840
- We as applyGuardedTransition,
841
- st as clearFetchHandlers,
842
- it as clearRegistry,
843
- ct as createDebugPlugin,
844
- lt as createStonecropPlugin,
845
- Qe as createStonecropPreset,
846
- $e as getAllMeta,
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
1145
+ /**
1146
+ * Resolve the PostgreSQL FROM clause target for a doctype.
1147
+ * Uses the `tables` override map first; falls back to camelToSnake(name).
1148
+ * Schema-qualified names (e.g. "orpin.plan") are emitted as "schema"."table".
1149
+ * Values must be bare identifiers or schema.table pairs — not SQL fragments.
1150
+ */
1151
+ //#endregion
1152
+ //#region src/debug.ts
1153
+ /**
1154
+ * Creates a PostGraphile plugin that wraps Stonecrop resolver plans with
1155
+ * debug logging. Use it in your preset file:
1156
+ *
1157
+ * ```typescript
1158
+ * import { createStonecropPlugin, createDebugPlugin } from '@stonecrop/graphql-middleware'
1159
+ *
1160
+ * export default {
1161
+ * plugins: [createStonecropPlugin(), createDebugPlugin()],
1162
+ * }
1163
+ * ```
1164
+ *
1165
+ * Place `createDebugPlugin()` **after** `createStonecropPlugin()` in the
1166
+ * plugins array so the wrapper sees the Stonecrop fields.
1167
+ *
1168
+ * @param options - Optional logging configuration
1169
+ * @returns A PostGraphile plugin
1170
+ * @public
1171
+ */
1172
+ var createDebugPlugin = (options = {}) => {
1173
+ const { logPlans = true, logTiming = false } = options;
1174
+ const wrapField = (typeName, fieldName) => ({ plan: (plan) => {
1175
+ if (logPlans) console.log(`[@stonecrop/graphql-middleware] Building plan for ${typeName}.${fieldName}`);
1176
+ const start = logTiming ? Date.now() : 0;
1177
+ const $result = plan();
1178
+ if (logTiming) console.log(`[@stonecrop/graphql-middleware] Plan built for ${typeName}.${fieldName} in ${Date.now() - start}ms`);
1179
+ return $result;
1180
+ } });
1181
+ return wrapPlans({
1182
+ Query: {
1183
+ stonecropRecord: wrapField("Query", "stonecropRecord"),
1184
+ stonecropRecords: wrapField("Query", "stonecropRecords"),
1185
+ stonecropMeta: wrapField("Query", "stonecropMeta"),
1186
+ stonecropAllMeta: wrapField("Query", "stonecropAllMeta")
1187
+ },
1188
+ Mutation: { stonecropAction: wrapField("Mutation", "stonecropAction") }
1189
+ });
1190
+ };
1191
+ //#endregion
1192
+ //#region src/preset.ts
1193
+ /**
1194
+ * Stops Amber taking `id` for Relay's global object identifier.
1195
+ *
1196
+ * Amber points `nodeIdFieldName` at `id`, so `PgAttributesPlugin` renames any real column called
1197
+ * `id` out of the way to `row_id` -> `rowId`. Stonecrop can use neither name: the middleware
1198
+ * resolves columns with raw SQL through `camelToSnake` and never reads the GraphQL surface, so `id`
1199
+ * is an opaque base64 node id with no column behind it, and `rowId` names a `row_id` that does not
1200
+ * exist. A doctype generated from the un-overridden schema is stamped `primaryKey: true` on that
1201
+ * node id and every read of it then fails on a missing column.
1202
+ *
1203
+ * Both inflectors must move together. Undoing the rename alone collides with the Relay field still
1204
+ * sitting on `id`; disabling `NodePlugin` alone removes the Relay field but leaves the column called
1205
+ * `rowId`, which is strictly worse — it drops the one case that used to warn. Moving the identifier
1206
+ * to `nodeId` keeps Relay working and is the name the schema converter already skips.
1207
+ *
1208
+ * Mirrors `postgraphile/presets/v4`, which reverses exactly these two inflectors.
1209
+ */
1210
+ var StonecropNaturalIdPlugin = {
1211
+ name: "StonecropNaturalIdPlugin",
1212
+ version: "0.0.0",
1213
+ after: ["PgAttributesPlugin"],
1214
+ inflection: { replace: {
1215
+ nodeIdFieldName() {
1216
+ return "nodeId";
1217
+ },
1218
+ _attributeName(previous, options, details) {
1219
+ const name = previous?.(details) ?? details.attributeName;
1220
+ if (!details.skipRowId && name === "row_id") {
1221
+ const { codec, attributeName } = details;
1222
+ const baseName = codec.attributes[attributeName]?.extensions?.tags?.name ?? attributeName;
1223
+ if (typeof baseName === "string" && baseName.toLowerCase() === "id" && !codec.isAnonymous) return "id";
1224
+ }
1225
+ return name;
1226
+ }
1227
+ } }
1228
+ };
1229
+ /**
1230
+ * Exposes the many side of a foreign key the database declares as owning.
1231
+ *
1232
+ * PostGraphile registers both directions of every foreign key, but Amber gives the many side no
1233
+ * `manyRelation:resource:connection` behavior — for a non-unique relation `PgRelationsPlugin`'s
1234
+ * inferred behavior is `["resource:select", behavior]` and nothing more. So a parent type carries
1235
+ * no field for its children, and a doctype generated from that schema can never contain a child
1236
+ * table. Every one a consumer has is hand-authored.
1237
+ *
1238
+ * `ON DELETE CASCADE` is the discriminator because it is the only place a schema states ownership.
1239
+ * `sc_tag.item_id` cascades: the tags are the item's rows and die with it. `sc_order.customer_id`
1240
+ * does not: an order references a party that outlives it. The two are otherwise the same shape, so
1241
+ * no amount of reading the relation itself can separate them — and turning the many side on for
1242
+ * *every* foreign key would make each referenced table look like somebody's child.
1243
+ *
1244
+ * Read at the gather phase rather than from the built relation: `confdeltype` is on the raw
1245
+ * `pg_constraint` and does not survive into `relation.extensions`, which carries only `isIndexed`.
1246
+ *
1247
+ * Connection only, deliberately. The converter recognises a Connection type through
1248
+ * `getConnectionNodeType`; a list field is not a shape it knows, so `+manyRelation:resource:list`
1249
+ * would add a second field per relation that generation then drops on the floor.
1250
+ *
1251
+ * A global `preset.schema.defaultBehavior` cannot do this. Inferred behaviors are applied after the
1252
+ * global default and take precedence, so `+manyRelation:resource:connection` there is overridden
1253
+ * for every relation — verified, it changes nothing, while `-connection +list` through the same
1254
+ * option visibly rewrites the Query fields.
1255
+ */
1256
+ var StonecropOwnedRelationsPlugin = {
1257
+ name: "StonecropOwnedRelationsPlugin",
1258
+ version: "0.0.0",
1259
+ gather: { hooks: { pgRelations_relation(_info, event) {
1260
+ const { relation, pgConstraint } = event;
1261
+ if (!relation.isReferencee) return;
1262
+ if (pgConstraint.confdeltype !== "c") return;
1263
+ relation.extensions ??= {};
1264
+ relation.extensions.tags ??= {};
1265
+ relation.extensions.tags.behavior = "+manyRelation:resource:connection";
1266
+ } } }
855
1267
  };
856
- //# sourceMappingURL=index.js.map
1268
+ var StonecropFieldCasingPlugin = {
1269
+ name: "StonecropFieldCasingPlugin",
1270
+ version: "0.0.0",
1271
+ inflection: { replace: { attribute(previous, options, details) {
1272
+ return this.upperCamelCase(this._attributeName(details));
1273
+ } } }
1274
+ };
1275
+ /**
1276
+ * Creates a Stonecrop-flavoured PostGraphile preset.
1277
+ *
1278
+ * The returned preset extends `PostGraphileAmberPreset` and applies Stonecrop's
1279
+ * recommended defaults. Pass it to `extends` in your PostGraphile configuration:
1280
+ *
1281
+ * ```typescript
1282
+ * import { createStonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'
1283
+ *
1284
+ * export default {
1285
+ * extends: [createStonecropPreset()],
1286
+ * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL, schemas: ['public'] })],
1287
+ * plugins: [createStonecropPlugin()],
1288
+ * }
1289
+ * ```
1290
+ *
1291
+ * @param options - Optional configuration. Pass `{ fieldCasing: 'pascal' }` to enable
1292
+ * `MyColumn`-style field names instead of the default `myColumn` (camelCase).
1293
+ * @public
1294
+ */
1295
+ var createStonecropPreset = (options) => ({
1296
+ extends: [PostGraphileAmberPreset],
1297
+ plugins: options?.fieldCasing === "pascal" ? [
1298
+ StonecropNaturalIdPlugin,
1299
+ StonecropOwnedRelationsPlugin,
1300
+ StonecropFieldCasingPlugin
1301
+ ] : [StonecropNaturalIdPlugin, StonecropOwnedRelationsPlugin]
1302
+ });
1303
+ /**
1304
+ * The default Stonecrop PostGraphile preset with camelCase field names.
1305
+ *
1306
+ * Equivalent to `createStonecropPreset()` with no options. Use this when you
1307
+ * do not need to customise field casing:
1308
+ *
1309
+ * ```typescript
1310
+ * import { StonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'
1311
+ *
1312
+ * export default {
1313
+ * extends: [StonecropPreset],
1314
+ * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],
1315
+ * plugins: [createStonecropPlugin()],
1316
+ * }
1317
+ * ```
1318
+ * @public
1319
+ */
1320
+ var StonecropPreset = createStonecropPreset();
1321
+ //#endregion
1322
+ export { DoctypeValidationError, StonecropPreset, applyGuardedTransition, clearFetchHandlers, clearRegistry, createDebugPlugin, createStonecropPlugin, createStonecropPreset, getAllMeta, getFetchHandler, getMeta, hasMeta, loadDoctypes, loadDoctypesFromObject, makePgService, registerFetchHandler, typeDefs };
1323
+
1324
+ //# sourceMappingURL=index.js.map