@stonecrop/schema 0.22.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +128 -57
- package/dist/index.js.map +1 -1
- package/dist/schema.d.ts +96 -5
- package/dist/src/badge.d.ts +74 -0
- package/dist/src/badge.d.ts.map +1 -0
- package/dist/src/badge.js +158 -0
- package/dist/src/column-schema.d.ts +8 -2
- package/dist/src/column-schema.d.ts.map +1 -1
- package/dist/src/field.d.ts +5 -3
- package/dist/src/field.d.ts.map +1 -1
- package/dist/src/field.js +1 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +1 -0
- package/dist/validation-1DGAGmuU.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-1DGAGmuU.js","sources":["../src/naming.ts","../src/converter/scalars.ts","../src/converter/heuristics.ts","../src/table.ts","../src/field.ts","../src/converter/merge.ts","../src/converter/index.ts","../src/doctype.ts","../src/validation.ts"],"sourcesContent":["/**\n * Naming Convention Utilities\n * Converts between various naming conventions (snake_case, camelCase, PascalCase, kebab-case)\n * @packageDocumentation\n */\n\n/**\n * Converts snake_case to camelCase\n * @param snakeCase - Snake case string\n * @returns Camel case string\n * @public\n * @example\n * ```typescript\n * snakeToCamel('user_email') // 'userEmail'\n * snakeToCamel('created_at') // 'createdAt'\n * ```\n */\nexport function snakeToCamel(snakeCase: string): string {\n\treturn snakeCase.replace(/_([a-z])/g, (_: string, letter: string) => letter.toUpperCase())\n}\n\n/**\n * Converts camelCase to snake_case\n * @param camelCase - Camel case string\n * @returns Snake case string\n * @public\n * @example\n * ```typescript\n * camelToSnake('userEmail') // 'user_email'\n * camelToSnake('createdAt') // 'created_at'\n * ```\n */\nexport function camelToSnake(camelCase: string): string {\n\treturn camelCase.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)\n}\n\n/**\n * Converts snake_case to Title Case label\n * @param snakeCase - Snake case string\n * @returns Title case label\n * @public\n * @example\n * ```typescript\n * snakeToLabel('user_email') // 'User Email'\n * snakeToLabel('first_name') // 'First Name'\n * ```\n */\nexport function snakeToLabel(snakeCase: string): string {\n\treturn snakeCase\n\t\t.split('_')\n\t\t.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n\t\t.join(' ')\n}\n\n/**\n * Converts camelCase to Title Case label\n * @param camelCase - Camel case string\n * @returns Title case label\n * @public\n * @example\n * ```typescript\n * camelToLabel('userEmail') // 'User Email'\n * camelToLabel('firstName') // 'First Name'\n * ```\n */\nexport function camelToLabel(camelCase: string): string {\n\tconst withSpaces = camelCase.replace(/([A-Z])/g, ' $1').trim()\n\treturn withSpaces.charAt(0).toUpperCase() + withSpaces.slice(1)\n}\n\n/**\n * Convert table name to PascalCase doctype name\n * @param tableName - SQL table name (snake_case)\n * @returns PascalCase name\n * @public\n */\nexport function toPascalCase(tableName: string): string {\n\treturn tableName\n\t\t.split(/[-_\\s]+/)\n\t\t.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n\t\t.join('')\n}\n\n/**\n * Convert to kebab-case slug\n * @param name - Name to convert\n * @returns kebab-case slug\n * @public\n */\nexport function toSlug(name: string): string {\n\treturn name\n\t\t.replace(/([a-z])([A-Z])/g, '$1-$2')\n\t\t.replace(/[\\s_]+/g, '-')\n\t\t.toLowerCase()\n}\n\n/**\n * Convert PascalCase to snake_case (e.g., for deriving table names from type names)\n * @param pascal - PascalCase string\n * @returns snake_case string\n * @public\n * @example\n * ```typescript\n * pascalToSnake('SalesOrder') // 'sales_order'\n * pascalToSnake('SalesOrderItem') // 'sales_order_item'\n * ```\n */\nexport function pascalToSnake(pascal: string): string {\n\treturn pascal\n\t\t.replace(/([a-z])([A-Z])/g, '$1_$2')\n\t\t.replace(/[\\s-]+/g, '_')\n\t\t.toLowerCase()\n}\n","/**\n * GraphQL Scalar Type Mappings\n *\n * Maps standard GraphQL scalars and well-known custom scalars to Stonecrop field types.\n * Source-agnostic — covers scalars commonly emitted by PostGraphile, Hasura, Apollo, etc.\n *\n * Users can extend these via the `customScalars` option in `GraphQLConversionOptions`.\n *\n * @packageDocumentation\n */\n\nimport type { FieldTemplate } from './types'\n\n/**\n * Mapping from standard GraphQL scalar types to Stonecrop field types.\n * These are defined by the GraphQL specification and are always available.\n *\n * @public\n */\nexport const GQL_SCALAR_MAP: Record<string, FieldTemplate> = {\n\tString: { component: 'ATextInput' },\n\tInt: { component: 'ANumericInput' },\n\tFloat: { component: 'ANumericInput' },\n\tBoolean: { component: 'ACheckbox' },\n\tID: { component: 'ATextInput' },\n}\n\n/**\n * Mapping from well-known custom GraphQL scalars to Stonecrop field types.\n * These cover scalars commonly used across GraphQL servers (PostGraphile, Hasura, etc.)\n * without baking in knowledge of any specific server.\n *\n * Entries here have lower precedence than `customScalars` from options, but higher\n * precedence than unknown/unmapped scalars.\n *\n * @public\n */\nexport const WELL_KNOWN_SCALARS: Record<string, FieldTemplate> = {\n\t// Arbitrary precision / large numbers — all numeric variants render with ANumericInput.\n\tBigFloat: { component: 'ANumericInput' },\n\tBigDecimal: { component: 'ANumericInput' },\n\tDecimal: { component: 'ANumericInput' },\n\tBigInt: { component: 'ANumericInput' },\n\tLong: { component: 'ANumericInput' },\n\n\t// Identifiers\n\tUUID: { component: 'ATextInput' },\n\n\t// Date / Time — no dedicated Time SFC exists; Time falls back to a plain text input.\n\tDateTime: { component: 'ADateTime' },\n\tDatetime: { component: 'ADateTime' },\n\tDate: { component: 'ADate' },\n\tTime: { component: 'ATextInput' },\n\tInterval: { component: 'ADuration' },\n\tDuration: { component: 'ADuration' },\n\n\t// Structured data\n\tJSON: { component: 'ACodeEditor' },\n\tJSONObject: { component: 'ACodeEditor' },\n\tJsonNode: { component: 'ACodeEditor' },\n}\n\n/**\n * Set of scalar type names that are internal to GraphQL servers and should be skipped\n * during field conversion (they don't represent meaningful data fields).\n *\n * @public\n */\nexport const INTERNAL_SCALARS = new Set(['Cursor'])\n\n/**\n * Build a merged scalar map from the built-in maps and user-provided custom scalars.\n * Precedence (highest to lowest): customScalars → GQL_SCALAR_MAP → WELL_KNOWN_SCALARS\n *\n * @param customScalars - User-provided scalar overrides\n * @returns Merged scalar map\n * @public\n */\nexport function buildScalarMap(customScalars?: Record<string, Partial<FieldTemplate>>): Record<string, FieldTemplate> {\n\tconst merged: Record<string, FieldTemplate> = { ...WELL_KNOWN_SCALARS }\n\n\t// Standard scalars override well-known\n\tfor (const [key, value] of Object.entries(GQL_SCALAR_MAP)) {\n\t\tmerged[key] = value\n\t}\n\n\t// Custom scalars override everything\n\tif (customScalars) {\n\t\tfor (const [key, value] of Object.entries(customScalars)) {\n\t\t\tmerged[key] = { component: value.component ?? 'ATextInput' }\n\t\t}\n\t}\n\n\treturn merged\n}\n","/**\n * Default heuristics for identifying entity types and fields in a GraphQL schema.\n *\n * These heuristics work across common GraphQL servers (PostGraphile, Hasura, Apollo, etc.)\n * by detecting widely-adopted conventions like the Relay connection pattern.\n *\n * All heuristics can be overridden via the `isEntityType`, `isEntityField`, and\n * `classifyField` options in `GraphQLConversionOptions`.\n *\n * @packageDocumentation\n */\n\nimport {\n\tisScalarType,\n\tisEnumType,\n\tisObjectType,\n\tisListType,\n\tisNonNullType,\n\tisNamedType,\n\ttype GraphQLObjectType,\n\ttype GraphQLField,\n\ttype GraphQLOutputType,\n\ttype GraphQLNamedType,\n} from 'graphql'\n\nimport type { FieldTemplate } from './types'\nimport type { GraphQLConversionFieldMeta, GraphQLConversionOptions } from './types'\nimport { buildScalarMap, INTERNAL_SCALARS } from './scalars'\nimport { toSlug, camelToLabel, toPascalCase } from '../naming'\n\n/**\n * Suffixes that identify synthetic/framework types generated by GraphQL servers.\n * Types ending with these suffixes are typically not entities.\n */\nconst SYNTHETIC_SUFFIXES = [\n\t'Connection',\n\t'Edge',\n\t'Input',\n\t'Patch',\n\t'Payload',\n\t'Condition',\n\t'Filter',\n\t'OrderBy',\n\t'Aggregate',\n\t'AggregateResult',\n\t'AggregateFilter',\n\t'DeleteResponse',\n\t'InsertResponse',\n\t'UpdateResponse',\n\t'MutationResponse',\n]\n\n/**\n * Root operation type names that are never entities.\n */\nconst ROOT_TYPE_NAMES = new Set(['Query', 'Mutation', 'Subscription'])\n\n/**\n * Default heuristic to determine if a GraphQL object type represents an entity.\n * An entity type becomes a Stonecrop doctype.\n *\n * This heuristic excludes:\n * - Introspection types (`__*`)\n * - Root operation types (`Query`, `Mutation`, `Subscription`)\n * - Types with synthetic suffixes (e.g., `*Connection`, `*Edge`, `*Input`)\n * - Types starting with `Node` interface marker (exact match only)\n *\n * @param typeName - The GraphQL type name\n * @param type - The GraphQL object type definition\n * @returns `true` if this type should become a Stonecrop doctype\n * @public\n */\nexport function defaultIsEntityType(typeName: string, type: GraphQLObjectType): boolean {\n\t// Exclude introspection types\n\tif (typeName.startsWith('__')) {\n\t\treturn false\n\t}\n\n\t// Exclude root operation types\n\tif (ROOT_TYPE_NAMES.has(typeName)) {\n\t\treturn false\n\t}\n\n\t// Exclude the Node interface marker type\n\tif (typeName === 'Node') {\n\t\treturn false\n\t}\n\n\t// Exclude types matching synthetic suffixes\n\tfor (const suffix of SYNTHETIC_SUFFIXES) {\n\t\tif (typeName.endsWith(suffix)) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Must have at least one field\n\tconst fields = type.getFields()\n\tif (Object.keys(fields).length === 0) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n/**\n * Fields to skip by default on entity types.\n * These are internal to GraphQL servers and don't represent semantic data.\n */\nconst SKIP_FIELDS = new Set(['nodeId', '__typename', 'clientMutationId'])\n\n/**\n * Default heuristic to filter fields on entity types.\n * Skips internal fields that don't represent meaningful data.\n *\n * @param fieldName - The GraphQL field name\n * @param _field - The GraphQL field definition (unused in default implementation)\n * @param _parentType - The parent entity type (unused in default implementation)\n * @returns `true` if this field should be included\n * @public\n */\nexport function defaultIsEntityField(\n\tfieldName: string,\n\t_field: GraphQLField<unknown, unknown>,\n\t_parentType: GraphQLObjectType\n): boolean {\n\treturn !SKIP_FIELDS.has(fieldName)\n}\n\n/**\n * Unwrap NonNull and List wrappers from a GraphQL type, tracking nullability.\n *\n * @param type - The GraphQL output type\n * @returns The unwrapped named type, whether it's required, and whether it's a list\n * @internal\n */\nfunction unwrapType(type: GraphQLOutputType): {\n\tnamedType: GraphQLNamedType\n\trequired: boolean\n\tisList: boolean\n} {\n\tlet required = false\n\tlet isList = false\n\tlet current: GraphQLOutputType = type\n\n\t// Unwrap outer NonNull\n\tif (isNonNullType(current)) {\n\t\trequired = true\n\t\tcurrent = current.ofType\n\t}\n\n\t// Unwrap List\n\tif (isListType(current)) {\n\t\tisList = true\n\t\tcurrent = current.ofType\n\n\t\t// Unwrap inner NonNull (e.g., [Type!])\n\t\tif (isNonNullType(current)) {\n\t\t\tcurrent = current.ofType\n\t\t}\n\t}\n\n\t// At this point, current should be a named type (scalar, enum, or object)\n\tif (!isNamedType(current)) {\n\t\tthrow new Error(`Expected a named GraphQL type, got: ${String(current)}`)\n\t}\n\treturn { namedType: current, required, isList }\n}\n\n/**\n * Check if a GraphQL object type looks like a Relay Connection type.\n * A connection type has an `edges` field returning a list of edge types,\n * where each edge has a `node` field.\n *\n * @param type - The GraphQL object type to check\n * @returns The node type name if this is a connection, or `undefined`\n * @internal\n */\nfunction getConnectionNodeType(type: GraphQLObjectType): string | undefined {\n\tconst fields = type.getFields()\n\n\t// Must have an 'edges' field\n\tconst edgesField = fields['edges']\n\tif (!edgesField) return undefined\n\n\t// edges must be a list\n\tconst { namedType: edgesType, isList: edgesIsList } = unwrapType(edgesField.type)\n\tif (!edgesIsList || !isObjectType(edgesType)) return undefined\n\n\t// Each edge must have a 'node' field\n\tconst edgeFields = edgesType.getFields()\n\tconst nodeField = edgeFields['node']\n\tif (!nodeField) return undefined\n\n\tconst { namedType: nodeType } = unwrapType(nodeField.type)\n\tif (!isObjectType(nodeType)) return undefined\n\n\treturn nodeType.name\n}\n\n/**\n * Classify a single GraphQL field into a Stonecrop field definition.\n *\n * Classification rules (in order):\n * 1. Scalar types → look up in merged scalar map\n * 2. Enum types → `Select` with enum values as options\n * 3. Object types that are entities → `Link` with slug as options\n * 4. Object types that are Connections → `Doctype` with node type slug as options\n * 5. List of entity type → `Doctype` with item type slug as options\n * 6. Anything else → `Data` with `_unmapped: true`\n *\n * @param fieldName - The GraphQL field name\n * @param field - The GraphQL field definition\n * @param entityTypes - Set of type names classified as entities\n * @param options - Conversion options (for custom scalars, unmapped meta, etc.)\n * @returns The Stonecrop field definition\n * @public\n */\nexport function classifyFieldType(\n\tfieldName: string,\n\tfield: GraphQLField<unknown, unknown>,\n\tentityTypes: Set<string>,\n\toptions: GraphQLConversionOptions = {}\n): GraphQLConversionFieldMeta {\n\tconst { namedType, required, isList } = unwrapType(field.type)\n\tconst scalarMap = buildScalarMap(options.customScalars)\n\n\tconst base: GraphQLConversionFieldMeta = {\n\t\tkind: 'field',\n\t\tfieldname: fieldName,\n\t\tlabel: camelToLabel(fieldName),\n\t\tcomponent: 'ATextInput',\n\t}\n\n\tif (required) {\n\t\tbase.required = true\n\t}\n\n\t// 1. Scalar types\n\tif (isScalarType(namedType)) {\n\t\t// Skip internal scalars (e.g., Cursor)\n\t\tif (INTERNAL_SCALARS.has(namedType.name)) {\n\t\t\tbase._unmapped = true\n\t\t\tif (options.includeUnmappedMeta) {\n\t\t\t\tbase._graphqlType = namedType.name\n\t\t\t}\n\t\t\treturn base\n\t\t}\n\n\t\t// Special case: ID fields that reference an entity type → Link\n\t\tif (namedType.name === 'ID') {\n\t\t\tconst candidateTypeName = toPascalCase(fieldName)\n\t\t\tif (entityTypes.has(candidateTypeName)) {\n\t\t\t\tbase.component = 'AFormLink'\n\t\t\t\tbase.doctype = toSlug(candidateTypeName)\n\t\t\t\treturn base\n\t\t\t}\n\t\t}\n\n\t\tconst template: FieldTemplate | undefined = scalarMap[namedType.name]\n\t\tif (template) {\n\t\t\tbase.component = template.component\n\t\t} else {\n\t\t\t// Unknown scalar — default to Data with unmapped marker\n\t\t\tbase._unmapped = true\n\t\t\tif (options.includeUnmappedMeta) {\n\t\t\t\tbase._graphqlType = namedType.name\n\t\t\t}\n\t\t}\n\t\treturn base\n\t}\n\n\t// 2. Enum types → Select\n\tif (isEnumType(namedType)) {\n\t\tbase.component = 'ADropdown'\n\t\tbase.options = namedType.getValues().map(v => v.name)\n\t\treturn base\n\t}\n\n\t// 3–5. Object types\n\tif (isObjectType(namedType)) {\n\t\t// 3. Direct reference to an entity type → Link\n\t\tif (!isList && entityTypes.has(namedType.name)) {\n\t\t\tbase.component = 'AFormLink'\n\t\t\tbase.doctype = toSlug(namedType.name)\n\t\t\treturn base\n\t\t}\n\n\t\t// 4. Connection type → link (child table)\n\t\tconst connectionNodeTypeName = getConnectionNodeType(namedType)\n\t\tif (connectionNodeTypeName && entityTypes.has(connectionNodeTypeName)) {\n\t\t\tbase.component = 'ATable'\n\t\t\tbase._isLink = true\n\t\t\tbase.doctype = toSlug(connectionNodeTypeName)\n\t\t\tbase.cardinality = 'noneOrMany'\n\t\t\treturn base\n\t\t}\n\n\t\t// 5. List of entity type → link\n\t\tif (isList && entityTypes.has(namedType.name)) {\n\t\t\tbase.component = 'ATable'\n\t\t\tbase._isLink = true\n\t\t\tbase.doctype = toSlug(namedType.name)\n\t\t\tbase.cardinality = 'noneOrMany'\n\t\t\treturn base\n\t\t}\n\n\t\t// Unknown object type — mark as unmapped\n\t\tbase._unmapped = true\n\t\tif (options.includeUnmappedMeta) {\n\t\t\tbase._graphqlType = namedType.name\n\t\t}\n\t\treturn base\n\t}\n\n\t// Fallback — shouldn't normally be reached\n\tbase._unmapped = true\n\tif (options.includeUnmappedMeta) {\n\t\tbase._graphqlType = namedType.name\n\t}\n\treturn base\n}\n","import { z } from 'zod'\n\n/**\n * JSON-safe view configuration for table fields in doctype authoring.\n *\n * This is the authoring-time subset of `@stonecrop/atable`'s `TableConfig`. It covers\n * the view discriminator and structural options that can be expressed in static JSON.\n * `rowActions` (which requires function-typed handlers) stays in the runtime `TableConfig`.\n *\n * @public\n */\nexport const TableViewConfig = z\n\t.object({\n\t\t/** The table view type */\n\t\tview: z.enum(['list', 'uncounted', 'list-expansion', 'tree', 'gantt', 'tree-gantt']).optional(),\n\n\t\t/** Allow the table to use the full width of its container */\n\t\tfullWidth: z.boolean().optional(),\n\n\t\t/** Default expansion state for tree views */\n\t\tdefaultTreeExpansion: z.enum(['root', 'branch', 'leaf']).optional(),\n\n\t\t/** Enable dependency graph connections for Gantt views */\n\t\tdependencyGraph: z.boolean().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'TableViewConfig',\n\t\tdescription: 'JSON-safe view configuration for table fields in doctype authoring',\n\t})\n\n/**\n * Table view configuration type inferred from Zod schema\n * @public\n */\nexport type TableViewConfig = z.infer<typeof TableViewConfig>\n","import { z } from 'zod'\n\nimport type { ColumnSchema } from './column-schema'\nimport type { InteractionMode } from './mode'\nimport { TableViewConfig } from './table'\n\n/**\n * Field options - flexible bag for type-specific configuration.\n *\n * Usage:\n * - Select: array of choices ([\"Draft\", \"Submitted\", \"Cancelled\"])\n * - Decimal: config object (\\{ precision: 10, scale: 2 \\})\n * - Code: config object (\\{ language: \"python\" \\})\n *\n * Deliberately *not* a bare string: a string once meant \"link target\", which made the value's\n * shape encode its meaning. That job belongs to `ValueField.doctype`, leaving this a plain\n * choices-or-config bag.\n *\n * @public\n */\nexport const FieldOptions = z\n\t.union([\n\t\tz.array(z.string()), // Select choices: [\"A\", \"B\", \"C\"]\n\t\tz.record(z.string(), z.unknown()), // Config: \\{ precision: 10, scale: 2 \\}\n\t])\n\t.meta({\n\t\ttitle: 'FieldOptions',\n\t\tdescription: 'Field options - flexible bag for type-specific configuration',\n\t})\n\n/**\n * Field options type inferred from Zod schema\n * @public\n */\nexport type FieldOptions = z.infer<typeof FieldOptions>\n\n/**\n * Validation configuration for form fields\n * @public\n */\nexport const FieldValidation = z\n\t.looseObject({\n\t\t/** Error message to display when validation fails */\n\t\terrorMessage: z.string(),\n\t})\n\t.meta({\n\t\ttitle: 'FieldValidation',\n\t\tdescription: 'Validation configuration for form fields',\n\t})\n\n/**\n * Field validation type inferred from Zod schema\n * @public\n */\nexport type FieldValidation = z.infer<typeof FieldValidation>\n\n// ---------------------------------------------------------------------------\n// DoctypeField — the discriminated union of authoring-time field variants\n// ---------------------------------------------------------------------------\n\n/**\n * A field that holds a scalar value, a link to another record, or a select choice.\n * The most common kind of field. `component` determines how it renders; the attributes below\n * carry everything else that is not a rendering concern.\n * @public\n */\nexport interface ValueField {\n\t/** Discriminator — identifies this as a value-holding field */\n\tkind: 'field'\n\t/** Unique identifier for this field within its doctype */\n\tfieldname: string\n\t/**\n\t * Vue component that renders this field — the primary (and only) rendering axis. Required:\n\t * there is nothing left to derive it from, and a field without one has nothing to render it.\n\t * Any string is valid; naming a custom component is how an app renders a field Stonecrop\n\t * ships no widget for. See `CANONICAL_COMPONENTS` for the set Stonecrop provides.\n\t */\n\tcomponent: string\n\t/** True for the field that identifies the record's primary-key column. */\n\tprimaryKey?: boolean\n\t/** True for a computed/display field with no backing DB column — excluded from SQL SELECT. */\n\tcomputed?: boolean\n\t/** Editor language for code fields (e.g. `'json'`, `'typescript'`) — the only thing distinguishing\n\t * a JSON editor from a code editor, since both render with `ACodeEditor`. */\n\tlanguage?: string\n\t/**\n\t * Target doctype slug. Presence is what makes a field a link.\n\t *\n\t * How it renders is decided by `component`, not by this: `AFormLink` renders an\n\t * inline id-picker, while `AForm`/`ATable` expand the target (see `linkRenderMode`). Expansion\n\t * metadata — backlink, fetch strategy, authoritative cardinality — lives in the doctype's\n\t * `links` map, which is additive and never required for a plain foreign key.\n\t */\n\tdoctype?: string\n\t/** Human-readable label */\n\tlabel?: string\n\t/** CSS width (e.g. `\"40ch\"`, `\"200px\"`) */\n\twidth?: string\n\t/** Text alignment */\n\talign?: 'left' | 'center' | 'right' | 'start' | 'end'\n\t/** Whether the field is editable in table cell context */\n\tedit?: boolean\n\t/** Input mask pattern or serialized function */\n\tmask?: string\n\t/** Serialized `(value) => string` function for display formatting — distinct from `mask` (input).\n\t * Spreads through `schemaToColumns` to `ColumnSchema.format`; deserialized at render time by\n\t * ATable's `getFormattedValue`. */\n\tformat?: string\n\t/** Per-field interaction mode override */\n\tmode?: InteractionMode\n\t/** Type-specific options: Select choices, Decimal precision config, etc. A link's target is not\n\t * here — it is `doctype`. */\n\toptions?: FieldOptions\n\t/** Whether the field is required */\n\trequired?: boolean\n\t/** Whether the field is read-only */\n\treadOnly?: boolean\n\t/** Whether the field is hidden from the UI */\n\thidden?: boolean\n\t/** Default value for new records */\n\tdefault?: unknown\n\t/** Validation configuration */\n\tvalidation?: FieldValidation\n\t/** Cardinality for Link fields — authoritative value on LinkDeclaration takes precedence */\n\tcardinality?: 'atMostOne' | 'one' | 'noneOrMany' | 'atLeastOne'\n\t/**\n\t * Provenance marker — stamped only by the GraphQL converter; absence means hand-authored.\n\t * When present, the docbuilder freezes the field's identity set (`fieldname`, `primaryKey`,\n\t * `required`, `options`, `cardinality`, `doctype`), since `fieldname` is the GraphQL/column\n\t * binding and `doctype` is the FK's target. `component` is deliberately **not** frozen: it\n\t * chooses the widget, which is an authoring decision the database has no opinion about.\n\t */\n\tsource?: 'introspected'\n}\n\n/**\n * A layout container that groups other fields. Resolves to a nested AForm.\n * @public\n */\nexport interface FieldsetField {\n\t/** Discriminator — identifies this as a fieldset container */\n\tkind: 'fieldset'\n\t/** Unique identifier for this fieldset within its doctype */\n\tfieldname: string\n\t/** Vue component to render this fieldset. Defaults to `'AFieldset'` in resolveSchema. */\n\tcomponent?: string\n\t/** Human-readable label for the fieldset legend */\n\tlabel?: string\n\t/** Whether the fieldset can be collapsed */\n\tcollapsible?: boolean\n\t/** Interaction mode for all children inside this fieldset */\n\tmode?: InteractionMode\n\t/** Nested field definitions — resolved recursively by resolveSchema */\n\tschema: DoctypeField[]\n}\n\n/**\n * An inline table whose columns are defined directly in the schema (no linked doctype).\n * Use when the table data does not warrant a separate doctype.\n * @public\n */\nexport interface TableField {\n\t/** Discriminator — identifies this as an inline table */\n\tkind: 'table'\n\t/** Unique identifier for this table within its doctype */\n\tfieldname: string\n\t/** Vue component to render this table. Defaults to `'ATable'` in resolveSchema. */\n\tcomponent?: string\n\t/** Human-readable label */\n\tlabel?: string\n\t/** Column definitions — use ColumnSchema (fieldname key) from \\@stonecrop/schema */\n\tcolumns: ColumnSchema[]\n\t/** View configuration — defaults to `{ view: 'list' }` in resolveSchema when absent */\n\tconfig?: TableViewConfig\n\t/** Interaction mode for all cells inside this table */\n\tmode?: InteractionMode\n}\n\n/**\n * Union of all authoring-time field variants.\n * Use `kind` to discriminate: `'field'` | `'fieldset'` | `'table'`.\n * @public\n */\nexport type DoctypeField = ValueField | FieldsetField | TableField\n\n// ---------------------------------------------------------------------------\n// Zod runtime validation schemas\n// ---------------------------------------------------------------------------\n\n/**\n * Infers the `kind` discriminant from the structural properties of a raw field\n * object, then injects it if absent. This allows authored JSON to omit `kind`\n * entirely — a `schema` key means fieldset, `columns` means table, anything else\n * is a value field.\n *\n * Rules (applied in order):\n * has `schema` → fieldset\n * has `columns` → table\n * otherwise → field (value-holding scalar or link)\n *\n * Objects that already carry `kind` pass through unchanged (backward-compatible).\n *\n * Single-node only. Zod applies this at every level of the discriminated union (via the\n * `z.lazy` in the fieldset schema), so nested fieldset children are normalized during a\n * parse. Callers that bypass Zod — notably `Doctype.fromObject` — must use the exported\n * {@link normalizeFieldKind} instead, which replicates that recursion.\n */\nfunction injectKind(data: unknown): unknown {\n\tif (typeof data !== 'object' || data === null || Array.isArray(data)) return data\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- safe: non-null, non-array object verified by guards above\n\tconst obj = data as Record<string, unknown>\n\tif ('kind' in obj) return data\n\tif ('schema' in obj) return { kind: 'fieldset', ...obj }\n\tif ('columns' in obj) return { kind: 'table', ...obj }\n\treturn { kind: 'field', ...obj }\n}\n\n/**\n * Recursively injects the `kind` discriminant into a raw field object and, for fieldsets,\n * into each of its nested `schema` children — mirroring exactly what Zod's `preprocess`\n * does at every level of the discriminated union.\n *\n * Table `columns` are {@link ColumnSchema} entries, not `DoctypeField`s, so they are left\n * untouched — the Zod table schema validates them with a plain passthrough and never injects\n * `kind` there either.\n *\n * Needed because `Doctype.fromObject` constructs a Doctype without running Zod, yet the\n * registry's `resolveFields` gates link and fieldset handling on `field.kind`. Without this,\n * a JSON-authored link resolves to a flat scalar and a fieldset's children are dropped.\n *\n * @public\n */\nexport function normalizeFieldKind(field: unknown): unknown {\n\tconst injected = injectKind(field)\n\tif (typeof injected !== 'object' || injected === null) return injected\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- injectKind returns a non-null object for object input; guarded above\n\tconst obj = injected as Record<string, unknown>\n\tif (obj.kind === 'fieldset' && Array.isArray(obj.schema)) {\n\t\treturn { ...obj, schema: obj.schema.map(normalizeFieldKind) }\n\t}\n\treturn injected\n}\n\n/**\n * The field properties a `source: 'introspected'` marker freezes — the ones the database owns.\n *\n * This is the single definition of the identity set. The docbuilder greys these inputs on an\n * introspected field, and the converter's merge refuses to rewrite them. Stating it twice is how\n * the two drift, so both read this constant.\n *\n * Everything absent from this list is author-owned, `component` most importantly: it chooses the\n * widget, which is an authoring decision the database has no opinion about.\n *\n * @public\n */\nexport const INTROSPECTED_IDENTITY_PROPS = [\n\t'fieldname',\n\t'primaryKey',\n\t'required',\n\t'options',\n\t'cardinality',\n\t'doctype',\n] as const\n\n/**\n * Find the field a doctype marks as its primary key, or `undefined` when none is marked.\n *\n * This is the single definition of \"which field identifies a record\". Both sides depend on it:\n * the middleware builds the SQL identity predicate from it, and the client resolves a record's\n * route/store key from it. Call this; never re-derive the rule at the call site, or the two will\n * drift and the client will key records by a column the server never queried.\n *\n * Two deliberate limits, both matching the shape `primaryKey` actually has:\n * - Only **top-level** fields are scanned. `primaryKey` is a `ValueField` flag and a fieldset's\n * children are not identity columns, so a nested match would be an authoring error, not a PK.\n * - The **first** match wins. Identity is single-valued by design — a doctype describes the API\n * surface, and mapping a composite database key onto one identity there is the adapter's job —\n * so a doctype declaring several is malformed rather than composite. `DoctypeMeta` rejects that\n * at the load gate; this stays total for callers holding fields that never went through it.\n *\n * @param fields - the doctype's top-level fields\n * @returns the primary-key field, or `undefined` for a PK-less doctype\n * @public\n */\nexport function getPrimaryKeyField(fields: readonly DoctypeField[]): ValueField | undefined {\n\treturn fields.find((f): f is ValueField => f.kind === 'field' && Boolean(f.primaryKey))\n}\n\n/**\n * Recursively flatten Fieldset containers into a flat array of non-container fields.\n * Fieldset entries are replaced by their children; all other fields pass through.\n *\n * A fieldset is a layout grouping, not a scope: every field inside one is a field of the doctype,\n * with a column of its own and a name a link can bind to. Anything asking \"what does this doctype\n * declare\" must therefore descend, and the two ways to get that wrong point opposite ways — the\n * SELECT builder would omit real columns, while a validator would report a working declaration as\n * broken.\n *\n * Lives here rather than in the adapter because both sides need it: the middleware builds SQL from\n * it, and `DoctypeMeta`'s own validation asks the same question at the load gate. It sat in the\n * adapter while the validator hand-rolled a top-level-only scan, and that is exactly the second\n * failure this comment names — a `displayField` inside a fieldset was rejected at authoring time\n * and would have worked at runtime.\n *\n * @param fields - the doctype's top-level fields\n * @returns every non-container field, fieldset children included\n * @public\n */\nexport function flattenFields(fields: readonly DoctypeField[]): (ValueField | TableField)[] {\n\tconst result: (ValueField | TableField)[] = []\n\tfor (const f of fields) {\n\t\tif (f.kind === 'fieldset') {\n\t\t\tresult.push(...flattenFields(f.schema))\n\t\t} else {\n\t\t\tresult.push(f)\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Resolve the field a doctype nominates as its display text, or `undefined` when the nomination\n * does not name a readable column.\n *\n * This is the single definition of \"is this a usable `displayField`\". Both sides depend on it:\n * `DoctypeMeta` refuses a bad nomination at the load gate, and the adapter builds a SELECT from\n * the field it returns. Call this; never re-derive the rule, or the gate and the query will\n * disagree about which nominations are legal — which they did, in both directions at once.\n *\n * Two things disqualify a nomination, and both are the doctype saying so itself:\n * - it names no field at all, fieldset children included\n * - it names a `computed` field, which is declared precisely to state it has no column, so a\n * SELECT built from it would reference a column the database does not have\n *\n * @param fields - the doctype's top-level fields\n * @param displayField - the nominated fieldname\n * @returns the nominated field, or `undefined` when it is not a readable column\n * @public\n */\nexport function getDisplayField(\n\tfields: readonly DoctypeField[],\n\tdisplayField: string | undefined\n): ValueField | undefined {\n\tif (!displayField) return undefined\n\treturn flattenFields(fields).find(\n\t\t(f): f is ValueField => f.kind === 'field' && !f.computed && f.fieldname === displayField\n\t)\n}\n\n/**\n * The name of the field a record is identified by: the declared `primaryKey`, or `id` when the\n * doctype declares none.\n *\n * The `id` fallback is load-bearing, not defensive — a surrogate-key doctype carries an `id`\n * column and marks no primary key, so \"nothing declared\" means `id`, not \"no identity\".\n *\n * This exists because that one-line rule had been restated at four sites — the client's\n * `Doctype.recordIdField`, both nuxt hosts' `recordLookupField`, and the Postgres adapter — and\n * the fourth had omitted the fallback, so a doctype the client keyed by `id` was one the adapter\n * could not look up at all. Call this; a fifth restatement is how they diverge again.\n *\n * The returned name is not guaranteed to be a declared field: a doctype that declares no\n * `primaryKey` and no `id` yields `'id'` regardless. An adapter that must build a SQL predicate\n * from it has to confirm the field exists and say so when it does not, because selecting a column\n * the doctype never declared returns nothing rather than failing.\n *\n * @param fields - the doctype's top-level fields\n * @returns the identifying fieldname\n * @public\n */\nexport function getRecordIdField(fields: readonly DoctypeField[]): string {\n\treturn getPrimaryKeyField(fields)?.fieldname ?? 'id'\n}\n\n/**\n * Resolve a record's identity value using the doctype's declared primary key.\n *\n * Falls back to `record.id` when the doctype declares no `primaryKey`. That fallback is\n * load-bearing, not defensive: surrogate-key doctypes carry an `id` column and never mark a\n * primary key, and PostGraphile renames a single-column `id` PK to `rowId` — so the declared\n * field and `id` are both real sources, in that order.\n *\n * @param fields - the doctype's top-level fields\n * @param record - the record to read the identity from\n * @returns the identity as a string, or `undefined` when neither source yields a usable value\n * @public\n */\nexport function getRecordIdentity(\n\tfields: readonly DoctypeField[],\n\trecord: Record<string, unknown>\n): string | undefined {\n\tconst pkField = getPrimaryKeyField(fields)\n\tconst candidates = pkField ? [record[pkField.fieldname], record.id] : [record.id]\n\n\tfor (const value of candidates) {\n\t\t// Numbers are valid keys (a serial PK); 0 is a legitimate id, so test the type, not truthiness.\n\t\tif (typeof value === 'number') return String(value)\n\t\tif (typeof value === 'string' && value !== '') return value\n\t}\n\treturn undefined\n}\n\nfunction createDoctypeFieldSchemas() {\n\tconst ValueFieldSchema = z\n\t\t.object({\n\t\t\tkind: z.literal('field'),\n\t\t\tfieldname: z.string().min(1),\n\t\t\tcomponent: z.string().min(1),\n\t\t\tprimaryKey: z.boolean().optional(),\n\t\t\tcomputed: z.boolean().optional(),\n\t\t\tlanguage: z.string().optional(),\n\t\t\tdoctype: z.string().min(1).optional(),\n\t\t\tlabel: z.string().optional(),\n\t\t\twidth: z.string().optional(),\n\t\t\talign: z.enum(['left', 'center', 'right', 'start', 'end']).optional(),\n\t\t\tedit: z.boolean().optional(),\n\t\t\tmask: z.string().optional(),\n\t\t\tformat: z.string().optional(),\n\t\t\tmode: z.enum(['edit', 'read', 'display']).optional(),\n\t\t\toptions: FieldOptions.optional(),\n\t\t\trequired: z.boolean().optional(),\n\t\t\treadOnly: z.boolean().optional(),\n\t\t\thidden: z.boolean().optional(),\n\t\t\tdefault: z.unknown().optional(),\n\t\t\tvalidation: FieldValidation.optional(),\n\t\t\tcardinality: z.enum(['atMostOne', 'one', 'noneOrMany', 'atLeastOne']).optional(),\n\t\t\tsource: z.literal('introspected').optional(),\n\t\t})\n\t\t.meta({ title: 'ValueField' })\n\n\tconst TableFieldSchema = z\n\t\t.object({\n\t\t\tkind: z.literal('table'),\n\t\t\tfieldname: z.string().min(1),\n\t\t\tcomponent: z.string().optional(),\n\t\t\tlabel: z.string().optional(),\n\t\t\t// Validates that each column has fieldname; allows all other ColumnSchema properties\n\t\t\tcolumns: z.array(z.object({ fieldname: z.string().min(1) }).passthrough()),\n\t\t\tconfig: TableViewConfig.optional(),\n\t\t\tmode: z.enum(['edit', 'read', 'display']).optional(),\n\t\t})\n\t\t.meta({ title: 'TableField' })\n\n\t// DoctypeFieldSchema must be declared before FieldsetFieldSchema so the z.lazy\n\t// callback can close over it. The placeholder is overwritten below; the callback\n\t// only runs at parse time, after the real discriminated union is assigned.\n\t// See: https://zod.dev/api?id=discriminated-unions#discriminated-unions\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- required by Zod's recursive schema pattern; z.never() placeholder is overwritten before any parse call\n\tlet DoctypeFieldSchema: z.ZodType<DoctypeField> = z.never() as unknown as z.ZodType<DoctypeField>\n\n\t// FieldsetFieldSchema stays as a plain ZodObject (not z.ZodType<T>) so that\n\t// z.discriminatedUnion can inspect its 'kind' discriminant property.\n\tconst FieldsetFieldSchema = z\n\t\t.object({\n\t\t\tkind: z.literal('fieldset'),\n\t\t\tfieldname: z.string().min(1),\n\t\t\tcomponent: z.string().optional(),\n\t\t\tlabel: z.string().optional(),\n\t\t\tcollapsible: z.boolean().optional(),\n\t\t\tmode: z.enum(['edit', 'read', 'display']).optional(),\n\t\t\tschema: z.lazy(() => DoctypeFieldSchema.array()),\n\t\t})\n\t\t.meta({ title: 'FieldsetField' })\n\n\tconst rawUnion = z.discriminatedUnion('kind', [ValueFieldSchema, FieldsetFieldSchema, TableFieldSchema])\n\n\t// Overwrite the placeholder with the preprocessed schema. Because z.lazy captures\n\t// DoctypeFieldSchema by closure reference, the lazy callback in FieldsetFieldSchema\n\t// will resolve to this preprocessed version — so nested fieldsets also inject `kind`.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ZodPipe output is DoctypeField; same pattern as the z.never() placeholder above\n\tDoctypeFieldSchema = z.preprocess(injectKind, rawUnion) as unknown as z.ZodType<DoctypeField>\n\n\treturn { ValueFieldSchema, TableFieldSchema, FieldsetFieldSchema, DoctypeFieldSchema }\n}\n\nconst schemas = createDoctypeFieldSchemas()\n\n/**\n * Zod runtime validation schema for ValueField.\n * @public\n */\nexport const ValueFieldSchema = schemas.ValueFieldSchema\n\n/**\n * Zod runtime validation schema for FieldsetField.\n * Recursive — FieldsetField.schema is validated against DoctypeFieldSchema.\n * @public\n */\nexport const FieldsetFieldSchema = schemas.FieldsetFieldSchema\n\n/**\n * Zod runtime validation schema for TableField.\n * @public\n */\nexport const TableFieldSchema = schemas.TableFieldSchema\n\n/**\n * Zod runtime validation schema for the DoctypeField discriminated union.\n * Validates all three field variants: `'field'`, `'fieldset'`, `'table'`.\n * @public\n */\nexport const DoctypeFieldSchema = schemas.DoctypeFieldSchema\n","/**\n * Merge introspected schema facts into an already-authored doctype.\n *\n * The authored doctype is the source of truth. Generation **verifies** it and stamps provenance;\n * it does not overwrite. That polarity is deliberate and load-bearing — a doctype legitimately\n * declares a `primaryKey` the schema cannot express. A natural business key is very often a\n * `UNIQUE` constraint rather than the table's `PRIMARY KEY`, and where a table carries several\n * uniques no rule can pick between them. Overwriting identity from the schema would silently\n * re-key such a doctype on every regeneration and break the handlers that key on the old value.\n *\n * So divergence is **reported, never applied** — a human decides. The only mutation this performs\n * is adding `source: 'introspected'` to fields confirmed to exist in the GraphQL schema.\n *\n * @packageDocumentation\n */\n\nimport { INTROSPECTED_IDENTITY_PROPS } from '../field'\nimport type { ConvertedGraphQLDoctype } from './types'\n\n/**\n * A doctype as it exists on disk: a plain object that may carry keys this package does not model\n * (`handler` on an action, `filterFunction` on a field, whatever an app has added). Typing it\n * loosely is what lets the merge round-trip those keys untouched instead of dropping them.\n *\n * @public\n */\nexport type AuthoredDoctype = Record<string, unknown>\n\n/**\n * What generation found that the authored doctype does not agree with. Every bucket is advisory —\n * nothing here is applied automatically.\n *\n * @public\n */\nexport interface DoctypeDrift {\n\t/** The authored doctype's name. */\n\tdoctype: string\n\t/**\n\t * `clean` — the authored primary key is the one generation would derive.\n\t * `partial` — the doctype declares an identity generation cannot derive, so identity was left alone.\n\t */\n\tmode: 'clean' | 'partial'\n\t/** Why the mode is `partial`, when it is. */\n\treason?: string\n\t/** Fieldnames confirmed against the schema and stamped. */\n\ttagged: string[]\n\t/** Authored fields with no matching schema field — app components, fieldsets, or stale entries. */\n\torphan: string[]\n\t/** Schema fields absent from the doctype. Usually deliberate curation, occasionally an oversight. */\n\tomitted: string[]\n\t/** `fieldname: authored=… schema=…` where the chosen component differs from the scalar mapping. */\n\tcomponentDrift: string[]\n\t/** `fieldname: authored=… schema=…` where nullability disagrees. */\n\trequiredDrift: string[]\n\t/** Identity properties that differ. These are the ones a human must adjudicate. */\n\tidentityDrift: string[]\n}\n\n/** Outcome of a merge: the doctype to write, plus what generation disagreed with. @public */\nexport interface MergeResult {\n\t/** The authored doctype with `source` markers added and nothing else changed. */\n\tdoctype: AuthoredDoctype\n\t/** Advisory report. Never applied. */\n\tdrift: DoctypeDrift\n}\n\n/** Recursively flatten authored fields, descending into fieldsets. */\nfunction flattenAuthored(fields: readonly AuthoredDoctype[]): AuthoredDoctype[] {\n\tconst out: AuthoredDoctype[] = []\n\tfor (const f of fields) {\n\t\tif (Array.isArray(f.schema)) {\n\t\t\tout.push(...flattenAuthored(f.schema.filter(isRecord)))\n\t\t} else {\n\t\t\tout.push(f)\n\t\t}\n\t}\n\treturn out\n}\n\nfunction isRecord(value: unknown): value is AuthoredDoctype {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction describe(value: unknown): string {\n\treturn value === undefined ? '—' : JSON.stringify(value)\n}\n\n/**\n * Verify an authored doctype against freshly generated output and stamp provenance.\n *\n * @param authored - the doctype as it exists on disk; every key not named below is preserved verbatim\n * @param generated - `convertGraphQLSchema` output for the corresponding GraphQL type\n * @returns the doctype to write, plus a drift report\n *\n * @example\n * ```ts\n * const [generated] = convertGraphQLSchema(introspection, { include: ['Uom'] })\n * const { doctype, drift } = mergeIntrospectedDoctype(JSON.parse(onDisk), generated)\n * if (drift.identityDrift.length) console.warn(drift.identityDrift.join('\\n'))\n * ```\n *\n * @public\n */\nexport function mergeIntrospectedDoctype(authored: AuthoredDoctype, generated: ConvertedGraphQLDoctype): MergeResult {\n\tconst authoredFields = Array.isArray(authored.fields) ? authored.fields.filter(isRecord) : []\n\tconst generatedByName = new Map(generated.fields.map(f => [f.fieldname, f]))\n\t// Expanding links live in `links`, not `fields`, so a field naming one is modelled, not orphaned.\n\tconst generatedLinkNames = new Set(Object.keys(generated.links ?? {}))\n\n\tconst drift: DoctypeDrift = {\n\t\tdoctype: typeof authored.name === 'string' ? authored.name : '(unnamed)',\n\t\tmode: 'clean',\n\t\ttagged: [],\n\t\torphan: [],\n\t\tomitted: [],\n\t\tcomponentDrift: [],\n\t\trequiredDrift: [],\n\t\tidentityDrift: [],\n\t}\n\n\tconst tag = (field: AuthoredDoctype): AuthoredDoctype => {\n\t\t// Containers have no column of their own; recurse and leave the container itself alone.\n\t\tif (Array.isArray(field.schema)) {\n\t\t\treturn { ...field, schema: field.schema.filter(isRecord).map(tag) }\n\t\t}\n\n\t\tconst name = typeof field.fieldname === 'string' ? field.fieldname : ''\n\t\tconst match = generatedByName.get(name)\n\n\t\tif (!match) {\n\t\t\t// A computed field declares up front that it has no backing column, so it is not a\n\t\t\t// discrepancy. Everything else is worth surfacing — it may be an app component, or a\n\t\t\t// column that has since been dropped.\n\t\t\tif (field.computed !== true && !generatedLinkNames.has(name)) drift.orphan.push(name)\n\t\t\treturn field\n\t\t}\n\n\t\tdrift.tagged.push(name)\n\n\t\tif (match.component !== field.component) {\n\t\t\tdrift.componentDrift.push(`${name}: authored=${describe(field.component)} schema=${describe(match.component)}`)\n\t\t}\n\t\tif (Boolean(match.required) !== Boolean(field.required)) {\n\t\t\tdrift.requiredDrift.push(`${name}: authored=${Boolean(field.required)} schema=${Boolean(match.required)}`)\n\t\t}\n\t\tfor (const prop of INTROSPECTED_IDENTITY_PROPS) {\n\t\t\tif (prop === 'fieldname' || prop === 'required') continue\n\t\t\tconst authoredValue = field[prop]\n\t\t\tconst schemaValue = match[prop]\n\t\t\t// Absent on both sides is agreement, not drift — most fields set none of these.\n\t\t\tif (authoredValue === undefined && schemaValue === undefined) continue\n\t\t\tif (JSON.stringify(authoredValue) !== JSON.stringify(schemaValue)) {\n\t\t\t\tdrift.identityDrift.push(`${name}.${prop}: authored=${describe(authoredValue)} schema=${describe(schemaValue)}`)\n\t\t\t}\n\t\t}\n\n\t\treturn { ...field, source: 'introspected' }\n\t}\n\n\tconst merged: AuthoredDoctype = { ...authored, fields: authoredFields.map(tag) }\n\n\tconst authoredNames = new Set(flattenAuthored(authoredFields).map(f => f.fieldname))\n\tdrift.omitted = generated.fields.map(f => f.fieldname).filter(n => !authoredNames.has(n))\n\n\t// Classify identity last, once every field has been compared.\n\tconst authoredPk = flattenAuthored(authoredFields).find(f => f.primaryKey === true)\n\tconst generatedPk = generated.fields.find(f => f.primaryKey === true)\n\tif (authoredPk && generatedPk && authoredPk.fieldname !== generatedPk.fieldname) {\n\t\tdrift.mode = 'partial'\n\t\tdrift.reason = `authored primary key '${String(authoredPk.fieldname)}' is not the derivable '${generatedPk.fieldname}' — left as authored`\n\t} else if (authoredPk && !generatedPk) {\n\t\tdrift.mode = 'partial'\n\t\tdrift.reason = `authored primary key '${String(authoredPk.fieldname)}' is not derivable from the schema — left as authored`\n\t} else if (!authoredPk && generatedPk) {\n\t\tdrift.mode = 'partial'\n\t\tdrift.reason = `schema suggests '${generatedPk.fieldname}' as primary key but the doctype declares none — not applied`\n\t}\n\n\treturn { doctype: merged, drift }\n}\n\n/**\n * Render a drift report as human-readable lines. Empty when generation agrees with the doctype.\n *\n * @param drift - a report from {@link mergeIntrospectedDoctype}\n * @returns one line per finding, ready to print\n *\n * @public\n */\nexport function formatDoctypeDrift(drift: DoctypeDrift): string[] {\n\tconst lines: string[] = []\n\tif (drift.reason) lines.push(` ${drift.doctype}: ${drift.reason}`)\n\tconst bucket = (label: string, entries: string[]) => {\n\t\tif (entries.length) lines.push(` ${drift.doctype}: ${label} ${entries.join('; ')}`)\n\t}\n\tbucket('identity drift', drift.identityDrift)\n\tbucket('component drift', drift.componentDrift)\n\tbucket('required drift', drift.requiredDrift)\n\tbucket('authored fields with no schema field:', drift.orphan)\n\tbucket('schema fields not modelled:', drift.omitted)\n\treturn lines\n}\n","/**\n * GraphQL Introspection to Stonecrop Schema Converter\n *\n * Converts a standard GraphQL introspection result (or SDL string) into\n * Stonecrop doctype schemas. Source-agnostic — works with any GraphQL server.\n *\n * @packageDocumentation\n */\n\nimport { buildClientSchema, buildSchema, isObjectType, type GraphQLSchema } from 'graphql'\n\nimport type { LinkDeclaration } from '../doctype'\nimport { toSlug } from '../naming'\nimport type { IntrospectionSource, GraphQLConversionOptions, ConvertedGraphQLDoctype } from './types'\nimport type { ValueField } from '../field'\nimport { defaultIsEntityType, defaultIsEntityField, classifyFieldType } from './heuristics'\n\n/**\n * Convert a GraphQL schema to Stonecrop doctype schemas.\n *\n * Accepts either an `IntrospectionQuery` result object or an SDL string.\n * Entity types are identified using heuristics (or a custom `isEntityType` function)\n * and converted to `DoctypeMeta`-compatible JSON objects.\n *\n * @param source - GraphQL introspection result or SDL string\n * @param options - Conversion options for controlling output format and behavior\n * @returns Array of converted Stonecrop doctype definitions\n *\n * @example\n * ```typescript\n * // From introspection result (fetched from any GraphQL server)\n * const introspection = await fetchIntrospection('http://localhost:5000/graphql')\n * const doctypes = convertGraphQLSchema(introspection)\n *\n * // From SDL string\n * const sdl = fs.readFileSync('schema.graphql', 'utf-8')\n * const doctypes = convertGraphQLSchema(sdl)\n *\n * // With PostGraphile custom scalars\n * const doctypes = convertGraphQLSchema(introspection, {\n * customScalars: {\n * BigFloat: { component: 'ANumericInput' }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function convertGraphQLSchema(\n\tsource: IntrospectionSource,\n\toptions: GraphQLConversionOptions = {}\n): ConvertedGraphQLDoctype[] {\n\tconst schema = buildGraphQLSchema(source)\n\tconst typeMap = schema.getTypeMap()\n\n\t// Determine the root operation type names to exclude\n\tconst rootTypeNames = new Set<string>()\n\tconst queryType = schema.getQueryType()\n\tconst mutationType = schema.getMutationType()\n\tconst subscriptionType = schema.getSubscriptionType()\n\tif (queryType) rootTypeNames.add(queryType.name)\n\tif (mutationType) rootTypeNames.add(mutationType.name)\n\tif (subscriptionType) rootTypeNames.add(subscriptionType.name)\n\n\t// Use custom or default entity type detector\n\tconst isEntityType = options.isEntityType ?? defaultIsEntityType\n\n\t// Phase 1: Identify all entity types\n\tconst entityTypes = new Set<string>()\n\tfor (const [typeName, type] of Object.entries(typeMap)) {\n\t\tif (!isObjectType(type)) continue\n\n\t\t// Always skip root operation types (even if custom isEntityType doesn't)\n\t\tif (rootTypeNames.has(typeName)) continue\n\n\t\tif (isEntityType(typeName, type)) {\n\t\t\tentityTypes.add(typeName)\n\t\t}\n\t}\n\n\t// Phase 2: Apply include/exclude filters\n\tlet filteredEntityTypes = entityTypes\n\n\tif (options.include) {\n\t\tconst includeSet = new Set(options.include)\n\t\tfilteredEntityTypes = new Set([...entityTypes].filter(t => includeSet.has(t)))\n\t}\n\n\tif (options.exclude) {\n\t\tconst excludeSet = new Set(options.exclude)\n\t\tfilteredEntityTypes = new Set([...filteredEntityTypes].filter(t => !excludeSet.has(t)))\n\t}\n\n\t// Phase 3: Convert each entity type to a doctype\n\tconst isEntityField = options.isEntityField ?? defaultIsEntityField\n\n\tconst doctypes: ConvertedGraphQLDoctype[] = []\n\n\tfor (const typeName of filteredEntityTypes) {\n\t\tconst type = typeMap[typeName]\n\t\tif (!isObjectType(type)) continue\n\n\t\tconst fields = type.getFields()\n\n\t\t// A type carrying BOTH `id` and `rowId` is PostGraphile Amber with its default inflection:\n\t\t// the Relay global identifier has taken `id`, displacing the real column to `rowId`. Neither\n\t\t// name can be emitted as-is — `id` is an opaque node id, and `rowId` does not name a column.\n\t\t// Refuse to guess: drop the Relay field and tell the caller to fix it at the inflector, where\n\t\t// it belongs. Normalizing here would bake a database fact into the doctype.\n\t\tconst isUnnormalizedPostGraphile = 'id' in fields && 'rowId' in fields\n\t\tif (isUnnormalizedPostGraphile) {\n\t\t\toptions.onWarning?.(\n\t\t\t\t`${typeName}: schema exposes both 'id' (Relay identifier) and 'rowId' (the real column). ` +\n\t\t\t\t\t`Skipping 'id' and emitting 'rowId' verbatim — no primary key can be derived. ` +\n\t\t\t\t\t`Override the '_attributeName' and 'nodeIdFieldName' inflectors so the column keeps its own name.`\n\t\t\t)\n\t\t}\n\n\t\tconst entityFields = Object.entries(fields).filter(\n\t\t\t([fieldName, field]) =>\n\t\t\t\tisEntityField(fieldName, field, type) && !(isUnnormalizedPostGraphile && fieldName === 'id')\n\t\t)\n\n\t\t// oxlint-disable-next-line oxc/no-map-spread -- ...custom spread required; Object.assign cannot preserve the metadata-carrying inferred union type from classifyField\n\t\tconst allClassifiedFields = entityFields.map(([fieldName, field]) => {\n\t\t\t// Check for full custom classification first\n\t\t\tif (options.classifyField) {\n\t\t\t\tconst custom = options.classifyField(fieldName, field, type)\n\t\t\t\tif (custom !== null && custom !== undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'field' as const,\n\t\t\t\t\t\tfieldname: fieldName,\n\t\t\t\t\t\tlabel: custom.label ?? fieldName,\n\t\t\t\t\t\tcomponent: custom.component ?? 'ATextInput',\n\t\t\t\t\t\t...custom,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Default classification\n\t\t\treturn classifyFieldType(fieldName, field, entityTypes, options)\n\t\t})\n\n\t\t// Derive the primary key, but only for the one case SDL actually settles: a non-null `id`\n\t\t// that is a plain scalar. A natural key is typically a UNIQUE constraint indistinguishable\n\t\t// from any other column here, and a table may carry several — so anything else is left for\n\t\t// the author to declare. Emitting a guess would be worse than emitting nothing, because the\n\t\t// middleware builds its identity predicate from this and the client keys records by it.\n\t\tconst primaryKeyFieldname = allClassifiedFields.find(\n\t\t\tfield => field.fieldname === 'id' && field.required && !field.doctype && !field._isLink\n\t\t)?.fieldname\n\n\t\t// Separate scalar fields from link fields\n\t\tconst links: Record<string, LinkDeclaration> = {}\n\t\tconst convertedFields = allClassifiedFields\n\t\t\t.filter(field => {\n\t\t\t\tif (field._isLink && field.doctype && field.cardinality) {\n\t\t\t\t\tlinks[field.fieldname] = {\n\t\t\t\t\t\ttarget: field.doctype,\n\t\t\t\t\t\tcardinality: field.cardinality,\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t})\n\t\t\t// Clean up internal metadata unless requested, and stamp identity + provenance.\n\t\t\t// Stamped last so every classification path (default, classifyField) carries the marker —\n\t\t\t// the docbuilder's identity lock keys off it, and no classifier may unset it.\n\t\t\t.map(field => {\n\t\t\t\tconst identity = field.fieldname === primaryKeyFieldname ? { primaryKey: true as const } : {}\n\t\t\t\tif (!options.includeUnmappedMeta) {\n\t\t\t\t\tconst { _graphqlType, _unmapped, _isLink, ...clean } = field\n\t\t\t\t\treturn Object.assign(clean, identity, { source: 'introspected' as const })\n\t\t\t\t}\n\t\t\t\tconst { _isLink, ...rest } = field\n\t\t\t\treturn Object.assign(rest, identity, { source: 'introspected' as const })\n\t\t\t})\n\n\t\tconst doctypeName = options.doctypeNames?.[typeName] ?? typeName\n\t\tconst doctype: ConvertedGraphQLDoctype = {\n\t\t\tname: doctypeName,\n\t\t\tslug: toSlug(doctypeName),\n\t\t\tfields: convertedFields as ValueField[],\n\t\t}\n\n\t\tif (Object.keys(links).length > 0) {\n\t\t\tdoctype.links = links\n\t\t}\n\n\t\tif (options.includeUnmappedMeta) {\n\t\t\tdoctype._graphqlTypeName = typeName\n\t\t}\n\n\t\tdoctypes.push(doctype)\n\t}\n\n\treturn doctypes\n}\n\n/**\n * Build a GraphQLSchema from either an introspection result or SDL string.\n *\n * @param source - IntrospectionQuery object or SDL string\n * @returns A complete GraphQLSchema\n * @internal\n */\nfunction buildGraphQLSchema(source: IntrospectionSource): GraphQLSchema {\n\tif (typeof source === 'string') {\n\t\t// SDL string\n\t\treturn buildSchema(source)\n\t}\n\n\t// IntrospectionQuery result\n\treturn buildClientSchema(source)\n}\n\n// ═══════════════════════════════════════════════════════════════\n// Re-exports\n// ═══════════════════════════════════════════════════════════════\n\n// Main converter (this file)\nexport { convertGraphQLSchema as default }\n\n// Types\nexport type {\n\tIntrospectionSource,\n\tGraphQLConversionOptions,\n\tGraphQLConversionFieldMeta,\n\tConvertedGraphQLDoctype,\n} from './types'\n\n// Scalar maps\nexport { GQL_SCALAR_MAP, WELL_KNOWN_SCALARS, INTERNAL_SCALARS, buildScalarMap } from './scalars'\n\n// Heuristics\nexport { defaultIsEntityType, defaultIsEntityField, classifyFieldType } from './heuristics'\n\n// Merge — verifies an authored doctype against the schema and stamps provenance\nexport { mergeIntrospectedDoctype, formatDoctypeDrift } from './merge'\nexport type { AuthoredDoctype, DoctypeDrift, MergeResult } from './merge'\n\n// Naming utilities\nexport { toSlug, toPascalCase, pascalToSnake, snakeToCamel, camelToSnake, snakeToLabel, camelToLabel } from '../naming'\n","import { z } from 'zod'\n\nimport { DoctypeFieldSchema, flattenFields, getDisplayField } from './field'\n\n/**\n * Cardinality for relationship links.\n * @public\n */\nexport const Cardinality = z.enum(['atMostOne', 'one', 'noneOrMany', 'atLeastOne']).meta({\n\ttitle: 'Cardinality',\n\tdescription: 'Cardinality for relationship links between doctypes',\n})\n\n/**\n * Cardinality type inferred from Zod schema\n * @public\n */\nexport type Cardinality = z.infer<typeof Cardinality>\n\n/**\n * Serialized function type - a function serialized to a string.\n * Used for custom fetch handlers.\n * @public\n */\nexport type SerializedFunction = string\n\n/**\n * Sync fetch strategy - data is fetched in the initial query.\n * @public\n */\nexport const SyncFetch = z\n\t.object({\n\t\t/** Fetch method type */\n\t\tmethod: z.literal('sync'),\n\t\t/** Optional limit on number of records to fetch */\n\t\tlimit: z.number().int().positive().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'SyncFetch',\n\t\tdescription: 'Sync fetch strategy - data is fetched in the initial query',\n\t})\n\n/**\n * Sync fetch strategy type\n * @public\n */\nexport type SyncFetch = z.infer<typeof SyncFetch>\n\n/**\n * Lazy fetch strategy - data is fetched on demand in a separate query.\n * @public\n */\nexport const LazyFetch = z\n\t.object({\n\t\t/** Fetch method type */\n\t\tmethod: z.literal('lazy'),\n\t})\n\t.meta({\n\t\ttitle: 'LazyFetch',\n\t\tdescription: 'Lazy fetch strategy - data is fetched on demand in a separate query',\n\t})\n\n/**\n * Lazy fetch strategy type\n * @public\n */\nexport type LazyFetch = z.infer<typeof LazyFetch>\n\n/**\n * Custom fetch strategy - uses a custom handler function.\n * @public\n */\nexport const CustomFetch = z\n\t.object({\n\t\t/** Fetch method type */\n\t\tmethod: z.literal('custom'),\n\t\t/** Serialized handler function to invoke */\n\t\thandler: z.string(),\n\t})\n\t.meta({\n\t\ttitle: 'CustomFetch',\n\t\tdescription: 'Custom fetch strategy - uses a custom handler function',\n\t})\n\n/**\n * Custom fetch strategy type\n * @public\n */\nexport type CustomFetch = z.infer<typeof CustomFetch>\n\n/**\n * Fetch strategy for link data loading.\n * - sync: fetched in the initial query\n * - lazy: fetched on demand in a separate query\n * - custom: uses a custom handler function\n * @public\n */\nexport const FetchStrategy = z.discriminatedUnion('method', [SyncFetch, LazyFetch, CustomFetch]).meta({\n\ttitle: 'FetchStrategy',\n\tdescription: 'Fetch strategy for link data loading',\n})\n\n/**\n * Fetch strategy type\n * @public\n */\nexport type FetchStrategy = z.infer<typeof FetchStrategy>\n\n/**\n * Link declaration - describes a relationship from one doctype to another.\n * @public\n */\nexport const LinkDeclaration = z\n\t.object({\n\t\t/** Target doctype slug */\n\t\ttarget: z.string().min(1),\n\n\t\t/** Cardinality of the relationship */\n\t\tcardinality: Cardinality,\n\n\t\t/** Backlink fieldname on the target doctype that points back to this link */\n\t\tbacklink: z.string().optional(),\n\n\t\t/** Override default rendering component (AForm for 1:1, ATable for 1:many) */\n\t\tcomponent: z.string().optional(),\n\n\t\t/** Fieldname of the corresponding Link field in the fields array */\n\t\tfieldname: z.string().min(1).optional(),\n\n\t\t/** Fetch strategy for loading nested data */\n\t\tfetch: FetchStrategy.optional(),\n\n\t\t/** Whether to block workflow actions until nested data is loaded (default: true) */\n\t\tblockWorkflows: z.boolean().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'LinkDeclaration',\n\t\tdescription: 'Declares a relationship from one doctype to another',\n\t})\n\n/**\n * Link declaration type inferred from Zod schema\n * @public\n */\nexport type LinkDeclaration = z.infer<typeof LinkDeclaration>\n\n/**\n * Action definition within a workflow\n * @public\n */\nexport const ActionDefinition = z\n\t.object({\n\t\t/** Display label for the action */\n\t\tlabel: z.string().min(1),\n\n\t\t/** Fields that must have values before action can execute */\n\t\trequiredFields: z.array(z.string()).optional(),\n\n\t\t/** Workflow states where this action is available */\n\t\tallowedStates: z.array(z.string()).optional(),\n\n\t\t/** The state the record transitions to after this action executes */\n\t\tnextState: z.string().optional(),\n\n\t\t/** True for stateless command actions with no workflow effect at all (print, email, etc.) */\n\t\tstateless: z.boolean().optional(),\n\n\t\t/**\n\t\t * True for an internal self-transition: the action runs within the current state without\n\t\t * advancing the workflow (e.g. `save`, which mutates record data but stays put). Scoped by\n\t\t * `allowedStates`, rendered as a self-loop in the graph, and has no `nextState`. Distinct from\n\t\t * `stateless` (which has no workflow presence at all): a self-transition is graph-owned and,\n\t\t * unlike a stateless command, persists record data on dispatch.\n\t\t */\n\t\tselfTransition: z.boolean().optional(),\n\n\t\t/** JS function body stored as a string; executed client-side via AsyncFunction with injected API surface */\n\t\tclientHandler: z.string().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'ActionDefinition',\n\t\tdescription: 'Action definition within a workflow',\n\t})\n\n/**\n * Action definition type inferred from Zod schema\n * @public\n */\nexport type ActionDefinition = z.infer<typeof ActionDefinition>\n\n/**\n * Reactive field-validation trigger — advisory, client-side only.\n *\n * A Trigger is a docbuilder-authored validator: when any field in `on` is edited, its\n * `clientHandler` runs (client-side, no rollback) and may flag a field inline to block save\n * in the UI. It is deliberately a **sibling** to {@link (ActionDefinition:type)}, not a member of it —\n * a reactive validator is not a user-invoked action, so it lives in the `triggers` map on\n * {@link (WorkflowMeta:type)} and never appears to action readers (transition/command dropdowns, the FSM graph).\n *\n * The two bindings are independent: `on` is the fire-set (which fields' edits run it), while the\n * `setError(field, msg)` call inside `clientHandler` chooses which field displays the error.\n * @public\n */\nexport const TriggerDefinition = z\n\t.object({\n\t\t/** Optional display label; the map key is the trigger's identity */\n\t\tlabel: z.string().optional(),\n\n\t\t/** Fieldnames whose edits fire this trigger (fires when any listed field changes) */\n\t\ton: z.array(z.string()),\n\n\t\t/** JS function body stored as a string; run client-side with `{ record, value, setError }`. Advisory. */\n\t\tclientHandler: z.string(),\n\t})\n\t.meta({\n\t\ttitle: 'TriggerDefinition',\n\t\tdescription: 'Reactive field-validation trigger — advisory client-side',\n\t})\n\n/**\n * Trigger definition type inferred from Zod schema\n * @public\n */\nexport type TriggerDefinition = z.infer<typeof TriggerDefinition>\n\n/**\n * Whether a workflow action may run from `currentState`.\n *\n * Single source of truth for the \"is this action available here\" rule, shared by\n * the frontend (`getAvailableTransitions`) and the server-side dispatch guard so\n * the two can never disagree. Empty or absent `allowedStates` means the action is\n * available in ALL states — a plain `allowedStates.includes(currentState)` would\n * wrongly block such actions everywhere.\n *\n * @public\n */\nexport function isActionAllowedInState(action: { allowedStates?: string[] | null }, currentState: string): boolean {\n\tconst allowedStates = action.allowedStates\n\tif (!allowedStates || allowedStates.length === 0) return true\n\treturn allowedStates.includes(currentState)\n}\n\n/**\n * DocBuilder graph layout — node positions for the workflow-state graph, keyed by state name.\n * Pure authoring view-state: persisted in the doctype JSON so an author's manual arrangement\n * survives reloads, but — exactly like {@link (WorkflowMeta:type)}'s `triggers` — it is client-only\n * and never mirrored into the runtime GraphQL SDL (see the WorkflowMeta type in the host SDLs, which\n * expose only `states`/`actions`). The shape mirrors VueFlow's node fields; `position` is the node's\n * canvas coordinate and `targetPosition`/`sourcePosition` are the handle sides.\n * @public\n */\nexport const WorkflowLayout = z.record(\n\tz.string(),\n\tz.object({\n\t\tposition: z.object({ x: z.number(), y: z.number() }).optional(),\n\t\ttargetPosition: z.enum(['left', 'top', 'right', 'bottom']).optional(),\n\t\tsourcePosition: z.enum(['left', 'top', 'right', 'bottom']).optional(),\n\t})\n)\n\n/**\n * Workflow layout type inferred from Zod schema\n * @public\n */\nexport type WorkflowLayout = z.infer<typeof WorkflowLayout>\n\n/**\n * Workflow metadata - states and actions for a doctype\n * @public\n */\nexport const WorkflowMeta = z\n\t.object({\n\t\t/** List of workflow states */\n\t\tstates: z.array(z.string()).optional(),\n\n\t\t/** Actions available in this workflow */\n\t\tactions: z.record(z.string(), ActionDefinition).optional(),\n\n\t\t/** Reactive field-validation triggers (advisory, client-side), keyed by trigger name */\n\t\ttriggers: z.record(z.string(), TriggerDefinition).optional(),\n\n\t\t/**\n\t\t * DocBuilder node positions keyed by state name — authoring view-state. Persisted here so a\n\t\t * doctype author's manual graph arrangement survives reloads; like `triggers`, it is client-only\n\t\t * and never enters the runtime GraphQL SDL. See {@link (WorkflowLayout:variable)}.\n\t\t */\n\t\tlayout: WorkflowLayout.optional(),\n\t})\n\t.meta({\n\t\ttitle: 'WorkflowMeta',\n\t\tdescription: 'Workflow metadata - states and actions for a doctype',\n\t})\n\n/**\n * Workflow metadata type inferred from Zod schema\n * @public\n */\nexport type WorkflowMeta = z.infer<typeof WorkflowMeta>\n\n/**\n * Doctype metadata - complete definition of a doctype\n * @public\n */\nexport const DoctypeMeta = z\n\t.object({\n\t\t/** Display name of the doctype */\n\t\tname: z.string().min(1),\n\n\t\t/** URL-friendly slug (kebab-case) */\n\t\tslug: z.string().min(1).optional(),\n\n\t\t/**\n\t\t * Field on this doctype used when displaying a reference to one of its records.\n\t\t * When a record elsewhere holds a foreign key to this doctype, the middleware may\n\t\t * include `fieldname__display` alongside the raw id, resolved from this field.\n\t\t */\n\t\tdisplayField: z.string().min(1).optional(),\n\n\t\t/** Field definitions (a link field is one carrying `doctype`) */\n\t\tfields: z.array(DoctypeFieldSchema),\n\n\t\t/** Relationship links to other doctypes */\n\t\tlinks: z.record(z.string(), LinkDeclaration).optional(),\n\n\t\t/** Workflow configuration */\n\t\tworkflow: WorkflowMeta.optional(),\n\n\t\t/** Parent doctype for inheritance */\n\t\tinherits: z.string().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'DoctypeMeta',\n\t\tdescription: 'Doctype metadata - complete definition of a doctype',\n\t})\n\t.superRefine((doctype, ctx) => {\n\t\t// A record is identified by exactly one field here, and that is the design rather than a\n\t\t// limitation awaiting composite support. A doctype describes the **API surface** a client\n\t\t// interacts with, not the table behind it; how a composite database key maps onto a single\n\t\t// identity on that surface is the server's business, and the client neither sees nor\n\t\t// encodes the parts. So there is nothing for a doctype-level composite key to express.\n\t\t//\n\t\t// Declaring several is therefore malformed, and silently so: `getPrimaryKeyField` takes the\n\t\t// first match and the rest are ignored, leaving an adapter to key records on a column that\n\t\t// need not be unique — `stonecropRecord`'s row map then keeps whichever row comes last.\n\t\t// Refusing at the gate is what makes it say so.\n\t\t//\n\t\t// Zero keys stays legal and is not an omission: a surrogate-key doctype declares none and\n\t\t// resolves through `getRecordIdField`'s documented `id` fallback.\n\t\tconst declared = doctype.fields.filter(f => f.kind === 'field' && f.primaryKey)\n\t\tif (declared.length > 1) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: 'custom',\n\t\t\t\tpath: ['fields'],\n\t\t\t\tmessage: `Doctype declares ${declared.length} primaryKey fields (${declared\n\t\t\t\t\t.map(f => (f.kind === 'field' ? f.fieldname : ''))\n\t\t\t\t\t.join(\n\t\t\t\t\t\t', '\n\t\t\t\t\t)}); a record is identified by exactly one field. A composite database key is mapped to a single identity by the adapter, so a doctype never declares its parts`,\n\t\t\t})\n\t\t}\n\n\t\t// Through `getDisplayField` rather than a scan written here, because the adapter builds its\n\t\t// SELECT from that same call. The two hand-rolled versions disagreed in both directions at\n\t\t// once: this gate scanned top-level only, so it rejected a fieldset-nested field that would\n\t\t// have worked, while neither side excluded `computed` fields, so a nomination naming one\n\t\t// passed the gate and then failed as a missing column at query time.\n\t\tif (doctype.displayField && !getDisplayField(doctype.fields, doctype.displayField)) {\n\t\t\tconst named = flattenFields(doctype.fields).find(f => f.fieldname === doctype.displayField)\n\t\t\tctx.addIssue({\n\t\t\t\tcode: 'custom',\n\t\t\t\tpath: ['displayField'],\n\t\t\t\tmessage: named\n\t\t\t\t\t? `displayField \"${doctype.displayField}\" names a computed field, which has no column to read a display value from`\n\t\t\t\t\t: `displayField \"${doctype.displayField}\" is not declared on this doctype`,\n\t\t\t})\n\t\t}\n\t})\n\n/**\n * Doctype metadata type inferred from Zod schema\n * @public\n */\nexport type DoctypeMeta = z.infer<typeof DoctypeMeta>\n\n/**\n * Suffix appended to a link fieldname for its pre-resolved display text in record payloads.\n *\n * @deprecated The `__display` suffix pattern is no longer used. Use the native PostGraphile\n * query methods (`getNativeRecord`/`getNativeRecords`) in `@stonecrop/graphql-client` which\n * return link fields as `{ id, displayText }` objects directly.\n * @public\n */\nexport const LINK_DISPLAY_SUFFIX = '__display'\n\n/**\n * Build the payload key for a link field's display text (e.g. `customerId__display`).\n *\n * @deprecated The `__display` suffix pattern is no longer used. Use the native PostGraphile\n * query methods (`getNativeRecord`/`getNativeRecords`) in `@stonecrop/graphql-client` which\n * return link fields as `{ id, displayText }` objects directly.\n * @public\n */\nexport function linkDisplayFieldname(fieldname: string): string {\n\treturn `${fieldname}${LINK_DISPLAY_SUFFIX}`\n}\n\n/**\n * Context for identifying what doctype/record we're working with.\n * Used by graphql-middleware and graphql-client to resolve schema metadata.\n * @public\n */\nexport interface DoctypeContext {\n\t/** Doctype name (e.g., 'Task', 'Customer') */\n\tdoctype: string\n\t/** Optional record ID for viewing/editing a specific record */\n\trecordId?: string\n\t/** Additional context properties */\n\t[key: string]: unknown\n}\n\n/**\n * Base interface for doctype metadata passed to DataClient methods.\n * Only requires properties needed for record fetching.\n * @public\n */\nexport interface DoctypeRef {\n\t/** Doctype name (e.g., 'Task', 'Customer') */\n\tname: string\n\t/** URL-friendly slug (e.g., 'task', 'customer') */\n\tslug?: string\n}\n\n/**\n * Options for fetching a single record\n * @public\n */\nexport interface GetRecordOptions {\n\t/**\n\t * Include nested link sub-selections.\n\t * - `true`: include all descendant links\n\t * - `string[]`: include only named links\n\t * - `false` / omitted: scalar fields only (default)\n\t */\n\tincludeNested?: boolean | string[]\n\n\t/**\n\t * Maximum depth for recursive sub-selections.\n\t * No default — unlimited when omitted.\n\t */\n\tmaxDepth?: number\n}\n\n/**\n * Options for fetching multiple records\n * @public\n */\nexport interface GetRecordsOptions {\n\t/** Filter expression (field-value pairs) */\n\tfilters?: Record<string, unknown>\n\t/** Order by expression (e.g. 'NAME_ASC') */\n\torderBy?: string\n\t/** Maximum number of records to return */\n\tlimit?: number\n\t/** Number of records to skip */\n\toffset?: number\n\t/**\n\t * Ask the backend for the total matching the filters as well as the page.\n\t *\n\t * Off by default because it costs a second query — a full scan on Postgres — and knowing\n\t * *whether* more exist (`hasMore`) is what a list view actually needs. Turn it on for a\n\t * \"showing 20 of 4,312\" style display.\n\t */\n\tincludeTotal?: boolean\n}\n\n/**\n * Result from getRecord - includes the record data\n * @public\n */\nexport interface GetRecordResult {\n\t/** The record data, or null if not found */\n\trecord: Record<string, unknown> | null\n}\n\n/**\n * Result from getRecords — a page of records, and enough to tell that it is one.\n *\n * A bare array used to be returned here, which claimed to be the whole collection. It is not:\n * a limit always applies, so a caller could not distinguish a complete list from a truncated\n * one. That is the entire reason this type exists.\n *\n * @public\n */\nexport interface GetRecordsResult {\n\t/** The records in this page */\n\tdata: Record<string, unknown>[]\n\t/** Whether the backend holds further records beyond this page */\n\thasMore: boolean\n\t/**\n\t * Total records matching the filters, ignoring limit/offset. Present only when the caller\n\t * asked for it via {@link GetRecordsOptions.includeTotal} — counting is a full scan on most\n\t * backends, so it is never computed speculatively.\n\t */\n\tcount?: number\n}\n\n/**\n * Interface for data clients that fetch doctype metadata and records.\n * Implemented by \\@stonecrop/graphql-client's StonecropClient.\n * Custom implementations can use any backend (REST, local storage, etc.).\n *\n * @typeParam T - Doctype reference type for record operations (defaults to DoctypeRef)\n * @typeParam M - Doctype metadata return type for getMeta (defaults to DoctypeMeta)\n * @public\n */\nexport interface DataClient<T extends DoctypeRef = DoctypeRef, M = DoctypeMeta> {\n\t/**\n\t * Fetch doctype metadata\n\t * @param context - Doctype context identifying the doctype\n\t * @returns Doctype metadata or null if not found\n\t */\n\tgetMeta(context: DoctypeContext): Promise<M | null>\n\n\t/**\n\t * Fetch a single record by ID\n\t *\n\t * When `includeNested` is set, builds a query with sub-selections for descendant\n\t * links and returns ancestor + merged descendants. When omitted, returns flat scalar data.\n\t *\n\t * @param doctype - Doctype reference (name and optional slug)\n\t * @param recordId - Record ID to fetch\n\t * @param options - Query options\n\t * @returns Record data wrapped in GetRecordResult\n\t */\n\tgetRecord(doctype: T, recordId: string, options?: GetRecordOptions): Promise<GetRecordResult>\n\n\t/**\n\t * Fetch a page of records\n\t * @param doctype - Doctype reference (name and optional slug)\n\t * @param options - Query options\n\t * @returns The page, plus whether more exist and (on request) the total\n\t */\n\tgetRecords(doctype: T, options?: GetRecordsOptions): Promise<GetRecordsResult>\n\n\t/**\n\t * Execute a doctype action (e.g., SUBMIT, APPROVE, save).\n\t * All state changes flow through this single mutation endpoint.\n\t *\n\t * @param doctype - Doctype reference (name and optional slug)\n\t * @param action - Action name to execute (e.g., 'SUBMIT', 'APPROVE', 'save')\n\t * @param args - Action arguments (typically record ID and/or form data)\n\t * @returns Action result with success status, response data, and any error\n\t */\n\trunAction(\n\t\tdoctype: T,\n\t\taction: string,\n\t\targs?: unknown[]\n\t): Promise<{ success: boolean; data: unknown; error: string | null }>\n}\n","import { DoctypeFieldSchema } from './field'\nimport { DoctypeMeta } from './doctype'\n\n/**\n * Validation error with path information\n * @public\n */\nexport interface ValidationError {\n\t/** Path to the invalid property */\n\tpath: PropertyKey[]\n\n\t/** Error message */\n\tmessage: string\n}\n\n/**\n * Result of a validation operation\n * @public\n */\nexport interface ValidationResult {\n\t/** Whether validation passed */\n\tsuccess: boolean\n\n\t/** List of validation errors (empty if success) */\n\terrors: ValidationError[]\n}\n\n/**\n * Validate a field definition against the DoctypeField discriminated union\n * @param data - Data to validate\n * @returns Validation result\n * @public\n */\nexport function validateField(data: unknown): ValidationResult {\n\tconst result = DoctypeFieldSchema.safeParse(data)\n\n\tif (result.success) {\n\t\treturn { success: true, errors: [] }\n\t}\n\n\treturn {\n\t\tsuccess: false,\n\t\terrors: result.error.issues.map(issue => ({\n\t\t\tpath: issue.path,\n\t\t\tmessage: issue.message,\n\t\t})),\n\t}\n}\n\n/**\n * Validate a doctype definition\n * @param data - Data to validate\n * @returns Validation result\n * @public\n */\nexport function validateDoctype(data: unknown): ValidationResult {\n\tconst result = DoctypeMeta.safeParse(data)\n\n\tif (result.success) {\n\t\treturn { success: true, errors: [] }\n\t}\n\n\treturn {\n\t\tsuccess: false,\n\t\terrors: result.error.issues.map(issue => ({\n\t\t\tpath: issue.path,\n\t\t\tmessage: issue.message,\n\t\t})),\n\t}\n}\n\n/**\n * Parse and validate a field, throwing on failure\n * @param data - Data to parse\n * @returns Validated DoctypeField\n * @throws ZodError if validation fails\n * @public\n */\nexport function parseField(data: unknown): import('./field').DoctypeField {\n\treturn DoctypeFieldSchema.parse(data)\n}\n\n/**\n * Parse and validate a doctype, throwing on failure\n * @param data - Data to parse\n * @returns Validated DoctypeMeta\n * @throws ZodError if validation fails\n * @public\n */\nexport function parseDoctype(data: unknown): DoctypeMeta {\n\treturn DoctypeMeta.parse(data)\n}\n\n// Re-export types for convenience\nexport type { DoctypeField, ValueField, FieldsetField, TableField } from './field'\nexport type { DoctypeMeta } from './doctype'\n"],"names":["snakeToCamel","snakeCase","_","letter","camelToSnake","camelCase","snakeToLabel","word","camelToLabel","withSpaces","toPascalCase","tableName","toSlug","name","pascalToSnake","pascal","GQL_SCALAR_MAP","WELL_KNOWN_SCALARS","INTERNAL_SCALARS","buildScalarMap","customScalars","merged","key","value","SYNTHETIC_SUFFIXES","ROOT_TYPE_NAMES","defaultIsEntityType","typeName","type","suffix","fields","SKIP_FIELDS","defaultIsEntityField","fieldName","_field","_parentType","unwrapType","required","isList","current","isNonNullType","isListType","isNamedType","getConnectionNodeType","edgesField","edgesType","edgesIsList","isObjectType","nodeField","nodeType","classifyFieldType","field","entityTypes","options","namedType","scalarMap","base","isScalarType","candidateTypeName","template","isEnumType","v","connectionNodeTypeName","TableViewConfig","z","FieldOptions","FieldValidation","injectKind","data","obj","normalizeFieldKind","injected","INTROSPECTED_IDENTITY_PROPS","getPrimaryKeyField","f","flattenFields","result","getDisplayField","displayField","getRecordIdField","getRecordIdentity","record","pkField","candidates","createDoctypeFieldSchemas","ValueFieldSchema","TableFieldSchema","DoctypeFieldSchema","FieldsetFieldSchema","rawUnion","schemas","flattenAuthored","out","isRecord","describe","mergeIntrospectedDoctype","authored","generated","authoredFields","generatedByName","generatedLinkNames","drift","tag","match","prop","authoredValue","schemaValue","authoredNames","n","authoredPk","generatedPk","formatDoctypeDrift","lines","bucket","label","entries","convertGraphQLSchema","source","schema","buildGraphQLSchema","typeMap","rootTypeNames","queryType","mutationType","subscriptionType","isEntityType","filteredEntityTypes","includeSet","t","excludeSet","isEntityField","doctypes","isUnnormalizedPostGraphile","allClassifiedFields","custom","primaryKeyFieldname","links","convertedFields","identity","_graphqlType","_unmapped","_isLink","clean","rest","doctypeName","doctype","buildSchema","buildClientSchema","Cardinality","SyncFetch","LazyFetch","CustomFetch","FetchStrategy","LinkDeclaration","ActionDefinition","TriggerDefinition","isActionAllowedInState","action","currentState","allowedStates","WorkflowLayout","WorkflowMeta","DoctypeMeta","ctx","declared","named","LINK_DISPLAY_SUFFIX","linkDisplayFieldname","fieldname","validateField","issue","validateDoctype","parseField","parseDoctype"],"mappings":";;AAiBO,SAASA,GAAaC,GAA2B;AACvD,SAAOA,EAAU,QAAQ,aAAa,CAACC,GAAWC,MAAmBA,EAAO,aAAa;AAC1F;AAaO,SAASC,GAAaC,GAA2B;AACvD,SAAOA,EAAU,QAAQ,UAAU,CAAAF,MAAU,IAAIA,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,EACd;AAAA,EAAA;AAEJ;AASO,SAASE,GAAWxG,GAA+C;AACzE,SAAOmB,EAAmB,MAAMnB,CAAI;AACrC;AASO,SAASyG,GAAazG,GAA4B;AACxD,SAAO8F,EAAY,MAAM9F,CAAI;AAC9B;"}
|
|
1
|
+
{"version":3,"file":"validation-1DGAGmuU.js","sources":["../src/naming.ts","../src/converter/scalars.ts","../src/converter/heuristics.ts","../src/table.ts","../src/field.ts","../src/converter/merge.ts","../src/converter/index.ts","../src/doctype.ts","../src/validation.ts"],"sourcesContent":["/**\n * Naming Convention Utilities\n * Converts between various naming conventions (snake_case, camelCase, PascalCase, kebab-case)\n * @packageDocumentation\n */\n\n/**\n * Converts snake_case to camelCase\n * @param snakeCase - Snake case string\n * @returns Camel case string\n * @public\n * @example\n * ```typescript\n * snakeToCamel('user_email') // 'userEmail'\n * snakeToCamel('created_at') // 'createdAt'\n * ```\n */\nexport function snakeToCamel(snakeCase: string): string {\n\treturn snakeCase.replace(/_([a-z])/g, (_: string, letter: string) => letter.toUpperCase())\n}\n\n/**\n * Converts camelCase to snake_case\n * @param camelCase - Camel case string\n * @returns Snake case string\n * @public\n * @example\n * ```typescript\n * camelToSnake('userEmail') // 'user_email'\n * camelToSnake('createdAt') // 'created_at'\n * ```\n */\nexport function camelToSnake(camelCase: string): string {\n\treturn camelCase.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)\n}\n\n/**\n * Converts snake_case to Title Case label\n * @param snakeCase - Snake case string\n * @returns Title case label\n * @public\n * @example\n * ```typescript\n * snakeToLabel('user_email') // 'User Email'\n * snakeToLabel('first_name') // 'First Name'\n * ```\n */\nexport function snakeToLabel(snakeCase: string): string {\n\treturn snakeCase\n\t\t.split('_')\n\t\t.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n\t\t.join(' ')\n}\n\n/**\n * Converts camelCase to Title Case label\n * @param camelCase - Camel case string\n * @returns Title case label\n * @public\n * @example\n * ```typescript\n * camelToLabel('userEmail') // 'User Email'\n * camelToLabel('firstName') // 'First Name'\n * ```\n */\nexport function camelToLabel(camelCase: string): string {\n\tconst withSpaces = camelCase.replace(/([A-Z])/g, ' $1').trim()\n\treturn withSpaces.charAt(0).toUpperCase() + withSpaces.slice(1)\n}\n\n/**\n * Convert table name to PascalCase doctype name\n * @param tableName - SQL table name (snake_case)\n * @returns PascalCase name\n * @public\n */\nexport function toPascalCase(tableName: string): string {\n\treturn tableName\n\t\t.split(/[-_\\s]+/)\n\t\t.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n\t\t.join('')\n}\n\n/**\n * Convert to kebab-case slug\n * @param name - Name to convert\n * @returns kebab-case slug\n * @public\n */\nexport function toSlug(name: string): string {\n\treturn name\n\t\t.replace(/([a-z])([A-Z])/g, '$1-$2')\n\t\t.replace(/[\\s_]+/g, '-')\n\t\t.toLowerCase()\n}\n\n/**\n * Convert PascalCase to snake_case (e.g., for deriving table names from type names)\n * @param pascal - PascalCase string\n * @returns snake_case string\n * @public\n * @example\n * ```typescript\n * pascalToSnake('SalesOrder') // 'sales_order'\n * pascalToSnake('SalesOrderItem') // 'sales_order_item'\n * ```\n */\nexport function pascalToSnake(pascal: string): string {\n\treturn pascal\n\t\t.replace(/([a-z])([A-Z])/g, '$1_$2')\n\t\t.replace(/[\\s-]+/g, '_')\n\t\t.toLowerCase()\n}\n","/**\n * GraphQL Scalar Type Mappings\n *\n * Maps standard GraphQL scalars and well-known custom scalars to Stonecrop field types.\n * Source-agnostic — covers scalars commonly emitted by PostGraphile, Hasura, Apollo, etc.\n *\n * Users can extend these via the `customScalars` option in `GraphQLConversionOptions`.\n *\n * @packageDocumentation\n */\n\nimport type { FieldTemplate } from './types'\n\n/**\n * Mapping from standard GraphQL scalar types to Stonecrop field types.\n * These are defined by the GraphQL specification and are always available.\n *\n * @public\n */\nexport const GQL_SCALAR_MAP: Record<string, FieldTemplate> = {\n\tString: { component: 'ATextInput' },\n\tInt: { component: 'ANumericInput' },\n\tFloat: { component: 'ANumericInput' },\n\tBoolean: { component: 'ACheckbox' },\n\tID: { component: 'ATextInput' },\n}\n\n/**\n * Mapping from well-known custom GraphQL scalars to Stonecrop field types.\n * These cover scalars commonly used across GraphQL servers (PostGraphile, Hasura, etc.)\n * without baking in knowledge of any specific server.\n *\n * Entries here have lower precedence than `customScalars` from options, but higher\n * precedence than unknown/unmapped scalars.\n *\n * @public\n */\nexport const WELL_KNOWN_SCALARS: Record<string, FieldTemplate> = {\n\t// Arbitrary precision / large numbers — all numeric variants render with ANumericInput.\n\tBigFloat: { component: 'ANumericInput' },\n\tBigDecimal: { component: 'ANumericInput' },\n\tDecimal: { component: 'ANumericInput' },\n\tBigInt: { component: 'ANumericInput' },\n\tLong: { component: 'ANumericInput' },\n\n\t// Identifiers\n\tUUID: { component: 'ATextInput' },\n\n\t// Date / Time — no dedicated Time SFC exists; Time falls back to a plain text input.\n\tDateTime: { component: 'ADateTime' },\n\tDatetime: { component: 'ADateTime' },\n\tDate: { component: 'ADate' },\n\tTime: { component: 'ATextInput' },\n\tInterval: { component: 'ADuration' },\n\tDuration: { component: 'ADuration' },\n\n\t// Structured data\n\tJSON: { component: 'ACodeEditor' },\n\tJSONObject: { component: 'ACodeEditor' },\n\tJsonNode: { component: 'ACodeEditor' },\n}\n\n/**\n * Set of scalar type names that are internal to GraphQL servers and should be skipped\n * during field conversion (they don't represent meaningful data fields).\n *\n * @public\n */\nexport const INTERNAL_SCALARS = new Set(['Cursor'])\n\n/**\n * Build a merged scalar map from the built-in maps and user-provided custom scalars.\n * Precedence (highest to lowest): customScalars → GQL_SCALAR_MAP → WELL_KNOWN_SCALARS\n *\n * @param customScalars - User-provided scalar overrides\n * @returns Merged scalar map\n * @public\n */\nexport function buildScalarMap(customScalars?: Record<string, Partial<FieldTemplate>>): Record<string, FieldTemplate> {\n\tconst merged: Record<string, FieldTemplate> = { ...WELL_KNOWN_SCALARS }\n\n\t// Standard scalars override well-known\n\tfor (const [key, value] of Object.entries(GQL_SCALAR_MAP)) {\n\t\tmerged[key] = value\n\t}\n\n\t// Custom scalars override everything\n\tif (customScalars) {\n\t\tfor (const [key, value] of Object.entries(customScalars)) {\n\t\t\tmerged[key] = { component: value.component ?? 'ATextInput' }\n\t\t}\n\t}\n\n\treturn merged\n}\n","/**\n * Default heuristics for identifying entity types and fields in a GraphQL schema.\n *\n * These heuristics work across common GraphQL servers (PostGraphile, Hasura, Apollo, etc.)\n * by detecting widely-adopted conventions like the Relay connection pattern.\n *\n * All heuristics can be overridden via the `isEntityType`, `isEntityField`, and\n * `classifyField` options in `GraphQLConversionOptions`.\n *\n * @packageDocumentation\n */\n\nimport {\n\tisScalarType,\n\tisEnumType,\n\tisObjectType,\n\tisListType,\n\tisNonNullType,\n\tisNamedType,\n\ttype GraphQLObjectType,\n\ttype GraphQLField,\n\ttype GraphQLOutputType,\n\ttype GraphQLNamedType,\n} from 'graphql'\n\nimport type { FieldTemplate } from './types'\nimport type { GraphQLConversionFieldMeta, GraphQLConversionOptions } from './types'\nimport { buildScalarMap, INTERNAL_SCALARS } from './scalars'\nimport { toSlug, camelToLabel, toPascalCase } from '../naming'\n\n/**\n * Suffixes that identify synthetic/framework types generated by GraphQL servers.\n * Types ending with these suffixes are typically not entities.\n */\nconst SYNTHETIC_SUFFIXES = [\n\t'Connection',\n\t'Edge',\n\t'Input',\n\t'Patch',\n\t'Payload',\n\t'Condition',\n\t'Filter',\n\t'OrderBy',\n\t'Aggregate',\n\t'AggregateResult',\n\t'AggregateFilter',\n\t'DeleteResponse',\n\t'InsertResponse',\n\t'UpdateResponse',\n\t'MutationResponse',\n]\n\n/**\n * Root operation type names that are never entities.\n */\nconst ROOT_TYPE_NAMES = new Set(['Query', 'Mutation', 'Subscription'])\n\n/**\n * Default heuristic to determine if a GraphQL object type represents an entity.\n * An entity type becomes a Stonecrop doctype.\n *\n * This heuristic excludes:\n * - Introspection types (`__*`)\n * - Root operation types (`Query`, `Mutation`, `Subscription`)\n * - Types with synthetic suffixes (e.g., `*Connection`, `*Edge`, `*Input`)\n * - Types starting with `Node` interface marker (exact match only)\n *\n * @param typeName - The GraphQL type name\n * @param type - The GraphQL object type definition\n * @returns `true` if this type should become a Stonecrop doctype\n * @public\n */\nexport function defaultIsEntityType(typeName: string, type: GraphQLObjectType): boolean {\n\t// Exclude introspection types\n\tif (typeName.startsWith('__')) {\n\t\treturn false\n\t}\n\n\t// Exclude root operation types\n\tif (ROOT_TYPE_NAMES.has(typeName)) {\n\t\treturn false\n\t}\n\n\t// Exclude the Node interface marker type\n\tif (typeName === 'Node') {\n\t\treturn false\n\t}\n\n\t// Exclude types matching synthetic suffixes\n\tfor (const suffix of SYNTHETIC_SUFFIXES) {\n\t\tif (typeName.endsWith(suffix)) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Must have at least one field\n\tconst fields = type.getFields()\n\tif (Object.keys(fields).length === 0) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n/**\n * Fields to skip by default on entity types.\n * These are internal to GraphQL servers and don't represent semantic data.\n */\nconst SKIP_FIELDS = new Set(['nodeId', '__typename', 'clientMutationId'])\n\n/**\n * Default heuristic to filter fields on entity types.\n * Skips internal fields that don't represent meaningful data.\n *\n * @param fieldName - The GraphQL field name\n * @param _field - The GraphQL field definition (unused in default implementation)\n * @param _parentType - The parent entity type (unused in default implementation)\n * @returns `true` if this field should be included\n * @public\n */\nexport function defaultIsEntityField(\n\tfieldName: string,\n\t_field: GraphQLField<unknown, unknown>,\n\t_parentType: GraphQLObjectType\n): boolean {\n\treturn !SKIP_FIELDS.has(fieldName)\n}\n\n/**\n * Unwrap NonNull and List wrappers from a GraphQL type, tracking nullability.\n *\n * @param type - The GraphQL output type\n * @returns The unwrapped named type, whether it's required, and whether it's a list\n * @internal\n */\nfunction unwrapType(type: GraphQLOutputType): {\n\tnamedType: GraphQLNamedType\n\trequired: boolean\n\tisList: boolean\n} {\n\tlet required = false\n\tlet isList = false\n\tlet current: GraphQLOutputType = type\n\n\t// Unwrap outer NonNull\n\tif (isNonNullType(current)) {\n\t\trequired = true\n\t\tcurrent = current.ofType\n\t}\n\n\t// Unwrap List\n\tif (isListType(current)) {\n\t\tisList = true\n\t\tcurrent = current.ofType\n\n\t\t// Unwrap inner NonNull (e.g., [Type!])\n\t\tif (isNonNullType(current)) {\n\t\t\tcurrent = current.ofType\n\t\t}\n\t}\n\n\t// At this point, current should be a named type (scalar, enum, or object)\n\tif (!isNamedType(current)) {\n\t\tthrow new Error(`Expected a named GraphQL type, got: ${String(current)}`)\n\t}\n\treturn { namedType: current, required, isList }\n}\n\n/**\n * Check if a GraphQL object type looks like a Relay Connection type.\n * A connection type has an `edges` field returning a list of edge types,\n * where each edge has a `node` field.\n *\n * @param type - The GraphQL object type to check\n * @returns The node type name if this is a connection, or `undefined`\n * @internal\n */\nfunction getConnectionNodeType(type: GraphQLObjectType): string | undefined {\n\tconst fields = type.getFields()\n\n\t// Must have an 'edges' field\n\tconst edgesField = fields['edges']\n\tif (!edgesField) return undefined\n\n\t// edges must be a list\n\tconst { namedType: edgesType, isList: edgesIsList } = unwrapType(edgesField.type)\n\tif (!edgesIsList || !isObjectType(edgesType)) return undefined\n\n\t// Each edge must have a 'node' field\n\tconst edgeFields = edgesType.getFields()\n\tconst nodeField = edgeFields['node']\n\tif (!nodeField) return undefined\n\n\tconst { namedType: nodeType } = unwrapType(nodeField.type)\n\tif (!isObjectType(nodeType)) return undefined\n\n\treturn nodeType.name\n}\n\n/**\n * Classify a single GraphQL field into a Stonecrop field definition.\n *\n * Classification rules (in order):\n * 1. Scalar types → look up in merged scalar map\n * 2. Enum types → `Select` with enum values as options\n * 3. Object types that are entities → `Link` with slug as options\n * 4. Object types that are Connections → `Doctype` with node type slug as options\n * 5. List of entity type → `Doctype` with item type slug as options\n * 6. Anything else → `Data` with `_unmapped: true`\n *\n * @param fieldName - The GraphQL field name\n * @param field - The GraphQL field definition\n * @param entityTypes - Set of type names classified as entities\n * @param options - Conversion options (for custom scalars, unmapped meta, etc.)\n * @returns The Stonecrop field definition\n * @public\n */\nexport function classifyFieldType(\n\tfieldName: string,\n\tfield: GraphQLField<unknown, unknown>,\n\tentityTypes: Set<string>,\n\toptions: GraphQLConversionOptions = {}\n): GraphQLConversionFieldMeta {\n\tconst { namedType, required, isList } = unwrapType(field.type)\n\tconst scalarMap = buildScalarMap(options.customScalars)\n\n\tconst base: GraphQLConversionFieldMeta = {\n\t\tkind: 'field',\n\t\tfieldname: fieldName,\n\t\tlabel: camelToLabel(fieldName),\n\t\tcomponent: 'ATextInput',\n\t}\n\n\tif (required) {\n\t\tbase.required = true\n\t}\n\n\t// 1. Scalar types\n\tif (isScalarType(namedType)) {\n\t\t// Skip internal scalars (e.g., Cursor)\n\t\tif (INTERNAL_SCALARS.has(namedType.name)) {\n\t\t\tbase._unmapped = true\n\t\t\tif (options.includeUnmappedMeta) {\n\t\t\t\tbase._graphqlType = namedType.name\n\t\t\t}\n\t\t\treturn base\n\t\t}\n\n\t\t// Special case: ID fields that reference an entity type → Link\n\t\tif (namedType.name === 'ID') {\n\t\t\tconst candidateTypeName = toPascalCase(fieldName)\n\t\t\tif (entityTypes.has(candidateTypeName)) {\n\t\t\t\tbase.component = 'AFormLink'\n\t\t\t\tbase.doctype = toSlug(candidateTypeName)\n\t\t\t\treturn base\n\t\t\t}\n\t\t}\n\n\t\tconst template: FieldTemplate | undefined = scalarMap[namedType.name]\n\t\tif (template) {\n\t\t\tbase.component = template.component\n\t\t} else {\n\t\t\t// Unknown scalar — default to Data with unmapped marker\n\t\t\tbase._unmapped = true\n\t\t\tif (options.includeUnmappedMeta) {\n\t\t\t\tbase._graphqlType = namedType.name\n\t\t\t}\n\t\t}\n\t\treturn base\n\t}\n\n\t// 2. Enum types → Select\n\tif (isEnumType(namedType)) {\n\t\tbase.component = 'ADropdown'\n\t\tbase.options = namedType.getValues().map(v => v.name)\n\t\treturn base\n\t}\n\n\t// 3–5. Object types\n\tif (isObjectType(namedType)) {\n\t\t// 3. Direct reference to an entity type → Link\n\t\tif (!isList && entityTypes.has(namedType.name)) {\n\t\t\tbase.component = 'AFormLink'\n\t\t\tbase.doctype = toSlug(namedType.name)\n\t\t\treturn base\n\t\t}\n\n\t\t// 4. Connection type → link (child table)\n\t\tconst connectionNodeTypeName = getConnectionNodeType(namedType)\n\t\tif (connectionNodeTypeName && entityTypes.has(connectionNodeTypeName)) {\n\t\t\tbase.component = 'ATable'\n\t\t\tbase._isLink = true\n\t\t\tbase.doctype = toSlug(connectionNodeTypeName)\n\t\t\tbase.cardinality = 'noneOrMany'\n\t\t\treturn base\n\t\t}\n\n\t\t// 5. List of entity type → link\n\t\tif (isList && entityTypes.has(namedType.name)) {\n\t\t\tbase.component = 'ATable'\n\t\t\tbase._isLink = true\n\t\t\tbase.doctype = toSlug(namedType.name)\n\t\t\tbase.cardinality = 'noneOrMany'\n\t\t\treturn base\n\t\t}\n\n\t\t// Unknown object type — mark as unmapped\n\t\tbase._unmapped = true\n\t\tif (options.includeUnmappedMeta) {\n\t\t\tbase._graphqlType = namedType.name\n\t\t}\n\t\treturn base\n\t}\n\n\t// Fallback — shouldn't normally be reached\n\tbase._unmapped = true\n\tif (options.includeUnmappedMeta) {\n\t\tbase._graphqlType = namedType.name\n\t}\n\treturn base\n}\n","import { z } from 'zod'\n\n/**\n * JSON-safe view configuration for table fields in doctype authoring.\n *\n * This is the authoring-time subset of `@stonecrop/atable`'s `TableConfig`. It covers\n * the view discriminator and structural options that can be expressed in static JSON.\n * `rowActions` (which requires function-typed handlers) stays in the runtime `TableConfig`.\n *\n * @public\n */\nexport const TableViewConfig = z\n\t.object({\n\t\t/** The table view type */\n\t\tview: z.enum(['list', 'uncounted', 'list-expansion', 'tree', 'gantt', 'tree-gantt']).optional(),\n\n\t\t/** Allow the table to use the full width of its container */\n\t\tfullWidth: z.boolean().optional(),\n\n\t\t/** Default expansion state for tree views */\n\t\tdefaultTreeExpansion: z.enum(['root', 'branch', 'leaf']).optional(),\n\n\t\t/** Enable dependency graph connections for Gantt views */\n\t\tdependencyGraph: z.boolean().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'TableViewConfig',\n\t\tdescription: 'JSON-safe view configuration for table fields in doctype authoring',\n\t})\n\n/**\n * Table view configuration type inferred from Zod schema\n * @public\n */\nexport type TableViewConfig = z.infer<typeof TableViewConfig>\n","import { z } from 'zod'\n\nimport type { ColumnSchema } from './column-schema'\nimport type { InteractionMode } from './mode'\nimport { TableViewConfig } from './table'\n\n/**\n * Field options - flexible bag for type-specific configuration.\n *\n * Usage:\n * - Select: array of choices ([\"Draft\", \"Submitted\", \"Cancelled\"])\n * - Select with badges: \\{ choices: [...], badges: \\{ Open: \"warning\", ... \\} \\} or bare map\n * - Decimal: config object (\\{ precision: 10, scale: 2 \\})\n * - Code: config object (\\{ language: \"python\" \\})\n *\n * Deliberately *not* a bare string: a string once meant \"link target\", which made the value's\n * shape encode its meaning. That job belongs to `ValueField.doctype`, leaving this a plain\n * choices-or-config bag.\n *\n * @public\n */\nexport const FieldOptions = z\n\t.union([\n\t\tz.array(z.string()), // Select choices: [\"A\", \"B\", \"C\"]\n\t\tz.record(z.string(), z.unknown()), // Config: \\{ precision: 10, scale: 2 \\}\n\t])\n\t.meta({\n\t\ttitle: 'FieldOptions',\n\t\tdescription: 'Field options - flexible bag for type-specific configuration',\n\t})\n\n/**\n * Field options type inferred from Zod schema\n * @public\n */\nexport type FieldOptions = z.infer<typeof FieldOptions>\n\n/**\n * Validation configuration for form fields\n * @public\n */\nexport const FieldValidation = z\n\t.looseObject({\n\t\t/** Error message to display when validation fails */\n\t\terrorMessage: z.string(),\n\t})\n\t.meta({\n\t\ttitle: 'FieldValidation',\n\t\tdescription: 'Validation configuration for form fields',\n\t})\n\n/**\n * Field validation type inferred from Zod schema\n * @public\n */\nexport type FieldValidation = z.infer<typeof FieldValidation>\n\n// ---------------------------------------------------------------------------\n// DoctypeField — the discriminated union of authoring-time field variants\n// ---------------------------------------------------------------------------\n\n/**\n * A field that holds a scalar value, a link to another record, or a select choice.\n * The most common kind of field. `component` determines how it renders; the attributes below\n * carry everything else that is not a rendering concern.\n * @public\n */\nexport interface ValueField {\n\t/** Discriminator — identifies this as a value-holding field */\n\tkind: 'field'\n\t/** Unique identifier for this field within its doctype */\n\tfieldname: string\n\t/**\n\t * Vue component that renders this field — the primary (and only) rendering axis. Required:\n\t * there is nothing left to derive it from, and a field without one has nothing to render it.\n\t * Any string is valid; naming a custom component is how an app renders a field Stonecrop\n\t * ships no widget for. See `CANONICAL_COMPONENTS` for the set Stonecrop provides.\n\t */\n\tcomponent: string\n\t/** True for the field that identifies the record's primary-key column. */\n\tprimaryKey?: boolean\n\t/** True for a computed/display field with no backing DB column — excluded from SQL SELECT. */\n\tcomputed?: boolean\n\t/** Editor language for code fields (e.g. `'json'`, `'typescript'`) — the only thing distinguishing\n\t * a JSON editor from a code editor, since both render with `ACodeEditor`. */\n\tlanguage?: string\n\t/**\n\t * Target doctype slug. Presence is what makes a field a link.\n\t *\n\t * How it renders is decided by `component`, not by this: `AFormLink` renders an\n\t * inline id-picker, while `AForm`/`ATable` expand the target (see `linkRenderMode`). Expansion\n\t * metadata — backlink, fetch strategy, authoritative cardinality — lives in the doctype's\n\t * `links` map, which is additive and never required for a plain foreign key.\n\t */\n\tdoctype?: string\n\t/** Human-readable label */\n\tlabel?: string\n\t/** CSS width (e.g. `\"40ch\"`, `\"200px\"`) */\n\twidth?: string\n\t/** Text alignment */\n\talign?: 'left' | 'center' | 'right' | 'start' | 'end'\n\t/** Whether the field is editable in table cell context */\n\tedit?: boolean\n\t/** Input mask pattern or serialized function */\n\tmask?: string\n\t/** Serialized display formatter — distinct from `mask` (input). Spreads through\n\t * `schemaToColumns` to `ColumnSchema.format`; deserialized at render time by ATable's\n\t * `getFormattedValue`. Returns a plain string, HTML, or a {@link BadgeDescriptor} for badge\n\t * cells. When a descriptor is returned it wins over any badge map on `options`. */\n\tformat?: string\n\t/** Per-field interaction mode override */\n\tmode?: InteractionMode\n\t/** Type-specific options: Select choices, Decimal precision config, etc. A link's target is not\n\t * here — it is `doctype`. */\n\toptions?: FieldOptions\n\t/** Whether the field is required */\n\trequired?: boolean\n\t/** Whether the field is read-only */\n\treadOnly?: boolean\n\t/** Whether the field is hidden from the UI */\n\thidden?: boolean\n\t/** Default value for new records */\n\tdefault?: unknown\n\t/** Validation configuration */\n\tvalidation?: FieldValidation\n\t/** Cardinality for Link fields — authoritative value on LinkDeclaration takes precedence */\n\tcardinality?: 'atMostOne' | 'one' | 'noneOrMany' | 'atLeastOne'\n\t/**\n\t * Provenance marker — stamped only by the GraphQL converter; absence means hand-authored.\n\t * When present, the docbuilder freezes the field's identity set (`fieldname`, `primaryKey`,\n\t * `required`, `options`, `cardinality`, `doctype`), since `fieldname` is the GraphQL/column\n\t * binding and `doctype` is the FK's target. `component` is deliberately **not** frozen: it\n\t * chooses the widget, which is an authoring decision the database has no opinion about.\n\t */\n\tsource?: 'introspected'\n}\n\n/**\n * A layout container that groups other fields. Resolves to a nested AForm.\n * @public\n */\nexport interface FieldsetField {\n\t/** Discriminator — identifies this as a fieldset container */\n\tkind: 'fieldset'\n\t/** Unique identifier for this fieldset within its doctype */\n\tfieldname: string\n\t/** Vue component to render this fieldset. Defaults to `'AFieldset'` in resolveSchema. */\n\tcomponent?: string\n\t/** Human-readable label for the fieldset legend */\n\tlabel?: string\n\t/** Whether the fieldset can be collapsed */\n\tcollapsible?: boolean\n\t/** Interaction mode for all children inside this fieldset */\n\tmode?: InteractionMode\n\t/** Nested field definitions — resolved recursively by resolveSchema */\n\tschema: DoctypeField[]\n}\n\n/**\n * An inline table whose columns are defined directly in the schema (no linked doctype).\n * Use when the table data does not warrant a separate doctype.\n * @public\n */\nexport interface TableField {\n\t/** Discriminator — identifies this as an inline table */\n\tkind: 'table'\n\t/** Unique identifier for this table within its doctype */\n\tfieldname: string\n\t/** Vue component to render this table. Defaults to `'ATable'` in resolveSchema. */\n\tcomponent?: string\n\t/** Human-readable label */\n\tlabel?: string\n\t/** Column definitions — use ColumnSchema (fieldname key) from \\@stonecrop/schema */\n\tcolumns: ColumnSchema[]\n\t/** View configuration — defaults to `{ view: 'list' }` in resolveSchema when absent */\n\tconfig?: TableViewConfig\n\t/** Interaction mode for all cells inside this table */\n\tmode?: InteractionMode\n}\n\n/**\n * Union of all authoring-time field variants.\n * Use `kind` to discriminate: `'field'` | `'fieldset'` | `'table'`.\n * @public\n */\nexport type DoctypeField = ValueField | FieldsetField | TableField\n\n// ---------------------------------------------------------------------------\n// Zod runtime validation schemas\n// ---------------------------------------------------------------------------\n\n/**\n * Infers the `kind` discriminant from the structural properties of a raw field\n * object, then injects it if absent. This allows authored JSON to omit `kind`\n * entirely — a `schema` key means fieldset, `columns` means table, anything else\n * is a value field.\n *\n * Rules (applied in order):\n * has `schema` → fieldset\n * has `columns` → table\n * otherwise → field (value-holding scalar or link)\n *\n * Objects that already carry `kind` pass through unchanged (backward-compatible).\n *\n * Single-node only. Zod applies this at every level of the discriminated union (via the\n * `z.lazy` in the fieldset schema), so nested fieldset children are normalized during a\n * parse. Callers that bypass Zod — notably `Doctype.fromObject` — must use the exported\n * {@link normalizeFieldKind} instead, which replicates that recursion.\n */\nfunction injectKind(data: unknown): unknown {\n\tif (typeof data !== 'object' || data === null || Array.isArray(data)) return data\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- safe: non-null, non-array object verified by guards above\n\tconst obj = data as Record<string, unknown>\n\tif ('kind' in obj) return data\n\tif ('schema' in obj) return { kind: 'fieldset', ...obj }\n\tif ('columns' in obj) return { kind: 'table', ...obj }\n\treturn { kind: 'field', ...obj }\n}\n\n/**\n * Recursively injects the `kind` discriminant into a raw field object and, for fieldsets,\n * into each of its nested `schema` children — mirroring exactly what Zod's `preprocess`\n * does at every level of the discriminated union.\n *\n * Table `columns` are {@link ColumnSchema} entries, not `DoctypeField`s, so they are left\n * untouched — the Zod table schema validates them with a plain passthrough and never injects\n * `kind` there either.\n *\n * Needed because `Doctype.fromObject` constructs a Doctype without running Zod, yet the\n * registry's `resolveFields` gates link and fieldset handling on `field.kind`. Without this,\n * a JSON-authored link resolves to a flat scalar and a fieldset's children are dropped.\n *\n * @public\n */\nexport function normalizeFieldKind(field: unknown): unknown {\n\tconst injected = injectKind(field)\n\tif (typeof injected !== 'object' || injected === null) return injected\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- injectKind returns a non-null object for object input; guarded above\n\tconst obj = injected as Record<string, unknown>\n\tif (obj.kind === 'fieldset' && Array.isArray(obj.schema)) {\n\t\treturn { ...obj, schema: obj.schema.map(normalizeFieldKind) }\n\t}\n\treturn injected\n}\n\n/**\n * The field properties a `source: 'introspected'` marker freezes — the ones the database owns.\n *\n * This is the single definition of the identity set. The docbuilder greys these inputs on an\n * introspected field, and the converter's merge refuses to rewrite them. Stating it twice is how\n * the two drift, so both read this constant.\n *\n * Everything absent from this list is author-owned, `component` most importantly: it chooses the\n * widget, which is an authoring decision the database has no opinion about.\n *\n * @public\n */\nexport const INTROSPECTED_IDENTITY_PROPS = [\n\t'fieldname',\n\t'primaryKey',\n\t'required',\n\t'options',\n\t'cardinality',\n\t'doctype',\n] as const\n\n/**\n * Find the field a doctype marks as its primary key, or `undefined` when none is marked.\n *\n * This is the single definition of \"which field identifies a record\". Both sides depend on it:\n * the middleware builds the SQL identity predicate from it, and the client resolves a record's\n * route/store key from it. Call this; never re-derive the rule at the call site, or the two will\n * drift and the client will key records by a column the server never queried.\n *\n * Two deliberate limits, both matching the shape `primaryKey` actually has:\n * - Only **top-level** fields are scanned. `primaryKey` is a `ValueField` flag and a fieldset's\n * children are not identity columns, so a nested match would be an authoring error, not a PK.\n * - The **first** match wins. Identity is single-valued by design — a doctype describes the API\n * surface, and mapping a composite database key onto one identity there is the adapter's job —\n * so a doctype declaring several is malformed rather than composite. `DoctypeMeta` rejects that\n * at the load gate; this stays total for callers holding fields that never went through it.\n *\n * @param fields - the doctype's top-level fields\n * @returns the primary-key field, or `undefined` for a PK-less doctype\n * @public\n */\nexport function getPrimaryKeyField(fields: readonly DoctypeField[]): ValueField | undefined {\n\treturn fields.find((f): f is ValueField => f.kind === 'field' && Boolean(f.primaryKey))\n}\n\n/**\n * Recursively flatten Fieldset containers into a flat array of non-container fields.\n * Fieldset entries are replaced by their children; all other fields pass through.\n *\n * A fieldset is a layout grouping, not a scope: every field inside one is a field of the doctype,\n * with a column of its own and a name a link can bind to. Anything asking \"what does this doctype\n * declare\" must therefore descend, and the two ways to get that wrong point opposite ways — the\n * SELECT builder would omit real columns, while a validator would report a working declaration as\n * broken.\n *\n * Lives here rather than in the adapter because both sides need it: the middleware builds SQL from\n * it, and `DoctypeMeta`'s own validation asks the same question at the load gate. It sat in the\n * adapter while the validator hand-rolled a top-level-only scan, and that is exactly the second\n * failure this comment names — a `displayField` inside a fieldset was rejected at authoring time\n * and would have worked at runtime.\n *\n * @param fields - the doctype's top-level fields\n * @returns every non-container field, fieldset children included\n * @public\n */\nexport function flattenFields(fields: readonly DoctypeField[]): (ValueField | TableField)[] {\n\tconst result: (ValueField | TableField)[] = []\n\tfor (const f of fields) {\n\t\tif (f.kind === 'fieldset') {\n\t\t\tresult.push(...flattenFields(f.schema))\n\t\t} else {\n\t\t\tresult.push(f)\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Resolve the field a doctype nominates as its display text, or `undefined` when the nomination\n * does not name a readable column.\n *\n * This is the single definition of \"is this a usable `displayField`\". Both sides depend on it:\n * `DoctypeMeta` refuses a bad nomination at the load gate, and the adapter builds a SELECT from\n * the field it returns. Call this; never re-derive the rule, or the gate and the query will\n * disagree about which nominations are legal — which they did, in both directions at once.\n *\n * Two things disqualify a nomination, and both are the doctype saying so itself:\n * - it names no field at all, fieldset children included\n * - it names a `computed` field, which is declared precisely to state it has no column, so a\n * SELECT built from it would reference a column the database does not have\n *\n * @param fields - the doctype's top-level fields\n * @param displayField - the nominated fieldname\n * @returns the nominated field, or `undefined` when it is not a readable column\n * @public\n */\nexport function getDisplayField(\n\tfields: readonly DoctypeField[],\n\tdisplayField: string | undefined\n): ValueField | undefined {\n\tif (!displayField) return undefined\n\treturn flattenFields(fields).find(\n\t\t(f): f is ValueField => f.kind === 'field' && !f.computed && f.fieldname === displayField\n\t)\n}\n\n/**\n * The name of the field a record is identified by: the declared `primaryKey`, or `id` when the\n * doctype declares none.\n *\n * The `id` fallback is load-bearing, not defensive — a surrogate-key doctype carries an `id`\n * column and marks no primary key, so \"nothing declared\" means `id`, not \"no identity\".\n *\n * This exists because that one-line rule had been restated at four sites — the client's\n * `Doctype.recordIdField`, both nuxt hosts' `recordLookupField`, and the Postgres adapter — and\n * the fourth had omitted the fallback, so a doctype the client keyed by `id` was one the adapter\n * could not look up at all. Call this; a fifth restatement is how they diverge again.\n *\n * The returned name is not guaranteed to be a declared field: a doctype that declares no\n * `primaryKey` and no `id` yields `'id'` regardless. An adapter that must build a SQL predicate\n * from it has to confirm the field exists and say so when it does not, because selecting a column\n * the doctype never declared returns nothing rather than failing.\n *\n * @param fields - the doctype's top-level fields\n * @returns the identifying fieldname\n * @public\n */\nexport function getRecordIdField(fields: readonly DoctypeField[]): string {\n\treturn getPrimaryKeyField(fields)?.fieldname ?? 'id'\n}\n\n/**\n * Resolve a record's identity value using the doctype's declared primary key.\n *\n * Falls back to `record.id` when the doctype declares no `primaryKey`. That fallback is\n * load-bearing, not defensive: surrogate-key doctypes carry an `id` column and never mark a\n * primary key, and PostGraphile renames a single-column `id` PK to `rowId` — so the declared\n * field and `id` are both real sources, in that order.\n *\n * @param fields - the doctype's top-level fields\n * @param record - the record to read the identity from\n * @returns the identity as a string, or `undefined` when neither source yields a usable value\n * @public\n */\nexport function getRecordIdentity(\n\tfields: readonly DoctypeField[],\n\trecord: Record<string, unknown>\n): string | undefined {\n\tconst pkField = getPrimaryKeyField(fields)\n\tconst candidates = pkField ? [record[pkField.fieldname], record.id] : [record.id]\n\n\tfor (const value of candidates) {\n\t\t// Numbers are valid keys (a serial PK); 0 is a legitimate id, so test the type, not truthiness.\n\t\tif (typeof value === 'number') return String(value)\n\t\tif (typeof value === 'string' && value !== '') return value\n\t}\n\treturn undefined\n}\n\nfunction createDoctypeFieldSchemas() {\n\tconst ValueFieldSchema = z\n\t\t.object({\n\t\t\tkind: z.literal('field'),\n\t\t\tfieldname: z.string().min(1),\n\t\t\tcomponent: z.string().min(1),\n\t\t\tprimaryKey: z.boolean().optional(),\n\t\t\tcomputed: z.boolean().optional(),\n\t\t\tlanguage: z.string().optional(),\n\t\t\tdoctype: z.string().min(1).optional(),\n\t\t\tlabel: z.string().optional(),\n\t\t\twidth: z.string().optional(),\n\t\t\talign: z.enum(['left', 'center', 'right', 'start', 'end']).optional(),\n\t\t\tedit: z.boolean().optional(),\n\t\t\tmask: z.string().optional(),\n\t\t\tformat: z.string().optional(),\n\t\t\tmode: z.enum(['edit', 'read', 'display']).optional(),\n\t\t\toptions: FieldOptions.optional(),\n\t\t\trequired: z.boolean().optional(),\n\t\t\treadOnly: z.boolean().optional(),\n\t\t\thidden: z.boolean().optional(),\n\t\t\tdefault: z.unknown().optional(),\n\t\t\tvalidation: FieldValidation.optional(),\n\t\t\tcardinality: z.enum(['atMostOne', 'one', 'noneOrMany', 'atLeastOne']).optional(),\n\t\t\tsource: z.literal('introspected').optional(),\n\t\t})\n\t\t.meta({ title: 'ValueField' })\n\n\tconst TableFieldSchema = z\n\t\t.object({\n\t\t\tkind: z.literal('table'),\n\t\t\tfieldname: z.string().min(1),\n\t\t\tcomponent: z.string().optional(),\n\t\t\tlabel: z.string().optional(),\n\t\t\t// Validates that each column has fieldname; allows all other ColumnSchema properties\n\t\t\tcolumns: z.array(z.object({ fieldname: z.string().min(1) }).passthrough()),\n\t\t\tconfig: TableViewConfig.optional(),\n\t\t\tmode: z.enum(['edit', 'read', 'display']).optional(),\n\t\t})\n\t\t.meta({ title: 'TableField' })\n\n\t// DoctypeFieldSchema must be declared before FieldsetFieldSchema so the z.lazy\n\t// callback can close over it. The placeholder is overwritten below; the callback\n\t// only runs at parse time, after the real discriminated union is assigned.\n\t// See: https://zod.dev/api?id=discriminated-unions#discriminated-unions\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- required by Zod's recursive schema pattern; z.never() placeholder is overwritten before any parse call\n\tlet DoctypeFieldSchema: z.ZodType<DoctypeField> = z.never() as unknown as z.ZodType<DoctypeField>\n\n\t// FieldsetFieldSchema stays as a plain ZodObject (not z.ZodType<T>) so that\n\t// z.discriminatedUnion can inspect its 'kind' discriminant property.\n\tconst FieldsetFieldSchema = z\n\t\t.object({\n\t\t\tkind: z.literal('fieldset'),\n\t\t\tfieldname: z.string().min(1),\n\t\t\tcomponent: z.string().optional(),\n\t\t\tlabel: z.string().optional(),\n\t\t\tcollapsible: z.boolean().optional(),\n\t\t\tmode: z.enum(['edit', 'read', 'display']).optional(),\n\t\t\tschema: z.lazy(() => DoctypeFieldSchema.array()),\n\t\t})\n\t\t.meta({ title: 'FieldsetField' })\n\n\tconst rawUnion = z.discriminatedUnion('kind', [ValueFieldSchema, FieldsetFieldSchema, TableFieldSchema])\n\n\t// Overwrite the placeholder with the preprocessed schema. Because z.lazy captures\n\t// DoctypeFieldSchema by closure reference, the lazy callback in FieldsetFieldSchema\n\t// will resolve to this preprocessed version — so nested fieldsets also inject `kind`.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ZodPipe output is DoctypeField; same pattern as the z.never() placeholder above\n\tDoctypeFieldSchema = z.preprocess(injectKind, rawUnion) as unknown as z.ZodType<DoctypeField>\n\n\treturn { ValueFieldSchema, TableFieldSchema, FieldsetFieldSchema, DoctypeFieldSchema }\n}\n\nconst schemas = createDoctypeFieldSchemas()\n\n/**\n * Zod runtime validation schema for ValueField.\n * @public\n */\nexport const ValueFieldSchema = schemas.ValueFieldSchema\n\n/**\n * Zod runtime validation schema for FieldsetField.\n * Recursive — FieldsetField.schema is validated against DoctypeFieldSchema.\n * @public\n */\nexport const FieldsetFieldSchema = schemas.FieldsetFieldSchema\n\n/**\n * Zod runtime validation schema for TableField.\n * @public\n */\nexport const TableFieldSchema = schemas.TableFieldSchema\n\n/**\n * Zod runtime validation schema for the DoctypeField discriminated union.\n * Validates all three field variants: `'field'`, `'fieldset'`, `'table'`.\n * @public\n */\nexport const DoctypeFieldSchema = schemas.DoctypeFieldSchema\n","/**\n * Merge introspected schema facts into an already-authored doctype.\n *\n * The authored doctype is the source of truth. Generation **verifies** it and stamps provenance;\n * it does not overwrite. That polarity is deliberate and load-bearing — a doctype legitimately\n * declares a `primaryKey` the schema cannot express. A natural business key is very often a\n * `UNIQUE` constraint rather than the table's `PRIMARY KEY`, and where a table carries several\n * uniques no rule can pick between them. Overwriting identity from the schema would silently\n * re-key such a doctype on every regeneration and break the handlers that key on the old value.\n *\n * So divergence is **reported, never applied** — a human decides. The only mutation this performs\n * is adding `source: 'introspected'` to fields confirmed to exist in the GraphQL schema.\n *\n * @packageDocumentation\n */\n\nimport { INTROSPECTED_IDENTITY_PROPS } from '../field'\nimport type { ConvertedGraphQLDoctype } from './types'\n\n/**\n * A doctype as it exists on disk: a plain object that may carry keys this package does not model\n * (`handler` on an action, `filterFunction` on a field, whatever an app has added). Typing it\n * loosely is what lets the merge round-trip those keys untouched instead of dropping them.\n *\n * @public\n */\nexport type AuthoredDoctype = Record<string, unknown>\n\n/**\n * What generation found that the authored doctype does not agree with. Every bucket is advisory —\n * nothing here is applied automatically.\n *\n * @public\n */\nexport interface DoctypeDrift {\n\t/** The authored doctype's name. */\n\tdoctype: string\n\t/**\n\t * `clean` — the authored primary key is the one generation would derive.\n\t * `partial` — the doctype declares an identity generation cannot derive, so identity was left alone.\n\t */\n\tmode: 'clean' | 'partial'\n\t/** Why the mode is `partial`, when it is. */\n\treason?: string\n\t/** Fieldnames confirmed against the schema and stamped. */\n\ttagged: string[]\n\t/** Authored fields with no matching schema field — app components, fieldsets, or stale entries. */\n\torphan: string[]\n\t/** Schema fields absent from the doctype. Usually deliberate curation, occasionally an oversight. */\n\tomitted: string[]\n\t/** `fieldname: authored=… schema=…` where the chosen component differs from the scalar mapping. */\n\tcomponentDrift: string[]\n\t/** `fieldname: authored=… schema=…` where nullability disagrees. */\n\trequiredDrift: string[]\n\t/** Identity properties that differ. These are the ones a human must adjudicate. */\n\tidentityDrift: string[]\n}\n\n/** Outcome of a merge: the doctype to write, plus what generation disagreed with. @public */\nexport interface MergeResult {\n\t/** The authored doctype with `source` markers added and nothing else changed. */\n\tdoctype: AuthoredDoctype\n\t/** Advisory report. Never applied. */\n\tdrift: DoctypeDrift\n}\n\n/** Recursively flatten authored fields, descending into fieldsets. */\nfunction flattenAuthored(fields: readonly AuthoredDoctype[]): AuthoredDoctype[] {\n\tconst out: AuthoredDoctype[] = []\n\tfor (const f of fields) {\n\t\tif (Array.isArray(f.schema)) {\n\t\t\tout.push(...flattenAuthored(f.schema.filter(isRecord)))\n\t\t} else {\n\t\t\tout.push(f)\n\t\t}\n\t}\n\treturn out\n}\n\nfunction isRecord(value: unknown): value is AuthoredDoctype {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction describe(value: unknown): string {\n\treturn value === undefined ? '—' : JSON.stringify(value)\n}\n\n/**\n * Verify an authored doctype against freshly generated output and stamp provenance.\n *\n * @param authored - the doctype as it exists on disk; every key not named below is preserved verbatim\n * @param generated - `convertGraphQLSchema` output for the corresponding GraphQL type\n * @returns the doctype to write, plus a drift report\n *\n * @example\n * ```ts\n * const [generated] = convertGraphQLSchema(introspection, { include: ['Uom'] })\n * const { doctype, drift } = mergeIntrospectedDoctype(JSON.parse(onDisk), generated)\n * if (drift.identityDrift.length) console.warn(drift.identityDrift.join('\\n'))\n * ```\n *\n * @public\n */\nexport function mergeIntrospectedDoctype(authored: AuthoredDoctype, generated: ConvertedGraphQLDoctype): MergeResult {\n\tconst authoredFields = Array.isArray(authored.fields) ? authored.fields.filter(isRecord) : []\n\tconst generatedByName = new Map(generated.fields.map(f => [f.fieldname, f]))\n\t// Expanding links live in `links`, not `fields`, so a field naming one is modelled, not orphaned.\n\tconst generatedLinkNames = new Set(Object.keys(generated.links ?? {}))\n\n\tconst drift: DoctypeDrift = {\n\t\tdoctype: typeof authored.name === 'string' ? authored.name : '(unnamed)',\n\t\tmode: 'clean',\n\t\ttagged: [],\n\t\torphan: [],\n\t\tomitted: [],\n\t\tcomponentDrift: [],\n\t\trequiredDrift: [],\n\t\tidentityDrift: [],\n\t}\n\n\tconst tag = (field: AuthoredDoctype): AuthoredDoctype => {\n\t\t// Containers have no column of their own; recurse and leave the container itself alone.\n\t\tif (Array.isArray(field.schema)) {\n\t\t\treturn { ...field, schema: field.schema.filter(isRecord).map(tag) }\n\t\t}\n\n\t\tconst name = typeof field.fieldname === 'string' ? field.fieldname : ''\n\t\tconst match = generatedByName.get(name)\n\n\t\tif (!match) {\n\t\t\t// A computed field declares up front that it has no backing column, so it is not a\n\t\t\t// discrepancy. Everything else is worth surfacing — it may be an app component, or a\n\t\t\t// column that has since been dropped.\n\t\t\tif (field.computed !== true && !generatedLinkNames.has(name)) drift.orphan.push(name)\n\t\t\treturn field\n\t\t}\n\n\t\tdrift.tagged.push(name)\n\n\t\tif (match.component !== field.component) {\n\t\t\tdrift.componentDrift.push(`${name}: authored=${describe(field.component)} schema=${describe(match.component)}`)\n\t\t}\n\t\tif (Boolean(match.required) !== Boolean(field.required)) {\n\t\t\tdrift.requiredDrift.push(`${name}: authored=${Boolean(field.required)} schema=${Boolean(match.required)}`)\n\t\t}\n\t\tfor (const prop of INTROSPECTED_IDENTITY_PROPS) {\n\t\t\tif (prop === 'fieldname' || prop === 'required') continue\n\t\t\tconst authoredValue = field[prop]\n\t\t\tconst schemaValue = match[prop]\n\t\t\t// Absent on both sides is agreement, not drift — most fields set none of these.\n\t\t\tif (authoredValue === undefined && schemaValue === undefined) continue\n\t\t\tif (JSON.stringify(authoredValue) !== JSON.stringify(schemaValue)) {\n\t\t\t\tdrift.identityDrift.push(`${name}.${prop}: authored=${describe(authoredValue)} schema=${describe(schemaValue)}`)\n\t\t\t}\n\t\t}\n\n\t\treturn { ...field, source: 'introspected' }\n\t}\n\n\tconst merged: AuthoredDoctype = { ...authored, fields: authoredFields.map(tag) }\n\n\tconst authoredNames = new Set(flattenAuthored(authoredFields).map(f => f.fieldname))\n\tdrift.omitted = generated.fields.map(f => f.fieldname).filter(n => !authoredNames.has(n))\n\n\t// Classify identity last, once every field has been compared.\n\tconst authoredPk = flattenAuthored(authoredFields).find(f => f.primaryKey === true)\n\tconst generatedPk = generated.fields.find(f => f.primaryKey === true)\n\tif (authoredPk && generatedPk && authoredPk.fieldname !== generatedPk.fieldname) {\n\t\tdrift.mode = 'partial'\n\t\tdrift.reason = `authored primary key '${String(authoredPk.fieldname)}' is not the derivable '${generatedPk.fieldname}' — left as authored`\n\t} else if (authoredPk && !generatedPk) {\n\t\tdrift.mode = 'partial'\n\t\tdrift.reason = `authored primary key '${String(authoredPk.fieldname)}' is not derivable from the schema — left as authored`\n\t} else if (!authoredPk && generatedPk) {\n\t\tdrift.mode = 'partial'\n\t\tdrift.reason = `schema suggests '${generatedPk.fieldname}' as primary key but the doctype declares none — not applied`\n\t}\n\n\treturn { doctype: merged, drift }\n}\n\n/**\n * Render a drift report as human-readable lines. Empty when generation agrees with the doctype.\n *\n * @param drift - a report from {@link mergeIntrospectedDoctype}\n * @returns one line per finding, ready to print\n *\n * @public\n */\nexport function formatDoctypeDrift(drift: DoctypeDrift): string[] {\n\tconst lines: string[] = []\n\tif (drift.reason) lines.push(` ${drift.doctype}: ${drift.reason}`)\n\tconst bucket = (label: string, entries: string[]) => {\n\t\tif (entries.length) lines.push(` ${drift.doctype}: ${label} ${entries.join('; ')}`)\n\t}\n\tbucket('identity drift', drift.identityDrift)\n\tbucket('component drift', drift.componentDrift)\n\tbucket('required drift', drift.requiredDrift)\n\tbucket('authored fields with no schema field:', drift.orphan)\n\tbucket('schema fields not modelled:', drift.omitted)\n\treturn lines\n}\n","/**\n * GraphQL Introspection to Stonecrop Schema Converter\n *\n * Converts a standard GraphQL introspection result (or SDL string) into\n * Stonecrop doctype schemas. Source-agnostic — works with any GraphQL server.\n *\n * @packageDocumentation\n */\n\nimport { buildClientSchema, buildSchema, isObjectType, type GraphQLSchema } from 'graphql'\n\nimport type { LinkDeclaration } from '../doctype'\nimport { toSlug } from '../naming'\nimport type { IntrospectionSource, GraphQLConversionOptions, ConvertedGraphQLDoctype } from './types'\nimport type { ValueField } from '../field'\nimport { defaultIsEntityType, defaultIsEntityField, classifyFieldType } from './heuristics'\n\n/**\n * Convert a GraphQL schema to Stonecrop doctype schemas.\n *\n * Accepts either an `IntrospectionQuery` result object or an SDL string.\n * Entity types are identified using heuristics (or a custom `isEntityType` function)\n * and converted to `DoctypeMeta`-compatible JSON objects.\n *\n * @param source - GraphQL introspection result or SDL string\n * @param options - Conversion options for controlling output format and behavior\n * @returns Array of converted Stonecrop doctype definitions\n *\n * @example\n * ```typescript\n * // From introspection result (fetched from any GraphQL server)\n * const introspection = await fetchIntrospection('http://localhost:5000/graphql')\n * const doctypes = convertGraphQLSchema(introspection)\n *\n * // From SDL string\n * const sdl = fs.readFileSync('schema.graphql', 'utf-8')\n * const doctypes = convertGraphQLSchema(sdl)\n *\n * // With PostGraphile custom scalars\n * const doctypes = convertGraphQLSchema(introspection, {\n * customScalars: {\n * BigFloat: { component: 'ANumericInput' }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function convertGraphQLSchema(\n\tsource: IntrospectionSource,\n\toptions: GraphQLConversionOptions = {}\n): ConvertedGraphQLDoctype[] {\n\tconst schema = buildGraphQLSchema(source)\n\tconst typeMap = schema.getTypeMap()\n\n\t// Determine the root operation type names to exclude\n\tconst rootTypeNames = new Set<string>()\n\tconst queryType = schema.getQueryType()\n\tconst mutationType = schema.getMutationType()\n\tconst subscriptionType = schema.getSubscriptionType()\n\tif (queryType) rootTypeNames.add(queryType.name)\n\tif (mutationType) rootTypeNames.add(mutationType.name)\n\tif (subscriptionType) rootTypeNames.add(subscriptionType.name)\n\n\t// Use custom or default entity type detector\n\tconst isEntityType = options.isEntityType ?? defaultIsEntityType\n\n\t// Phase 1: Identify all entity types\n\tconst entityTypes = new Set<string>()\n\tfor (const [typeName, type] of Object.entries(typeMap)) {\n\t\tif (!isObjectType(type)) continue\n\n\t\t// Always skip root operation types (even if custom isEntityType doesn't)\n\t\tif (rootTypeNames.has(typeName)) continue\n\n\t\tif (isEntityType(typeName, type)) {\n\t\t\tentityTypes.add(typeName)\n\t\t}\n\t}\n\n\t// Phase 2: Apply include/exclude filters\n\tlet filteredEntityTypes = entityTypes\n\n\tif (options.include) {\n\t\tconst includeSet = new Set(options.include)\n\t\tfilteredEntityTypes = new Set([...entityTypes].filter(t => includeSet.has(t)))\n\t}\n\n\tif (options.exclude) {\n\t\tconst excludeSet = new Set(options.exclude)\n\t\tfilteredEntityTypes = new Set([...filteredEntityTypes].filter(t => !excludeSet.has(t)))\n\t}\n\n\t// Phase 3: Convert each entity type to a doctype\n\tconst isEntityField = options.isEntityField ?? defaultIsEntityField\n\n\tconst doctypes: ConvertedGraphQLDoctype[] = []\n\n\tfor (const typeName of filteredEntityTypes) {\n\t\tconst type = typeMap[typeName]\n\t\tif (!isObjectType(type)) continue\n\n\t\tconst fields = type.getFields()\n\n\t\t// A type carrying BOTH `id` and `rowId` is PostGraphile Amber with its default inflection:\n\t\t// the Relay global identifier has taken `id`, displacing the real column to `rowId`. Neither\n\t\t// name can be emitted as-is — `id` is an opaque node id, and `rowId` does not name a column.\n\t\t// Refuse to guess: drop the Relay field and tell the caller to fix it at the inflector, where\n\t\t// it belongs. Normalizing here would bake a database fact into the doctype.\n\t\tconst isUnnormalizedPostGraphile = 'id' in fields && 'rowId' in fields\n\t\tif (isUnnormalizedPostGraphile) {\n\t\t\toptions.onWarning?.(\n\t\t\t\t`${typeName}: schema exposes both 'id' (Relay identifier) and 'rowId' (the real column). ` +\n\t\t\t\t\t`Skipping 'id' and emitting 'rowId' verbatim — no primary key can be derived. ` +\n\t\t\t\t\t`Override the '_attributeName' and 'nodeIdFieldName' inflectors so the column keeps its own name.`\n\t\t\t)\n\t\t}\n\n\t\tconst entityFields = Object.entries(fields).filter(\n\t\t\t([fieldName, field]) =>\n\t\t\t\tisEntityField(fieldName, field, type) && !(isUnnormalizedPostGraphile && fieldName === 'id')\n\t\t)\n\n\t\t// oxlint-disable-next-line oxc/no-map-spread -- ...custom spread required; Object.assign cannot preserve the metadata-carrying inferred union type from classifyField\n\t\tconst allClassifiedFields = entityFields.map(([fieldName, field]) => {\n\t\t\t// Check for full custom classification first\n\t\t\tif (options.classifyField) {\n\t\t\t\tconst custom = options.classifyField(fieldName, field, type)\n\t\t\t\tif (custom !== null && custom !== undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'field' as const,\n\t\t\t\t\t\tfieldname: fieldName,\n\t\t\t\t\t\tlabel: custom.label ?? fieldName,\n\t\t\t\t\t\tcomponent: custom.component ?? 'ATextInput',\n\t\t\t\t\t\t...custom,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Default classification\n\t\t\treturn classifyFieldType(fieldName, field, entityTypes, options)\n\t\t})\n\n\t\t// Derive the primary key, but only for the one case SDL actually settles: a non-null `id`\n\t\t// that is a plain scalar. A natural key is typically a UNIQUE constraint indistinguishable\n\t\t// from any other column here, and a table may carry several — so anything else is left for\n\t\t// the author to declare. Emitting a guess would be worse than emitting nothing, because the\n\t\t// middleware builds its identity predicate from this and the client keys records by it.\n\t\tconst primaryKeyFieldname = allClassifiedFields.find(\n\t\t\tfield => field.fieldname === 'id' && field.required && !field.doctype && !field._isLink\n\t\t)?.fieldname\n\n\t\t// Separate scalar fields from link fields\n\t\tconst links: Record<string, LinkDeclaration> = {}\n\t\tconst convertedFields = allClassifiedFields\n\t\t\t.filter(field => {\n\t\t\t\tif (field._isLink && field.doctype && field.cardinality) {\n\t\t\t\t\tlinks[field.fieldname] = {\n\t\t\t\t\t\ttarget: field.doctype,\n\t\t\t\t\t\tcardinality: field.cardinality,\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t})\n\t\t\t// Clean up internal metadata unless requested, and stamp identity + provenance.\n\t\t\t// Stamped last so every classification path (default, classifyField) carries the marker —\n\t\t\t// the docbuilder's identity lock keys off it, and no classifier may unset it.\n\t\t\t.map(field => {\n\t\t\t\tconst identity = field.fieldname === primaryKeyFieldname ? { primaryKey: true as const } : {}\n\t\t\t\tif (!options.includeUnmappedMeta) {\n\t\t\t\t\tconst { _graphqlType, _unmapped, _isLink, ...clean } = field\n\t\t\t\t\treturn Object.assign(clean, identity, { source: 'introspected' as const })\n\t\t\t\t}\n\t\t\t\tconst { _isLink, ...rest } = field\n\t\t\t\treturn Object.assign(rest, identity, { source: 'introspected' as const })\n\t\t\t})\n\n\t\tconst doctypeName = options.doctypeNames?.[typeName] ?? typeName\n\t\tconst doctype: ConvertedGraphQLDoctype = {\n\t\t\tname: doctypeName,\n\t\t\tslug: toSlug(doctypeName),\n\t\t\tfields: convertedFields as ValueField[],\n\t\t}\n\n\t\tif (Object.keys(links).length > 0) {\n\t\t\tdoctype.links = links\n\t\t}\n\n\t\tif (options.includeUnmappedMeta) {\n\t\t\tdoctype._graphqlTypeName = typeName\n\t\t}\n\n\t\tdoctypes.push(doctype)\n\t}\n\n\treturn doctypes\n}\n\n/**\n * Build a GraphQLSchema from either an introspection result or SDL string.\n *\n * @param source - IntrospectionQuery object or SDL string\n * @returns A complete GraphQLSchema\n * @internal\n */\nfunction buildGraphQLSchema(source: IntrospectionSource): GraphQLSchema {\n\tif (typeof source === 'string') {\n\t\t// SDL string\n\t\treturn buildSchema(source)\n\t}\n\n\t// IntrospectionQuery result\n\treturn buildClientSchema(source)\n}\n\n// ═══════════════════════════════════════════════════════════════\n// Re-exports\n// ═══════════════════════════════════════════════════════════════\n\n// Main converter (this file)\nexport { convertGraphQLSchema as default }\n\n// Types\nexport type {\n\tIntrospectionSource,\n\tGraphQLConversionOptions,\n\tGraphQLConversionFieldMeta,\n\tConvertedGraphQLDoctype,\n} from './types'\n\n// Scalar maps\nexport { GQL_SCALAR_MAP, WELL_KNOWN_SCALARS, INTERNAL_SCALARS, buildScalarMap } from './scalars'\n\n// Heuristics\nexport { defaultIsEntityType, defaultIsEntityField, classifyFieldType } from './heuristics'\n\n// Merge — verifies an authored doctype against the schema and stamps provenance\nexport { mergeIntrospectedDoctype, formatDoctypeDrift } from './merge'\nexport type { AuthoredDoctype, DoctypeDrift, MergeResult } from './merge'\n\n// Naming utilities\nexport { toSlug, toPascalCase, pascalToSnake, snakeToCamel, camelToSnake, snakeToLabel, camelToLabel } from '../naming'\n","import { z } from 'zod'\n\nimport { DoctypeFieldSchema, flattenFields, getDisplayField } from './field'\n\n/**\n * Cardinality for relationship links.\n * @public\n */\nexport const Cardinality = z.enum(['atMostOne', 'one', 'noneOrMany', 'atLeastOne']).meta({\n\ttitle: 'Cardinality',\n\tdescription: 'Cardinality for relationship links between doctypes',\n})\n\n/**\n * Cardinality type inferred from Zod schema\n * @public\n */\nexport type Cardinality = z.infer<typeof Cardinality>\n\n/**\n * Serialized function type - a function serialized to a string.\n * Used for custom fetch handlers.\n * @public\n */\nexport type SerializedFunction = string\n\n/**\n * Sync fetch strategy - data is fetched in the initial query.\n * @public\n */\nexport const SyncFetch = z\n\t.object({\n\t\t/** Fetch method type */\n\t\tmethod: z.literal('sync'),\n\t\t/** Optional limit on number of records to fetch */\n\t\tlimit: z.number().int().positive().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'SyncFetch',\n\t\tdescription: 'Sync fetch strategy - data is fetched in the initial query',\n\t})\n\n/**\n * Sync fetch strategy type\n * @public\n */\nexport type SyncFetch = z.infer<typeof SyncFetch>\n\n/**\n * Lazy fetch strategy - data is fetched on demand in a separate query.\n * @public\n */\nexport const LazyFetch = z\n\t.object({\n\t\t/** Fetch method type */\n\t\tmethod: z.literal('lazy'),\n\t})\n\t.meta({\n\t\ttitle: 'LazyFetch',\n\t\tdescription: 'Lazy fetch strategy - data is fetched on demand in a separate query',\n\t})\n\n/**\n * Lazy fetch strategy type\n * @public\n */\nexport type LazyFetch = z.infer<typeof LazyFetch>\n\n/**\n * Custom fetch strategy - uses a custom handler function.\n * @public\n */\nexport const CustomFetch = z\n\t.object({\n\t\t/** Fetch method type */\n\t\tmethod: z.literal('custom'),\n\t\t/** Serialized handler function to invoke */\n\t\thandler: z.string(),\n\t})\n\t.meta({\n\t\ttitle: 'CustomFetch',\n\t\tdescription: 'Custom fetch strategy - uses a custom handler function',\n\t})\n\n/**\n * Custom fetch strategy type\n * @public\n */\nexport type CustomFetch = z.infer<typeof CustomFetch>\n\n/**\n * Fetch strategy for link data loading.\n * - sync: fetched in the initial query\n * - lazy: fetched on demand in a separate query\n * - custom: uses a custom handler function\n * @public\n */\nexport const FetchStrategy = z.discriminatedUnion('method', [SyncFetch, LazyFetch, CustomFetch]).meta({\n\ttitle: 'FetchStrategy',\n\tdescription: 'Fetch strategy for link data loading',\n})\n\n/**\n * Fetch strategy type\n * @public\n */\nexport type FetchStrategy = z.infer<typeof FetchStrategy>\n\n/**\n * Link declaration - describes a relationship from one doctype to another.\n * @public\n */\nexport const LinkDeclaration = z\n\t.object({\n\t\t/** Target doctype slug */\n\t\ttarget: z.string().min(1),\n\n\t\t/** Cardinality of the relationship */\n\t\tcardinality: Cardinality,\n\n\t\t/** Backlink fieldname on the target doctype that points back to this link */\n\t\tbacklink: z.string().optional(),\n\n\t\t/** Override default rendering component (AForm for 1:1, ATable for 1:many) */\n\t\tcomponent: z.string().optional(),\n\n\t\t/** Fieldname of the corresponding Link field in the fields array */\n\t\tfieldname: z.string().min(1).optional(),\n\n\t\t/** Fetch strategy for loading nested data */\n\t\tfetch: FetchStrategy.optional(),\n\n\t\t/** Whether to block workflow actions until nested data is loaded (default: true) */\n\t\tblockWorkflows: z.boolean().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'LinkDeclaration',\n\t\tdescription: 'Declares a relationship from one doctype to another',\n\t})\n\n/**\n * Link declaration type inferred from Zod schema\n * @public\n */\nexport type LinkDeclaration = z.infer<typeof LinkDeclaration>\n\n/**\n * Action definition within a workflow\n * @public\n */\nexport const ActionDefinition = z\n\t.object({\n\t\t/** Display label for the action */\n\t\tlabel: z.string().min(1),\n\n\t\t/** Fields that must have values before action can execute */\n\t\trequiredFields: z.array(z.string()).optional(),\n\n\t\t/** Workflow states where this action is available */\n\t\tallowedStates: z.array(z.string()).optional(),\n\n\t\t/** The state the record transitions to after this action executes */\n\t\tnextState: z.string().optional(),\n\n\t\t/** True for stateless command actions with no workflow effect at all (print, email, etc.) */\n\t\tstateless: z.boolean().optional(),\n\n\t\t/**\n\t\t * True for an internal self-transition: the action runs within the current state without\n\t\t * advancing the workflow (e.g. `save`, which mutates record data but stays put). Scoped by\n\t\t * `allowedStates`, rendered as a self-loop in the graph, and has no `nextState`. Distinct from\n\t\t * `stateless` (which has no workflow presence at all): a self-transition is graph-owned and,\n\t\t * unlike a stateless command, persists record data on dispatch.\n\t\t */\n\t\tselfTransition: z.boolean().optional(),\n\n\t\t/** JS function body stored as a string; executed client-side via AsyncFunction with injected API surface */\n\t\tclientHandler: z.string().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'ActionDefinition',\n\t\tdescription: 'Action definition within a workflow',\n\t})\n\n/**\n * Action definition type inferred from Zod schema\n * @public\n */\nexport type ActionDefinition = z.infer<typeof ActionDefinition>\n\n/**\n * Reactive field-validation trigger — advisory, client-side only.\n *\n * A Trigger is a docbuilder-authored validator: when any field in `on` is edited, its\n * `clientHandler` runs (client-side, no rollback) and may flag a field inline to block save\n * in the UI. It is deliberately a **sibling** to {@link (ActionDefinition:type)}, not a member of it —\n * a reactive validator is not a user-invoked action, so it lives in the `triggers` map on\n * {@link (WorkflowMeta:type)} and never appears to action readers (transition/command dropdowns, the FSM graph).\n *\n * The two bindings are independent: `on` is the fire-set (which fields' edits run it), while the\n * `setError(field, msg)` call inside `clientHandler` chooses which field displays the error.\n * @public\n */\nexport const TriggerDefinition = z\n\t.object({\n\t\t/** Optional display label; the map key is the trigger's identity */\n\t\tlabel: z.string().optional(),\n\n\t\t/** Fieldnames whose edits fire this trigger (fires when any listed field changes) */\n\t\ton: z.array(z.string()),\n\n\t\t/** JS function body stored as a string; run client-side with `{ record, value, setError }`. Advisory. */\n\t\tclientHandler: z.string(),\n\t})\n\t.meta({\n\t\ttitle: 'TriggerDefinition',\n\t\tdescription: 'Reactive field-validation trigger — advisory client-side',\n\t})\n\n/**\n * Trigger definition type inferred from Zod schema\n * @public\n */\nexport type TriggerDefinition = z.infer<typeof TriggerDefinition>\n\n/**\n * Whether a workflow action may run from `currentState`.\n *\n * Single source of truth for the \"is this action available here\" rule, shared by\n * the frontend (`getAvailableTransitions`) and the server-side dispatch guard so\n * the two can never disagree. Empty or absent `allowedStates` means the action is\n * available in ALL states — a plain `allowedStates.includes(currentState)` would\n * wrongly block such actions everywhere.\n *\n * @public\n */\nexport function isActionAllowedInState(action: { allowedStates?: string[] | null }, currentState: string): boolean {\n\tconst allowedStates = action.allowedStates\n\tif (!allowedStates || allowedStates.length === 0) return true\n\treturn allowedStates.includes(currentState)\n}\n\n/**\n * DocBuilder graph layout — node positions for the workflow-state graph, keyed by state name.\n * Pure authoring view-state: persisted in the doctype JSON so an author's manual arrangement\n * survives reloads, but — exactly like {@link (WorkflowMeta:type)}'s `triggers` — it is client-only\n * and never mirrored into the runtime GraphQL SDL (see the WorkflowMeta type in the host SDLs, which\n * expose only `states`/`actions`). The shape mirrors VueFlow's node fields; `position` is the node's\n * canvas coordinate and `targetPosition`/`sourcePosition` are the handle sides.\n * @public\n */\nexport const WorkflowLayout = z.record(\n\tz.string(),\n\tz.object({\n\t\tposition: z.object({ x: z.number(), y: z.number() }).optional(),\n\t\ttargetPosition: z.enum(['left', 'top', 'right', 'bottom']).optional(),\n\t\tsourcePosition: z.enum(['left', 'top', 'right', 'bottom']).optional(),\n\t})\n)\n\n/**\n * Workflow layout type inferred from Zod schema\n * @public\n */\nexport type WorkflowLayout = z.infer<typeof WorkflowLayout>\n\n/**\n * Workflow metadata - states and actions for a doctype\n * @public\n */\nexport const WorkflowMeta = z\n\t.object({\n\t\t/** List of workflow states */\n\t\tstates: z.array(z.string()).optional(),\n\n\t\t/** Actions available in this workflow */\n\t\tactions: z.record(z.string(), ActionDefinition).optional(),\n\n\t\t/** Reactive field-validation triggers (advisory, client-side), keyed by trigger name */\n\t\ttriggers: z.record(z.string(), TriggerDefinition).optional(),\n\n\t\t/**\n\t\t * DocBuilder node positions keyed by state name — authoring view-state. Persisted here so a\n\t\t * doctype author's manual graph arrangement survives reloads; like `triggers`, it is client-only\n\t\t * and never enters the runtime GraphQL SDL. See {@link (WorkflowLayout:variable)}.\n\t\t */\n\t\tlayout: WorkflowLayout.optional(),\n\t})\n\t.meta({\n\t\ttitle: 'WorkflowMeta',\n\t\tdescription: 'Workflow metadata - states and actions for a doctype',\n\t})\n\n/**\n * Workflow metadata type inferred from Zod schema\n * @public\n */\nexport type WorkflowMeta = z.infer<typeof WorkflowMeta>\n\n/**\n * Doctype metadata - complete definition of a doctype\n * @public\n */\nexport const DoctypeMeta = z\n\t.object({\n\t\t/** Display name of the doctype */\n\t\tname: z.string().min(1),\n\n\t\t/** URL-friendly slug (kebab-case) */\n\t\tslug: z.string().min(1).optional(),\n\n\t\t/**\n\t\t * Field on this doctype used when displaying a reference to one of its records.\n\t\t * When a record elsewhere holds a foreign key to this doctype, the middleware may\n\t\t * include `fieldname__display` alongside the raw id, resolved from this field.\n\t\t */\n\t\tdisplayField: z.string().min(1).optional(),\n\n\t\t/** Field definitions (a link field is one carrying `doctype`) */\n\t\tfields: z.array(DoctypeFieldSchema),\n\n\t\t/** Relationship links to other doctypes */\n\t\tlinks: z.record(z.string(), LinkDeclaration).optional(),\n\n\t\t/** Workflow configuration */\n\t\tworkflow: WorkflowMeta.optional(),\n\n\t\t/** Parent doctype for inheritance */\n\t\tinherits: z.string().optional(),\n\t})\n\t.meta({\n\t\ttitle: 'DoctypeMeta',\n\t\tdescription: 'Doctype metadata - complete definition of a doctype',\n\t})\n\t.superRefine((doctype, ctx) => {\n\t\t// A record is identified by exactly one field here, and that is the design rather than a\n\t\t// limitation awaiting composite support. A doctype describes the **API surface** a client\n\t\t// interacts with, not the table behind it; how a composite database key maps onto a single\n\t\t// identity on that surface is the server's business, and the client neither sees nor\n\t\t// encodes the parts. So there is nothing for a doctype-level composite key to express.\n\t\t//\n\t\t// Declaring several is therefore malformed, and silently so: `getPrimaryKeyField` takes the\n\t\t// first match and the rest are ignored, leaving an adapter to key records on a column that\n\t\t// need not be unique — `stonecropRecord`'s row map then keeps whichever row comes last.\n\t\t// Refusing at the gate is what makes it say so.\n\t\t//\n\t\t// Zero keys stays legal and is not an omission: a surrogate-key doctype declares none and\n\t\t// resolves through `getRecordIdField`'s documented `id` fallback.\n\t\tconst declared = doctype.fields.filter(f => f.kind === 'field' && f.primaryKey)\n\t\tif (declared.length > 1) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: 'custom',\n\t\t\t\tpath: ['fields'],\n\t\t\t\tmessage: `Doctype declares ${declared.length} primaryKey fields (${declared\n\t\t\t\t\t.map(f => (f.kind === 'field' ? f.fieldname : ''))\n\t\t\t\t\t.join(\n\t\t\t\t\t\t', '\n\t\t\t\t\t)}); a record is identified by exactly one field. A composite database key is mapped to a single identity by the adapter, so a doctype never declares its parts`,\n\t\t\t})\n\t\t}\n\n\t\t// Through `getDisplayField` rather than a scan written here, because the adapter builds its\n\t\t// SELECT from that same call. The two hand-rolled versions disagreed in both directions at\n\t\t// once: this gate scanned top-level only, so it rejected a fieldset-nested field that would\n\t\t// have worked, while neither side excluded `computed` fields, so a nomination naming one\n\t\t// passed the gate and then failed as a missing column at query time.\n\t\tif (doctype.displayField && !getDisplayField(doctype.fields, doctype.displayField)) {\n\t\t\tconst named = flattenFields(doctype.fields).find(f => f.fieldname === doctype.displayField)\n\t\t\tctx.addIssue({\n\t\t\t\tcode: 'custom',\n\t\t\t\tpath: ['displayField'],\n\t\t\t\tmessage: named\n\t\t\t\t\t? `displayField \"${doctype.displayField}\" names a computed field, which has no column to read a display value from`\n\t\t\t\t\t: `displayField \"${doctype.displayField}\" is not declared on this doctype`,\n\t\t\t})\n\t\t}\n\t})\n\n/**\n * Doctype metadata type inferred from Zod schema\n * @public\n */\nexport type DoctypeMeta = z.infer<typeof DoctypeMeta>\n\n/**\n * Suffix appended to a link fieldname for its pre-resolved display text in record payloads.\n *\n * @deprecated The `__display` suffix pattern is no longer used. Use the native PostGraphile\n * query methods (`getNativeRecord`/`getNativeRecords`) in `@stonecrop/graphql-client` which\n * return link fields as `{ id, displayText }` objects directly.\n * @public\n */\nexport const LINK_DISPLAY_SUFFIX = '__display'\n\n/**\n * Build the payload key for a link field's display text (e.g. `customerId__display`).\n *\n * @deprecated The `__display` suffix pattern is no longer used. Use the native PostGraphile\n * query methods (`getNativeRecord`/`getNativeRecords`) in `@stonecrop/graphql-client` which\n * return link fields as `{ id, displayText }` objects directly.\n * @public\n */\nexport function linkDisplayFieldname(fieldname: string): string {\n\treturn `${fieldname}${LINK_DISPLAY_SUFFIX}`\n}\n\n/**\n * Context for identifying what doctype/record we're working with.\n * Used by graphql-middleware and graphql-client to resolve schema metadata.\n * @public\n */\nexport interface DoctypeContext {\n\t/** Doctype name (e.g., 'Task', 'Customer') */\n\tdoctype: string\n\t/** Optional record ID for viewing/editing a specific record */\n\trecordId?: string\n\t/** Additional context properties */\n\t[key: string]: unknown\n}\n\n/**\n * Base interface for doctype metadata passed to DataClient methods.\n * Only requires properties needed for record fetching.\n * @public\n */\nexport interface DoctypeRef {\n\t/** Doctype name (e.g., 'Task', 'Customer') */\n\tname: string\n\t/** URL-friendly slug (e.g., 'task', 'customer') */\n\tslug?: string\n}\n\n/**\n * Options for fetching a single record\n * @public\n */\nexport interface GetRecordOptions {\n\t/**\n\t * Include nested link sub-selections.\n\t * - `true`: include all descendant links\n\t * - `string[]`: include only named links\n\t * - `false` / omitted: scalar fields only (default)\n\t */\n\tincludeNested?: boolean | string[]\n\n\t/**\n\t * Maximum depth for recursive sub-selections.\n\t * No default — unlimited when omitted.\n\t */\n\tmaxDepth?: number\n}\n\n/**\n * Options for fetching multiple records\n * @public\n */\nexport interface GetRecordsOptions {\n\t/** Filter expression (field-value pairs) */\n\tfilters?: Record<string, unknown>\n\t/** Order by expression (e.g. 'NAME_ASC') */\n\torderBy?: string\n\t/** Maximum number of records to return */\n\tlimit?: number\n\t/** Number of records to skip */\n\toffset?: number\n\t/**\n\t * Ask the backend for the total matching the filters as well as the page.\n\t *\n\t * Off by default because it costs a second query — a full scan on Postgres — and knowing\n\t * *whether* more exist (`hasMore`) is what a list view actually needs. Turn it on for a\n\t * \"showing 20 of 4,312\" style display.\n\t */\n\tincludeTotal?: boolean\n}\n\n/**\n * Result from getRecord - includes the record data\n * @public\n */\nexport interface GetRecordResult {\n\t/** The record data, or null if not found */\n\trecord: Record<string, unknown> | null\n}\n\n/**\n * Result from getRecords — a page of records, and enough to tell that it is one.\n *\n * A bare array used to be returned here, which claimed to be the whole collection. It is not:\n * a limit always applies, so a caller could not distinguish a complete list from a truncated\n * one. That is the entire reason this type exists.\n *\n * @public\n */\nexport interface GetRecordsResult {\n\t/** The records in this page */\n\tdata: Record<string, unknown>[]\n\t/** Whether the backend holds further records beyond this page */\n\thasMore: boolean\n\t/**\n\t * Total records matching the filters, ignoring limit/offset. Present only when the caller\n\t * asked for it via {@link GetRecordsOptions.includeTotal} — counting is a full scan on most\n\t * backends, so it is never computed speculatively.\n\t */\n\tcount?: number\n}\n\n/**\n * Interface for data clients that fetch doctype metadata and records.\n * Implemented by \\@stonecrop/graphql-client's StonecropClient.\n * Custom implementations can use any backend (REST, local storage, etc.).\n *\n * @typeParam T - Doctype reference type for record operations (defaults to DoctypeRef)\n * @typeParam M - Doctype metadata return type for getMeta (defaults to DoctypeMeta)\n * @public\n */\nexport interface DataClient<T extends DoctypeRef = DoctypeRef, M = DoctypeMeta> {\n\t/**\n\t * Fetch doctype metadata\n\t * @param context - Doctype context identifying the doctype\n\t * @returns Doctype metadata or null if not found\n\t */\n\tgetMeta(context: DoctypeContext): Promise<M | null>\n\n\t/**\n\t * Fetch a single record by ID\n\t *\n\t * When `includeNested` is set, builds a query with sub-selections for descendant\n\t * links and returns ancestor + merged descendants. When omitted, returns flat scalar data.\n\t *\n\t * @param doctype - Doctype reference (name and optional slug)\n\t * @param recordId - Record ID to fetch\n\t * @param options - Query options\n\t * @returns Record data wrapped in GetRecordResult\n\t */\n\tgetRecord(doctype: T, recordId: string, options?: GetRecordOptions): Promise<GetRecordResult>\n\n\t/**\n\t * Fetch a page of records\n\t * @param doctype - Doctype reference (name and optional slug)\n\t * @param options - Query options\n\t * @returns The page, plus whether more exist and (on request) the total\n\t */\n\tgetRecords(doctype: T, options?: GetRecordsOptions): Promise<GetRecordsResult>\n\n\t/**\n\t * Execute a doctype action (e.g., SUBMIT, APPROVE, save).\n\t * All state changes flow through this single mutation endpoint.\n\t *\n\t * @param doctype - Doctype reference (name and optional slug)\n\t * @param action - Action name to execute (e.g., 'SUBMIT', 'APPROVE', 'save')\n\t * @param args - Action arguments (typically record ID and/or form data)\n\t * @returns Action result with success status, response data, and any error\n\t */\n\trunAction(\n\t\tdoctype: T,\n\t\taction: string,\n\t\targs?: unknown[]\n\t): Promise<{ success: boolean; data: unknown; error: string | null }>\n}\n","import { DoctypeFieldSchema } from './field'\nimport { DoctypeMeta } from './doctype'\n\n/**\n * Validation error with path information\n * @public\n */\nexport interface ValidationError {\n\t/** Path to the invalid property */\n\tpath: PropertyKey[]\n\n\t/** Error message */\n\tmessage: string\n}\n\n/**\n * Result of a validation operation\n * @public\n */\nexport interface ValidationResult {\n\t/** Whether validation passed */\n\tsuccess: boolean\n\n\t/** List of validation errors (empty if success) */\n\terrors: ValidationError[]\n}\n\n/**\n * Validate a field definition against the DoctypeField discriminated union\n * @param data - Data to validate\n * @returns Validation result\n * @public\n */\nexport function validateField(data: unknown): ValidationResult {\n\tconst result = DoctypeFieldSchema.safeParse(data)\n\n\tif (result.success) {\n\t\treturn { success: true, errors: [] }\n\t}\n\n\treturn {\n\t\tsuccess: false,\n\t\terrors: result.error.issues.map(issue => ({\n\t\t\tpath: issue.path,\n\t\t\tmessage: issue.message,\n\t\t})),\n\t}\n}\n\n/**\n * Validate a doctype definition\n * @param data - Data to validate\n * @returns Validation result\n * @public\n */\nexport function validateDoctype(data: unknown): ValidationResult {\n\tconst result = DoctypeMeta.safeParse(data)\n\n\tif (result.success) {\n\t\treturn { success: true, errors: [] }\n\t}\n\n\treturn {\n\t\tsuccess: false,\n\t\terrors: result.error.issues.map(issue => ({\n\t\t\tpath: issue.path,\n\t\t\tmessage: issue.message,\n\t\t})),\n\t}\n}\n\n/**\n * Parse and validate a field, throwing on failure\n * @param data - Data to parse\n * @returns Validated DoctypeField\n * @throws ZodError if validation fails\n * @public\n */\nexport function parseField(data: unknown): import('./field').DoctypeField {\n\treturn DoctypeFieldSchema.parse(data)\n}\n\n/**\n * Parse and validate a doctype, throwing on failure\n * @param data - Data to parse\n * @returns Validated DoctypeMeta\n * @throws ZodError if validation fails\n * @public\n */\nexport function parseDoctype(data: unknown): DoctypeMeta {\n\treturn DoctypeMeta.parse(data)\n}\n\n// Re-export types for convenience\nexport type { DoctypeField, ValueField, FieldsetField, TableField } from './field'\nexport type { DoctypeMeta } from './doctype'\n"],"names":["snakeToCamel","snakeCase","_","letter","camelToSnake","camelCase","snakeToLabel","word","camelToLabel","withSpaces","toPascalCase","tableName","toSlug","name","pascalToSnake","pascal","GQL_SCALAR_MAP","WELL_KNOWN_SCALARS","INTERNAL_SCALARS","buildScalarMap","customScalars","merged","key","value","SYNTHETIC_SUFFIXES","ROOT_TYPE_NAMES","defaultIsEntityType","typeName","type","suffix","fields","SKIP_FIELDS","defaultIsEntityField","fieldName","_field","_parentType","unwrapType","required","isList","current","isNonNullType","isListType","isNamedType","getConnectionNodeType","edgesField","edgesType","edgesIsList","isObjectType","nodeField","nodeType","classifyFieldType","field","entityTypes","options","namedType","scalarMap","base","isScalarType","candidateTypeName","template","isEnumType","v","connectionNodeTypeName","TableViewConfig","z","FieldOptions","FieldValidation","injectKind","data","obj","normalizeFieldKind","injected","INTROSPECTED_IDENTITY_PROPS","getPrimaryKeyField","f","flattenFields","result","getDisplayField","displayField","getRecordIdField","getRecordIdentity","record","pkField","candidates","createDoctypeFieldSchemas","ValueFieldSchema","TableFieldSchema","DoctypeFieldSchema","FieldsetFieldSchema","rawUnion","schemas","flattenAuthored","out","isRecord","describe","mergeIntrospectedDoctype","authored","generated","authoredFields","generatedByName","generatedLinkNames","drift","tag","match","prop","authoredValue","schemaValue","authoredNames","n","authoredPk","generatedPk","formatDoctypeDrift","lines","bucket","label","entries","convertGraphQLSchema","source","schema","buildGraphQLSchema","typeMap","rootTypeNames","queryType","mutationType","subscriptionType","isEntityType","filteredEntityTypes","includeSet","t","excludeSet","isEntityField","doctypes","isUnnormalizedPostGraphile","allClassifiedFields","custom","primaryKeyFieldname","links","convertedFields","identity","_graphqlType","_unmapped","_isLink","clean","rest","doctypeName","doctype","buildSchema","buildClientSchema","Cardinality","SyncFetch","LazyFetch","CustomFetch","FetchStrategy","LinkDeclaration","ActionDefinition","TriggerDefinition","isActionAllowedInState","action","currentState","allowedStates","WorkflowLayout","WorkflowMeta","DoctypeMeta","ctx","declared","named","LINK_DISPLAY_SUFFIX","linkDisplayFieldname","fieldname","validateField","issue","validateDoctype","parseField","parseDoctype"],"mappings":";;AAiBO,SAASA,GAAaC,GAA2B;AACvD,SAAOA,EAAU,QAAQ,aAAa,CAACC,GAAWC,MAAmBA,EAAO,aAAa;AAC1F;AAaO,SAASC,GAAaC,GAA2B;AACvD,SAAOA,EAAU,QAAQ,UAAU,CAAAF,MAAU,IAAIA,EAAO,YAAA,CAAa,EAAE;AACxE;AAaO,SAASG,GAAaL,GAA2B;AACvD,SAAOA,EACL,MAAM,GAAG,EACT,IAAI,CAAAM,MAAQA,EAAK,OAAO,CAAC,EAAE,gBAAgBA,EAAK,MAAM,CAAC,EAAE,aAAa,EACtE,KAAK,GAAG;AACX;AAaO,SAASC,EAAaH,GAA2B;AACv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