@stonecrop/graphql-middleware 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { readdirSync as B, statSync as M, readFileSync as x } from "node:fs";
2
2
  import { join as E } from "node:path";
3
- import { validateDoctype as k, parseDoctype as O, toPascalCase as D, snakeToCamel as j } from "@stonecrop/schema";
3
+ import { validateDoctype as R, parseDoctype as O, toPascalCase as A, snakeToCamel as j } from "@stonecrop/schema";
4
4
  import { loadOne as b, object as w, constant as F, lambda as q } from "postgraphile/grafast";
5
5
  import { extendSchema as I, gql as T } from "postgraphile/utils";
6
6
  import J from "pluralize";
7
7
  const u = /* @__PURE__ */ new Map();
8
- class R extends Error {
8
+ class k extends Error {
9
9
  constructor(t, r) {
10
10
  const i = r.map((n) => ` ${n.path.join(".")}: ${n.message}`).join(`
11
11
  `);
@@ -34,28 +34,28 @@ function C(e, t) {
34
34
  t.onError?.(e, [o]);
35
35
  return;
36
36
  }
37
- throw new R(e, [o]);
37
+ throw new k(e, [o]);
38
38
  }
39
- const n = k(i);
39
+ const n = R(i);
40
40
  if (!n.success) {
41
41
  if (t.continueOnError) {
42
42
  t.onError?.(e, n.errors);
43
43
  return;
44
44
  }
45
- throw new R(e, n.errors);
45
+ throw new k(e, n.errors);
46
46
  }
47
47
  const a = O(i);
48
48
  u.set(a.name, a);
49
49
  }
50
50
  function de(e, t = {}) {
51
51
  for (const [r, i] of Object.entries(e)) {
52
- const n = { ...i, name: r }, a = k(n);
52
+ const n = { ...i, name: r }, a = R(n);
53
53
  if (!a.success) {
54
54
  if (t.continueOnError) {
55
55
  t.onError?.(r, a.errors);
56
56
  continue;
57
57
  }
58
- throw new R(r, a.errors);
58
+ throw new k(r, a.errors);
59
59
  }
60
60
  const c = O(n);
61
61
  u.set(c.name, c);
@@ -113,7 +113,7 @@ const U = async (e, t) => {
113
113
  for (const a of i.fields) {
114
114
  const c = r[a.fieldname];
115
115
  if (c == null) continue;
116
- const o = P(a, c);
116
+ const o = W(a, c);
117
117
  o && n.push(o);
118
118
  }
119
119
  if (i.links)
@@ -128,7 +128,7 @@ ${n.join(`
128
128
  `)}`);
129
129
  return { valid: !0 };
130
130
  };
131
- function P(e, t) {
131
+ function W(e, t) {
132
132
  const { fieldname: r, fieldtype: i, cardinality: n } = e;
133
133
  switch (i) {
134
134
  case "Int":
@@ -166,13 +166,13 @@ function P(e, t) {
166
166
  }
167
167
  return null;
168
168
  }
169
- const V = async () => ({ ok: !0 }), W = {
169
+ const P = async () => ({ ok: !0 }), V = {
170
170
  validateRequiredFields: U,
171
171
  validateFieldTypes: Q,
172
- noop: V
172
+ noop: P
173
173
  };
174
174
  function ge() {
175
- for (const [e, t] of Object.entries(W))
175
+ for (const [e, t] of Object.entries(V))
176
176
  _(e, t);
177
177
  }
178
178
  const Se = (e) => {
@@ -199,7 +199,7 @@ const Se = (e) => {
199
199
  validation: JSON
200
200
  }
201
201
 
202
- type StonecropActionDefinition {
202
+ type StonecropWorkflowAction {
203
203
  label: String!
204
204
  handler: String!
205
205
  requiredFields: [String!]
@@ -210,7 +210,7 @@ const Se = (e) => {
210
210
 
211
211
  type StonecropWorkflowMeta {
212
212
  states: [String!]
213
- actions: JSON
213
+ actions: [StonecropWorkflowAction!]
214
214
  }
215
215
 
216
216
  type StonecropDoctypeMeta {
@@ -387,10 +387,10 @@ function G(e) {
387
387
  return `${j(t)}ById`;
388
388
  }
389
389
  function z(e) {
390
- return `all${D(e)}`;
390
+ return `all${A(e)}`;
391
391
  }
392
392
  function Y(e) {
393
- return `${D(e)}OrderBy`;
393
+ return `${A(e)}OrderBy`;
394
394
  }
395
395
  function K(e) {
396
396
  return "id";
@@ -399,12 +399,12 @@ function X(e) {
399
399
  return "UUID!";
400
400
  }
401
401
  const Z = /* @__PURE__ */ new Set(["Link"]);
402
- function A(e) {
402
+ function D(e) {
403
403
  return e.fields.filter((t) => !Z.has(t.fieldtype)).map((t) => t.fieldname).join(`
404
404
  `);
405
405
  }
406
406
  function ee(e, t, r, i) {
407
- const n = A(e), a = t(e.tableName), c = r(e.tableName), o = i(e.tableName);
407
+ const n = D(e), a = t(e.tableName), c = r(e.tableName), o = i(e.tableName);
408
408
  return `
409
409
  query GetRecord($${c}: ${o}) {
410
410
  ${a}(${c}: $${c}) {
@@ -414,7 +414,7 @@ function ee(e, t, r, i) {
414
414
  `;
415
415
  }
416
416
  function te(e, t, r, i) {
417
- const n = A(e), a = r(e.tableName), c = i(e.tableName), o = [], l = [];
417
+ const n = D(e), a = r(e.tableName), c = i(e.tableName), o = [], l = [];
418
418
  t.limit && (o.push("$limit: Int"), l.push("first: $limit")), t.offset && (o.push("$offset: Int"), l.push("offset: $offset")), t.orderBy && (o.push(`$orderBy: [${c}!]`), l.push("orderBy: $orderBy"));
419
419
  const y = o.length > 0 ? `(${o.join(", ")})` : "", f = l.length > 0 ? `(${l.join(", ")})` : "";
420
420
  return `
@@ -436,9 +436,9 @@ function ne(e, t, r) {
436
436
  return e[i]?.nodes ?? [];
437
437
  }
438
438
  export {
439
- R as DoctypeValidationError,
439
+ k as DoctypeValidationError,
440
440
  Z as RELATION_FIELDTYPES,
441
- W as builtinHandlers,
441
+ V as builtinHandlers,
442
442
  me as clearHandlers,
443
443
  ue as clearRegistry,
444
444
  Se as createStonecropPlugin,
@@ -454,7 +454,7 @@ export {
454
454
  fe as hasMeta,
455
455
  L as loadDoctypes,
456
456
  de as loadDoctypesFromObject,
457
- A as queryableFieldNames,
457
+ D as queryableFieldNames,
458
458
  ge as registerBuiltinHandlers,
459
459
  _ as registerHandler,
460
460
  ye as validateReferences
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/registry/doctypes.ts","../src/registry/actions.ts","../src/plugin/postgraphile.ts"],"sourcesContent":["import { readFileSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { parseDoctype, validateDoctype } from '@stonecrop/schema'\nimport type { DoctypeMeta, ValidationError } from '@stonecrop/schema'\n\nconst doctypeRegistry: Map<string, DoctypeMeta> = new Map()\n\n/**\n * Error thrown when a doctype definition fails validation\n * @public\n */\nexport class DoctypeValidationError extends Error {\n\tconstructor(\n\t\t/** File path or name where the validation error occurred */\n\t\tpublic readonly file: string,\n\t\t/** List of validation errors found */\n\t\tpublic readonly errors: ValidationError[]\n\t) {\n\t\tconst errorMessages = errors.map(e => ` ${e.path.join('.')}: ${e.message}`).join('\\n')\n\t\tsuper(`Invalid doctype definition in ${file}:\\n${errorMessages}`)\n\t\tthis.name = 'DoctypeValidationError'\n\t}\n}\n\n/**\n * Options for loading doctype definitions\n * @public\n */\nexport interface LoadDoctypesOptions {\n\t/** Continue loading other files if one fails validation */\n\tcontinueOnError?: boolean\n\t/** Callback for validation errors when continueOnError is true */\n\tonError?: (file: string, errors: ValidationError[]) => void\n}\n\n/**\n * Load doctype definitions from a directory of JSON files\n * @param dir - Directory path containing doctype JSON files\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypes(dir: string, options: LoadDoctypesOptions = {}): void {\n\tconst entries = readdirSync(dir)\n\n\tfor (const entry of entries) {\n\t\tconst fullPath = join(dir, entry)\n\t\tconst stat = statSync(fullPath)\n\n\t\tif (stat.isDirectory()) {\n\t\t\tloadDoctypes(fullPath, options)\n\t\t} else if (entry.endsWith('.json')) {\n\t\t\tloadDoctypeFile(fullPath, options)\n\t\t}\n\t}\n}\n\n/**\n * Load and validate a single doctype file\n */\nfunction loadDoctypeFile(filePath: string, options: LoadDoctypesOptions): void {\n\tconst content = readFileSync(filePath, 'utf-8')\n\tlet data: unknown\n\n\ttry {\n\t\tdata = JSON.parse(content)\n\t} catch (err) {\n\t\tconst parseError: ValidationError = {\n\t\t\tpath: [],\n\t\t\tmessage: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t}\n\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, [parseError])\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, [parseError])\n\t}\n\n\tconst result = validateDoctype(data)\n\n\tif (!result.success) {\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, result.errors)\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, result.errors)\n\t}\n\n\tconst doctype = parseDoctype(data)\n\tdoctypeRegistry.set(doctype.name, doctype)\n}\n\n/**\n * Load doctypes from an object (for programmatic use)\n * @param doctypes - Object mapping doctype names to doctype definitions\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypesFromObject(doctypes: Record<string, unknown>, options: LoadDoctypesOptions = {}): void {\n\tfor (const [name, data] of Object.entries(doctypes)) {\n\t\tconst withName = { ...(data as object), name }\n\t\tconst result = validateDoctype(withName)\n\n\t\tif (!result.success) {\n\t\t\tif (options.continueOnError) {\n\t\t\t\toptions.onError?.(name, result.errors)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthrow new DoctypeValidationError(name, result.errors)\n\t\t}\n\n\t\tconst doctype = parseDoctype(withName)\n\t\tdoctypeRegistry.set(doctype.name, doctype)\n\t}\n}\n\n/**\n * Get a doctype by name\n * @param name - Name of the doctype to retrieve\n * @public\n */\nexport function getMeta(name: string): DoctypeMeta | undefined {\n\treturn doctypeRegistry.get(name)\n}\n\n/**\n * Get all loaded doctypes\n * @public\n */\nexport function getAllMeta(): DoctypeMeta[] {\n\treturn Array.from(doctypeRegistry.values())\n}\n\n/**\n * Check if a doctype is registered\n * @param name - Name of the doctype to check\n * @public\n */\nexport function hasMeta(name: string): boolean {\n\treturn doctypeRegistry.has(name)\n}\n\n/**\n * Clear all registered doctypes\n * @public\n */\nexport function clearRegistry(): void {\n\tdoctypeRegistry.clear()\n}\n\n/**\n * Validate cross-doctype references (Link fields, inherits, etc.)\n * Call after all doctypes are loaded.\n * @public\n */\nexport function validateReferences(): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\t// Check inherits reference\n\t\tif (doctype.inherits && !doctypeRegistry.has(doctype.inherits)) {\n\t\t\terrors.push({\n\t\t\t\tpath: [doctype.name, 'inherits'],\n\t\t\t\tmessage: `References unknown doctype: ${doctype.inherits}`,\n\t\t\t})\n\t\t}\n\n\t\t// Check Link field targets\n\t\tfor (const field of doctype.fields) {\n\t\t\tif (field.fieldtype === 'Link' && typeof field.options === 'string') {\n\t\t\t\tif (!doctypeRegistry.has(field.options)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'fields', field.fieldname, 'options'],\n\t\t\t\t\t\tmessage: `Link references unknown doctype: ${field.options}`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors\n}\n","import type { DoctypeMeta, FieldMeta } from '@stonecrop/schema'\nimport type { ActionHandler, ActionContext } from '../types'\n\nconst handlerRegistry: Map<string, ActionHandler> = new Map()\n\n/**\n * Register an action handler\n * @param name - Unique name for the action handler\n * @param handler - Action handler function to register\n * @public\n */\nexport function registerHandler(name: string, handler: ActionHandler): void {\n\thandlerRegistry.set(name, handler)\n}\n\n/**\n * Get a registered handler by name\n * @param name - Name of the action handler to retrieve\n * @public\n */\nexport function getHandler(name: string): ActionHandler | undefined {\n\treturn handlerRegistry.get(name)\n}\n\n/**\n * Check if a handler is registered\n * @param name - Name of the action handler to check\n * @public\n */\nexport function hasHandler(name: string): boolean {\n\treturn handlerRegistry.has(name)\n}\n\n/**\n * Clear all registered handlers\n * @public\n */\nexport function clearHandlers(): void {\n\thandlerRegistry.clear()\n}\n\n// =============================================================================\n// Built-in Handlers\n// =============================================================================\n\n/**\n * Validate that all required fields are present in a record\n */\nconst validateRequiredFields: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst missing: string[] = []\n\tfor (const field of doctype.fields) {\n\t\tif (field.required && (record[field.fieldname] === undefined || record[field.fieldname] === null)) {\n\t\t\tmissing.push(field.label ?? field.fieldname)\n\t\t}\n\t}\n\n\tif (missing.length > 0) {\n\t\tthrow new Error(`Missing required fields: ${missing.join(', ')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate field types match expected types\n */\nconst validateFieldTypes: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst errors: string[] = []\n\n\tfor (const field of doctype.fields) {\n\t\tconst value = record[field.fieldname]\n\t\tif (value === undefined || value === null) continue\n\n\t\tconst error = validateFieldValue(field, value)\n\t\tif (error) errors.push(error)\n\t}\n\n\t// Validate link fields\n\tif (doctype.links) {\n\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\tconst value = record[fieldname]\n\t\t\tif (value === undefined || value === null) continue\n\n\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\tif (isMany) {\n\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\terrors.push(`${fieldname}: expected array, got ${typeof value}`)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (typeof value !== 'object' || Array.isArray(value)) {\n\t\t\t\t\terrors.push(`${fieldname}: expected object, got ${typeof value}`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new Error(`Field type validation failed:\\n${errors.join('\\n')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate a single field value against its expected type\n */\nfunction validateFieldValue(field: FieldMeta, value: unknown): string | null {\n\tconst { fieldname, fieldtype, cardinality } = field\n\n\tswitch (fieldtype) {\n\t\tcase 'Int':\n\t\t\tif (typeof value !== 'number' || !Number.isInteger(value)) {\n\t\t\t\treturn `${fieldname}: expected integer, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Float':\n\t\tcase 'Decimal':\n\t\tcase 'Currency':\n\t\tcase 'Quantity':\n\t\t\tif (typeof value !== 'number' && typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected number, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Check':\n\t\t\tif (typeof value !== 'boolean') {\n\t\t\t\treturn `${fieldname}: expected boolean, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Data':\n\t\tcase 'Text':\n\t\tcase 'Code':\n\t\tcase 'Link':\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected string, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Date':\n\t\tcase 'Time':\n\t\tcase 'Datetime':\n\t\t\tif (typeof value !== 'string' && !(value instanceof Date)) {\n\t\t\t\treturn `${fieldname}: expected date string or Date, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'JSON':\n\t\t\tif (typeof value !== 'object') {\n\t\t\t\treturn `${fieldname}: expected object, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\t}\n\n\treturn null\n}\n\n/**\n * No-op handler for testing or placeholder actions\n */\nconst noop: ActionHandler = async () => {\n\treturn { ok: true }\n}\n\n/**\n * Built-in handlers available for registration\n * @public\n */\nexport const builtinHandlers: Record<string, ActionHandler> = {\n\tvalidateRequiredFields,\n\tvalidateFieldTypes,\n\tnoop,\n}\n\n/**\n * Register all built-in handlers\n * @public\n */\nexport function registerBuiltinHandlers(): void {\n\tfor (const [name, handler] of Object.entries(builtinHandlers)) {\n\t\tregisterHandler(name, handler)\n\t}\n}\n","import type { DoctypeMeta } from '@stonecrop/schema'\nimport { snakeToCamel, toPascalCase } from '@stonecrop/schema'\nimport { constant, lambda, object, loadOne } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema, gql } from 'postgraphile/utils'\nimport pluralize from 'pluralize'\n\nimport { getHandler, registerHandler } from '../registry/actions'\nimport { getMeta, getAllMeta } from '../registry/doctypes'\nimport type { ActionContext, GraphQLExecutor } from '../types'\n\n/**\n * Inflection callbacks for mapping table names to GraphQL query field names.\n * Override these when using a non-Amber inflection preset (e.g., V4, SimplifyInflection).\n *\n * Defaults match the PostGraphile Amber preset conventions.\n * @public\n */\nexport interface StonecropInflectionConfig {\n\t/**\n\t * Given a table name, return the GraphQL field name for fetching a single record by ID.\n\t * @example Amber default: \"sales_orders\" → \"salesOrderById\"\n\t * @example V4 preset: \"sales_orders\" → \"salesOrderByRowId\"\n\t */\n\trecordFieldName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL field name for fetching a list/connection.\n\t * @example Amber default: \"sales_orders\" → \"allSalesOrders\"\n\t * @example SimplifyInflection: \"sales_orders\" → \"salesOrders\"\n\t */\n\tconnectionFieldName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL OrderBy enum type name.\n\t * @example Amber default: \"sales_orders\" → \"SalesOrdersOrderBy\"\n\t */\n\torderByTypeName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL argument name used to look up a record by PK.\n\t * @example Amber default (Relay Global ID): \"sales_orders\" → \"id\"\n\t * @example row_id PK: \"sales_orders\" → \"rowId\"\n\t */\n\trecordArgName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL variable type for the PK argument.\n\t * @example Default UUID PK: \"sales_orders\" → \"UUID!\"\n\t * @example Integer PK: \"sales_orders\" → \"Int!\"\n\t */\n\trecordArgType?: (tableName: string) => string\n}\n\n/**\n * Options for creating a Stonecrop PostGraphile plugin\n * @public\n */\nexport interface StonecropPluginOptions {\n\t/** GraphQL executor for running queries/mutations */\n\texecutor: GraphQLExecutor\n\n\t/**\n\t * Override inflection conventions for mapping table names to GraphQL field names.\n\t * Defaults to PostGraphile Amber preset conventions.\n\t */\n\tinflection?: StonecropInflectionConfig\n}\n\n/**\n * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality\n * @param options - Plugin configuration options\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createStonecropPlugin = (options: StonecropPluginOptions): GraphileConfig.Plugin => {\n\t// Resolve inflection callbacks with Amber defaults\n\tconst recordFieldName = options.inflection?.recordFieldName ?? defaultRecordFieldName\n\tconst connectionFieldName = options.inflection?.connectionFieldName ?? defaultConnectionFieldName\n\tconst orderByTypeName = options.inflection?.orderByTypeName ?? defaultOrderByTypeName\n\tconst recordArgName = options.inflection?.recordArgName ?? defaultRecordArgName\n\tconst recordArgType = options.inflection?.recordArgType ?? defaultRecordArgType\n\n\treturn extendSchema(() => {\n\t\treturn {\n\t\t\ttypeDefs: gql`\n\t\t\t\ttype StonecropFieldMeta {\n\t\t\t\t\tfieldname: String!\n\t\t\t\t\tfieldtype: String!\n\t\t\t\t\tcomponent: String\n\t\t\t\t\tlabel: String\n\t\t\t\t\twidth: String\n\t\t\t\t\talign: String\n\t\t\t\t\trequired: Boolean\n\t\t\t\t\treadOnly: Boolean\n\t\t\t\t\tedit: Boolean\n\t\t\t\t\thidden: Boolean\n\t\t\t\t\tdefault: JSON\n\t\t\t\t\toptions: JSON\n\t\t\t\t\tmask: String\n\t\t\t\t\tprecision: Int\n\t\t\t\t\tscale: Int\n\t\t\t\t\tmode: String\n\t\t\t\t\tvalidation: JSON\n\t\t\t\t}\n\n\t\t\t\ttype StonecropActionDefinition {\n\t\t\t\t\tlabel: String!\n\t\t\t\t\thandler: String!\n\t\t\t\t\trequiredFields: [String!]\n\t\t\t\t\tallowedStates: [String!]\n\t\t\t\t\tconfirm: Boolean\n\t\t\t\t\targs: JSON\n\t\t\t\t}\n\n\t\t\t\ttype StonecropWorkflowMeta {\n\t\t\t\t\tstates: [String!]\n\t\t\t\t\tactions: JSON\n\t\t\t\t}\n\n\t\t\t\ttype StonecropDoctypeMeta {\n\t\t\t\t\tname: String!\n\t\t\t\t\tslug: String\n\t\t\t\t\ttableName: String\n\t\t\t\t\tfields: [StonecropFieldMeta!]!\n\t\t\t\t\tworkflow: StonecropWorkflowMeta\n\t\t\t\t\tinherits: String\n\t\t\t\t}\n\n\t\t\t\ttype StonecropRecordResult {\n\t\t\t\t\tdata: JSON\n\t\t\t\t\tdoctype: String!\n\t\t\t\t}\n\n\t\t\t\ttype StonecropRecordsResult {\n\t\t\t\t\tdata: [JSON!]!\n\t\t\t\t\tdoctype: String!\n\t\t\t\t\tcount: Int!\n\t\t\t\t}\n\n\t\t\t\ttype StonecropActionResult {\n\t\t\t\t\tsuccess: Boolean!\n\t\t\t\t\tdata: JSON\n\t\t\t\t\terror: String\n\t\t\t\t}\n\n\t\t\t\textend type Query {\n\t\t\t\t\tstonecropMeta(doctype: String!): StonecropDoctypeMeta\n\t\t\t\t\tstonecropAllMeta: [StonecropDoctypeMeta!]!\n\t\t\t\t\tstonecropRecord(doctype: String!, id: String!): StonecropRecordResult\n\t\t\t\t\tstonecropRecords(\n\t\t\t\t\t\tdoctype: String!\n\t\t\t\t\t\tfilters: JSON\n\t\t\t\t\t\torderBy: String\n\t\t\t\t\t\tlimit: Int\n\t\t\t\t\t\toffset: Int\n\t\t\t\t\t): StonecropRecordsResult\n\t\t\t\t}\n\n\t\t\t\textend type Mutation {\n\t\t\t\t\tstonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!\n\t\t\t\t}\n\t\t\t`,\n\n\t\t\tobjects: {\n\t\t\t\tQuery: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropMeta(_: any, { $doctype }: any) {\n\t\t\t\t\t\t\treturn lambda($doctype, (doctype: unknown) => {\n\t\t\t\t\t\t\t\tconst meta = getMeta(doctype as string)\n\t\t\t\t\t\t\t\treturn meta ?? null\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropAllMeta() {\n\t\t\t\t\t\t\treturn constant(getAllMeta())\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecord(_: any, { $doctype, $id }: any) {\n\t\t\t\t\t\t\treturn loadOne(object({ doctype: $doctype, id: $id }), async (specs: readonly any[]) => {\n\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(spec.doctype)\n\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown doctype: ${spec.doctype}`)\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif (!meta.tableName) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Doctype ${spec.doctype} has no table mapping`)\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tconst query = buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType)\n\t\t\t\t\t\t\t\t\t\tconst result = await options.executor.query(query, {\n\t\t\t\t\t\t\t\t\t\t\t[recordArgName(meta.tableName!)]: spec.id,\n\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tdata: extractSingleResult(result, meta, recordFieldName),\n\t\t\t\t\t\t\t\t\t\t\tdoctype: spec.doctype,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecords(_: any, { $doctype, $filters, $orderBy, $limit, $offset }: any) {\n\t\t\t\t\t\t\treturn loadOne(\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\tfilters: $filters,\n\t\t\t\t\t\t\t\t\torderBy: $orderBy,\n\t\t\t\t\t\t\t\t\tlimit: $limit,\n\t\t\t\t\t\t\t\t\toffset: $offset,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (specs: readonly any[]) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown doctype: ${spec.doctype}`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif (!meta.tableName) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Doctype ${spec.doctype} has no table mapping`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst query = buildListQuery(\n\t\t\t\t\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tlimit: spec.limit,\n\t\t\t\t\t\t\t\t\t\t\t\t\toffset: spec.offset,\n\t\t\t\t\t\t\t\t\t\t\t\t\torderBy: spec.orderBy,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\tconnectionFieldName,\n\t\t\t\t\t\t\t\t\t\t\t\torderByTypeName\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\tconst result = await options.executor.query(query, {\n\t\t\t\t\t\t\t\t\t\t\t\tlimit: spec.limit,\n\t\t\t\t\t\t\t\t\t\t\t\toffset: spec.offset,\n\t\t\t\t\t\t\t\t\t\t\t\torderBy: spec.orderBy,\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\tconst data = extractListResult(result, meta, connectionFieldName)\n\n\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype: spec.doctype,\n\t\t\t\t\t\t\t\t\t\t\t\tcount: data.length,\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\tMutation: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropAction(_: any, { $doctype, $action, $args: $actionArgs }: any) {\n\t\t\t\t\t\t\treturn loadOne(\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\taction: $action,\n\t\t\t\t\t\t\t\t\tactionArgs: $actionArgs,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (specs: readonly any[]) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `Unknown doctype: ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst actionDef = meta.workflow?.actions?.[spec.action]\n\t\t\t\t\t\t\t\t\t\t\tif (!actionDef) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `Unknown action: ${spec.action} on ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst handlerName = actionDef.handler\n\t\t\t\t\t\t\t\t\t\t\tconst handler = getHandler(handlerName)\n\t\t\t\t\t\t\t\t\t\t\tif (!handler) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `Handler not registered: ${handlerName}`,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst actionContext: ActionContext = {\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype: meta,\n\t\t\t\t\t\t\t\t\t\t\t\texecutor: options.executor,\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\tconst result = await handler(spec.actionArgs ?? [], actionContext)\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: null,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n}\n\n// =============================================================================\n// Inflection helpers — default to PostGraphile Amber preset conventions\n// Uses `pluralize` for proper English singularization (handles irregular\n// plurals like statuses→status, categories→category, addresses→address).\n// snakeToCamel / toPascalCase are imported from @stonecrop/schema.\n// =============================================================================\n\n/**\n * Amber default: sales_orders → salesOrderById\n * Uses `pluralize` for proper singularization of irregular plurals.\n * Override via `StonecropInflectionConfig.recordFieldName` for non-standard PK columns.\n * @public\n */\nfunction defaultRecordFieldName(tableName: string): string {\n\tconst singular = pluralize.singular(tableName)\n\treturn `${snakeToCamel(singular)}ById`\n}\n\n/**\n * Amber default: sales_orders → allSalesOrders\n * @public\n */\nfunction defaultConnectionFieldName(tableName: string): string {\n\treturn `all${toPascalCase(tableName)}`\n}\n\n/**\n * Amber default: sales_orders → SalesOrdersOrderBy\n * @public\n */\nfunction defaultOrderByTypeName(tableName: string): string {\n\treturn `${toPascalCase(tableName)}OrderBy`\n}\n\n/**\n * Default PK argument name: 'id' (standard Relay Global ID pattern).\n * Override via `StonecropInflectionConfig.recordArgName` when using row_id columns;\n * PostGraphile Amber generates `rowId: UUID!` for those fields.\n * @public\n */\nfunction defaultRecordArgName(_tableName: string): string {\n\treturn 'id'\n}\n\n/**\n * Default PK argument type: 'UUID!' (PostGraphile Amber default for UUID PKs).\n * Override via `StonecropInflectionConfig.recordArgType` when using non-UUID PKs\n * such as integer serials or Relay Global IDs ('ID!').\n * @public\n */\nfunction defaultRecordArgType(_tableName: string): string {\n\treturn 'UUID!'\n}\n\n// =============================================================================\n// Query builders — generate GraphQL queries to send to the underlying schema\n// =============================================================================\n\n/**\n * Fieldtypes that map to GraphQL object/connection types and require sub-selections.\n * These fields are excluded from generated query field selections.\n * @public\n */\nconst RELATION_FIELDTYPES = new Set(['Link'])\n\n/**\n * Filter fields to only those directly queryable as scalars, excluding Link and Doctype\n * relation fields that require GraphQL sub-selections.\n * @public\n */\nfunction queryableFieldNames(meta: DoctypeMeta): string {\n\treturn meta.fields\n\t\t.filter(f => !RELATION_FIELDTYPES.has(f.fieldtype))\n\t\t.map(f => f.fieldname)\n\t\t.join('\\n ')\n}\n\n/**\n * Build a GraphQL query to fetch a single record by ID.\n * Excludes Link and Doctype relation fields from the selection set.\n * The PK argument name and type are configurable via `StonecropInflectionConfig.recordArgName`\n * and `StonecropInflectionConfig.recordArgType` to match the target schema's conventions\n * (e.g. `rowId: UUID!` for PostGraphile Amber with row_id columns).\n * @public\n */\nfunction buildRecordQuery(\n\tmeta: DoctypeMeta,\n\trecordFieldName: (t: string) => string,\n\trecordArgName: (t: string) => string,\n\trecordArgType: (t: string) => string\n): string {\n\tconst fieldNames = queryableFieldNames(meta)\n\tconst queryName = recordFieldName(meta.tableName!)\n\tconst argName = recordArgName(meta.tableName!)\n\tconst argType = recordArgType(meta.tableName!)\n\n\treturn `\n\t\tquery GetRecord($${argName}: ${argType}) {\n\t\t\t${queryName}(${argName}: $${argName}) {\n\t\t\t\t${fieldNames}\n\t\t\t}\n\t\t}\n\t`\n}\n\n/**\n * Build a GraphQL connection query to fetch a list of records.\n * Only declares variables ($limit, $offset, $orderBy) that are actually used in the query,\n * avoiding GraphQL spec §5.8.3 violations from unused variable declarations.\n * Excludes Link and Doctype relation fields from the selection set.\n * @public\n */\nfunction buildListQuery(\n\tmeta: DoctypeMeta,\n\targs: { limit?: number; offset?: number; orderBy?: string },\n\tconnectionFieldName: (t: string) => string,\n\torderByTypeName: (t: string) => string\n): string {\n\tconst fieldNames = queryableFieldNames(meta)\n\tconst connectionName = connectionFieldName(meta.tableName!)\n\tconst orderByType = orderByTypeName(meta.tableName!)\n\n\tconst varDecls: string[] = []\n\tconst queryArgs: string[] = []\n\tif (args.limit) {\n\t\tvarDecls.push('$limit: Int')\n\t\tqueryArgs.push(`first: $limit`)\n\t}\n\tif (args.offset) {\n\t\tvarDecls.push('$offset: Int')\n\t\tqueryArgs.push(`offset: $offset`)\n\t}\n\tif (args.orderBy) {\n\t\tvarDecls.push(`$orderBy: [${orderByType}!]`)\n\t\tqueryArgs.push(`orderBy: $orderBy`)\n\t}\n\n\tconst varStr = varDecls.length > 0 ? `(${varDecls.join(', ')})` : ''\n\tconst argsStr = queryArgs.length > 0 ? `(${queryArgs.join(', ')})` : ''\n\n\treturn `\n\t\tquery GetRecords${varStr} {\n\t\t\t${connectionName}${argsStr} {\n\t\t\t\tnodes {\n\t\t\t\t${fieldNames}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`\n}\n\n/**\n * Extract a single record from a PostGraphile query result using the record field name.\n * @internal\n */\nfunction extractSingleResult(result: unknown, meta: DoctypeMeta, recordFieldName: (t: string) => string): unknown {\n\tconst queryName = recordFieldName(meta.tableName!)\n\treturn (result as Record<string, unknown>)[queryName]\n}\n\n/**\n * Extract the list of nodes from a PostGraphile connection query result.\n * Returns an empty array if the connection field is absent.\n * @internal\n */\nfunction extractListResult(result: unknown, meta: DoctypeMeta, connectionFieldName: (t: string) => string): unknown[] {\n\tconst connectionName = connectionFieldName(meta.tableName!)\n\tconst connection = (result as Record<string, unknown>)[connectionName] as {\n\t\tnodes: unknown[]\n\t}\n\treturn connection?.nodes ?? []\n}\n\n// =============================================================================\n// Exported for testing and advanced usage\n// =============================================================================\n\nexport {\n\tdefaultRecordFieldName,\n\tdefaultConnectionFieldName,\n\tdefaultOrderByTypeName,\n\tdefaultRecordArgName,\n\tdefaultRecordArgType,\n\tbuildRecordQuery,\n\tbuildListQuery,\n\tqueryableFieldNames,\n\tRELATION_FIELDTYPES,\n\textractSingleResult,\n\textractListResult,\n}\n"],"names":["doctypeRegistry","DoctypeValidationError","file","errors","errorMessages","e","loadDoctypes","dir","options","entries","readdirSync","entry","fullPath","join","statSync","loadDoctypeFile","filePath","content","readFileSync","data","err","parseError","result","validateDoctype","doctype","parseDoctype","loadDoctypesFromObject","doctypes","name","withName","getMeta","getAllMeta","hasMeta","clearRegistry","validateReferences","field","handlerRegistry","registerHandler","handler","getHandler","hasHandler","clearHandlers","validateRequiredFields","args","context","record","missing","validateFieldTypes","value","error","validateFieldValue","fieldname","link","fieldtype","cardinality","noop","builtinHandlers","registerBuiltinHandlers","createStonecropPlugin","recordFieldName","defaultRecordFieldName","connectionFieldName","defaultConnectionFieldName","orderByTypeName","defaultOrderByTypeName","recordArgName","defaultRecordArgName","recordArgType","defaultRecordArgType","extendSchema","gql","_","$doctype","lambda","constant","$id","loadOne","object","specs","spec","meta","query","buildRecordQuery","extractSingleResult","$filters","$orderBy","$limit","$offset","buildListQuery","extractListResult","$action","$actionArgs","actionDef","handlerName","actionContext","tableName","singular","pluralize","snakeToCamel","toPascalCase","_tableName","RELATION_FIELDTYPES","queryableFieldNames","f","fieldNames","queryName","argName","argType","connectionName","orderByType","varDecls","queryArgs","varStr","argsStr"],"mappings":";;;;;;AAMA,MAAMA,wBAAgD,IAAA;AAM/C,MAAMC,UAA+B,MAAM;AAAA,EACjD,YAEiBC,GAEAC,GACf;AACD,UAAMC,IAAgBD,EAAO,IAAI,CAAAE,MAAK,KAAKA,EAAE,KAAK,KAAK,GAAG,CAAC,KAAKA,EAAE,OAAO,EAAE,EAAE,KAAK;AAAA,CAAI;AACtF,UAAM,iCAAiCH,CAAI;AAAA,EAAME,CAAa,EAAE,GALhD,KAAA,OAAAF,GAEA,KAAA,SAAAC,GAIhB,KAAK,OAAO;AAAA,EACb;AACD;AAmBO,SAASG,EAAaC,GAAaC,IAA+B,IAAU;AAClF,QAAMC,IAAUC,EAAYH,CAAG;AAE/B,aAAWI,KAASF,GAAS;AAC5B,UAAMG,IAAWC,EAAKN,GAAKI,CAAK;AAGhC,IAFaG,EAASF,CAAQ,EAErB,gBACRN,EAAaM,GAAUJ,CAAO,IACpBG,EAAM,SAAS,OAAO,KAChCI,EAAgBH,GAAUJ,CAAO;AAAA,EAEnC;AACD;AAKA,SAASO,EAAgBC,GAAkBR,GAAoC;AAC9E,QAAMS,IAAUC,EAAaF,GAAU,OAAO;AAC9C,MAAIG;AAEJ,MAAI;AACH,IAAAA,IAAO,KAAK,MAAMF,CAAO;AAAA,EAC1B,SAASG,GAAK;AACb,UAAM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ACpD6B,IAAc9C,EAAgBiB,EAAK,SAAU,GAE7C8B,IAAqB,CAAA,GACrBC,IAAsB,CAAA;AAC5B,EAAIpE,EAAK,UACRmE,EAAS,KAAK,aAAa,GAC3BC,EAAU,KAAK,eAAe,IAE3BpE,EAAK,WACRmE,EAAS,KAAK,cAAc,GAC5BC,EAAU,KAAK,iBAAiB,IAE7BpE,EAAK,YACRmE,EAAS,KAAK,cAAcD,CAAW,IAAI,GAC3CE,EAAU,KAAK,mBAAmB;AAGnC,QAAMC,IAASF,EAAS,SAAS,IAAI,IAAIA,EAAS,KAAK,IAAI,CAAC,MAAM,IAC5DG,IAAUF,EAAU,SAAS,IAAI,IAAIA,EAAU,KAAK,IAAI,CAAC,MAAM;AAErE,SAAO;AAAA,oBACYC,CAAM;AAAA,KACrBJ,CAAc,GAAGK,CAAO;AAAA;AAAA,MAEvBT,CAAU;AAAA;AAAA;AAAA;AAAA;AAKhB;AAMA,SAASrB,GAAoB7D,GAAiB0D,GAAmBrB,GAAiD;AACjH,QAAM8C,IAAY9C,EAAgBqB,EAAK,SAAU;AACjD,SAAQ1D,EAAmCmF,CAAS;AACrD;AAOA,SAAShB,GAAkBnE,GAAiB0D,GAAmBnB,GAAuD;AACrH,QAAM+C,IAAiB/C,EAAoBmB,EAAK,SAAU;AAI1D,SAHoB1D,EAAmCsF,CAAc,GAGlD,SAAS,CAAA;AAC7B;"}
1
+ {"version":3,"file":"index.js","sources":["../src/registry/doctypes.ts","../src/registry/actions.ts","../src/plugin/postgraphile.ts"],"sourcesContent":["import { readFileSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { parseDoctype, validateDoctype } from '@stonecrop/schema'\nimport type { DoctypeMeta, ValidationError } from '@stonecrop/schema'\n\nconst doctypeRegistry: Map<string, DoctypeMeta> = new Map()\n\n/**\n * Error thrown when a doctype definition fails validation\n * @public\n */\nexport class DoctypeValidationError extends Error {\n\tconstructor(\n\t\t/** File path or name where the validation error occurred */\n\t\tpublic readonly file: string,\n\t\t/** List of validation errors found */\n\t\tpublic readonly errors: ValidationError[]\n\t) {\n\t\tconst errorMessages = errors.map(e => ` ${e.path.join('.')}: ${e.message}`).join('\\n')\n\t\tsuper(`Invalid doctype definition in ${file}:\\n${errorMessages}`)\n\t\tthis.name = 'DoctypeValidationError'\n\t}\n}\n\n/**\n * Options for loading doctype definitions\n * @public\n */\nexport interface LoadDoctypesOptions {\n\t/** Continue loading other files if one fails validation */\n\tcontinueOnError?: boolean\n\t/** Callback for validation errors when continueOnError is true */\n\tonError?: (file: string, errors: ValidationError[]) => void\n}\n\n/**\n * Load doctype definitions from a directory of JSON files\n * @param dir - Directory path containing doctype JSON files\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypes(dir: string, options: LoadDoctypesOptions = {}): void {\n\tconst entries = readdirSync(dir)\n\n\tfor (const entry of entries) {\n\t\tconst fullPath = join(dir, entry)\n\t\tconst stat = statSync(fullPath)\n\n\t\tif (stat.isDirectory()) {\n\t\t\tloadDoctypes(fullPath, options)\n\t\t} else if (entry.endsWith('.json')) {\n\t\t\tloadDoctypeFile(fullPath, options)\n\t\t}\n\t}\n}\n\n/**\n * Load and validate a single doctype file\n */\nfunction loadDoctypeFile(filePath: string, options: LoadDoctypesOptions): void {\n\tconst content = readFileSync(filePath, 'utf-8')\n\tlet data: unknown\n\n\ttry {\n\t\tdata = JSON.parse(content)\n\t} catch (err) {\n\t\tconst parseError: ValidationError = {\n\t\t\tpath: [],\n\t\t\tmessage: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t}\n\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, [parseError])\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, [parseError])\n\t}\n\n\tconst result = validateDoctype(data)\n\n\tif (!result.success) {\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, result.errors)\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, result.errors)\n\t}\n\n\tconst doctype = parseDoctype(data)\n\tdoctypeRegistry.set(doctype.name, doctype)\n}\n\n/**\n * Load doctypes from an object (for programmatic use)\n * @param doctypes - Object mapping doctype names to doctype definitions\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypesFromObject(doctypes: Record<string, unknown>, options: LoadDoctypesOptions = {}): void {\n\tfor (const [name, data] of Object.entries(doctypes)) {\n\t\tconst withName = { ...(data as object), name }\n\t\tconst result = validateDoctype(withName)\n\n\t\tif (!result.success) {\n\t\t\tif (options.continueOnError) {\n\t\t\t\toptions.onError?.(name, result.errors)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthrow new DoctypeValidationError(name, result.errors)\n\t\t}\n\n\t\tconst doctype = parseDoctype(withName)\n\t\tdoctypeRegistry.set(doctype.name, doctype)\n\t}\n}\n\n/**\n * Get a doctype by name\n * @param name - Name of the doctype to retrieve\n * @public\n */\nexport function getMeta(name: string): DoctypeMeta | undefined {\n\treturn doctypeRegistry.get(name)\n}\n\n/**\n * Get all loaded doctypes\n * @public\n */\nexport function getAllMeta(): DoctypeMeta[] {\n\treturn Array.from(doctypeRegistry.values())\n}\n\n/**\n * Check if a doctype is registered\n * @param name - Name of the doctype to check\n * @public\n */\nexport function hasMeta(name: string): boolean {\n\treturn doctypeRegistry.has(name)\n}\n\n/**\n * Clear all registered doctypes\n * @public\n */\nexport function clearRegistry(): void {\n\tdoctypeRegistry.clear()\n}\n\n/**\n * Validate cross-doctype references (Link fields, inherits, etc.)\n * Call after all doctypes are loaded.\n * @public\n */\nexport function validateReferences(): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\t// Check inherits reference\n\t\tif (doctype.inherits && !doctypeRegistry.has(doctype.inherits)) {\n\t\t\terrors.push({\n\t\t\t\tpath: [doctype.name, 'inherits'],\n\t\t\t\tmessage: `References unknown doctype: ${doctype.inherits}`,\n\t\t\t})\n\t\t}\n\n\t\t// Check Link field targets\n\t\tfor (const field of doctype.fields) {\n\t\t\tif (field.fieldtype === 'Link' && typeof field.options === 'string') {\n\t\t\t\tif (!doctypeRegistry.has(field.options)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'fields', field.fieldname, 'options'],\n\t\t\t\t\t\tmessage: `Link references unknown doctype: ${field.options}`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors\n}\n","import type { DoctypeMeta, FieldMeta } from '@stonecrop/schema'\nimport type { ActionHandler, ActionContext } from '../types'\n\nconst handlerRegistry: Map<string, ActionHandler> = new Map()\n\n/**\n * Register an action handler\n * @param name - Unique name for the action handler\n * @param handler - Action handler function to register\n * @public\n */\nexport function registerHandler(name: string, handler: ActionHandler): void {\n\thandlerRegistry.set(name, handler)\n}\n\n/**\n * Get a registered handler by name\n * @param name - Name of the action handler to retrieve\n * @public\n */\nexport function getHandler(name: string): ActionHandler | undefined {\n\treturn handlerRegistry.get(name)\n}\n\n/**\n * Check if a handler is registered\n * @param name - Name of the action handler to check\n * @public\n */\nexport function hasHandler(name: string): boolean {\n\treturn handlerRegistry.has(name)\n}\n\n/**\n * Clear all registered handlers\n * @public\n */\nexport function clearHandlers(): void {\n\thandlerRegistry.clear()\n}\n\n// =============================================================================\n// Built-in Handlers\n// =============================================================================\n\n/**\n * Validate that all required fields are present in a record\n */\nconst validateRequiredFields: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst missing: string[] = []\n\tfor (const field of doctype.fields) {\n\t\tif (field.required && (record[field.fieldname] === undefined || record[field.fieldname] === null)) {\n\t\t\tmissing.push(field.label ?? field.fieldname)\n\t\t}\n\t}\n\n\tif (missing.length > 0) {\n\t\tthrow new Error(`Missing required fields: ${missing.join(', ')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate field types match expected types\n */\nconst validateFieldTypes: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst errors: string[] = []\n\n\tfor (const field of doctype.fields) {\n\t\tconst value = record[field.fieldname]\n\t\tif (value === undefined || value === null) continue\n\n\t\tconst error = validateFieldValue(field, value)\n\t\tif (error) errors.push(error)\n\t}\n\n\t// Validate link fields\n\tif (doctype.links) {\n\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\tconst value = record[fieldname]\n\t\t\tif (value === undefined || value === null) continue\n\n\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\tif (isMany) {\n\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\terrors.push(`${fieldname}: expected array, got ${typeof value}`)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (typeof value !== 'object' || Array.isArray(value)) {\n\t\t\t\t\terrors.push(`${fieldname}: expected object, got ${typeof value}`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new Error(`Field type validation failed:\\n${errors.join('\\n')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate a single field value against its expected type\n */\nfunction validateFieldValue(field: FieldMeta, value: unknown): string | null {\n\tconst { fieldname, fieldtype, cardinality } = field\n\n\tswitch (fieldtype) {\n\t\tcase 'Int':\n\t\t\tif (typeof value !== 'number' || !Number.isInteger(value)) {\n\t\t\t\treturn `${fieldname}: expected integer, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Float':\n\t\tcase 'Decimal':\n\t\tcase 'Currency':\n\t\tcase 'Quantity':\n\t\t\tif (typeof value !== 'number' && typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected number, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Check':\n\t\t\tif (typeof value !== 'boolean') {\n\t\t\t\treturn `${fieldname}: expected boolean, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Data':\n\t\tcase 'Text':\n\t\tcase 'Code':\n\t\tcase 'Link':\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected string, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Date':\n\t\tcase 'Time':\n\t\tcase 'Datetime':\n\t\t\tif (typeof value !== 'string' && !(value instanceof Date)) {\n\t\t\t\treturn `${fieldname}: expected date string or Date, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'JSON':\n\t\t\tif (typeof value !== 'object') {\n\t\t\t\treturn `${fieldname}: expected object, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\t}\n\n\treturn null\n}\n\n/**\n * No-op handler for testing or placeholder actions\n */\nconst noop: ActionHandler = async () => {\n\treturn { ok: true }\n}\n\n/**\n * Built-in handlers available for registration\n * @public\n */\nexport const builtinHandlers: Record<string, ActionHandler> = {\n\tvalidateRequiredFields,\n\tvalidateFieldTypes,\n\tnoop,\n}\n\n/**\n * Register all built-in handlers\n * @public\n */\nexport function registerBuiltinHandlers(): void {\n\tfor (const [name, handler] of Object.entries(builtinHandlers)) {\n\t\tregisterHandler(name, handler)\n\t}\n}\n","import type { DoctypeMeta } from '@stonecrop/schema'\nimport { snakeToCamel, toPascalCase } from '@stonecrop/schema'\nimport { constant, lambda, object, loadOne } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema, gql } from 'postgraphile/utils'\nimport pluralize from 'pluralize'\n\nimport { getHandler, registerHandler } from '../registry/actions'\nimport { getMeta, getAllMeta } from '../registry/doctypes'\nimport type { ActionContext, GraphQLExecutor } from '../types'\n\n/**\n * Inflection callbacks for mapping table names to GraphQL query field names.\n * Override these when using a non-Amber inflection preset (e.g., V4, SimplifyInflection).\n *\n * Defaults match the PostGraphile Amber preset conventions.\n * @public\n */\nexport interface StonecropInflectionConfig {\n\t/**\n\t * Given a table name, return the GraphQL field name for fetching a single record by ID.\n\t * @example Amber default: \"sales_orders\" → \"salesOrderById\"\n\t * @example V4 preset: \"sales_orders\" → \"salesOrderByRowId\"\n\t */\n\trecordFieldName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL field name for fetching a list/connection.\n\t * @example Amber default: \"sales_orders\" → \"allSalesOrders\"\n\t * @example SimplifyInflection: \"sales_orders\" → \"salesOrders\"\n\t */\n\tconnectionFieldName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL OrderBy enum type name.\n\t * @example Amber default: \"sales_orders\" → \"SalesOrdersOrderBy\"\n\t */\n\torderByTypeName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL argument name used to look up a record by PK.\n\t * @example Amber default (Relay Global ID): \"sales_orders\" → \"id\"\n\t * @example row_id PK: \"sales_orders\" → \"rowId\"\n\t */\n\trecordArgName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL variable type for the PK argument.\n\t * @example Default UUID PK: \"sales_orders\" → \"UUID!\"\n\t * @example Integer PK: \"sales_orders\" → \"Int!\"\n\t */\n\trecordArgType?: (tableName: string) => string\n}\n\n/**\n * Options for creating a Stonecrop PostGraphile plugin\n * @public\n */\nexport interface StonecropPluginOptions {\n\t/** GraphQL executor for running queries/mutations */\n\texecutor: GraphQLExecutor\n\n\t/**\n\t * Override inflection conventions for mapping table names to GraphQL field names.\n\t * Defaults to PostGraphile Amber preset conventions.\n\t */\n\tinflection?: StonecropInflectionConfig\n}\n\n/**\n * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality\n * @param options - Plugin configuration options\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createStonecropPlugin = (options: StonecropPluginOptions): GraphileConfig.Plugin => {\n\t// Resolve inflection callbacks with Amber defaults\n\tconst recordFieldName = options.inflection?.recordFieldName ?? defaultRecordFieldName\n\tconst connectionFieldName = options.inflection?.connectionFieldName ?? defaultConnectionFieldName\n\tconst orderByTypeName = options.inflection?.orderByTypeName ?? defaultOrderByTypeName\n\tconst recordArgName = options.inflection?.recordArgName ?? defaultRecordArgName\n\tconst recordArgType = options.inflection?.recordArgType ?? defaultRecordArgType\n\n\treturn extendSchema(() => {\n\t\treturn {\n\t\t\ttypeDefs: gql`\n\t\t\t\ttype StonecropFieldMeta {\n\t\t\t\t\tfieldname: String!\n\t\t\t\t\tfieldtype: String!\n\t\t\t\t\tcomponent: String\n\t\t\t\t\tlabel: String\n\t\t\t\t\twidth: String\n\t\t\t\t\talign: String\n\t\t\t\t\trequired: Boolean\n\t\t\t\t\treadOnly: Boolean\n\t\t\t\t\tedit: Boolean\n\t\t\t\t\thidden: Boolean\n\t\t\t\t\tdefault: JSON\n\t\t\t\t\toptions: JSON\n\t\t\t\t\tmask: String\n\t\t\t\t\tprecision: Int\n\t\t\t\t\tscale: Int\n\t\t\t\t\tmode: String\n\t\t\t\t\tvalidation: JSON\n\t\t\t\t}\n\n\t\t\t\ttype StonecropWorkflowAction {\n\t\t\t\t\tlabel: String!\n\t\t\t\t\thandler: String!\n\t\t\t\t\trequiredFields: [String!]\n\t\t\t\t\tallowedStates: [String!]\n\t\t\t\t\tconfirm: Boolean\n\t\t\t\t\targs: JSON\n\t\t\t\t}\n\n\t\t\t\ttype StonecropWorkflowMeta {\n\t\t\t\t\tstates: [String!]\n\t\t\t\t\tactions: [StonecropWorkflowAction!]\n\t\t\t\t}\n\n\t\t\t\ttype StonecropDoctypeMeta {\n\t\t\t\t\tname: String!\n\t\t\t\t\tslug: String\n\t\t\t\t\ttableName: String\n\t\t\t\t\tfields: [StonecropFieldMeta!]!\n\t\t\t\t\tworkflow: StonecropWorkflowMeta\n\t\t\t\t\tinherits: String\n\t\t\t\t}\n\n\t\t\t\ttype StonecropRecordResult {\n\t\t\t\t\tdata: JSON\n\t\t\t\t\tdoctype: String!\n\t\t\t\t}\n\n\t\t\t\ttype StonecropRecordsResult {\n\t\t\t\t\tdata: [JSON!]!\n\t\t\t\t\tdoctype: String!\n\t\t\t\t\tcount: Int!\n\t\t\t\t}\n\n\t\t\t\ttype StonecropActionResult {\n\t\t\t\t\tsuccess: Boolean!\n\t\t\t\t\tdata: JSON\n\t\t\t\t\terror: String\n\t\t\t\t}\n\n\t\t\t\textend type Query {\n\t\t\t\t\tstonecropMeta(doctype: String!): StonecropDoctypeMeta\n\t\t\t\t\tstonecropAllMeta: [StonecropDoctypeMeta!]!\n\t\t\t\t\tstonecropRecord(doctype: String!, id: String!): StonecropRecordResult\n\t\t\t\t\tstonecropRecords(\n\t\t\t\t\t\tdoctype: String!\n\t\t\t\t\t\tfilters: JSON\n\t\t\t\t\t\torderBy: String\n\t\t\t\t\t\tlimit: Int\n\t\t\t\t\t\toffset: Int\n\t\t\t\t\t): StonecropRecordsResult\n\t\t\t\t}\n\n\t\t\t\textend type Mutation {\n\t\t\t\t\tstonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!\n\t\t\t\t}\n\t\t\t`,\n\n\t\t\tobjects: {\n\t\t\t\tQuery: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropMeta(_: any, { $doctype }: any) {\n\t\t\t\t\t\t\treturn lambda($doctype, (doctype: unknown) => {\n\t\t\t\t\t\t\t\tconst meta = getMeta(doctype as string)\n\t\t\t\t\t\t\t\treturn meta ?? null\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropAllMeta() {\n\t\t\t\t\t\t\treturn constant(getAllMeta())\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecord(_: any, { $doctype, $id }: any) {\n\t\t\t\t\t\t\treturn loadOne(object({ doctype: $doctype, id: $id }), async (specs: readonly any[]) => {\n\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(spec.doctype)\n\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown doctype: ${spec.doctype}`)\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif (!meta.tableName) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Doctype ${spec.doctype} has no table mapping`)\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tconst query = buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType)\n\t\t\t\t\t\t\t\t\t\tconst result = await options.executor.query(query, {\n\t\t\t\t\t\t\t\t\t\t\t[recordArgName(meta.tableName!)]: spec.id,\n\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tdata: extractSingleResult(result, meta, recordFieldName),\n\t\t\t\t\t\t\t\t\t\t\tdoctype: spec.doctype,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecords(_: any, { $doctype, $filters, $orderBy, $limit, $offset }: any) {\n\t\t\t\t\t\t\treturn loadOne(\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\tfilters: $filters,\n\t\t\t\t\t\t\t\t\torderBy: $orderBy,\n\t\t\t\t\t\t\t\t\tlimit: $limit,\n\t\t\t\t\t\t\t\t\toffset: $offset,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (specs: readonly any[]) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown doctype: ${spec.doctype}`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif (!meta.tableName) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Doctype ${spec.doctype} has no table mapping`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst query = buildListQuery(\n\t\t\t\t\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tlimit: spec.limit,\n\t\t\t\t\t\t\t\t\t\t\t\t\toffset: spec.offset,\n\t\t\t\t\t\t\t\t\t\t\t\t\torderBy: spec.orderBy,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\tconnectionFieldName,\n\t\t\t\t\t\t\t\t\t\t\t\torderByTypeName\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\tconst result = await options.executor.query(query, {\n\t\t\t\t\t\t\t\t\t\t\t\tlimit: spec.limit,\n\t\t\t\t\t\t\t\t\t\t\t\toffset: spec.offset,\n\t\t\t\t\t\t\t\t\t\t\t\torderBy: spec.orderBy,\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\tconst data = extractListResult(result, meta, connectionFieldName)\n\n\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype: spec.doctype,\n\t\t\t\t\t\t\t\t\t\t\t\tcount: data.length,\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\tMutation: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropAction(_: any, { $doctype, $action, $args: $actionArgs }: any) {\n\t\t\t\t\t\t\treturn loadOne(\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\taction: $action,\n\t\t\t\t\t\t\t\t\tactionArgs: $actionArgs,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (specs: readonly any[]) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `Unknown doctype: ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst actionDef = meta.workflow?.actions?.[spec.action]\n\t\t\t\t\t\t\t\t\t\t\tif (!actionDef) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `Unknown action: ${spec.action} on ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst handlerName = actionDef.handler\n\t\t\t\t\t\t\t\t\t\t\tconst handler = getHandler(handlerName)\n\t\t\t\t\t\t\t\t\t\t\tif (!handler) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `Handler not registered: ${handlerName}`,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst actionContext: ActionContext = {\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype: meta,\n\t\t\t\t\t\t\t\t\t\t\t\texecutor: options.executor,\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\tconst result = await handler(spec.actionArgs ?? [], actionContext)\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: null,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n}\n\n// =============================================================================\n// Inflection helpers — default to PostGraphile Amber preset conventions\n// Uses `pluralize` for proper English singularization (handles irregular\n// plurals like statuses→status, categories→category, addresses→address).\n// snakeToCamel / toPascalCase are imported from @stonecrop/schema.\n// =============================================================================\n\n/**\n * Amber default: sales_orders → salesOrderById\n * Uses `pluralize` for proper singularization of irregular plurals.\n * Override via `StonecropInflectionConfig.recordFieldName` for non-standard PK columns.\n * @public\n */\nfunction defaultRecordFieldName(tableName: string): string {\n\tconst singular = pluralize.singular(tableName)\n\treturn `${snakeToCamel(singular)}ById`\n}\n\n/**\n * Amber default: sales_orders → allSalesOrders\n * @public\n */\nfunction defaultConnectionFieldName(tableName: string): string {\n\treturn `all${toPascalCase(tableName)}`\n}\n\n/**\n * Amber default: sales_orders → SalesOrdersOrderBy\n * @public\n */\nfunction defaultOrderByTypeName(tableName: string): string {\n\treturn `${toPascalCase(tableName)}OrderBy`\n}\n\n/**\n * Default PK argument name: 'id' (standard Relay Global ID pattern).\n * Override via `StonecropInflectionConfig.recordArgName` when using row_id columns;\n * PostGraphile Amber generates `rowId: UUID!` for those fields.\n * @public\n */\nfunction defaultRecordArgName(_tableName: string): string {\n\treturn 'id'\n}\n\n/**\n * Default PK argument type: 'UUID!' (PostGraphile Amber default for UUID PKs).\n * Override via `StonecropInflectionConfig.recordArgType` when using non-UUID PKs\n * such as integer serials or Relay Global IDs ('ID!').\n * @public\n */\nfunction defaultRecordArgType(_tableName: string): string {\n\treturn 'UUID!'\n}\n\n// =============================================================================\n// Query builders — generate GraphQL queries to send to the underlying schema\n// =============================================================================\n\n/**\n * Fieldtypes that map to GraphQL object/connection types and require sub-selections.\n * These fields are excluded from generated query field selections.\n * @public\n */\nconst RELATION_FIELDTYPES = new Set(['Link'])\n\n/**\n * Filter fields to only those directly queryable as scalars, excluding Link and Doctype\n * relation fields that require GraphQL sub-selections.\n * @public\n */\nfunction queryableFieldNames(meta: DoctypeMeta): string {\n\treturn meta.fields\n\t\t.filter(f => !RELATION_FIELDTYPES.has(f.fieldtype))\n\t\t.map(f => f.fieldname)\n\t\t.join('\\n ')\n}\n\n/**\n * Build a GraphQL query to fetch a single record by ID.\n * Excludes Link and Doctype relation fields from the selection set.\n * The PK argument name and type are configurable via `StonecropInflectionConfig.recordArgName`\n * and `StonecropInflectionConfig.recordArgType` to match the target schema's conventions\n * (e.g. `rowId: UUID!` for PostGraphile Amber with row_id columns).\n * @public\n */\nfunction buildRecordQuery(\n\tmeta: DoctypeMeta,\n\trecordFieldName: (t: string) => string,\n\trecordArgName: (t: string) => string,\n\trecordArgType: (t: string) => string\n): string {\n\tconst fieldNames = queryableFieldNames(meta)\n\tconst queryName = recordFieldName(meta.tableName!)\n\tconst argName = recordArgName(meta.tableName!)\n\tconst argType = recordArgType(meta.tableName!)\n\n\treturn `\n\t\tquery GetRecord($${argName}: ${argType}) {\n\t\t\t${queryName}(${argName}: $${argName}) {\n\t\t\t\t${fieldNames}\n\t\t\t}\n\t\t}\n\t`\n}\n\n/**\n * Build a GraphQL connection query to fetch a list of records.\n * Only declares variables ($limit, $offset, $orderBy) that are actually used in the query,\n * avoiding GraphQL spec §5.8.3 violations from unused variable declarations.\n * Excludes Link and Doctype relation fields from the selection set.\n * @public\n */\nfunction buildListQuery(\n\tmeta: DoctypeMeta,\n\targs: { limit?: number; offset?: number; orderBy?: string },\n\tconnectionFieldName: (t: string) => string,\n\torderByTypeName: (t: string) => string\n): string {\n\tconst fieldNames = queryableFieldNames(meta)\n\tconst connectionName = connectionFieldName(meta.tableName!)\n\tconst orderByType = orderByTypeName(meta.tableName!)\n\n\tconst varDecls: string[] = []\n\tconst queryArgs: string[] = []\n\tif (args.limit) {\n\t\tvarDecls.push('$limit: Int')\n\t\tqueryArgs.push(`first: $limit`)\n\t}\n\tif (args.offset) {\n\t\tvarDecls.push('$offset: Int')\n\t\tqueryArgs.push(`offset: $offset`)\n\t}\n\tif (args.orderBy) {\n\t\tvarDecls.push(`$orderBy: [${orderByType}!]`)\n\t\tqueryArgs.push(`orderBy: $orderBy`)\n\t}\n\n\tconst varStr = varDecls.length > 0 ? `(${varDecls.join(', ')})` : ''\n\tconst argsStr = queryArgs.length > 0 ? `(${queryArgs.join(', ')})` : ''\n\n\treturn `\n\t\tquery GetRecords${varStr} {\n\t\t\t${connectionName}${argsStr} {\n\t\t\t\tnodes {\n\t\t\t\t${fieldNames}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`\n}\n\n/**\n * Extract a single record from a PostGraphile query result using the record field name.\n * @internal\n */\nfunction extractSingleResult(result: unknown, meta: DoctypeMeta, recordFieldName: (t: string) => string): unknown {\n\tconst queryName = recordFieldName(meta.tableName!)\n\treturn (result as Record<string, unknown>)[queryName]\n}\n\n/**\n * Extract the list of nodes from a PostGraphile connection query result.\n * Returns an empty array if the connection field is absent.\n * @internal\n */\nfunction extractListResult(result: unknown, meta: DoctypeMeta, connectionFieldName: (t: string) => string): unknown[] {\n\tconst connectionName = connectionFieldName(meta.tableName!)\n\tconst connection = (result as Record<string, unknown>)[connectionName] as {\n\t\tnodes: unknown[]\n\t}\n\treturn connection?.nodes ?? []\n}\n\n// =============================================================================\n// Exported for testing and advanced usage\n// =============================================================================\n\nexport {\n\tdefaultRecordFieldName,\n\tdefaultConnectionFieldName,\n\tdefaultOrderByTypeName,\n\tdefaultRecordArgName,\n\tdefaultRecordArgType,\n\tbuildRecordQuery,\n\tbuildListQuery,\n\tqueryableFieldNames,\n\tRELATION_FIELDTYPES,\n\textractSingleResult,\n\textractListResult,\n}\n"],"names":["doctypeRegistry","DoctypeValidationError","file","errors","errorMessages","e","loadDoctypes","dir","options","entries","readdirSync","entry","fullPath","join","statSync","loadDoctypeFile","filePath","content","readFileSync","data","err","parseError","result","validateDoctype","doctype","parseDoctype","loadDoctypesFromObject","doctypes","name","withName","getMeta","getAllMeta","hasMeta","clearRegistry","validateReferences","field","handlerRegistry","registerHandler","handler","getHandler","hasHandler","clearHandlers","validateRequiredFields","args","context","record","missing","validateFieldTypes","value","error","validateFieldValue","fieldname","link","fieldtype","cardinality","noop","builtinHandlers","registerBuiltinHandlers","createStonecropPlugin","recordFieldName","defaultRecordFieldName","connectionFieldName","defaultConnectionFieldName","orderByTypeName","defaultOrderByTypeName","recordArgName","defaultRecordArgName","recordArgType","defaultRecordArgType","extendSchema","gql","_","$doctype","lambda","constant","$id","loadOne","object","specs","spec","meta","query","buildRecordQuery","extractSingleResult","$filters","$orderBy","$limit","$offset","buildListQuery","extractListResult","$action","$actionArgs","actionDef","handlerName","actionContext","tableName","singular","pluralize","snakeToCamel","toPascalCase","_tableName","RELATION_FIELDTYPES","queryableFieldNames","f","fieldNames","queryName","argName","argType","connectionName","orderByType","varDecls","queryArgs","varStr","argsStr"],"mappings":";;;;;;AAMA,MAAMA,wBAAgD,IAAA;AAM/C,MAAMC,UAA+B,MAAM;AAAA,EACjD,YAEiBC,GAEAC,GACf;AACD,UAAMC,IAAgBD,EAAO,IAAI,CAAAE,MAAK,KAAKA,EAAE,KAAK,KAAK,GAAG,CAAC,KAAKA,EAAE,OAAO,EAAE,EAAE,KAAK;AAAA,CAAI;AACtF,UAAM,iCAAiCH,CAAI;AAAA,EAAME,CAAa,EAAE,GALhD,KAAA,OAAAF,GAEA,KAAA,SAAAC,GAIhB,KAAK,OAAO;AAAA,EACb;AACD;AAmBO,SAASG,EAAaC,GAAaC,IAA+B,IAAU;AAClF,QAAMC,IAAUC,EAAYH,CAAG;AAE/B,aAAWI,KAASF,GAAS;AAC5B,UAAMG,IAAWC,EAAKN,GAAKI,CAAK;AAGhC,IAFaG,EAASF,CAAQ,EAErB,gBACRN,EAAaM,GAAUJ,CAAO,IACpBG,EAAM,SAAS,OAAO,KAChCI,EAAgBH,GAAUJ,CAAO;AAAA,EAEnC;AACD;AAKA,SAASO,EAAgBC,GAAkBR,GAAoC;AAC9E,QAAMS,IAAUC,EAAaF,GAAU,OAAO;AAC9C,MAAIG;AAEJ,MAAI;AACH,IAAAA,IAAO,KAAK,MAAMF,CAAO;AAAA,EAC1B,SAASG,GAAK;AACb,UAAMC,IAA8B;AAAA,MACnC,MAAM,CAAA;AAAA,MACN,SAAS,iBAAiBD,aAAe,QAAQA,EAAI,UAAU,OAAOA,CAAG,CAAC;AAAA,IAAA;AAG3E,QAAIZ,EAAQ,iBAAiB;AAC5B,MAAAA,EAAQ,UAAUQ,GAAU,CAACK,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AAc,GAC5BC,EAAU,KAAK,iBAAiB,IAE7BpE,EAAK,YACRmE,EAAS,KAAK,cAAcD,CAAW,IAAI,GAC3CE,EAAU,KAAK,mBAAmB;AAGnC,QAAMC,IAASF,EAAS,SAAS,IAAI,IAAIA,EAAS,KAAK,IAAI,CAAC,MAAM,IAC5DG,IAAUF,EAAU,SAAS,IAAI,IAAIA,EAAU,KAAK,IAAI,CAAC,MAAM;AAErE,SAAO;AAAA,oBACYC,CAAM;AAAA,KACrBJ,CAAc,GAAGK,CAAO;AAAA;AAAA,MAEvBT,CAAU;AAAA;AAAA;AAAA;AAAA;AAKhB;AAMA,SAASrB,GAAoB7D,GAAiB0D,GAAmBrB,GAAiD;AACjH,QAAM8C,IAAY9C,EAAgBqB,EAAK,SAAU;AACjD,SAAQ1D,EAAmCmF,CAAS;AACrD;AAOA,SAAShB,GAAkBnE,GAAiB0D,GAAmBnB,GAAuD;AACrH,QAAM+C,IAAiB/C,EAAoBmB,EAAK,SAAU;AAI1D,SAHoB1D,EAAmCsF,CAAc,GAGlD,SAAS,CAAA;AAC7B;"}
@@ -40,7 +40,7 @@ export const createStonecropPlugin = (options) => {
40
40
  validation: JSON
41
41
  }
42
42
 
43
- type StonecropActionDefinition {
43
+ type StonecropWorkflowAction {
44
44
  label: String!
45
45
  handler: String!
46
46
  requiredFields: [String!]
@@ -51,7 +51,7 @@ export const createStonecropPlugin = (options) => {
51
51
 
52
52
  type StonecropWorkflowMeta {
53
53
  states: [String!]
54
- actions: JSON
54
+ actions: [StonecropWorkflowAction!]
55
55
  }
56
56
 
57
57
  type StonecropDoctypeMeta {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stonecrop/graphql-middleware",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "type": "module",
5
5
  "types": "./dist/graphql-middleware.d.ts",
6
6
  "exports": {
@@ -17,7 +17,7 @@
17
17
  "graphql": "^16.12.0",
18
18
  "pluralize": "^8.0.0",
19
19
  "postgraphile": "^5.0.0-rc.7",
20
- "@stonecrop/schema": "0.11.0"
20
+ "@stonecrop/schema": "0.11.1"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@rushstack/heft": "^1.2.0",
package/dist/index.cjs DELETED
@@ -1,86 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("node:fs"),J=require("node:path"),h=require("@stonecrop/schema"),k=require("postgraphile/utils"),p=require("postgraphile/grafast"),L=require("pluralize"),f=new Map;class b extends Error{constructor(t,r){const o=r.map(n=>` ${n.path.join(".")}: ${n.message}`).join(`
2
- `);super(`Invalid doctype definition in ${t}:
3
- ${o}`),this.file=t,this.errors=r,this.name="DoctypeValidationError"}}function E(e,t={}){const r=D.readdirSync(e);for(const o of r){const n=J.join(e,o);D.statSync(n).isDirectory()?E(n,t):o.endsWith(".json")&&_(n,t)}}function _(e,t){const r=D.readFileSync(e,"utf-8");let o;try{o=JSON.parse(r)}catch(s){const c={path:[],message:`Invalid JSON: ${s instanceof Error?s.message:String(s)}`};if(t.continueOnError){t.onError?.(e,[c]);return}throw new b(e,[c])}const n=h.validateDoctype(o);if(!n.success){if(t.continueOnError){t.onError?.(e,n.errors);return}throw new b(e,n.errors)}const a=h.parseDoctype(o);f.set(a.name,a)}function C(e,t={}){for(const[r,o]of Object.entries(e)){const n={...o,name:r},a=h.validateDoctype(n);if(!a.success){if(t.continueOnError){t.onError?.(r,a.errors);continue}throw new b(r,a.errors)}const s=h.parseDoctype(n);f.set(s.name,s)}}function $(e){return f.get(e)}function F(){return Array.from(f.values())}function P(e){return f.has(e)}function Q(){f.clear()}function U(){const e=[];for(const t of f.values()){t.inherits&&!f.has(t.inherits)&&e.push({path:[t.name,"inherits"],message:`References unknown doctype: ${t.inherits}`}),t.listDoctype&&!f.has(t.listDoctype)&&e.push({path:[t.name,"listDoctype"],message:`References unknown doctype: ${t.listDoctype}`}),t.parentDoctype&&!f.has(t.parentDoctype)&&e.push({path:[t.name,"parentDoctype"],message:`References unknown doctype: ${t.parentDoctype}`});for(const r of t.fields)r.fieldtype==="Link"&&typeof r.options=="string"&&(f.has(r.options)||e.push({path:[t.name,"fields",r.fieldname,"options"],message:`Link references unknown doctype: ${r.options}`}))}return e}const N=new Map;function M(e,t){N.set(e,t)}function q(e){return N.get(e)}function v(e){return N.has(e)}function V(){N.clear()}const W=async(e,t)=>{const[r]=e,{doctype:o}=t,n=[];for(const a of o.fields)a.required&&(r[a.fieldname]===void 0||r[a.fieldname]===null)&&n.push(a.label??a.fieldname);if(n.length>0)throw new Error(`Missing required fields: ${n.join(", ")}`);return{valid:!0}},G=async(e,t)=>{const[r]=e,{doctype:o}=t,n=[];for(const a of o.fields){const s=r[a.fieldname];if(s==null)continue;const c=Y(a.fieldname,s,a.fieldtype);c&&n.push(c)}if(n.length>0)throw new Error(`Field type validation failed:
4
- ${n.join(`
5
- `)}`);return{valid:!0}};function Y(e,t,r){switch(r){case"Int":if(typeof t!="number"||!Number.isInteger(t))return`${e}: expected integer, got ${typeof t}`;break;case"Float":case"Decimal":case"Currency":case"Quantity":if(typeof t!="number"&&typeof t!="string")return`${e}: expected number, got ${typeof t}`;break;case"Check":if(typeof t!="boolean")return`${e}: expected boolean, got ${typeof t}`;break;case"Data":case"Text":case"Code":case"Link":if(typeof t!="string")return`${e}: expected string, got ${typeof t}`;break;case"Date":case"Time":case"Datetime":if(typeof t!="string"&&!(t instanceof Date))return`${e}: expected date string or Date, got ${typeof t}`;break;case"JSON":if(typeof t!="object")return`${e}: expected object, got ${typeof t}`;break;case"Table":if(!Array.isArray(t))return`${e}: expected array, got ${typeof t}`;break}return null}const z=async()=>({ok:!0}),A={validateRequiredFields:W,validateFieldTypes:G,noop:z};function K(){for(const[e,t]of Object.entries(A))M(e,t)}const X=e=>{const t=e.inflection?.recordFieldName??B,r=e.inflection?.connectionFieldName??j,o=e.inflection?.orderByTypeName??x,n=e.inflection?.recordArgName??Z,a=e.inflection?.recordArgType??ee;return k.extendSchema(()=>({typeDefs:k.gql`
6
- type StonecropFieldMeta {
7
- fieldname: String!
8
- fieldtype: String!
9
- label: String
10
- required: Boolean
11
- options: JSON
12
- }
13
-
14
- type StonecropActionDefinition {
15
- label: String!
16
- handler: String!
17
- requiredFields: [String!]
18
- allowedStates: [String!]
19
- confirm: Boolean
20
- args: JSON
21
- }
22
-
23
- type StonecropWorkflowMeta {
24
- states: [String!]
25
- actions: JSON
26
- }
27
-
28
- type StonecropDoctypeMeta {
29
- name: String!
30
- tableName: String
31
- fields: [StonecropFieldMeta!]!
32
- workflow: StonecropWorkflowMeta
33
- listDoctype: String
34
- parentDoctype: String
35
- }
36
-
37
- type StonecropRecordResult {
38
- data: JSON
39
- doctype: String!
40
- }
41
-
42
- type StonecropRecordsResult {
43
- data: [JSON!]!
44
- doctype: String!
45
- count: Int!
46
- }
47
-
48
- type StonecropActionResult {
49
- success: Boolean!
50
- data: JSON
51
- error: String
52
- }
53
-
54
- extend type Query {
55
- stonecropMeta(doctype: String!): StonecropDoctypeMeta
56
- stonecropAllMeta: [StonecropDoctypeMeta!]!
57
- stonecropRecord(doctype: String!, id: String!): StonecropRecordResult
58
- stonecropRecords(
59
- doctype: String!
60
- filters: JSON
61
- orderBy: String
62
- limit: Int
63
- offset: Int
64
- ): StonecropRecordsResult
65
- }
66
-
67
- extend type Mutation {
68
- stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
69
- }
70
- `,objects:{Query:{plans:{stonecropMeta(s,{$doctype:c}){return p.lambda(c,d=>$(d)??null)},stonecropAllMeta(){return p.constant(F())},stonecropRecord(s,{$doctype:c,$id:d}){return p.loadOne(p.object({doctype:c,id:d}),async y=>await Promise.all(y.map(async u=>{const l=$(u.doctype);if(!l)throw new Error(`Unknown doctype: ${u.doctype}`);if(!l.tableName)throw new Error(`Doctype ${u.doctype} has no table mapping`);const g=I(l,t,n,a),i=await e.executor.query(g,{[n(l.tableName)]:u.id});return{data:te(i,l,t),doctype:u.doctype}})))},stonecropRecords(s,{$doctype:c,$filters:d,$orderBy:y,$limit:u,$offset:l}){return p.loadOne(p.object({doctype:c,filters:d,orderBy:y,limit:u,offset:l}),async g=>await Promise.all(g.map(async i=>{const m=$(i.doctype);if(!m)throw new Error(`Unknown doctype: ${i.doctype}`);if(!m.tableName)throw new Error(`Doctype ${i.doctype} has no table mapping`);const w=H(m,{limit:i.limit,offset:i.offset,orderBy:i.orderBy},r,o),S=await e.executor.query(w,{limit:i.limit,offset:i.offset,orderBy:i.orderBy}),O=re(S,m,r);return{data:O,doctype:i.doctype,count:O.length}})))}}},Mutation:{plans:{stonecropAction(s,{$doctype:c,$action:d,$args:y}){return p.loadOne(p.object({doctype:c,action:d,actionArgs:y}),async u=>await Promise.all(u.map(async l=>{const g=$(l.doctype);if(!g)return{success:!1,data:null,error:`Unknown doctype: ${l.doctype}`};const i=g.workflow?.actions?.[l.action];if(!i)return{success:!1,data:null,error:`Unknown action: ${l.action} on ${l.doctype}`};const m=q(i.handler);if(!m)return{success:!1,data:null,error:`Handler not registered: ${i.handler}`};const w={doctype:g,executor:e.executor};try{return{success:!0,data:await m(l.actionArgs??[],w),error:null}}catch(S){return{success:!1,data:null,error:S instanceof Error?S.message:String(S)}}})))}}}}}))};function B(e){const t=L.singular(e);return`${h.snakeToCamel(t)}ById`}function j(e){return`all${h.toPascalCase(e)}`}function x(e){return`${h.toPascalCase(e)}OrderBy`}function Z(e){return"id"}function ee(e){return"UUID!"}const T=new Set(["Link","Doctype"]);function R(e){return e.fields.filter(t=>!T.has(t.fieldtype)).map(t=>t.fieldname).join(`
71
- `)}function I(e,t,r,o){const n=R(e),a=t(e.tableName),s=r(e.tableName),c=o(e.tableName);return`
72
- query GetRecord($${s}: ${c}) {
73
- ${a}(${s}: $${s}) {
74
- ${n}
75
- }
76
- }
77
- `}function H(e,t,r,o){const n=R(e),a=r(e.tableName),s=o(e.tableName),c=[],d=[];t.limit&&(c.push("$limit: Int"),d.push("first: $limit")),t.offset&&(c.push("$offset: Int"),d.push("offset: $offset")),t.orderBy&&(c.push(`$orderBy: [${s}!]`),d.push("orderBy: $orderBy"));const y=c.length>0?`(${c.join(", ")})`:"",u=d.length>0?`(${d.join(", ")})`:"";return`
78
- query GetRecords${y} {
79
- ${a}${u} {
80
- nodes {
81
- ${n}
82
- }
83
- }
84
- }
85
- `}function te(e,t,r){const o=r(t.tableName);return e[o]}function re(e,t,r){const o=r(t.tableName);return e[o]?.nodes??[]}exports.DoctypeValidationError=b;exports.RELATION_FIELDTYPES=T;exports.buildListQuery=H;exports.buildRecordQuery=I;exports.builtinHandlers=A;exports.clearHandlers=V;exports.clearRegistry=Q;exports.createStonecropPlugin=X;exports.defaultConnectionFieldName=j;exports.defaultOrderByTypeName=x;exports.defaultRecordFieldName=B;exports.getAllMeta=F;exports.getHandler=q;exports.getMeta=$;exports.hasHandler=v;exports.hasMeta=P;exports.loadDoctypes=E;exports.loadDoctypesFromObject=C;exports.queryableFieldNames=R;exports.registerBuiltinHandlers=K;exports.registerHandler=M;exports.validateReferences=U;
86
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/registry/doctypes.ts","../src/registry/actions.ts","../src/plugin/postgraphile.ts"],"sourcesContent":["import { readFileSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { parseDoctype, validateDoctype } from '@stonecrop/schema'\nimport type { DoctypeMeta, ValidationError } from '@stonecrop/schema'\n\nconst doctypeRegistry: Map<string, DoctypeMeta> = new Map()\n\n/**\n * Error thrown when a doctype definition fails validation\n * @public\n */\nexport class DoctypeValidationError extends Error {\n\tconstructor(\n\t\t/** File path or name where the validation error occurred */\n\t\tpublic readonly file: string,\n\t\t/** List of validation errors found */\n\t\tpublic readonly errors: ValidationError[]\n\t) {\n\t\tconst errorMessages = errors.map(e => ` ${e.path.join('.')}: ${e.message}`).join('\\n')\n\t\tsuper(`Invalid doctype definition in ${file}:\\n${errorMessages}`)\n\t\tthis.name = 'DoctypeValidationError'\n\t}\n}\n\n/**\n * Options for loading doctype definitions\n * @public\n */\nexport interface LoadDoctypesOptions {\n\t/** Continue loading other files if one fails validation */\n\tcontinueOnError?: boolean\n\t/** Callback for validation errors when continueOnError is true */\n\tonError?: (file: string, errors: ValidationError[]) => void\n}\n\n/**\n * Load doctype definitions from a directory of JSON files\n * @param dir - Directory path containing doctype JSON files\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypes(dir: string, options: LoadDoctypesOptions = {}): void {\n\tconst entries = readdirSync(dir)\n\n\tfor (const entry of entries) {\n\t\tconst fullPath = join(dir, entry)\n\t\tconst stat = statSync(fullPath)\n\n\t\tif (stat.isDirectory()) {\n\t\t\tloadDoctypes(fullPath, options)\n\t\t} else if (entry.endsWith('.json')) {\n\t\t\tloadDoctypeFile(fullPath, options)\n\t\t}\n\t}\n}\n\n/**\n * Load and validate a single doctype file\n */\nfunction loadDoctypeFile(filePath: string, options: LoadDoctypesOptions): void {\n\tconst content = readFileSync(filePath, 'utf-8')\n\tlet data: unknown\n\n\ttry {\n\t\tdata = JSON.parse(content)\n\t} catch (err) {\n\t\tconst parseError: ValidationError = {\n\t\t\tpath: [],\n\t\t\tmessage: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t}\n\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, [parseError])\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, [parseError])\n\t}\n\n\tconst result = validateDoctype(data)\n\n\tif (!result.success) {\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, result.errors)\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, result.errors)\n\t}\n\n\tconst doctype = parseDoctype(data)\n\tdoctypeRegistry.set(doctype.name, doctype)\n}\n\n/**\n * Load doctypes from an object (for programmatic use)\n * @param doctypes - Object mapping doctype names to doctype definitions\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypesFromObject(doctypes: Record<string, unknown>, options: LoadDoctypesOptions = {}): void {\n\tfor (const [name, data] of Object.entries(doctypes)) {\n\t\tconst withName = { ...(data as object), name }\n\t\tconst result = validateDoctype(withName)\n\n\t\tif (!result.success) {\n\t\t\tif (options.continueOnError) {\n\t\t\t\toptions.onError?.(name, result.errors)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthrow new DoctypeValidationError(name, result.errors)\n\t\t}\n\n\t\tconst doctype = parseDoctype(withName)\n\t\tdoctypeRegistry.set(doctype.name, doctype)\n\t}\n}\n\n/**\n * Get a doctype by name\n * @param name - Name of the doctype to retrieve\n * @public\n */\nexport function getMeta(name: string): DoctypeMeta | undefined {\n\treturn doctypeRegistry.get(name)\n}\n\n/**\n * Get all loaded doctypes\n * @public\n */\nexport function getAllMeta(): DoctypeMeta[] {\n\treturn Array.from(doctypeRegistry.values())\n}\n\n/**\n * Check if a doctype is registered\n * @param name - Name of the doctype to check\n * @public\n */\nexport function hasMeta(name: string): boolean {\n\treturn doctypeRegistry.has(name)\n}\n\n/**\n * Clear all registered doctypes\n * @public\n */\nexport function clearRegistry(): void {\n\tdoctypeRegistry.clear()\n}\n\n/**\n * Validate cross-doctype references (Link fields, inherits, etc.)\n * Call after all doctypes are loaded.\n * @public\n */\nexport function validateReferences(): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\t// Check inherits reference\n\t\tif (doctype.inherits && !doctypeRegistry.has(doctype.inherits)) {\n\t\t\terrors.push({\n\t\t\t\tpath: [doctype.name, 'inherits'],\n\t\t\t\tmessage: `References unknown doctype: ${doctype.inherits}`,\n\t\t\t})\n\t\t}\n\n\t\t// Check listDoctype reference\n\t\tif (doctype.listDoctype && !doctypeRegistry.has(doctype.listDoctype)) {\n\t\t\terrors.push({\n\t\t\t\tpath: [doctype.name, 'listDoctype'],\n\t\t\t\tmessage: `References unknown doctype: ${doctype.listDoctype}`,\n\t\t\t})\n\t\t}\n\n\t\t// Check parentDoctype reference\n\t\tif (doctype.parentDoctype && !doctypeRegistry.has(doctype.parentDoctype)) {\n\t\t\terrors.push({\n\t\t\t\tpath: [doctype.name, 'parentDoctype'],\n\t\t\t\tmessage: `References unknown doctype: ${doctype.parentDoctype}`,\n\t\t\t})\n\t\t}\n\n\t\t// Check Link field targets\n\t\tfor (const field of doctype.fields) {\n\t\t\tif (field.fieldtype === 'Link' && typeof field.options === 'string') {\n\t\t\t\tif (!doctypeRegistry.has(field.options)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'fields', field.fieldname, 'options'],\n\t\t\t\t\t\tmessage: `Link references unknown doctype: ${field.options}`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors\n}\n","import type { DoctypeMeta } from '@stonecrop/schema'\nimport type { ActionHandler, ActionContext } from '../types'\n\nconst handlerRegistry: Map<string, ActionHandler> = new Map()\n\n/**\n * Register an action handler\n * @param name - Unique name for the action handler\n * @param handler - Action handler function to register\n * @public\n */\nexport function registerHandler(name: string, handler: ActionHandler): void {\n\thandlerRegistry.set(name, handler)\n}\n\n/**\n * Get a registered handler by name\n * @param name - Name of the action handler to retrieve\n * @public\n */\nexport function getHandler(name: string): ActionHandler | undefined {\n\treturn handlerRegistry.get(name)\n}\n\n/**\n * Check if a handler is registered\n * @param name - Name of the action handler to check\n * @public\n */\nexport function hasHandler(name: string): boolean {\n\treturn handlerRegistry.has(name)\n}\n\n/**\n * Clear all registered handlers\n * @public\n */\nexport function clearHandlers(): void {\n\thandlerRegistry.clear()\n}\n\n// =============================================================================\n// Built-in Handlers\n// =============================================================================\n\n/**\n * Validate that all required fields are present in a record\n */\nconst validateRequiredFields: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst missing: string[] = []\n\tfor (const field of doctype.fields) {\n\t\tif (field.required && (record[field.fieldname] === undefined || record[field.fieldname] === null)) {\n\t\t\tmissing.push(field.label ?? field.fieldname)\n\t\t}\n\t}\n\n\tif (missing.length > 0) {\n\t\tthrow new Error(`Missing required fields: ${missing.join(', ')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate field types match expected types\n */\nconst validateFieldTypes: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst errors: string[] = []\n\n\tfor (const field of doctype.fields) {\n\t\tconst value = record[field.fieldname]\n\t\tif (value === undefined || value === null) continue\n\n\t\tconst error = validateFieldValue(field.fieldname, value, field.fieldtype)\n\t\tif (error) errors.push(error)\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new Error(`Field type validation failed:\\n${errors.join('\\n')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate a single field value against its expected type\n */\nfunction validateFieldValue(fieldname: string, value: unknown, fieldtype: string): string | null {\n\tswitch (fieldtype) {\n\t\tcase 'Int':\n\t\t\tif (typeof value !== 'number' || !Number.isInteger(value)) {\n\t\t\t\treturn `${fieldname}: expected integer, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Float':\n\t\tcase 'Decimal':\n\t\tcase 'Currency':\n\t\tcase 'Quantity':\n\t\t\tif (typeof value !== 'number' && typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected number, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Check':\n\t\t\tif (typeof value !== 'boolean') {\n\t\t\t\treturn `${fieldname}: expected boolean, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Data':\n\t\tcase 'Text':\n\t\tcase 'Code':\n\t\tcase 'Link':\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected string, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Date':\n\t\tcase 'Time':\n\t\tcase 'Datetime':\n\t\t\tif (typeof value !== 'string' && !(value instanceof Date)) {\n\t\t\t\treturn `${fieldname}: expected date string or Date, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'JSON':\n\t\t\tif (typeof value !== 'object') {\n\t\t\t\treturn `${fieldname}: expected object, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Table':\n\t\t\tif (!Array.isArray(value)) {\n\t\t\t\treturn `${fieldname}: expected array, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\t}\n\n\treturn null\n}\n\n/**\n * No-op handler for testing or placeholder actions\n */\nconst noop: ActionHandler = async () => {\n\treturn { ok: true }\n}\n\n/**\n * Built-in handlers available for registration\n * @public\n */\nexport const builtinHandlers: Record<string, ActionHandler> = {\n\tvalidateRequiredFields,\n\tvalidateFieldTypes,\n\tnoop,\n}\n\n/**\n * Register all built-in handlers\n * @public\n */\nexport function registerBuiltinHandlers(): void {\n\tfor (const [name, handler] of Object.entries(builtinHandlers)) {\n\t\tregisterHandler(name, handler)\n\t}\n}\n","import { extendSchema, gql } from 'postgraphile/utils'\nimport { constant, lambda, object, loadOne } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\n\nimport pluralize from 'pluralize'\n\nimport { snakeToCamel, toPascalCase } from '@stonecrop/schema'\nimport { getHandler } from '../registry/actions'\nimport { getMeta, getAllMeta } from '../registry/doctypes'\nimport type { DoctypeMeta } from '@stonecrop/schema'\nimport type { ActionContext, GraphQLExecutor } from '../types'\n\n/**\n * Inflection callbacks for mapping table names to GraphQL query field names.\n * Override these when using a non-Amber inflection preset (e.g., V4, SimplifyInflection).\n *\n * Defaults match the PostGraphile Amber preset conventions.\n * @public\n */\nexport interface StonecropInflectionConfig {\n\t/**\n\t * Given a table name, return the GraphQL field name for fetching a single record by ID.\n\t * @example Amber default: \"sales_orders\" → \"salesOrderById\"\n\t * @example V4 preset: \"sales_orders\" → \"salesOrderByRowId\"\n\t */\n\trecordFieldName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL field name for fetching a list/connection.\n\t * @example Amber default: \"sales_orders\" → \"allSalesOrders\"\n\t * @example SimplifyInflection: \"sales_orders\" → \"salesOrders\"\n\t */\n\tconnectionFieldName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL OrderBy enum type name.\n\t * @example Amber default: \"sales_orders\" → \"SalesOrdersOrderBy\"\n\t */\n\torderByTypeName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL argument name used to look up a record by PK.\n\t * @example Amber default (Relay Global ID): \"sales_orders\" → \"id\"\n\t * @example row_id PK: \"sales_orders\" → \"rowId\"\n\t */\n\trecordArgName?: (tableName: string) => string\n\n\t/**\n\t * Given a table name, return the GraphQL variable type for the PK argument.\n\t * @example Default UUID PK: \"sales_orders\" → \"UUID!\"\n\t * @example Integer PK: \"sales_orders\" → \"Int!\"\n\t */\n\trecordArgType?: (tableName: string) => string\n}\n\n/**\n * Options for creating a Stonecrop PostGraphile plugin\n * @public\n */\nexport interface StonecropPluginOptions {\n\t/** GraphQL executor for running queries/mutations */\n\texecutor: GraphQLExecutor\n\n\t/**\n\t * Override inflection conventions for mapping table names to GraphQL field names.\n\t * Defaults to PostGraphile Amber preset conventions.\n\t */\n\tinflection?: StonecropInflectionConfig\n}\n\n/**\n * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality\n * @param options - Plugin configuration options\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createStonecropPlugin = (options: StonecropPluginOptions): GraphileConfig.Plugin => {\n\t// Resolve inflection callbacks with Amber defaults\n\tconst recordFieldName = options.inflection?.recordFieldName ?? defaultRecordFieldName\n\tconst connectionFieldName = options.inflection?.connectionFieldName ?? defaultConnectionFieldName\n\tconst orderByTypeName = options.inflection?.orderByTypeName ?? defaultOrderByTypeName\n\tconst recordArgName = options.inflection?.recordArgName ?? defaultRecordArgName\n\tconst recordArgType = options.inflection?.recordArgType ?? defaultRecordArgType\n\n\treturn extendSchema(() => {\n\t\treturn {\n\t\t\ttypeDefs: gql`\n\t\t\t\ttype StonecropFieldMeta {\n\t\t\t\t\tfieldname: String!\n\t\t\t\t\tfieldtype: String!\n\t\t\t\t\tlabel: String\n\t\t\t\t\trequired: Boolean\n\t\t\t\t\toptions: JSON\n\t\t\t\t}\n\n\t\t\t\ttype StonecropActionDefinition {\n\t\t\t\t\tlabel: String!\n\t\t\t\t\thandler: String!\n\t\t\t\t\trequiredFields: [String!]\n\t\t\t\t\tallowedStates: [String!]\n\t\t\t\t\tconfirm: Boolean\n\t\t\t\t\targs: JSON\n\t\t\t\t}\n\n\t\t\t\ttype StonecropWorkflowMeta {\n\t\t\t\t\tstates: [String!]\n\t\t\t\t\tactions: JSON\n\t\t\t\t}\n\n\t\t\t\ttype StonecropDoctypeMeta {\n\t\t\t\t\tname: String!\n\t\t\t\t\ttableName: String\n\t\t\t\t\tfields: [StonecropFieldMeta!]!\n\t\t\t\t\tworkflow: StonecropWorkflowMeta\n\t\t\t\t\tlistDoctype: String\n\t\t\t\t\tparentDoctype: String\n\t\t\t\t}\n\n\t\t\t\ttype StonecropRecordResult {\n\t\t\t\t\tdata: JSON\n\t\t\t\t\tdoctype: String!\n\t\t\t\t}\n\n\t\t\t\ttype StonecropRecordsResult {\n\t\t\t\t\tdata: [JSON!]!\n\t\t\t\t\tdoctype: String!\n\t\t\t\t\tcount: Int!\n\t\t\t\t}\n\n\t\t\t\ttype StonecropActionResult {\n\t\t\t\t\tsuccess: Boolean!\n\t\t\t\t\tdata: JSON\n\t\t\t\t\terror: String\n\t\t\t\t}\n\n\t\t\t\textend type Query {\n\t\t\t\t\tstonecropMeta(doctype: String!): StonecropDoctypeMeta\n\t\t\t\t\tstonecropAllMeta: [StonecropDoctypeMeta!]!\n\t\t\t\t\tstonecropRecord(doctype: String!, id: String!): StonecropRecordResult\n\t\t\t\t\tstonecropRecords(\n\t\t\t\t\t\tdoctype: String!\n\t\t\t\t\t\tfilters: JSON\n\t\t\t\t\t\torderBy: String\n\t\t\t\t\t\tlimit: Int\n\t\t\t\t\t\toffset: Int\n\t\t\t\t\t): StonecropRecordsResult\n\t\t\t\t}\n\n\t\t\t\textend type Mutation {\n\t\t\t\t\tstonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!\n\t\t\t\t}\n\t\t\t`,\n\n\t\t\tobjects: {\n\t\t\t\tQuery: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropMeta(_: any, { $doctype }: any) {\n\t\t\t\t\t\t\treturn lambda($doctype, (doctype: unknown) => {\n\t\t\t\t\t\t\t\tconst meta = getMeta(doctype as string)\n\t\t\t\t\t\t\t\treturn meta ?? null\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropAllMeta() {\n\t\t\t\t\t\t\treturn constant(getAllMeta())\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecord(_: any, { $doctype, $id }: any) {\n\t\t\t\t\t\t\treturn loadOne(object({ doctype: $doctype, id: $id }), async (specs: readonly any[]) => {\n\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(spec.doctype)\n\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown doctype: ${spec.doctype}`)\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif (!meta.tableName) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Doctype ${spec.doctype} has no table mapping`)\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tconst query = buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType)\n\t\t\t\t\t\t\t\t\t\tconst result = await options.executor.query(query, {\n\t\t\t\t\t\t\t\t\t\t\t[recordArgName(meta.tableName!)]: spec.id,\n\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tdata: extractSingleResult(result, meta, recordFieldName),\n\t\t\t\t\t\t\t\t\t\t\tdoctype: spec.doctype,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecords(_: any, { $doctype, $filters, $orderBy, $limit, $offset }: any) {\n\t\t\t\t\t\t\treturn loadOne(\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\tfilters: $filters,\n\t\t\t\t\t\t\t\t\torderBy: $orderBy,\n\t\t\t\t\t\t\t\t\tlimit: $limit,\n\t\t\t\t\t\t\t\t\toffset: $offset,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (specs: readonly any[]) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown doctype: ${spec.doctype}`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif (!meta.tableName) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Doctype ${spec.doctype} has no table mapping`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst query = buildListQuery(\n\t\t\t\t\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tlimit: spec.limit,\n\t\t\t\t\t\t\t\t\t\t\t\t\toffset: spec.offset,\n\t\t\t\t\t\t\t\t\t\t\t\t\torderBy: spec.orderBy,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\tconnectionFieldName,\n\t\t\t\t\t\t\t\t\t\t\t\torderByTypeName\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\tconst result = await options.executor.query(query, {\n\t\t\t\t\t\t\t\t\t\t\t\tlimit: spec.limit,\n\t\t\t\t\t\t\t\t\t\t\t\toffset: spec.offset,\n\t\t\t\t\t\t\t\t\t\t\t\torderBy: spec.orderBy,\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\tconst data = extractListResult(result, meta, connectionFieldName)\n\n\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype: spec.doctype,\n\t\t\t\t\t\t\t\t\t\t\t\tcount: data.length,\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\tMutation: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropAction(_: any, { $doctype, $action, $args: $actionArgs }: any) {\n\t\t\t\t\t\t\treturn loadOne(\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\taction: $action,\n\t\t\t\t\t\t\t\t\tactionArgs: $actionArgs,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (specs: readonly any[]) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `Unknown doctype: ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst actionDef = meta.workflow?.actions?.[spec.action]\n\t\t\t\t\t\t\t\t\t\t\tif (!actionDef) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `Unknown action: ${spec.action} on ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst handler = getHandler(actionDef.handler)\n\t\t\t\t\t\t\t\t\t\t\tif (!handler) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `Handler not registered: ${actionDef.handler}`,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst actionContext: ActionContext = {\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype: meta,\n\t\t\t\t\t\t\t\t\t\t\t\texecutor: options.executor,\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\tconst result = await handler(spec.actionArgs ?? [], actionContext)\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: null,\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n}\n\n// =============================================================================\n// Inflection helpers — default to PostGraphile Amber preset conventions\n// Uses `pluralize` for proper English singularization (handles irregular\n// plurals like statuses→status, categories→category, addresses→address).\n// snakeToCamel / toPascalCase are imported from @stonecrop/schema.\n// =============================================================================\n\n/**\n * Amber default: sales_orders → salesOrderById\n * Uses `pluralize` for proper singularization of irregular plurals.\n * Override via `StonecropInflectionConfig.recordFieldName` for non-standard PK columns.\n * @public\n */\nfunction defaultRecordFieldName(tableName: string): string {\n\tconst singular = pluralize.singular(tableName)\n\treturn `${snakeToCamel(singular)}ById`\n}\n\n/**\n * Amber default: sales_orders → allSalesOrders\n * @public\n */\nfunction defaultConnectionFieldName(tableName: string): string {\n\treturn `all${toPascalCase(tableName)}`\n}\n\n/**\n * Amber default: sales_orders → SalesOrdersOrderBy\n * @public\n */\nfunction defaultOrderByTypeName(tableName: string): string {\n\treturn `${toPascalCase(tableName)}OrderBy`\n}\n\n/**\n * Default PK argument name: 'id' (standard Relay Global ID pattern).\n * Override via `StonecropInflectionConfig.recordArgName` when using row_id columns;\n * PostGraphile Amber generates `rowId: UUID!` for those fields.\n * @internal\n */\nfunction defaultRecordArgName(_tableName: string): string {\n\treturn 'id'\n}\n\n/**\n * Default PK argument type: 'UUID!' (PostGraphile Amber default for UUID PKs).\n * Override via `StonecropInflectionConfig.recordArgType` when using non-UUID PKs\n * such as integer serials or Relay Global IDs ('ID!').\n * @internal\n */\nfunction defaultRecordArgType(_tableName: string): string {\n\treturn 'UUID!'\n}\n\n// =============================================================================\n// Query builders — generate GraphQL queries to send to the underlying schema\n// =============================================================================\n\n/**\n * Fieldtypes that map to GraphQL object/connection types and require sub-selections.\n * These fields are excluded from generated query field selections.\n * @public\n */\nconst RELATION_FIELDTYPES = new Set(['Link', 'Doctype'])\n\n/**\n * Filter fields to only those directly queryable as scalars, excluding Link and Doctype\n * relation fields that require GraphQL sub-selections.\n * @public\n */\nfunction queryableFieldNames(meta: DoctypeMeta): string {\n\treturn meta.fields\n\t\t.filter(f => !RELATION_FIELDTYPES.has(f.fieldtype))\n\t\t.map(f => f.fieldname)\n\t\t.join('\\n ')\n}\n\n/**\n * Build a GraphQL query to fetch a single record by ID.\n * Excludes Link and Doctype relation fields from the selection set.\n * The PK argument name and type are configurable via `StonecropInflectionConfig.recordArgName`\n * and `StonecropInflectionConfig.recordArgType` to match the target schema's conventions\n * (e.g. `rowId: UUID!` for PostGraphile Amber with row_id columns).\n * @public\n */\nfunction buildRecordQuery(\n\tmeta: DoctypeMeta,\n\trecordFieldName: (t: string) => string,\n\trecordArgName: (t: string) => string,\n\trecordArgType: (t: string) => string\n): string {\n\tconst fieldNames = queryableFieldNames(meta)\n\tconst queryName = recordFieldName(meta.tableName!)\n\tconst argName = recordArgName(meta.tableName!)\n\tconst argType = recordArgType(meta.tableName!)\n\n\treturn `\n\t\tquery GetRecord($${argName}: ${argType}) {\n\t\t\t${queryName}(${argName}: $${argName}) {\n\t\t\t\t${fieldNames}\n\t\t\t}\n\t\t}\n\t`\n}\n\n/**\n * Build a GraphQL connection query to fetch a list of records.\n * Only declares variables ($limit, $offset, $orderBy) that are actually used in the query,\n * avoiding GraphQL spec §5.8.3 violations from unused variable declarations.\n * Excludes Link and Doctype relation fields from the selection set.\n * @public\n */\nfunction buildListQuery(\n\tmeta: DoctypeMeta,\n\targs: { limit?: number; offset?: number; orderBy?: string },\n\tconnectionFieldName: (t: string) => string,\n\torderByTypeName: (t: string) => string\n): string {\n\tconst fieldNames = queryableFieldNames(meta)\n\tconst connectionName = connectionFieldName(meta.tableName!)\n\tconst orderByType = orderByTypeName(meta.tableName!)\n\n\tconst varDecls: string[] = []\n\tconst queryArgs: string[] = []\n\tif (args.limit) {\n\t\tvarDecls.push('$limit: Int')\n\t\tqueryArgs.push(`first: $limit`)\n\t}\n\tif (args.offset) {\n\t\tvarDecls.push('$offset: Int')\n\t\tqueryArgs.push(`offset: $offset`)\n\t}\n\tif (args.orderBy) {\n\t\tvarDecls.push(`$orderBy: [${orderByType}!]`)\n\t\tqueryArgs.push(`orderBy: $orderBy`)\n\t}\n\n\tconst varStr = varDecls.length > 0 ? `(${varDecls.join(', ')})` : ''\n\tconst argsStr = queryArgs.length > 0 ? `(${queryArgs.join(', ')})` : ''\n\n\treturn `\n\t\tquery GetRecords${varStr} {\n\t\t\t${connectionName}${argsStr} {\n\t\t\t\tnodes {\n\t\t\t\t${fieldNames}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`\n}\n\n/**\n * Extract a single record from a PostGraphile query result using the record field name.\n * @internal\n */\nfunction extractSingleResult(result: unknown, meta: DoctypeMeta, recordFieldName: (t: string) => string): unknown {\n\tconst queryName = recordFieldName(meta.tableName!)\n\treturn (result as Record<string, unknown>)[queryName]\n}\n\n/**\n * Extract the list of nodes from a PostGraphile connection query result.\n * Returns an empty array if the connection field is absent.\n * @internal\n */\nfunction extractListResult(result: unknown, meta: DoctypeMeta, connectionFieldName: (t: string) => string): unknown[] {\n\tconst connectionName = connectionFieldName(meta.tableName!)\n\tconst connection = (result as Record<string, unknown>)[connectionName] as {\n\t\tnodes: unknown[]\n\t}\n\treturn connection?.nodes ?? []\n}\n\n// =============================================================================\n// Exported for testing and advanced usage\n// =============================================================================\n\nexport {\n\tdefaultRecordFieldName,\n\tdefaultConnectionFieldName,\n\tdefaultOrderByTypeName,\n\tdefaultRecordArgName,\n\tdefaultRecordArgType,\n\tbuildRecordQuery,\n\tbuildListQuery,\n\tqueryableFieldNames,\n\tRELATION_FIELDTYPES,\n\textractSingleResult,\n\textractListResult,\n}\n"],"names":["doctypeRegistry","DoctypeValidationError","file","errors","errorMessages","e","loadDoctypes","dir","options","entries","readdirSync","entry","fullPath","join","statSync","loadDoctypeFile","filePath","content","readFileSync","data","err","parseError","result","validateDoctype","doctype","parseDoctype","loadDoctypesFromObject","doctypes","name","withName","getMeta","getAllMeta","hasMeta","clearRegistry","validateReferences","field","handlerRegistry","registerHandler","handler","getHandler","hasHandler","clearHandlers","validateRequiredFields","args","context","record","missing","validateFieldTypes","value","error","validateFieldValue","fieldname","fieldtype","noop","builtinHandlers","registerBuiltinHandlers","createStonecropPlugin","recordFieldName","defaultRecordFieldName","connectionFieldName","defaultConnectionFieldName","orderByTypeName","defaultOrderByTypeName","recordArgName","defaultRecordArgName","recordArgType","defaultRecordArgType","extendSchema","gql","_","$doctype","lambda","constant","$id","loadOne","object","specs","spec","meta","query","buildRecordQuery","extractSingleResult","$filters","$orderBy","$limit","$offset","buildListQuery","extractListResult","$action","$actionArgs","actionDef","actionContext","tableName","singular","pluralize","snakeToCamel","toPascalCase","_tableName","RELATION_FIELDTYPES","queryableFieldNames","f","fieldNames","queryName","argName","argType","connectionName","orderByType","varDecls","queryArgs","varStr","argsStr"],"mappings":"0PAMMA,MAAgD,IAM/C,MAAMC,UAA+B,KAAM,CACjD,YAEiBC,EAEAC,EACf,CACD,MAAMC,EAAgBD,EAAO,IAAIE,GAAK,KAAKA,EAAE,KAAK,KAAK,GAAG,CAAC,KAAKA,EAAE,OAAO,EAAE,EAAE,KAAK;AAAA,CAAI,EACtF,MAAM,iCAAiCH,CAAI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EAAU,OAAS,EAAI,IAAIA,EAAU,KAAK,IAAI,CAAC,IAAM,GAErE,MAAO;AAAA,oBACYC,CAAM;AAAA,KACrBJ,CAAc,GAAGK,CAAO;AAAA;AAAA,MAEvBT,CAAU;AAAA;AAAA;AAAA;AAAA,EAKhB,CAMA,SAASpB,GAAoB3D,EAAiBwD,EAAmBrB,EAAiD,CACjH,MAAM6C,EAAY7C,EAAgBqB,EAAK,SAAU,EACjD,OAAQxD,EAAmCgF,CAAS,CACrD,CAOA,SAASf,GAAkBjE,EAAiBwD,EAAmBnB,EAAuD,CACrH,MAAM8C,EAAiB9C,EAAoBmB,EAAK,SAAU,EAI1D,OAHoBxD,EAAmCmF,CAAc,GAGlD,OAAS,CAAA,CAC7B"}
package/dist/src/index.js DELETED
@@ -1,8 +0,0 @@
1
- // Doctype registry
2
- export { loadDoctypes, loadDoctypesFromObject, getMeta, getAllMeta, hasMeta, clearRegistry, validateReferences, DoctypeValidationError, } from './registry/doctypes';
3
- // Action handlers
4
- export { registerHandler, getHandler, hasHandler, clearHandlers, registerBuiltinHandlers, builtinHandlers, } from './registry/actions';
5
- // PostGraphile plugin
6
- export { createStonecropPlugin } from './plugin/postgraphile';
7
- // Query builders and inflection helpers (exported for testing and advanced usage)
8
- export { defaultRecordFieldName, defaultConnectionFieldName, defaultOrderByTypeName, defaultRecordArgName, defaultRecordArgType, buildRecordQuery, buildListQuery, queryableFieldNames, RELATION_FIELDTYPES, } from './plugin/postgraphile';
@@ -1,381 +0,0 @@
1
- import { snakeToCamel, toPascalCase } from '@stonecrop/schema';
2
- import { constant, lambda, object, loadOne } from 'postgraphile/grafast';
3
- import { extendSchema, gql } from 'postgraphile/utils';
4
- import pluralize from 'pluralize';
5
- import { getHandler } from '../registry/actions';
6
- import { getMeta, getAllMeta } from '../registry/doctypes';
7
- /**
8
- * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality
9
- * @param options - Plugin configuration options
10
- * @returns A PostGraphile plugin
11
- * @public
12
- */
13
- export const createStonecropPlugin = (options) => {
14
- // Resolve inflection callbacks with Amber defaults
15
- const recordFieldName = options.inflection?.recordFieldName ?? defaultRecordFieldName;
16
- const connectionFieldName = options.inflection?.connectionFieldName ?? defaultConnectionFieldName;
17
- const orderByTypeName = options.inflection?.orderByTypeName ?? defaultOrderByTypeName;
18
- const recordArgName = options.inflection?.recordArgName ?? defaultRecordArgName;
19
- const recordArgType = options.inflection?.recordArgType ?? defaultRecordArgType;
20
- return extendSchema(() => {
21
- return {
22
- typeDefs: gql `
23
- type StonecropFieldMeta {
24
- fieldname: String!
25
- fieldtype: String!
26
- component: String
27
- label: String
28
- width: String
29
- align: String
30
- required: Boolean
31
- readOnly: Boolean
32
- edit: Boolean
33
- hidden: Boolean
34
- default: JSON
35
- options: JSON
36
- mask: String
37
- precision: Int
38
- scale: Int
39
- mode: String
40
- validation: JSON
41
- }
42
-
43
- type StonecropActionDefinition {
44
- label: String!
45
- handler: String!
46
- requiredFields: [String!]
47
- allowedStates: [String!]
48
- confirm: Boolean
49
- args: JSON
50
- }
51
-
52
- type StonecropWorkflowMeta {
53
- states: [String!]
54
- actions: JSON
55
- }
56
-
57
- type StonecropDoctypeMeta {
58
- name: String!
59
- slug: String
60
- tableName: String
61
- fields: [StonecropFieldMeta!]!
62
- workflow: StonecropWorkflowMeta
63
- inherits: String
64
- listDoctype: String
65
- parentDoctype: String
66
- }
67
-
68
- type StonecropRecordResult {
69
- data: JSON
70
- doctype: String!
71
- }
72
-
73
- type StonecropRecordsResult {
74
- data: [JSON!]!
75
- doctype: String!
76
- count: Int!
77
- }
78
-
79
- type StonecropActionResult {
80
- success: Boolean!
81
- data: JSON
82
- error: String
83
- }
84
-
85
- extend type Query {
86
- stonecropMeta(doctype: String!): StonecropDoctypeMeta
87
- stonecropAllMeta: [StonecropDoctypeMeta!]!
88
- stonecropRecord(doctype: String!, id: String!): StonecropRecordResult
89
- stonecropRecords(
90
- doctype: String!
91
- filters: JSON
92
- orderBy: String
93
- limit: Int
94
- offset: Int
95
- ): StonecropRecordsResult
96
- }
97
-
98
- extend type Mutation {
99
- stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
100
- }
101
- `,
102
- objects: {
103
- Query: {
104
- plans: {
105
- stonecropMeta(_, { $doctype }) {
106
- return lambda($doctype, (doctype) => {
107
- const meta = getMeta(doctype);
108
- return meta ?? null;
109
- });
110
- },
111
- stonecropAllMeta() {
112
- return constant(getAllMeta());
113
- },
114
- stonecropRecord(_, { $doctype, $id }) {
115
- return loadOne(object({ doctype: $doctype, id: $id }), async (specs) => {
116
- return await Promise.all(specs.map(async (spec) => {
117
- const meta = getMeta(spec.doctype);
118
- if (!meta) {
119
- throw new Error(`Unknown doctype: ${spec.doctype}`);
120
- }
121
- if (!meta.tableName) {
122
- throw new Error(`Doctype ${spec.doctype} has no table mapping`);
123
- }
124
- const query = buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType);
125
- const result = await options.executor.query(query, {
126
- [recordArgName(meta.tableName)]: spec.id,
127
- });
128
- return {
129
- data: extractSingleResult(result, meta, recordFieldName),
130
- doctype: spec.doctype,
131
- };
132
- }));
133
- });
134
- },
135
- stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset }) {
136
- return loadOne(object({
137
- doctype: $doctype,
138
- filters: $filters,
139
- orderBy: $orderBy,
140
- limit: $limit,
141
- offset: $offset,
142
- }), async (specs) => {
143
- return await Promise.all(specs.map(async (spec) => {
144
- const meta = getMeta(spec.doctype);
145
- if (!meta) {
146
- throw new Error(`Unknown doctype: ${spec.doctype}`);
147
- }
148
- if (!meta.tableName) {
149
- throw new Error(`Doctype ${spec.doctype} has no table mapping`);
150
- }
151
- const query = buildListQuery(meta, {
152
- limit: spec.limit,
153
- offset: spec.offset,
154
- orderBy: spec.orderBy,
155
- }, connectionFieldName, orderByTypeName);
156
- const result = await options.executor.query(query, {
157
- limit: spec.limit,
158
- offset: spec.offset,
159
- orderBy: spec.orderBy,
160
- });
161
- const data = extractListResult(result, meta, connectionFieldName);
162
- return {
163
- data,
164
- doctype: spec.doctype,
165
- count: data.length,
166
- };
167
- }));
168
- });
169
- },
170
- },
171
- },
172
- Mutation: {
173
- plans: {
174
- stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
175
- return loadOne(object({
176
- doctype: $doctype,
177
- action: $action,
178
- actionArgs: $actionArgs,
179
- }), async (specs) => {
180
- return await Promise.all(specs.map(async (spec) => {
181
- const meta = getMeta(spec.doctype);
182
- if (!meta) {
183
- return {
184
- success: false,
185
- data: null,
186
- error: `Unknown doctype: ${spec.doctype}`,
187
- };
188
- }
189
- const actionDef = meta.workflow?.actions?.[spec.action];
190
- if (!actionDef) {
191
- return {
192
- success: false,
193
- data: null,
194
- error: `Unknown action: ${spec.action} on ${spec.doctype}`,
195
- };
196
- }
197
- const handlerName = actionDef.handler;
198
- const handler = getHandler(handlerName);
199
- if (!handler) {
200
- return {
201
- success: false,
202
- data: null,
203
- error: `Handler not registered: ${handlerName}`,
204
- };
205
- }
206
- const actionContext = {
207
- doctype: meta,
208
- executor: options.executor,
209
- };
210
- try {
211
- const result = await handler(spec.actionArgs ?? [], actionContext);
212
- return {
213
- success: true,
214
- data: result,
215
- error: null,
216
- };
217
- }
218
- catch (err) {
219
- return {
220
- success: false,
221
- data: null,
222
- error: err instanceof Error ? err.message : String(err),
223
- };
224
- }
225
- }));
226
- });
227
- },
228
- },
229
- },
230
- },
231
- };
232
- });
233
- };
234
- // =============================================================================
235
- // Inflection helpers — default to PostGraphile Amber preset conventions
236
- // Uses `pluralize` for proper English singularization (handles irregular
237
- // plurals like statuses→status, categories→category, addresses→address).
238
- // snakeToCamel / toPascalCase are imported from @stonecrop/schema.
239
- // =============================================================================
240
- /**
241
- * Amber default: sales_orders → salesOrderById
242
- * Uses `pluralize` for proper singularization of irregular plurals.
243
- * Override via `StonecropInflectionConfig.recordFieldName` for non-standard PK columns.
244
- * @public
245
- */
246
- function defaultRecordFieldName(tableName) {
247
- const singular = pluralize.singular(tableName);
248
- return `${snakeToCamel(singular)}ById`;
249
- }
250
- /**
251
- * Amber default: sales_orders → allSalesOrders
252
- * @public
253
- */
254
- function defaultConnectionFieldName(tableName) {
255
- return `all${toPascalCase(tableName)}`;
256
- }
257
- /**
258
- * Amber default: sales_orders → SalesOrdersOrderBy
259
- * @public
260
- */
261
- function defaultOrderByTypeName(tableName) {
262
- return `${toPascalCase(tableName)}OrderBy`;
263
- }
264
- /**
265
- * Default PK argument name: 'id' (standard Relay Global ID pattern).
266
- * Override via `StonecropInflectionConfig.recordArgName` when using row_id columns;
267
- * PostGraphile Amber generates `rowId: UUID!` for those fields.
268
- * @public
269
- */
270
- function defaultRecordArgName(_tableName) {
271
- return 'id';
272
- }
273
- /**
274
- * Default PK argument type: 'UUID!' (PostGraphile Amber default for UUID PKs).
275
- * Override via `StonecropInflectionConfig.recordArgType` when using non-UUID PKs
276
- * such as integer serials or Relay Global IDs ('ID!').
277
- * @public
278
- */
279
- function defaultRecordArgType(_tableName) {
280
- return 'UUID!';
281
- }
282
- // =============================================================================
283
- // Query builders — generate GraphQL queries to send to the underlying schema
284
- // =============================================================================
285
- /**
286
- * Fieldtypes that map to GraphQL object/connection types and require sub-selections.
287
- * These fields are excluded from generated query field selections.
288
- * @public
289
- */
290
- const RELATION_FIELDTYPES = new Set(['Link', 'Doctype']);
291
- /**
292
- * Filter fields to only those directly queryable as scalars, excluding Link and Doctype
293
- * relation fields that require GraphQL sub-selections.
294
- * @public
295
- */
296
- function queryableFieldNames(meta) {
297
- return meta.fields
298
- .filter(f => !RELATION_FIELDTYPES.has(f.fieldtype))
299
- .map(f => f.fieldname)
300
- .join('\n ');
301
- }
302
- /**
303
- * Build a GraphQL query to fetch a single record by ID.
304
- * Excludes Link and Doctype relation fields from the selection set.
305
- * The PK argument name and type are configurable via `StonecropInflectionConfig.recordArgName`
306
- * and `StonecropInflectionConfig.recordArgType` to match the target schema's conventions
307
- * (e.g. `rowId: UUID!` for PostGraphile Amber with row_id columns).
308
- * @public
309
- */
310
- function buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType) {
311
- const fieldNames = queryableFieldNames(meta);
312
- const queryName = recordFieldName(meta.tableName);
313
- const argName = recordArgName(meta.tableName);
314
- const argType = recordArgType(meta.tableName);
315
- return `
316
- query GetRecord($${argName}: ${argType}) {
317
- ${queryName}(${argName}: $${argName}) {
318
- ${fieldNames}
319
- }
320
- }
321
- `;
322
- }
323
- /**
324
- * Build a GraphQL connection query to fetch a list of records.
325
- * Only declares variables ($limit, $offset, $orderBy) that are actually used in the query,
326
- * avoiding GraphQL spec §5.8.3 violations from unused variable declarations.
327
- * Excludes Link and Doctype relation fields from the selection set.
328
- * @public
329
- */
330
- function buildListQuery(meta, args, connectionFieldName, orderByTypeName) {
331
- const fieldNames = queryableFieldNames(meta);
332
- const connectionName = connectionFieldName(meta.tableName);
333
- const orderByType = orderByTypeName(meta.tableName);
334
- const varDecls = [];
335
- const queryArgs = [];
336
- if (args.limit) {
337
- varDecls.push('$limit: Int');
338
- queryArgs.push(`first: $limit`);
339
- }
340
- if (args.offset) {
341
- varDecls.push('$offset: Int');
342
- queryArgs.push(`offset: $offset`);
343
- }
344
- if (args.orderBy) {
345
- varDecls.push(`$orderBy: [${orderByType}!]`);
346
- queryArgs.push(`orderBy: $orderBy`);
347
- }
348
- const varStr = varDecls.length > 0 ? `(${varDecls.join(', ')})` : '';
349
- const argsStr = queryArgs.length > 0 ? `(${queryArgs.join(', ')})` : '';
350
- return `
351
- query GetRecords${varStr} {
352
- ${connectionName}${argsStr} {
353
- nodes {
354
- ${fieldNames}
355
- }
356
- }
357
- }
358
- `;
359
- }
360
- /**
361
- * Extract a single record from a PostGraphile query result using the record field name.
362
- * @internal
363
- */
364
- function extractSingleResult(result, meta, recordFieldName) {
365
- const queryName = recordFieldName(meta.tableName);
366
- return result[queryName];
367
- }
368
- /**
369
- * Extract the list of nodes from a PostGraphile connection query result.
370
- * Returns an empty array if the connection field is absent.
371
- * @internal
372
- */
373
- function extractListResult(result, meta, connectionFieldName) {
374
- const connectionName = connectionFieldName(meta.tableName);
375
- const connection = result[connectionName];
376
- return connection?.nodes ?? [];
377
- }
378
- // =============================================================================
379
- // Exported for testing and advanced usage
380
- // =============================================================================
381
- export { defaultRecordFieldName, defaultConnectionFieldName, defaultOrderByTypeName, defaultRecordArgName, defaultRecordArgType, buildRecordQuery, buildListQuery, queryableFieldNames, RELATION_FIELDTYPES, extractSingleResult, extractListResult, };
@@ -1,156 +0,0 @@
1
- const handlerRegistry = new Map();
2
- /**
3
- * Register an action handler
4
- * @param name - Unique name for the action handler
5
- * @param handler - Action handler function to register
6
- * @public
7
- */
8
- export function registerHandler(name, handler) {
9
- handlerRegistry.set(name, handler);
10
- }
11
- /**
12
- * Get a registered handler by name
13
- * @param name - Name of the action handler to retrieve
14
- * @public
15
- */
16
- export function getHandler(name) {
17
- return handlerRegistry.get(name);
18
- }
19
- /**
20
- * Check if a handler is registered
21
- * @param name - Name of the action handler to check
22
- * @public
23
- */
24
- export function hasHandler(name) {
25
- return handlerRegistry.has(name);
26
- }
27
- /**
28
- * Clear all registered handlers
29
- * @public
30
- */
31
- export function clearHandlers() {
32
- handlerRegistry.clear();
33
- }
34
- // =============================================================================
35
- // Built-in Handlers
36
- // =============================================================================
37
- /**
38
- * Validate that all required fields are present in a record
39
- */
40
- const validateRequiredFields = async (args, context) => {
41
- const [record] = args;
42
- const { doctype } = context;
43
- const missing = [];
44
- for (const field of doctype.fields) {
45
- if (field.required && (record[field.fieldname] === undefined || record[field.fieldname] === null)) {
46
- missing.push(field.label ?? field.fieldname);
47
- }
48
- }
49
- if (missing.length > 0) {
50
- throw new Error(`Missing required fields: ${missing.join(', ')}`);
51
- }
52
- return { valid: true };
53
- };
54
- /**
55
- * Validate field types match expected types
56
- */
57
- const validateFieldTypes = async (args, context) => {
58
- const [record] = args;
59
- const { doctype } = context;
60
- const errors = [];
61
- for (const field of doctype.fields) {
62
- const value = record[field.fieldname];
63
- if (value === undefined || value === null)
64
- continue;
65
- const error = validateFieldValue(field, value);
66
- if (error)
67
- errors.push(error);
68
- }
69
- if (errors.length > 0) {
70
- throw new Error(`Field type validation failed:\n${errors.join('\n')}`);
71
- }
72
- return { valid: true };
73
- };
74
- /**
75
- * Validate a single field value against its expected type
76
- */
77
- function validateFieldValue(field, value) {
78
- const { fieldname, fieldtype, cardinality } = field;
79
- switch (fieldtype) {
80
- case 'Int':
81
- if (typeof value !== 'number' || !Number.isInteger(value)) {
82
- return `${fieldname}: expected integer, got ${typeof value}`;
83
- }
84
- break;
85
- case 'Float':
86
- case 'Decimal':
87
- case 'Currency':
88
- case 'Quantity':
89
- if (typeof value !== 'number' && typeof value !== 'string') {
90
- return `${fieldname}: expected number, got ${typeof value}`;
91
- }
92
- break;
93
- case 'Check':
94
- if (typeof value !== 'boolean') {
95
- return `${fieldname}: expected boolean, got ${typeof value}`;
96
- }
97
- break;
98
- case 'Data':
99
- case 'Text':
100
- case 'Code':
101
- case 'Link':
102
- if (typeof value !== 'string') {
103
- return `${fieldname}: expected string, got ${typeof value}`;
104
- }
105
- break;
106
- case 'Date':
107
- case 'Time':
108
- case 'Datetime':
109
- if (typeof value !== 'string' && !(value instanceof Date)) {
110
- return `${fieldname}: expected date string or Date, got ${typeof value}`;
111
- }
112
- break;
113
- case 'JSON':
114
- if (typeof value !== 'object') {
115
- return `${fieldname}: expected object, got ${typeof value}`;
116
- }
117
- break;
118
- case 'Doctype':
119
- if (cardinality === 'many') {
120
- if (!Array.isArray(value)) {
121
- return `${fieldname}: expected array, got ${typeof value}`;
122
- }
123
- }
124
- else {
125
- if (typeof value !== 'object' || Array.isArray(value)) {
126
- return `${fieldname}: expected object, got ${typeof value}`;
127
- }
128
- }
129
- break;
130
- }
131
- return null;
132
- }
133
- /**
134
- * No-op handler for testing or placeholder actions
135
- */
136
- const noop = async () => {
137
- return { ok: true };
138
- };
139
- /**
140
- * Built-in handlers available for registration
141
- * @public
142
- */
143
- export const builtinHandlers = {
144
- validateRequiredFields,
145
- validateFieldTypes,
146
- noop,
147
- };
148
- /**
149
- * Register all built-in handlers
150
- * @public
151
- */
152
- export function registerBuiltinHandlers() {
153
- for (const [name, handler] of Object.entries(builtinHandlers)) {
154
- registerHandler(name, handler);
155
- }
156
- }
@@ -1,167 +0,0 @@
1
- import { readFileSync, readdirSync, statSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { parseDoctype, validateDoctype } from '@stonecrop/schema';
4
- const doctypeRegistry = new Map();
5
- /**
6
- * Error thrown when a doctype definition fails validation
7
- * @public
8
- */
9
- export class DoctypeValidationError extends Error {
10
- file;
11
- errors;
12
- constructor(
13
- /** File path or name where the validation error occurred */
14
- file,
15
- /** List of validation errors found */
16
- errors) {
17
- const errorMessages = errors.map(e => ` ${e.path.join('.')}: ${e.message}`).join('\n');
18
- super(`Invalid doctype definition in ${file}:\n${errorMessages}`);
19
- this.file = file;
20
- this.errors = errors;
21
- this.name = 'DoctypeValidationError';
22
- }
23
- }
24
- /**
25
- * Load doctype definitions from a directory of JSON files
26
- * @param dir - Directory path containing doctype JSON files
27
- * @param options - Options for loading doctypes (continueOnError, onError callback)
28
- * @public
29
- */
30
- export function loadDoctypes(dir, options = {}) {
31
- const entries = readdirSync(dir);
32
- for (const entry of entries) {
33
- const fullPath = join(dir, entry);
34
- const stat = statSync(fullPath);
35
- if (stat.isDirectory()) {
36
- loadDoctypes(fullPath, options);
37
- }
38
- else if (entry.endsWith('.json')) {
39
- loadDoctypeFile(fullPath, options);
40
- }
41
- }
42
- }
43
- /**
44
- * Load and validate a single doctype file
45
- */
46
- function loadDoctypeFile(filePath, options) {
47
- const content = readFileSync(filePath, 'utf-8');
48
- let data;
49
- try {
50
- data = JSON.parse(content);
51
- }
52
- catch (err) {
53
- const parseError = {
54
- path: [],
55
- message: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,
56
- };
57
- if (options.continueOnError) {
58
- options.onError?.(filePath, [parseError]);
59
- return;
60
- }
61
- throw new DoctypeValidationError(filePath, [parseError]);
62
- }
63
- const result = validateDoctype(data);
64
- if (!result.success) {
65
- if (options.continueOnError) {
66
- options.onError?.(filePath, result.errors);
67
- return;
68
- }
69
- throw new DoctypeValidationError(filePath, result.errors);
70
- }
71
- const doctype = parseDoctype(data);
72
- doctypeRegistry.set(doctype.name, doctype);
73
- }
74
- /**
75
- * Load doctypes from an object (for programmatic use)
76
- * @param doctypes - Object mapping doctype names to doctype definitions
77
- * @param options - Options for loading doctypes (continueOnError, onError callback)
78
- * @public
79
- */
80
- export function loadDoctypesFromObject(doctypes, options = {}) {
81
- for (const [name, data] of Object.entries(doctypes)) {
82
- const withName = { ...data, name };
83
- const result = validateDoctype(withName);
84
- if (!result.success) {
85
- if (options.continueOnError) {
86
- options.onError?.(name, result.errors);
87
- continue;
88
- }
89
- throw new DoctypeValidationError(name, result.errors);
90
- }
91
- const doctype = parseDoctype(withName);
92
- doctypeRegistry.set(doctype.name, doctype);
93
- }
94
- }
95
- /**
96
- * Get a doctype by name
97
- * @param name - Name of the doctype to retrieve
98
- * @public
99
- */
100
- export function getMeta(name) {
101
- return doctypeRegistry.get(name);
102
- }
103
- /**
104
- * Get all loaded doctypes
105
- * @public
106
- */
107
- export function getAllMeta() {
108
- return Array.from(doctypeRegistry.values());
109
- }
110
- /**
111
- * Check if a doctype is registered
112
- * @param name - Name of the doctype to check
113
- * @public
114
- */
115
- export function hasMeta(name) {
116
- return doctypeRegistry.has(name);
117
- }
118
- /**
119
- * Clear all registered doctypes
120
- * @public
121
- */
122
- export function clearRegistry() {
123
- doctypeRegistry.clear();
124
- }
125
- /**
126
- * Validate cross-doctype references (Link fields, inherits, etc.)
127
- * Call after all doctypes are loaded.
128
- * @public
129
- */
130
- export function validateReferences() {
131
- const errors = [];
132
- for (const doctype of doctypeRegistry.values()) {
133
- // Check inherits reference
134
- if (doctype.inherits && !doctypeRegistry.has(doctype.inherits)) {
135
- errors.push({
136
- path: [doctype.name, 'inherits'],
137
- message: `References unknown doctype: ${doctype.inherits}`,
138
- });
139
- }
140
- // Check listDoctype reference
141
- if (doctype.listDoctype && !doctypeRegistry.has(doctype.listDoctype)) {
142
- errors.push({
143
- path: [doctype.name, 'listDoctype'],
144
- message: `References unknown doctype: ${doctype.listDoctype}`,
145
- });
146
- }
147
- // Check parentDoctype reference
148
- if (doctype.parentDoctype && !doctypeRegistry.has(doctype.parentDoctype)) {
149
- errors.push({
150
- path: [doctype.name, 'parentDoctype'],
151
- message: `References unknown doctype: ${doctype.parentDoctype}`,
152
- });
153
- }
154
- // Check Link field targets
155
- for (const field of doctype.fields) {
156
- if (field.fieldtype === 'Link' && typeof field.options === 'string') {
157
- if (!doctypeRegistry.has(field.options)) {
158
- errors.push({
159
- path: [doctype.name, 'fields', field.fieldname, 'options'],
160
- message: `Link references unknown doctype: ${field.options}`,
161
- });
162
- }
163
- }
164
- }
165
- }
166
- return errors;
167
- }
@@ -1,11 +0,0 @@
1
- // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
- // It should be published with your NPM package. It should not be tracked by Git.
3
- {
4
- "tsdocVersion": "0.12",
5
- "toolPackages": [
6
- {
7
- "packageName": "@microsoft/api-extractor",
8
- "packageVersion": "7.57.0"
9
- }
10
- ]
11
- }
@@ -1,3 +0,0 @@
1
- // =============================================================================
2
- // Runtime Context Types (unique to graphql_middleware)
3
- // =============================================================================