@stonecrop/graphql-middleware 0.44.0 → 0.45.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
@@ -288,14 +288,18 @@ function clearFetchHandlers() {
288
288
  * handler never overrides the guard.
289
289
  *
290
290
  * There are four action shapes this distinguishes:
291
+ *
291
292
  * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.
293
+ *
292
294
  * - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current
293
295
  * state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.
294
296
  * When the target record does not exist the same write creates it — saving a record is one
295
297
  * request whether or not the row is there yet, so there is no separate create action, no create
296
298
  * mutation, and no second write path for it.
299
+ *
297
300
  * - A **stateless command** (neither of the above) with an `io.runEffect`: the handler is the whole
298
301
  * outcome. Still guarded by `allowedStates`, and still forbidden from moving the record.
302
+ *
299
303
  * - Anything else — no `nextState`, no `selfTransition`, no registered effect — is either a genuine
300
304
  * authoring mistake or a command whose handler was never wired. It fails loudly before touching
301
305
  * the backend rather than reporting a false success.
@@ -499,10 +503,10 @@ function createColumnReader(codecs, executor, tables) {
499
503
  const schemas = matches.map((codec) => codec.extensions?.pg?.schemaName).join(", ");
500
504
  throw new Error(`Doctype "${doctype}" reads ${quoted}, a name PostGraphile knows in more than one schema (${schemas}). Map the doctype in \`tables\` to "schema.table".`);
501
505
  };
502
- const findColumnCodec = (doctype, tableCodec, column) => {
506
+ const findAttribute = (doctype, tableCodec, column) => {
503
507
  const attribute = tableCodec.attributes?.[column];
504
508
  if (!attribute) throw new Error(`Doctype "${doctype}" declares a field for column "${column}", which ${resolveTableName(doctype, tables)} does not have.`);
505
- return attribute.codec;
509
+ return attribute;
506
510
  };
507
511
  return {
508
512
  select(doctype, selections) {
@@ -512,7 +516,7 @@ function createColumnReader(codecs, executor, tables) {
512
516
  return {
513
517
  table,
514
518
  list: selections.map(({ column, alias }) => {
515
- const columnCodec = findColumnCodec(doctype, tableCodec, column);
519
+ const columnCodec = findAttribute(doctype, tableCodec, column).codec;
516
520
  const conversion = momentConversion(columnCodec);
517
521
  const readCodec = conversion?.codec ?? columnCodec;
518
522
  const columnSql = conversion ? sql`${sql.identifier(column)}${conversion.castSql}` : sql.identifier(column);
@@ -535,8 +539,12 @@ function createColumnReader(codecs, executor, tables) {
535
539
  };
536
540
  },
537
541
  bind(doctype, column, placeholder) {
538
- const conversion = momentConversion(findColumnCodec(doctype, findTableCodec(doctype), column));
542
+ const conversion = momentConversion(findAttribute(doctype, findTableCodec(doctype), column).codec);
539
543
  return conversion ? `${placeholder}::${conversion.type}` : placeholder;
544
+ },
545
+ writable(doctype, column) {
546
+ const { extensions } = findAttribute(doctype, findTableCodec(doctype), column);
547
+ return extensions?.isInsertable !== false || extensions?.isUpdatable !== false;
540
548
  }
541
549
  };
542
550
  }
@@ -807,391 +815,400 @@ var createStonecropPlugin = (options = {}) => {
807
815
  return pgClient.query(query);
808
816
  } : (pgClient, query) => pgClient.query(query);
809
817
  const defaultRowLimit = options.defaultRecordLimit === void 0 ? 200 : options.defaultRecordLimit;
810
- return extendSchema((build) => {
811
- const pgRegistry = build.input?.pgRegistry;
812
- const executor = pgRegistry?.pgExecutors ? Object.values(pgRegistry.pgExecutors)[0] : void 0;
813
- if (!executor) throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
814
- const columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables);
815
- if (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers);
816
- assertReferencesResolve();
817
- /** Reads each requested record, batched by doctype: what `stonecropRecord` serves, and what an action replies with. */
818
- const readRecords = async (pgClient, specs) => {
819
- const byDoctype = /* @__PURE__ */ new Map();
820
- for (let i = 0; i < specs.length; i++) {
821
- const d = String(specs[i].doctype);
822
- if (!byDoctype.has(d)) byDoctype.set(d, []);
823
- byDoctype.get(d).push(i);
824
- }
825
- const results = Array.from({ length: specs.length });
826
- for (const [doctype, indices] of byDoctype) {
827
- const meta = getMeta(doctype);
828
- if (!meta) {
829
- for (const i of indices) results[i] = {
830
- data: null,
831
- doctype
832
- };
833
- continue;
834
- }
835
- const pkMeta = getPkMeta(meta);
836
- if (!pkMeta) throw unresolvableIdentityError(doctype);
837
- const pkColumn = camelToSnake(pkMeta.fieldname);
838
- const ids = indices.map((i) => String(specs[i].id));
839
- const fieldByName = new Map(flattenFields$1(meta.fields).map((f) => [f.fieldname, f]));
840
- const linkFkAliases = [];
841
- for (const [linkName, link] of Object.entries(meta.links ?? {})) {
842
- if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") continue;
843
- const fieldname = link.fieldname ?? linkName;
844
- if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
845
- linkFkAliases.push({
846
- fieldname,
847
- alias: `${LINK_FK_ALIAS}${fieldname}`
848
- });
818
+ return {
819
+ ...extendSchema((build) => {
820
+ const pgRegistry = build.input?.pgRegistry;
821
+ const executor = pgRegistry?.pgExecutors ? Object.values(pgRegistry.pgExecutors)[0] : void 0;
822
+ if (!executor) throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
823
+ const columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables);
824
+ if (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers);
825
+ assertReferencesResolve();
826
+ /** Reads each requested record, batched by doctype: what `stonecropRecord` serves, and what an action replies with. */
827
+ const readRecords = async (pgClient, specs) => {
828
+ const byDoctype = /* @__PURE__ */ new Map();
829
+ for (let i = 0; i < specs.length; i++) {
830
+ const d = String(specs[i].doctype);
831
+ if (!byDoctype.has(d)) byDoctype.set(d, []);
832
+ byDoctype.get(d).push(i);
849
833
  }
850
- const select = columns.select(meta.name, [...getColumnSelections(meta), ...linkFkAliases.map(({ fieldname, alias }) => ({
851
- column: camelToSnake(fieldname),
852
- alias
853
- }))]);
854
- const { rows } = await debugSql(pgClient, {
855
- text: `SELECT ${select.list} FROM ${select.table} WHERE "${pkColumn}"::text = ANY($1::text[])`,
856
- values: [ids]
857
- });
858
- select.decodeRows(rows);
859
- const rowByPk = new Map(rows.map((r) => [String(r[pkMeta.fieldname]), r]));
860
- 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.`);
861
- const enrichedRows = [];
862
- for (const i of indices) {
863
- const specId = String(specs[i].id);
864
- const row = rowByPk.get(specId);
865
- if (!row) {
866
- results[i] = {
834
+ const results = Array.from({ length: specs.length });
835
+ for (const [doctype, indices] of byDoctype) {
836
+ const meta = getMeta(doctype);
837
+ if (!meta) {
838
+ for (const i of indices) results[i] = {
867
839
  data: null,
868
840
  doctype
869
841
  };
870
842
  continue;
871
843
  }
872
- const rowData = { ...row };
873
- enrichedRows.push(rowData);
874
- const truncatedLinks = [];
875
- const recordOptions = specs[i].options ?? {};
876
- const includeAll = recordOptions.includeNested === true;
877
- const includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null;
878
- if (meta.links) for (const [linkName, link] of Object.entries(meta.links)) {
844
+ const pkMeta = getPkMeta(meta);
845
+ if (!pkMeta) throw unresolvableIdentityError(doctype);
846
+ const pkColumn = camelToSnake(pkMeta.fieldname);
847
+ const ids = indices.map((i) => String(specs[i].id));
848
+ const fieldByName = new Map(flattenFields$1(meta.fields).map((f) => [f.fieldname, f]));
849
+ const linkFkAliases = [];
850
+ for (const [linkName, link] of Object.entries(meta.links ?? {})) {
851
+ if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") continue;
879
852
  const fieldname = link.fieldname ?? linkName;
880
- const fetch = link.fetch;
881
- const isMany = link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne";
882
- const effectiveMethod = fetch?.method ?? (isMany ? "sync" : "lazy");
883
- const declaredLimit = fetch?.method === "sync" ? fetch.limit : void 0;
884
- const effectiveLimit = isMany ? declaredLimit ?? defaultRowLimit : void 0;
885
- if (!(includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === "sync"))) continue;
886
- if (effectiveMethod === "custom" && fetch?.method === "custom") {
887
- const handlerName = fetch.handler;
888
- const handler = getFetchHandler(handlerName);
889
- if (handler) rowData[fieldname] = await handler(pgClient, rowData, link);
853
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
854
+ linkFkAliases.push({
855
+ fieldname,
856
+ alias: `${LINK_FK_ALIAS}${fieldname}`
857
+ });
858
+ }
859
+ const select = columns.select(meta.name, [...getColumnSelections(meta), ...linkFkAliases.map(({ fieldname, alias }) => ({
860
+ column: camelToSnake(fieldname),
861
+ alias
862
+ }))]);
863
+ const { rows } = await debugSql(pgClient, {
864
+ text: `SELECT ${select.list} FROM ${select.table} WHERE "${pkColumn}"::text = ANY($1::text[])`,
865
+ values: [ids]
866
+ });
867
+ select.decodeRows(rows);
868
+ const rowByPk = new Map(rows.map((r) => [String(r[pkMeta.fieldname]), r]));
869
+ 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.`);
870
+ const enrichedRows = [];
871
+ for (const i of indices) {
872
+ const specId = String(specs[i].id);
873
+ const row = rowByPk.get(specId);
874
+ if (!row) {
875
+ results[i] = {
876
+ data: null,
877
+ doctype
878
+ };
890
879
  continue;
891
880
  }
892
- if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
893
- const targetMeta = getMeta(link.target);
894
- if (!targetMeta) continue;
895
- const targetSelect = columns.select(targetMeta.name, getColumnSelections(targetMeta));
896
- if (isMany) {
897
- if (!link.backlink) continue;
898
- const backlinkCol = camelToSnake(link.backlink);
899
- let sql = `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE "${backlinkCol}"::text = $1`;
900
- const linkValues = [specId];
901
- const linkPkMeta = getPkMeta(targetMeta);
902
- if (linkPkMeta) sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
903
- if (effectiveLimit != null) {
904
- sql += ` LIMIT $2`;
905
- linkValues.push(effectiveLimit + 1);
906
- }
907
- const { rows: linked } = await debugSql(pgClient, {
908
- text: sql,
909
- values: linkValues
910
- });
911
- targetSelect.decodeRows(linked);
912
- if (effectiveLimit != null && linked.length > effectiveLimit) {
913
- truncatedLinks.push(fieldname);
914
- rowData[fieldname] = linked.slice(0, effectiveLimit);
915
- } else rowData[fieldname] = linked;
916
- } else {
917
- const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
918
- if (fkValue == null) {
919
- rowData[fieldname] = null;
881
+ const rowData = { ...row };
882
+ enrichedRows.push(rowData);
883
+ const truncatedLinks = [];
884
+ const recordOptions = specs[i].options ?? {};
885
+ const includeAll = recordOptions.includeNested === true;
886
+ const includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null;
887
+ if (meta.links) for (const [linkName, link] of Object.entries(meta.links)) {
888
+ const fieldname = link.fieldname ?? linkName;
889
+ const fetch = link.fetch;
890
+ const isMany = link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne";
891
+ const effectiveMethod = fetch?.method ?? (isMany ? "sync" : "lazy");
892
+ const declaredLimit = fetch?.method === "sync" ? fetch.limit : void 0;
893
+ const effectiveLimit = isMany ? declaredLimit ?? defaultRowLimit : void 0;
894
+ if (!(includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === "sync"))) continue;
895
+ if (effectiveMethod === "custom" && fetch?.method === "custom") {
896
+ const handlerName = fetch.handler;
897
+ const handler = getFetchHandler(handlerName);
898
+ if (handler) rowData[fieldname] = await handler(pgClient, rowData, link);
920
899
  continue;
921
900
  }
922
- const targetPkMeta = getPkMeta(targetMeta);
923
- if (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name);
924
- const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
925
- const { rows: linked } = await debugSql(pgClient, {
926
- text: `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE "${targetPkColumn}" = $1`,
927
- values: [fkValue]
928
- });
929
- targetSelect.decodeRows(linked);
930
- rowData[fieldname] = linked[0] ?? null;
931
- }
932
- }
933
- for (const { alias } of linkFkAliases) delete rowData[alias];
934
- const unknownLinks = includeSet && meta.links ? [...includeSet].filter((name) => !(name in meta.links)) : void 0;
935
- results[i] = {
936
- data: rowData,
937
- doctype,
938
- unknownLinks: unknownLinks?.length ? unknownLinks : void 0,
939
- truncatedLinks: truncatedLinks.length ? truncatedLinks : void 0
940
- };
941
- }
942
- await enrichLinkDisplayFields(pgClient, meta, enrichedRows, columns, debugSql);
943
- }
944
- return results;
945
- };
946
- return {
947
- typeDefs,
948
- objects: {
949
- Query: { plans: {
950
- stonecropMeta(_, { $doctype }) {
951
- return lambda($doctype, (doctype) => {
952
- return getMeta(String(doctype)) ?? null;
953
- });
954
- },
955
- stonecropAllMeta() {
956
- return constant(getAllMeta());
957
- },
958
- stonecropRecord(_, { $doctype, $id, $options }) {
959
- return loadOneWithPgClient(executor, object({
960
- doctype: $doctype,
961
- id: $id,
962
- options: $options
963
- }), readRecords);
964
- },
965
- stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
966
- return loadOneWithPgClient(executor, object({
967
- doctype: $doctype,
968
- filters: $filters,
969
- orderBy: $orderBy,
970
- limit: $limit,
971
- offset: $offset,
972
- includeTotal: $includeTotal
973
- }), async (pgClient, specs) => {
974
- return await Promise.all(specs.map(async (spec) => {
975
- const doctype = String(spec.doctype);
976
- const meta = getMeta(doctype);
977
- if (!meta) return {
978
- data: [],
979
- doctype,
980
- hasMore: false,
981
- count: spec.includeTotal === true ? 0 : null
982
- };
983
- const knownFields = new Set(flattenFields$1(meta.fields).map((f) => f.fieldname));
984
- const select = columns.select(meta.name, getColumnSelections(meta));
985
- const filterValues = [];
986
- const whereClauses = [];
987
- if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
988
- if (!knownFields.has(field)) throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
989
- filterValues.push(value);
990
- const column = camelToSnake(field);
991
- whereClauses.push(`"${column}" = ${columns.bind(meta.name, column, `$${filterValues.length}`)}`);
992
- }
993
- const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(" AND ")}` : "";
994
- const values = [...filterValues];
995
- let orderByClause = "";
996
- if (spec.orderBy != null) {
997
- if (typeof spec.orderBy !== "string") throw new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`);
998
- const orderByStr = spec.orderBy;
999
- const lastUnder = orderByStr.lastIndexOf("_");
1000
- if (lastUnder <= 0) throw new Error(`Invalid orderBy format: "${orderByStr}". Expected FIELD_ASC or FIELD_DESC`);
1001
- const dir = orderByStr.slice(lastUnder + 1).toUpperCase();
1002
- if (dir !== "ASC" && dir !== "DESC") throw new Error(`Invalid orderBy direction: "${dir}". Must be ASC or DESC`);
1003
- const fieldName = orderByStr.slice(0, lastUnder);
1004
- if (!knownFields.has(fieldName)) throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
1005
- orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
1006
- }
1007
- if (orderByClause === "") {
1008
- const listPkMeta = getPkMeta(meta);
1009
- if (listPkMeta) orderByClause = ` ORDER BY "${camelToSnake(listPkMeta.fieldname)}" ASC`;
1010
- }
1011
- if (spec.limit != null && typeof spec.limit !== "number") throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
1012
- const effectiveLimit = spec.limit ?? defaultRowLimit;
1013
- let pagingClause = "";
901
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
902
+ const targetMeta = getMeta(link.target);
903
+ if (!targetMeta) continue;
904
+ const targetSelect = columns.select(targetMeta.name, getColumnSelections(targetMeta));
905
+ if (isMany) {
906
+ if (!link.backlink) continue;
907
+ const backlinkCol = camelToSnake(link.backlink);
908
+ let sql = `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE "${backlinkCol}"::text = $1`;
909
+ const linkValues = [specId];
910
+ const linkPkMeta = getPkMeta(targetMeta);
911
+ if (linkPkMeta) sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
1014
912
  if (effectiveLimit != null) {
1015
- values.push(effectiveLimit + 1);
1016
- pagingClause += ` LIMIT $${values.length}`;
913
+ sql += ` LIMIT $2`;
914
+ linkValues.push(effectiveLimit + 1);
1017
915
  }
1018
- if (spec.offset != null) {
1019
- values.push(spec.offset);
1020
- pagingClause += ` OFFSET $${values.length}`;
916
+ const { rows: linked } = await debugSql(pgClient, {
917
+ text: sql,
918
+ values: linkValues
919
+ });
920
+ targetSelect.decodeRows(linked);
921
+ if (effectiveLimit != null && linked.length > effectiveLimit) {
922
+ truncatedLinks.push(fieldname);
923
+ rowData[fieldname] = linked.slice(0, effectiveLimit);
924
+ } else rowData[fieldname] = linked;
925
+ } else {
926
+ const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
927
+ if (fkValue == null) {
928
+ rowData[fieldname] = null;
929
+ continue;
1021
930
  }
1022
- const { rows } = await debugSql(pgClient, {
1023
- text: `SELECT ${select.list} FROM ${select.table}${whereClause}${orderByClause}${pagingClause}`,
1024
- values
931
+ const targetPkMeta = getPkMeta(targetMeta);
932
+ if (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name);
933
+ const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
934
+ const { rows: linked } = await debugSql(pgClient, {
935
+ text: `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE "${targetPkColumn}" = $1`,
936
+ values: [fkValue]
1025
937
  });
1026
- select.decodeRows(rows);
1027
- const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
1028
- const data = [...hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows];
1029
- await enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql);
1030
- let count = null;
1031
- if (spec.includeTotal === true) {
1032
- const { rows: countRows } = await debugSql(pgClient, {
1033
- text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${whereClause}`,
1034
- values: filterValues
938
+ targetSelect.decodeRows(linked);
939
+ rowData[fieldname] = linked[0] ?? null;
940
+ }
941
+ }
942
+ for (const { alias } of linkFkAliases) delete rowData[alias];
943
+ const unknownLinks = includeSet && meta.links ? [...includeSet].filter((name) => !(name in meta.links)) : void 0;
944
+ results[i] = {
945
+ data: rowData,
946
+ doctype,
947
+ unknownLinks: unknownLinks?.length ? unknownLinks : void 0,
948
+ truncatedLinks: truncatedLinks.length ? truncatedLinks : void 0
949
+ };
950
+ }
951
+ await enrichLinkDisplayFields(pgClient, meta, enrichedRows, columns, debugSql);
952
+ }
953
+ return results;
954
+ };
955
+ return {
956
+ typeDefs,
957
+ objects: {
958
+ Query: { plans: {
959
+ stonecropMeta(_, { $doctype }) {
960
+ return lambda($doctype, (doctype) => {
961
+ return getMeta(String(doctype)) ?? null;
962
+ });
963
+ },
964
+ stonecropAllMeta() {
965
+ return constant(getAllMeta());
966
+ },
967
+ stonecropRecord(_, { $doctype, $id, $options }) {
968
+ return loadOneWithPgClient(executor, object({
969
+ doctype: $doctype,
970
+ id: $id,
971
+ options: $options
972
+ }), readRecords);
973
+ },
974
+ stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
975
+ return loadOneWithPgClient(executor, object({
976
+ doctype: $doctype,
977
+ filters: $filters,
978
+ orderBy: $orderBy,
979
+ limit: $limit,
980
+ offset: $offset,
981
+ includeTotal: $includeTotal
982
+ }), async (pgClient, specs) => {
983
+ return await Promise.all(specs.map(async (spec) => {
984
+ const doctype = String(spec.doctype);
985
+ const meta = getMeta(doctype);
986
+ if (!meta) return {
987
+ data: [],
988
+ doctype,
989
+ hasMore: false,
990
+ count: spec.includeTotal === true ? 0 : null
991
+ };
992
+ const knownFields = new Set(flattenFields$1(meta.fields).map((f) => f.fieldname));
993
+ const select = columns.select(meta.name, getColumnSelections(meta));
994
+ const filterValues = [];
995
+ const whereClauses = [];
996
+ if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
997
+ if (!knownFields.has(field)) throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
998
+ filterValues.push(value);
999
+ const column = camelToSnake(field);
1000
+ whereClauses.push(`"${column}" = ${columns.bind(meta.name, column, `$${filterValues.length}`)}`);
1001
+ }
1002
+ const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(" AND ")}` : "";
1003
+ const values = [...filterValues];
1004
+ let orderByClause = "";
1005
+ if (spec.orderBy != null) {
1006
+ if (typeof spec.orderBy !== "string") throw new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`);
1007
+ const orderByStr = spec.orderBy;
1008
+ const lastUnder = orderByStr.lastIndexOf("_");
1009
+ if (lastUnder <= 0) throw new Error(`Invalid orderBy format: "${orderByStr}". Expected FIELD_ASC or FIELD_DESC`);
1010
+ const dir = orderByStr.slice(lastUnder + 1).toUpperCase();
1011
+ if (dir !== "ASC" && dir !== "DESC") throw new Error(`Invalid orderBy direction: "${dir}". Must be ASC or DESC`);
1012
+ const fieldName = orderByStr.slice(0, lastUnder);
1013
+ if (!knownFields.has(fieldName)) throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
1014
+ orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
1015
+ }
1016
+ if (orderByClause === "") {
1017
+ const listPkMeta = getPkMeta(meta);
1018
+ if (listPkMeta) orderByClause = ` ORDER BY "${camelToSnake(listPkMeta.fieldname)}" ASC`;
1019
+ }
1020
+ if (spec.limit != null && typeof spec.limit !== "number") throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
1021
+ const effectiveLimit = spec.limit ?? defaultRowLimit;
1022
+ let pagingClause = "";
1023
+ if (effectiveLimit != null) {
1024
+ values.push(effectiveLimit + 1);
1025
+ pagingClause += ` LIMIT $${values.length}`;
1026
+ }
1027
+ if (spec.offset != null) {
1028
+ values.push(spec.offset);
1029
+ pagingClause += ` OFFSET $${values.length}`;
1030
+ }
1031
+ const { rows } = await debugSql(pgClient, {
1032
+ text: `SELECT ${select.list} FROM ${select.table}${whereClause}${orderByClause}${pagingClause}`,
1033
+ values
1035
1034
  });
1036
- count = parseInt(countRows[0]?.row_count ?? "0", 10);
1035
+ select.decodeRows(rows);
1036
+ const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
1037
+ const data = [...hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows];
1038
+ await enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql);
1039
+ let count = null;
1040
+ if (spec.includeTotal === true) {
1041
+ const { rows: countRows } = await debugSql(pgClient, {
1042
+ text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${whereClause}`,
1043
+ values: filterValues
1044
+ });
1045
+ count = parseInt(countRows[0]?.row_count ?? "0", 10);
1046
+ }
1047
+ return {
1048
+ data,
1049
+ doctype,
1050
+ hasMore,
1051
+ count
1052
+ };
1053
+ }));
1054
+ });
1055
+ }
1056
+ } },
1057
+ Mutation: { plans: { stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
1058
+ return sideEffectWithPgClient(executor, object({
1059
+ doctype: $doctype,
1060
+ action: $action,
1061
+ actionArgs: $actionArgs
1062
+ }), async (pgClient, spec) => {
1063
+ const meta = getMeta(String(spec.doctype));
1064
+ if (!meta) return {
1065
+ success: false,
1066
+ data: null,
1067
+ error: `Unknown doctype: ${spec.doctype}`
1068
+ };
1069
+ const actionDef = meta.workflow?.actions?.[spec.action];
1070
+ if (!actionDef) return {
1071
+ success: false,
1072
+ data: null,
1073
+ error: `Unknown action: ${spec.action} on ${spec.doctype}`
1074
+ };
1075
+ const table = resolveTableName(meta.name, options.tables);
1076
+ const pkColumn = () => {
1077
+ const pkMeta = getPkMeta(meta);
1078
+ if (!pkMeta) throw unresolvableIdentityError(String(spec.doctype));
1079
+ return camelToSnake(pkMeta.fieldname);
1080
+ };
1081
+ const argList = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []).map((entry) => entry?.data ? {
1082
+ ...entry,
1083
+ data: unwrapInlineLinks(meta.fields, entry.data)
1084
+ } : entry);
1085
+ const recordId = argList[0]?.id;
1086
+ const recordData = argList[0]?.data ?? {};
1087
+ const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
1088
+ const writable = new Map(columnBackedFields(meta.fields).filter((f) => camelToSnake(f.fieldname) !== STATE_COLUMN).map((f) => [f.fieldname, f]));
1089
+ const declaresState = columnBackedFields(meta.fields).some((f) => camelToSnake(f.fieldname) === STATE_COLUMN);
1090
+ const droppedFields = [];
1091
+ const partitionPatch = (patch) => {
1092
+ const cols = [];
1093
+ const values = [];
1094
+ for (const [key, value] of Object.entries(patch)) {
1095
+ if (!writable.has(key) || !columns.writable(meta.name, camelToSnake(key))) {
1096
+ droppedFields.push(key);
1097
+ continue;
1098
+ }
1099
+ if (value !== null && typeof value === "object") {
1100
+ droppedFields.push(key);
1101
+ continue;
1102
+ }
1103
+ cols.push(camelToSnake(key));
1104
+ values.push(value);
1037
1105
  }
1038
1106
  return {
1039
- data,
1040
- doctype,
1041
- hasMore,
1042
- count
1107
+ cols,
1108
+ values
1043
1109
  };
1044
- }));
1045
- });
1046
- }
1047
- } },
1048
- Mutation: { plans: { stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
1049
- return sideEffectWithPgClient(executor, object({
1050
- doctype: $doctype,
1051
- action: $action,
1052
- actionArgs: $actionArgs
1053
- }), async (pgClient, spec) => {
1054
- const meta = getMeta(String(spec.doctype));
1055
- if (!meta) return {
1056
- success: false,
1057
- data: null,
1058
- error: `Unknown doctype: ${spec.doctype}`
1059
- };
1060
- const actionDef = meta.workflow?.actions?.[spec.action];
1061
- if (!actionDef) return {
1062
- success: false,
1063
- data: null,
1064
- error: `Unknown action: ${spec.action} on ${spec.doctype}`
1065
- };
1066
- const table = resolveTableName(meta.name, options.tables);
1067
- const pkColumn = () => {
1068
- const pkMeta = getPkMeta(meta);
1069
- if (!pkMeta) throw unresolvableIdentityError(String(spec.doctype));
1070
- return camelToSnake(pkMeta.fieldname);
1071
- };
1072
- const argList = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []).map((entry) => entry?.data ? {
1073
- ...entry,
1074
- data: unwrapInlineLinks(meta.fields, entry.data)
1075
- } : entry);
1076
- const recordId = argList[0]?.id;
1077
- const recordData = argList[0]?.data ?? {};
1078
- const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
1079
- const writable = new Map(columnBackedFields(meta.fields).filter((f) => camelToSnake(f.fieldname) !== STATE_COLUMN).map((f) => [f.fieldname, f]));
1080
- const declaresState = columnBackedFields(meta.fields).some((f) => camelToSnake(f.fieldname) === STATE_COLUMN);
1081
- const droppedFields = [];
1082
- const partitionPatch = (patch) => {
1083
- const cols = [];
1084
- const values = [];
1085
- for (const [key, value] of Object.entries(patch)) {
1086
- if (!writable.has(key)) {
1087
- droppedFields.push(key);
1088
- continue;
1089
- }
1090
- if (value !== null && typeof value === "object") {
1091
- droppedFields.push(key);
1092
- continue;
1093
- }
1094
- cols.push(camelToSnake(key));
1095
- values.push(value);
1096
- }
1097
- return {
1098
- cols,
1099
- values
1100
1110
  };
1101
- };
1102
- try {
1103
- return await pgClient.withTransaction(async (tx) => {
1104
- const outcome = await applyGuardedTransition(actionDef, {
1105
- readState: async () => {
1106
- if (recordId == null) return null;
1107
- const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
1108
- const { rows } = await debugSql(tx, {
1109
- text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
1110
- values: [String(recordId)]
1111
- });
1112
- if (rows.length === 0) return null;
1113
- if (!declaresState) return void 0;
1114
- return rows[0][STATE_COLUMN] ?? void 0;
1115
- },
1116
- writeState: async (nextState) => {
1117
- await debugSql(tx, {
1118
- text: `UPDATE ${table} SET "${STATE_COLUMN}" = $1 WHERE "${pkColumn()}"::text = $2`,
1119
- values: [nextState, String(recordId)]
1120
- });
1121
- },
1122
- writeData: async (patch, exists) => {
1123
- const { cols, values } = partitionPatch(patch);
1124
- const returning = columns.select(meta.name, getColumnSelections(meta));
1125
- if (!exists) {
1126
- 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.`);
1127
- const text = cols.length ? `INSERT INTO ${table} (${cols.map((c) => `"${c}"`).join(", ")}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(", ")}) RETURNING ${returning.list}` : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`;
1111
+ try {
1112
+ return await pgClient.withTransaction(async (tx) => {
1113
+ const outcome = await applyGuardedTransition(actionDef, {
1114
+ readState: async () => {
1115
+ if (recordId == null) return null;
1116
+ const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
1128
1117
  const { rows } = await debugSql(tx, {
1129
- text,
1130
- values
1118
+ text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
1119
+ values: [String(recordId)]
1131
1120
  });
1132
- returning.decodeRows(rows);
1133
- return rows[0] ?? {};
1134
- }
1135
- if (cols.length === 0) {
1121
+ if (rows.length === 0) return null;
1122
+ if (!declaresState) return void 0;
1123
+ return rows[0][STATE_COLUMN] ?? void 0;
1124
+ },
1125
+ writeState: async (nextState) => {
1126
+ await debugSql(tx, {
1127
+ text: `UPDATE ${table} SET "${STATE_COLUMN}" = $1 WHERE "${pkColumn()}"::text = $2`,
1128
+ values: [nextState, String(recordId)]
1129
+ });
1130
+ },
1131
+ writeData: async (patch, exists) => {
1132
+ const { cols, values } = partitionPatch(patch);
1133
+ const returning = columns.select(meta.name, getColumnSelections(meta));
1134
+ if (!exists) {
1135
+ 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.`);
1136
+ const text = cols.length ? `INSERT INTO ${table} (${cols.map((c) => `"${c}"`).join(", ")}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(", ")}) RETURNING ${returning.list}` : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`;
1137
+ const { rows } = await debugSql(tx, {
1138
+ text,
1139
+ values
1140
+ });
1141
+ returning.decodeRows(rows);
1142
+ return rows[0] ?? {};
1143
+ }
1144
+ if (cols.length === 0) {
1145
+ const { rows } = await debugSql(tx, {
1146
+ text: `SELECT ${returning.list} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
1147
+ values: [String(recordId)]
1148
+ });
1149
+ returning.decodeRows(rows);
1150
+ return rows[0] ?? {};
1151
+ }
1152
+ const assignments = cols.map((c, i) => `"${c}" = ${columns.bind(meta.name, c, `$${i + 1}`)}`).join(", ");
1136
1153
  const { rows } = await debugSql(tx, {
1137
- text: `SELECT ${returning.list} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
1138
- values: [String(recordId)]
1154
+ text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning.list}`,
1155
+ values: [...values, String(recordId)]
1139
1156
  });
1140
1157
  returning.decodeRows(rows);
1141
1158
  return rows[0] ?? {};
1142
- }
1143
- const assignments = cols.map((c, i) => `"${c}" = ${columns.bind(meta.name, c, `$${i + 1}`)}`).join(", ");
1144
- const { rows } = await debugSql(tx, {
1145
- text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning.list}`,
1146
- values: [...values, String(recordId)]
1147
- });
1148
- returning.decodeRows(rows);
1149
- return rows[0] ?? {};
1150
- },
1151
- runEffect: handler ? (currentState) => handler({
1152
- pgClient: tx,
1153
- doctype: String(spec.doctype),
1154
- action: String(spec.action),
1155
- meta,
1156
- recordId,
1157
- data: recordData,
1158
- args: argList,
1159
- currentState
1160
- }) : void 0
1161
- }, recordData);
1162
- if (!outcome.success) throw new ActionRolledBack(outcome);
1163
- if (outcome.success && outcome.data !== null && typeof outcome.data === "object") {
1164
- const written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter((row) => row !== null && typeof row === "object");
1165
- await enrichLinkDisplayFields(tx, meta, written, columns, debugSql);
1166
- }
1167
- const pkField = getPkMeta(meta)?.fieldname;
1168
- const readId = (pkField !== void 0 && outcome.data !== null && typeof outcome.data === "object" ? Reflect.get(outcome.data, pkField) : void 0) ?? recordId;
1169
- const record = readId == null ? null : (await readRecords(tx, [{
1170
- doctype: meta.name,
1171
- id: readId
1172
- }]))[0]?.data ?? null;
1173
- const reply = {
1174
- ...outcome,
1175
- record
1159
+ },
1160
+ runEffect: handler ? (currentState) => handler({
1161
+ pgClient: tx,
1162
+ doctype: String(spec.doctype),
1163
+ action: String(spec.action),
1164
+ meta,
1165
+ recordId,
1166
+ data: recordData,
1167
+ args: argList,
1168
+ currentState
1169
+ }) : void 0
1170
+ }, recordData);
1171
+ if (!outcome.success) throw new ActionRolledBack(outcome);
1172
+ if (outcome.success && outcome.data !== null && typeof outcome.data === "object") {
1173
+ const written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter((row) => row !== null && typeof row === "object");
1174
+ await enrichLinkDisplayFields(tx, meta, written, columns, debugSql);
1175
+ }
1176
+ const pkField = getPkMeta(meta)?.fieldname;
1177
+ const readId = (pkField !== void 0 && outcome.data !== null && typeof outcome.data === "object" ? Reflect.get(outcome.data, pkField) : void 0) ?? recordId;
1178
+ const record = readId == null ? null : (await readRecords(tx, [{
1179
+ doctype: meta.name,
1180
+ id: readId
1181
+ }]))[0]?.data ?? null;
1182
+ const reply = {
1183
+ ...outcome,
1184
+ record
1185
+ };
1186
+ return droppedFields.length ? {
1187
+ ...reply,
1188
+ droppedFields
1189
+ } : reply;
1190
+ });
1191
+ } catch (err) {
1192
+ if (err instanceof ActionRolledBack) return err.outcome;
1193
+ return {
1194
+ success: false,
1195
+ data: null,
1196
+ error: err instanceof Error ? err.message : String(err)
1176
1197
  };
1177
- return droppedFields.length ? {
1178
- ...reply,
1179
- droppedFields
1180
- } : reply;
1181
- });
1182
- } catch (err) {
1183
- if (err instanceof ActionRolledBack) return err.outcome;
1184
- return {
1185
- success: false,
1186
- data: null,
1187
- error: err instanceof Error ? err.message : String(err)
1188
- };
1189
- }
1190
- });
1191
- } } }
1192
- }
1193
- };
1194
- });
1198
+ }
1199
+ });
1200
+ } } }
1201
+ }
1202
+ };
1203
+ }),
1204
+ gather: { hooks: { pgCodecs_attribute(_info, event) {
1205
+ const { attgenerated } = event.pgAttribute;
1206
+ if (attgenerated == null || attgenerated === "") return;
1207
+ event.attribute.extensions ??= {};
1208
+ event.attribute.extensions.isInsertable = false;
1209
+ event.attribute.extensions.isUpdatable = false;
1210
+ } } }
1211
+ };
1195
1212
  };
1196
1213
  /**
1197
1214
  * Derive column selections from a flat field array.
@@ -1442,6 +1459,23 @@ var StonecropOwnedRelationsPlugin = {
1442
1459
  relation.extensions.tags.behavior = "+manyRelation:resource:connection";
1443
1460
  } } }
1444
1461
  };
1462
+ /**
1463
+ * Offers no database function as a mutation.
1464
+ *
1465
+ * PostGraphile makes a mutation of every `VOLATILE` function, which writes past the doctype's guard
1466
+ * as Amber's table mutations do. Not done by disabling `PgCustomTypeFieldPlugin`, which also builds
1467
+ * the queries and computed fields of `STABLE` and `IMMUTABLE` functions.
1468
+ */
1469
+ var StonecropNoFunctionMutationsPlugin = {
1470
+ name: "StonecropNoFunctionMutationsPlugin",
1471
+ version: "0.0.0",
1472
+ schema: { entityBehavior: { pgResource: { override: {
1473
+ after: ["PgBasicsPlugin"],
1474
+ callback(behavior) {
1475
+ return [behavior, "-mutationField"];
1476
+ }
1477
+ } } } }
1478
+ };
1445
1479
  var StonecropFieldCasingPlugin = {
1446
1480
  name: "StonecropFieldCasingPlugin",
1447
1481
  version: "0.0.0",
@@ -1453,7 +1487,9 @@ var StonecropFieldCasingPlugin = {
1453
1487
  * Creates a Stonecrop-flavoured PostGraphile preset.
1454
1488
  *
1455
1489
  * The returned preset extends `PostGraphileAmberPreset` and applies Stonecrop's
1456
- * recommended defaults. Pass it to `extends` in your PostGraphile configuration:
1490
+ * recommended defaults. It turns off the mutations Amber generates, a create, update and delete for
1491
+ * every table and one for every `VOLATILE` database function, so `stonecropAction` is the only write
1492
+ * the API offers. Pass it to `extends` in your PostGraphile configuration:
1457
1493
  *
1458
1494
  * ```typescript
1459
1495
  * import { createStonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'
@@ -1471,11 +1507,13 @@ var StonecropFieldCasingPlugin = {
1471
1507
  */
1472
1508
  var createStonecropPreset = (options) => ({
1473
1509
  extends: [PostGraphileAmberPreset],
1474
- plugins: options?.fieldCasing === "pascal" ? [
1510
+ plugins: [
1475
1511
  StonecropNaturalIdPlugin,
1476
1512
  StonecropOwnedRelationsPlugin,
1477
- StonecropFieldCasingPlugin
1478
- ] : [StonecropNaturalIdPlugin, StonecropOwnedRelationsPlugin]
1513
+ StonecropNoFunctionMutationsPlugin,
1514
+ ...options?.fieldCasing === "pascal" ? [StonecropFieldCasingPlugin] : []
1515
+ ],
1516
+ disablePlugins: ["PgMutationCreatePlugin", "PgMutationUpdateDeletePlugin"]
1479
1517
  });
1480
1518
  /**
1481
1519
  * The default Stonecrop PostGraphile preset with camelCase field names.