@murumets-ee/entity 0.2.1 → 0.3.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/cursor.ts","../../src/dto-shaper.ts","../../src/refs/errors.ts","../../src/refs/extract-refs.ts","../../src/refs/schema.ts","../../src/refs/find-usages.ts","../../src/validation.ts","../../src/admin/client.ts"],"sourcesContent":["/**\n * Cursor-based (keyset) pagination utilities.\n *\n * Cursor pagination avoids the performance cliff of OFFSET at scale (1M+ rows).\n * Instead of `OFFSET N`, it uses a WHERE condition:\n * `WHERE (sortField < lastValue) OR (sortField = lastValue AND id < lastId)`\n * which Postgres can serve from an index in constant time.\n *\n * The cursor is opaque to the client — base64-encoded JSON.\n *\n * Security:\n * - `field` must be whitelisted against the entity's actual fields\n * - `id` must be a valid UUID\n * - `value` is parameterized (never interpolated into SQL)\n * - Malformed cursors return null (caller returns 400)\n */\n\nimport { and, eq, gt, lt, or, type SQL } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Cursor input for keyset pagination. */\nexport interface CursorInput {\n /** Sort field name (e.g. 'createdAt'). Must be a real column on the entity. */\n field: string\n /** Last seen value of the sort field. */\n value: string | number\n /** Sort direction — must match the ORDER BY direction. */\n direction: 'asc' | 'desc'\n /** Tie-breaker: last seen entity ID. Required for non-unique sort fields. */\n id?: string\n}\n\n/** Decoded cursor (internal, after validation). */\ninterface DecodedCursor {\n field: string\n value: string | number\n direction: 'asc' | 'desc'\n id?: string\n}\n\n// ---------------------------------------------------------------------------\n// UUID validation (same format used throughout the toolkit)\n// ---------------------------------------------------------------------------\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n// ---------------------------------------------------------------------------\n// Encode / decode\n// ---------------------------------------------------------------------------\n\n/**\n * Encode a cursor for API transport (base64url).\n * Built from the last item in a result set.\n */\nexport function encodeCursor(\n item: Record<string, unknown>,\n sortField: string,\n direction: 'asc' | 'desc',\n): string {\n const payload: CursorInput = {\n field: sortField,\n value: item[sortField] as string | number,\n direction,\n id: item.id as string | undefined,\n }\n return btoa(JSON.stringify(payload))\n}\n\n/**\n * Decode and validate a cursor string from query params.\n * Returns null if the cursor is malformed, tampered, or invalid.\n *\n * Security: the `field` value is NOT validated here — the caller must\n * whitelist it against the entity's actual columns.\n */\nexport function decodeCursor(encoded: string): DecodedCursor | null {\n try {\n const json = atob(encoded)\n const parsed: unknown = JSON.parse(json)\n\n if (typeof parsed !== 'object' || parsed === null) return null\n const obj = parsed as Record<string, unknown>\n\n // Validate field\n if (typeof obj.field !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(obj.field)) {\n return null\n }\n\n // Validate value (string or number)\n if (typeof obj.value !== 'string' && typeof obj.value !== 'number') {\n return null\n }\n\n // Validate direction\n if (obj.direction !== 'asc' && obj.direction !== 'desc') {\n return null\n }\n\n // Validate id (optional, must be UUID if present)\n if (obj.id !== undefined) {\n if (typeof obj.id !== 'string' || !UUID_RE.test(obj.id)) {\n return null\n }\n }\n\n return {\n field: obj.field,\n value: obj.value,\n direction: obj.direction,\n id: obj.id as string | undefined,\n }\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// SQL condition builder\n// ---------------------------------------------------------------------------\n\n/**\n * Build the keyset WHERE condition from a decoded cursor.\n *\n * For DESC: `WHERE (field < value) OR (field = value AND id < cursorId)`\n * For ASC: `WHERE (field > value) OR (field = value AND id > cursorId)`\n *\n * The caller must verify that `cursor.field` exists on the table before calling.\n *\n * @param table - Drizzle table with columns\n * @param cursor - Decoded and validated cursor\n * @returns SQL condition, or null if the field doesn't exist on the table\n */\nexport function buildCursorCondition(\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any> for property access\n table: PgTableWithColumns<any>,\n cursor: DecodedCursor,\n): SQL | null {\n const column = table[cursor.field]\n if (!column) return null\n\n const isDesc = cursor.direction === 'desc'\n const compare = isDesc ? lt : gt\n\n // Primary condition: sort field passes the cursor value\n const fieldCondition = compare(column, cursor.value)\n\n // Without tie-breaker ID, use simple comparison\n if (!cursor.id) {\n return fieldCondition\n }\n\n // With tie-breaker: (field < value) OR (field = value AND id < cursorId)\n const idColumn = table.id\n if (!idColumn) return fieldCondition\n\n const idCondition = compare(idColumn, cursor.id)\n return or(fieldCondition, and(eq(column, cursor.value), idCondition))!\n}\n","/**\n * DTO Shaper\n * Transforms raw DB rows into clean DTOs.\n * All fields are real columns — just read from row directly.\n */\n\nimport type { Entity } from './define-entity.js'\nimport type { FieldConfig } from './fields/base.js'\nimport type { InferEntityDTO } from './types/infer.js'\n\nexport interface ShapeDtoOptions {\n select?: string[] // Explicit field selection\n includeInternal?: boolean // Include _version, _scopeId\n}\n\n/**\n * Shape a raw DB row into a typed DTO.\n * Every field is a real column — read directly from row.\n */\nexport function shapeDto<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n row: Record<string, unknown>,\n options?: ShapeDtoOptions,\n): InferEntityDTO<AllFields> | null {\n if (!row) return null\n\n const result: Record<string, unknown> = {}\n const fieldsToInclude = options?.select || Object.keys(entity.allFields)\n\n for (const fieldName of fieldsToInclude) {\n if (!options?.includeInternal && fieldName.startsWith('_')) continue\n\n const fieldConfig = (entity.allFields as Record<string, FieldConfig>)[fieldName]\n if (!fieldConfig) continue\n\n // Blocks are loaded separately from layout tables\n if (fieldConfig.type === 'blocks') continue\n\n result[fieldName] = row[fieldName]\n }\n\n return result as InferEntityDTO<AllFields>\n}\n\n/**\n * Shape multiple rows\n */\nexport function shapeDtos<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n rows: Record<string, unknown>[],\n options?: ShapeDtoOptions,\n): (InferEntityDTO<AllFields> | null)[] {\n return rows.map((row) => shapeDto(entity, row, options))\n}\n","/**\n * Error thrown when attempting to delete an entity that is still referenced.\n */\n\nimport type { EntityUsage } from './find-usages.js'\n\nexport class ReferencedEntityError extends Error {\n public readonly entityName: string\n public readonly entityId: string\n public readonly usages: EntityUsage[]\n\n constructor(entityName: string, entityId: string, usages: EntityUsage[]) {\n const count = usages.length\n super(\n `Cannot delete ${entityName} '${entityId}': referenced by ${count} other entit${count === 1 ? 'y' : 'ies'}`,\n )\n this.name = 'ReferencedEntityError'\n this.entityName = entityName\n this.entityId = entityId\n this.usages = usages\n }\n}\n","/**\n * Schema-aware reference extraction.\n *\n * Walks entity field definitions and data to find all outgoing references.\n * Handles:\n * - field.media() → target = 'media', single UUID\n * - field.reference() → target = config.entity, single UUID or UUID[]\n * - field.blocks() → inspects block instance data for media/reference fields\n */\n\nimport type { BlocksField, FieldConfig, ReferenceField } from '../fields/base.js'\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport interface ExtractedRef {\n sourceField: string\n targetEntity: string\n targetId: string\n}\n\n/**\n * Extract all outgoing references from entity data.\n *\n * @param allFields - The entity's complete field map (entity.allFields)\n * @param data - The entity data (full on create, partial on update)\n * @returns Deduplicated array of extracted references\n */\nexport function extractRefs(\n allFields: Record<string, FieldConfig>,\n data: Record<string, unknown>,\n): ExtractedRef[] {\n const refs: ExtractedRef[] = []\n const seen = new Set<string>()\n\n function add(sourceField: string, targetEntity: string, targetId: string) {\n if (!UUID_RE.test(targetId)) return\n const key = `${sourceField}|${targetEntity}|${targetId}`\n if (seen.has(key)) return\n seen.add(key)\n refs.push({ sourceField, targetEntity, targetId })\n }\n\n for (const [fieldName, config] of Object.entries(allFields)) {\n const value = data[fieldName]\n if (value == null) continue\n\n switch (config.type) {\n case 'media': {\n if (typeof value === 'string') {\n add(fieldName, 'media', value)\n }\n break\n }\n\n case 'reference': {\n const refConfig = config as ReferenceField\n if (refConfig.cardinality === 'many' && Array.isArray(value)) {\n for (const id of value) {\n if (typeof id === 'string') {\n add(fieldName, refConfig.entity, id)\n }\n }\n } else if (typeof value === 'string') {\n add(fieldName, refConfig.entity, value)\n }\n break\n }\n\n case 'blocks': {\n const blocksConfig = config as BlocksField\n if (!Array.isArray(value)) break\n\n for (const block of value) {\n const inst = block as Record<string, unknown>\n const blockType = inst._block as string | undefined\n if (!blockType) continue\n\n // Find the block definition to know its field types\n const blockDef = blocksConfig.blocks.find((b) => b.slug === blockType)\n if (!blockDef) continue\n\n // Scan block fields for media/reference values\n for (const [blockFieldName, blockFieldConfig] of Object.entries(blockDef.fields)) {\n const blockValue = inst[blockFieldName]\n if (blockValue == null) continue\n\n if (blockFieldConfig.type === 'media' && typeof blockValue === 'string') {\n add(fieldName, 'media', blockValue)\n }\n\n if (blockFieldConfig.type === 'reference') {\n const blockRefConfig = blockFieldConfig as ReferenceField\n if (blockRefConfig.cardinality === 'many' && Array.isArray(blockValue)) {\n for (const id of blockValue) {\n if (typeof id === 'string') {\n add(fieldName, blockRefConfig.entity, id)\n }\n }\n } else if (typeof blockValue === 'string') {\n add(fieldName, blockRefConfig.entity, blockValue)\n }\n }\n }\n }\n break\n }\n }\n }\n\n return refs\n}\n\n/**\n * Get the names of all ref-bearing fields in the entity.\n * Used to scope partial-update ref deletion.\n */\nexport function getRefBearingFields(allFields: Record<string, FieldConfig>): string[] {\n const names: string[] = []\n for (const [fieldName, config] of Object.entries(allFields)) {\n if (config.type === 'media' || config.type === 'reference' || config.type === 'blocks') {\n names.push(fieldName)\n }\n }\n return names\n}\n","/**\n * entity_refs — Universal reference tracking table.\n *\n * Every reference between entities (field.media(), field.reference(), block media fields)\n * gets a row here at write time. This enables:\n * - Instant \"where is this used?\" queries (one indexed lookup)\n * - Universal delete protection (can't delete referenced entities)\n * - Correct results (schema-aware, no LIKE text search)\n */\n\nimport { index, pgTable, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\nexport const entityRefs = pgTable(\n 'entity_refs',\n {\n sourceEntity: varchar('source_entity', { length: 100 }).notNull(),\n sourceId: uuid('source_id').notNull(),\n sourceField: varchar('source_field', { length: 100 }).notNull(),\n targetEntity: varchar('target_entity', { length: 100 }).notNull(),\n targetId: uuid('target_id').notNull(),\n },\n (t) => [\n unique('uq_entity_refs').on(\n t.sourceEntity,\n t.sourceId,\n t.sourceField,\n t.targetEntity,\n t.targetId,\n ),\n index('idx_entity_refs_target').on(t.targetEntity, t.targetId),\n index('idx_entity_refs_source').on(t.sourceEntity, t.sourceId),\n ],\n)\n","/**\n * Generic entity usage lookup — \"where is this entity referenced?\"\n *\n * One indexed query on entity_refs instead of scanning every table.\n */\n\nimport { and, eq } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport { entityRefs } from './schema.js'\n\nexport interface EntityUsage {\n sourceEntity: string\n sourceId: string\n sourceField: string\n}\n\n/**\n * Find all entities that reference a given entity.\n *\n * @param targetEntity - Entity type name (e.g. 'media', 'category')\n * @param targetId - UUID of the referenced entity\n * @param db - Database connection\n * @returns Array of usage records (empty if unreferenced)\n */\nexport async function findEntityUsages(\n targetEntity: string,\n targetId: string,\n db: PostgresJsDatabase,\n): Promise<EntityUsage[]> {\n const rows = await db\n .select({\n sourceEntity: entityRefs.sourceEntity,\n sourceId: entityRefs.sourceId,\n sourceField: entityRefs.sourceField,\n })\n .from(entityRefs)\n .where(and(eq(entityRefs.targetEntity, targetEntity), eq(entityRefs.targetId, targetId)))\n\n return rows\n}\n","/**\n * Validation schema generator\n * Converts entity field definitions to Zod schemas for runtime validation\n */\n\nimport { z } from 'zod'\nimport type { Entity } from './define-entity.js'\nimport type { FieldConfig } from './fields/base.js'\n\n/**\n * Convert a field definition to a Zod schema\n */\nfunction fieldToZod(fieldConfig: FieldConfig): z.ZodType {\n let schema: z.ZodType\n\n switch (fieldConfig.type) {\n case 'id':\n schema = z.string().uuid()\n break\n\n case 'text':\n schema = z.string()\n if (fieldConfig.maxLength) {\n schema = (schema as z.ZodString).max(fieldConfig.maxLength)\n }\n if (fieldConfig.minLength) {\n schema = (schema as z.ZodString).min(fieldConfig.minLength)\n }\n if (fieldConfig.pattern) {\n schema = (schema as z.ZodString).regex(fieldConfig.pattern)\n }\n break\n\n case 'number':\n schema = z.number()\n if (fieldConfig.integer) {\n schema = (schema as z.ZodNumber).int()\n }\n if (fieldConfig.min !== undefined) {\n schema = (schema as z.ZodNumber).min(fieldConfig.min)\n }\n if (fieldConfig.max !== undefined) {\n schema = (schema as z.ZodNumber).max(fieldConfig.max)\n }\n break\n\n case 'boolean':\n schema = z.boolean()\n break\n\n case 'date':\n schema = z.date().or(z.string().datetime())\n // Allow either Date object or ISO string, coerce to Date\n break\n\n case 'select':\n schema = z.enum(fieldConfig.options as [string, ...string[]])\n break\n\n case 'reference':\n if (fieldConfig.cardinality === 'many') {\n schema = z.array(z.string().uuid())\n } else {\n schema = z.string().uuid()\n }\n break\n\n case 'media':\n schema = z.string().uuid() // Media entity ID\n break\n\n case 'richtext':\n // HTML string (TipTap/Puck) or Slate JSON array (Plate/entity forms)\n schema = z.union([z.string(), z.array(z.record(z.unknown()))])\n break\n\n case 'slug':\n schema = z.string().regex(/^[a-z0-9-]+$/)\n break\n\n case 'json':\n schema = z.record(z.unknown())\n break\n\n case 'blocks':\n // Array of block instances with _block discriminator.\n // .passthrough() is required because each block type has different dynamic props\n // (title, image, content, etc.) that can't be validated generically here.\n // Per-block-type validation happens in the block editor's converter layer.\n // Security: extra props are harmless at storage level since rendering maps to\n // known component definitions and ignores unknown fields.\n schema = z.array(\n z\n .object({\n _block: z.string(),\n })\n .passthrough(),\n )\n break\n\n default:\n schema = z.unknown()\n }\n\n // Apply required/optional — non-required fields accept both undefined and null\n if (!fieldConfig.required) {\n schema = schema.nullable().optional()\n }\n\n // Apply default value\n if (fieldConfig.default !== undefined) {\n schema = schema.default(fieldConfig.default)\n }\n\n return schema\n}\n\n/**\n * Generate complete validation schema for an entity\n */\nexport function generateValidationSchema(entity: Entity): z.AnyZodObject {\n const shape: Record<string, z.ZodType> = {}\n\n for (const [fieldName, fieldConfig] of Object.entries(entity.allFields)) {\n shape[fieldName] = fieldToZod(fieldConfig)\n }\n\n return z.object(shape)\n}\n\n/**\n * Generate schema for entity creation (omit auto-generated fields)\n */\nexport function generateCreateSchema(entity: Entity): z.AnyZodObject {\n const shape: Record<string, z.ZodType> = {}\n\n // Fields to omit from create schema (auto-generated + server-set behavior fields)\n const omitFields = new Set(['id', 'createdAt', 'updatedAt', 'createdBy', '_version'])\n\n for (const [fieldName, fieldConfig] of Object.entries(entity.allFields)) {\n if (!omitFields.has(fieldName)) {\n shape[fieldName] = fieldToZod(fieldConfig)\n }\n }\n\n return z.object(shape)\n}\n\n/**\n * Generate schema for entity updates (all fields optional, omit immutable fields)\n */\nexport function generateUpdateSchema(entity: Entity): z.AnyZodObject {\n const shape: Record<string, z.ZodType> = {}\n\n // Fields to omit from update schema (immutable + server-set behavior fields)\n const omitFields = new Set(['id', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy', '_version'])\n\n for (const [fieldName, fieldConfig] of Object.entries(entity.allFields)) {\n if (!omitFields.has(fieldName)) {\n // All fields optional for updates\n const fieldSchema = fieldToZod(fieldConfig)\n shape[fieldName] = fieldSchema.optional()\n }\n }\n\n return z.object(shape)\n}\n","/**\n * AdminClient - Full CRUD with server-only enforcement\n * CRITICAL: This file MUST NOT be imported in client code\n */\n\n// NOTE: We use runtime check instead of 'server-only' import to allow CLI scripts\n// The 'server-only' package blocks ALL non-Next.js contexts (including Node.js scripts)\n// Layer 3: Runtime check (catches what bundlers miss, allows CLI usage)\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport type { CountCacheLike } from '../count-cache.js'\nimport type { CursorInput } from '../cursor.js'\nimport { buildCursorCondition } from '../cursor.js'\nimport type { Entity } from '../define-entity.js'\nimport { shapeDto, shapeDtos } from '../dto-shaper.js'\nimport type { FieldConfig } from '../fields/base.js'\nimport { ReferencedEntityError } from '../refs/errors.js'\nimport { extractRefs } from '../refs/extract-refs.js'\nimport { findEntityUsages } from '../refs/find-usages.js'\nimport { entityRefs } from '../refs/schema.js'\nimport type { InferCreateInput, InferEntityDTO, InferUpdateInput } from '../types/infer.js'\nimport type { Logger } from '../types/logger.js'\nimport { generateCreateSchema, generateUpdateSchema } from '../validation.js'\n\nexport interface AdminClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n entity: Entity<AllFields>\n db: PostgresJsDatabase\n logger?: Logger\n /** Optional count cache for COUNT(*) query optimization. */\n countCache?: CountCacheLike\n}\n\nexport interface FindManyOptions {\n where?: SQL | undefined\n limit?: number\n offset?: number\n orderBy?: SQL | SQL[]\n locale?: string\n /** Default content locale. For localized blocks, NULL rows (from initial create)\n * are only returned as fallback when locale matches defaultLocale. */\n defaultLocale?: string\n /**\n * Cursor-based (keyset) pagination. When provided, replaces OFFSET with a\n * WHERE condition for O(1) page access at any depth. The `offset` option\n * is ignored when `cursor` is set.\n *\n * The cursor `field` must be a real column on the entity table.\n */\n cursor?: CursorInput\n}\n\nexport interface CountOptions {\n where?: SQL | undefined\n}\n\n/**\n * AdminClient - Full CRUD operations with security enforcement\n *\n * Security layers:\n * 1. Runtime check: typeof window !== 'undefined' → throw (allows CLI scripts)\n * 2. Uses read-write DB connection\n * 3. Validation with Zod before every write\n * 4. Hook execution (beforeCreate, afterCreate, etc.)\n *\n * Note: We don't use 'server-only' import because it blocks CLI scripts.\n * Next.js bundler protection comes from subpath exports (@murumets-ee/core/clients).\n *\n * Phase 1: Core CRUD + hooks + validation\n * Phase 2 (TODO): Access control, request context, scoping\n *\n * @typeParam AllFields - The entity's complete field map. Inferred automatically\n * when constructing via `createAdminClient(entity)`.\n */\nexport class AdminClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private entity: Entity<AllFields>\n private db: PostgresJsDatabase\n private logger?: Logger\n private createSchema: ZodType\n private updateSchema: ZodType\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any> for property access\n private table: PgTableWithColumns<any>\n private countCache?: CountCacheLike\n\n constructor(config: AdminClientConfig<AllFields>) {\n // Runtime enforcement: prevent usage in browser contexts\n if (typeof window !== 'undefined') {\n throw new Error(\n 'AdminClient cannot be used in browser code. ' +\n 'Use QueryClient for frontend data access.',\n )\n }\n\n this.entity = config.entity\n this.db = config.db\n this.logger = config.logger\n this.countCache = config.countCache\n\n // Pre-generate validation schemas for performance\n this.createSchema = generateCreateSchema(config.entity)\n this.updateSchema = generateUpdateSchema(config.entity)\n\n // Get table from schema registry\n const table = schemaRegistry.get(config.entity.name)\n if (!table) {\n throw new Error(\n `Schema for entity '${config.entity.name}' not found in registry. ` +\n 'Ensure schemas are generated and registered before creating AdminClient.',\n )\n }\n this.table = table\n }\n\n /**\n * Create a new entity\n *\n * Flow:\n * 1. Validate input with Zod\n * 2. Execute beforeCreate hooks\n * 3. Prepare data for insert\n * 4. Insert into database\n * 5. Execute afterCreate hooks\n * 6. Shape DTO and return\n */\n async create(data: InferCreateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n this.logger?.info({ entity: this.entity.name }, 'Creating entity')\n\n // TODO (Phase 2): Access control check\n // const ctx = getRequestContext()\n // if (!hasAccess(ctx.user, this.entity.access.create)) {\n // throw new ForbiddenError('User not authorized to create this entity')\n // }\n\n // Execute beforeCreate hooks BEFORE validation — hooks may populate required fields\n let dataToInsert = data as Record<string, unknown>\n if (this.entity.hooks?.beforeCreate) {\n const hookResult = await this.entity.hooks.beforeCreate(dataToInsert)\n dataToInsert = hookResult !== undefined ? hookResult : dataToInsert\n }\n\n // Preserve server-set fields that hooks added but createSchema omits\n // (e.g. createdAt/updatedAt from timestamped(), createdBy/updatedBy from auditable())\n const serverFields: Record<string, unknown> = {}\n for (const key of ['createdAt', 'updatedAt', 'createdBy', 'updatedBy']) {\n if (dataToInsert[key] !== undefined) serverFields[key] = dataToInsert[key]\n }\n\n // Validate after hooks (hooks may add required fields like senderEmail)\n dataToInsert = { ...this.createSchema.parse(dataToInsert), ...serverFields }\n\n // TODO (Phase 2): Add scope if entity is scoped\n // if (this.entity.scope === 'team' || this.entity.scope === 'user') {\n // const ctx = getRequestContext()\n // dataToInsert._scopeId = ctx.scopeId\n // }\n\n // Prepare data for insert\n const columns = this.prepareDataForInsert(dataToInsert)\n\n // Insert into database\n const [row] = await this.db.insert(this.table).values(columns).returning()\n\n // Save blocks to layout table\n await this.saveBlocks(row.id, dataToInsert)\n\n // Track outgoing references (entity_refs)\n await this.syncRefs(row.id as string, dataToInsert, 'create')\n\n // Execute afterCreate hooks\n if (this.entity.hooks?.afterCreate) {\n await this.entity.hooks.afterCreate(row)\n }\n\n // Invalidate count cache after creation\n this.invalidateCountCache()\n\n // Shape DTO and attach blocks\n const shaped = shapeDto(this.entity, row) as Record<string, unknown>\n if (shaped && this.getBlocksFields().length > 0) {\n const blocksMap = await this.loadBlocks([shaped.id as string])\n this.attachBlocks([shaped], blocksMap)\n }\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Find entity by ID\n */\n async findById(\n id: string,\n options?: { locale?: string; defaultLocale?: string },\n ): Promise<InferEntityDTO<AllFields> | null> {\n this.logger?.info({ entity: this.entity.name, id }, 'Finding entity by ID')\n\n // TODO (Phase 2): Access control check\n // const ctx = getRequestContext()\n // if (!hasAccess(ctx.user, this.entity.access.view)) {\n // throw new ForbiddenError('User not authorized to view this entity')\n // }\n\n // Query database\n const [row] = await this.db.select().from(this.table).where(eq(this.table.id, id))\n\n if (!row) return null\n\n // TODO (Phase 2): Scope check\n // if (this.entity.scope !== 'global') {\n // const ctx = getRequestContext()\n // if (row._scopeId !== ctx.scopeId) {\n // return null // Not in user's scope\n // }\n // }\n\n const shaped = shapeDto(this.entity, row) as Record<string, unknown>\n if (!shaped) return null\n\n // Attach blocks from layout table (with locale for block translations)\n if (this.getBlocksFields().length > 0) {\n const blocksMap = await this.loadBlocks([shaped.id as string], options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n this.attachBlocks([shaped], blocksMap)\n }\n\n if (options?.locale) {\n const [merged] = await this.mergeTranslations([shaped], options.locale)\n return merged as InferEntityDTO<AllFields>\n }\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Find multiple entities\n */\n async findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n this.logger?.info({ entity: this.entity.name, options }, 'Finding entities')\n\n // TODO (Phase 2): Access control check\n // const ctx = getRequestContext()\n // if (!hasAccess(ctx.user, this.entity.access.view)) {\n // throw new ForbiddenError('User not authorized to view this entity')\n // }\n\n // Build and execute query\n // TODO (Phase 2): Add scope filter\n let query = this.db.select().from(this.table).$dynamic()\n\n // Collect WHERE conditions\n const conditions: SQL[] = []\n\n if (options?.where) {\n conditions.push(options.where)\n }\n\n // Cursor-based pagination: add keyset WHERE condition (replaces OFFSET)\n if (options?.cursor) {\n // Whitelist: cursor field must be a real column on the entity\n const allFields = this.entity.allFields as Record<string, FieldConfig>\n if (!(options.cursor.field in allFields) && options.cursor.field !== 'id') {\n throw new Error(\n `Invalid cursor field: '${options.cursor.field}' is not a field on '${this.entity.name}'`,\n )\n }\n const cursorCondition = buildCursorCondition(this.table, options.cursor)\n if (cursorCondition) {\n conditions.push(cursorCondition)\n }\n }\n\n if (conditions.length > 0) {\n query = query.where(and(...conditions))\n }\n\n if (options?.limit) {\n query = query.limit(options.limit)\n }\n // Cursor takes precedence over offset — skip offset when cursor is active\n if (options?.offset && !options?.cursor) {\n query = query.offset(options.offset)\n }\n if (options?.orderBy) {\n const cols = Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy]\n query = query.orderBy(...cols)\n }\n\n const rows = await query\n\n const shaped = shapeDtos(this.entity, rows).filter(\n (e): e is NonNullable<typeof e> => e !== null,\n ) as Record<string, unknown>[]\n\n // Attach blocks from layout table (with locale for block translations)\n if (this.getBlocksFields().length > 0 && shaped.length > 0) {\n const entityIds = shaped.map((e) => e.id as string)\n const blocksMap = await this.loadBlocks(entityIds, options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n this.attachBlocks(shaped, blocksMap)\n }\n\n if (options?.locale) {\n return (await this.mergeTranslations(shaped, options.locale)) as InferEntityDTO<AllFields>[]\n }\n\n return shaped as InferEntityDTO<AllFields>[]\n }\n\n /**\n * Count entities matching optional conditions\n */\n async count(options?: CountOptions): Promise<number> {\n this.logger?.info({ entity: this.entity.name, options }, 'Counting entities')\n\n // Build cache key: entityName + serialized WHERE (or empty for unfiltered)\n const cacheKey = this.buildCountCacheKey(options?.where)\n if (this.countCache) {\n const cached = this.countCache.get(cacheKey)\n if (cached !== undefined) {\n this.logger?.debug?.({ entity: this.entity.name, cached }, 'Count cache hit')\n return cached\n }\n }\n\n let query = this.db.select({ count: sql<number>`count(*)` }).from(this.table).$dynamic()\n\n if (options?.where) {\n query = query.where(options.where)\n }\n\n const [result] = await query\n const count = Number(result.count)\n\n // Cache the result\n if (this.countCache) {\n this.countCache.set(cacheKey, count)\n }\n\n return count\n }\n\n /**\n * Update entity by ID\n *\n * Flow:\n * 1. Validate input with Zod\n * 2. Execute beforeUpdate hooks\n * 3. Prepare data for update\n * 4. Update in database\n * 5. Execute afterUpdate hooks\n * 6. Shape DTO and return\n */\n async update(\n id: string,\n data: InferUpdateInput<AllFields>,\n options?: { locale?: string },\n ): Promise<InferEntityDTO<AllFields>> {\n this.logger?.info({ entity: this.entity.name, id }, 'Updating entity')\n\n // TODO (Phase 2): Access control check\n // const ctx = getRequestContext()\n // if (!hasAccess(ctx.user, this.entity.access.update)) {\n // throw new ForbiddenError('User not authorized to update this entity')\n // }\n\n // Execute beforeUpdate hooks BEFORE validation — hooks may modify fields\n let dataToUpdate = data as Record<string, unknown>\n if (this.entity.hooks?.beforeUpdate) {\n const hookResult = await this.entity.hooks.beforeUpdate(id, dataToUpdate)\n dataToUpdate = hookResult !== undefined ? hookResult : dataToUpdate\n }\n\n // Validate after hooks\n dataToUpdate = this.updateSchema.parse(dataToUpdate)\n\n // Prepare data for update\n const columns = this.prepareDataForUpdate(dataToUpdate)\n\n // Update in database (only if there are non-blocks fields to update)\n let row: Record<string, unknown>\n if (Object.keys(columns).length > 0) {\n const [updated] = await this.db\n .update(this.table)\n .set(columns)\n .where(eq(this.table.id, id))\n .returning()\n row = updated\n } else {\n // Only blocks changed — fetch current row\n const [current] = await this.db.select().from(this.table).where(eq(this.table.id, id))\n row = current\n }\n\n // Update blocks in layout table (thread locale for per-locale blocks)\n await this.saveBlocks(id, dataToUpdate, options)\n\n // Update outgoing references (entity_refs) — only for changed fields\n await this.syncRefs(id, dataToUpdate, 'update')\n\n // Execute afterUpdate hooks\n if (this.entity.hooks?.afterUpdate) {\n await this.entity.hooks.afterUpdate(row)\n }\n\n // Shape DTO and attach blocks\n const shaped = shapeDto(this.entity, row) as Record<string, unknown>\n if (shaped && this.getBlocksFields().length > 0) {\n const blocksMap = await this.loadBlocks([id])\n this.attachBlocks([shaped], blocksMap)\n }\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Delete entity by ID.\n *\n * Checks entity_refs for incoming references first — throws\n * ReferencedEntityError if this entity is still used somewhere.\n */\n async delete(id: string): Promise<void> {\n this.logger?.info({ entity: this.entity.name, id }, 'Deleting entity')\n\n // TODO (Phase 2): Access control check\n // const ctx = getRequestContext()\n // if (!hasAccess(ctx.user, this.entity.access.delete)) {\n // throw new ForbiddenError('User not authorized to delete this entity')\n // }\n\n // Check for incoming references — prevent deleting entities in use\n const usages = await findEntityUsages(this.entity.name, id, this.db)\n if (usages.length > 0) {\n throw new ReferencedEntityError(this.entity.name, id, usages)\n }\n\n // Execute beforeDelete hooks\n if (this.entity.hooks?.beforeDelete) {\n await this.entity.hooks.beforeDelete(id)\n }\n\n // Delete from database\n await this.db.delete(this.table).where(eq(this.table.id, id))\n\n // Clean up outgoing references from entity_refs\n await this.db\n .delete(entityRefs)\n .where(and(eq(entityRefs.sourceEntity, this.entity.name), eq(entityRefs.sourceId, id)))\n\n // Execute afterDelete hooks\n if (this.entity.hooks?.afterDelete) {\n await this.entity.hooks.afterDelete(id)\n }\n\n // Invalidate count cache after deletion\n this.invalidateCountCache()\n }\n\n /**\n * Prepare data for insert — every field is a real column.\n */\n private prepareDataForInsert(data: Record<string, unknown>): Record<string, unknown> {\n const columns: Record<string, unknown> = {}\n\n for (const [fieldName, value] of Object.entries(data)) {\n const fieldConfig = (this.entity.allFields as Record<string, FieldConfig>)[fieldName]\n if (!fieldConfig) continue\n if (fieldName === 'id') continue\n if (fieldConfig.type === 'blocks') continue\n columns[fieldName] = value\n }\n\n return columns\n }\n\n /**\n * Prepare data for update — every field is a real column.\n * Standard column SET, no JSONB merge needed.\n */\n private prepareDataForUpdate(data: Record<string, unknown>): Record<string, unknown> {\n const columns: Record<string, unknown> = {}\n\n for (const [fieldName, value] of Object.entries(data)) {\n const fieldConfig = (this.entity.allFields as Record<string, FieldConfig>)[fieldName]\n if (!fieldConfig) continue\n if (fieldName === 'id') continue\n if (fieldConfig.type === 'blocks') continue\n columns[fieldName] = value\n }\n\n return columns\n }\n\n /**\n * Merge translations into entities for the specified locale.\n * Reads translatable field values from real columns on the translation row.\n */\n private async mergeTranslations<T extends Record<string, unknown>>(\n entities: T[],\n locale: string,\n ): Promise<T[]> {\n if (!entities.length) return entities\n\n const translationTableName = `${this.entity.name}_translations`\n const translationTable = schemaRegistry.get(translationTableName)\n\n if (!translationTable) return entities\n\n const entityIds = entities.map((e) => e.id)\n\n const translations = await this.db\n .select()\n .from(translationTable)\n .where(\n and(inArray(translationTable.entityId, entityIds), eq(translationTable.locale, locale)),\n )\n\n // Get translatable field names\n const translatableFields = Object.entries(this.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, config]) => config.translatable)\n .map(([name]) => name)\n\n const translationMap = new Map<unknown, Record<string, unknown>>()\n for (const translation of translations) {\n const translatedValues: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n const value = (translation as Record<string, unknown>)[fieldName]\n if (value !== undefined && value !== null) {\n translatedValues[fieldName] = value\n }\n }\n translationMap.set(translation.entityId, translatedValues)\n }\n\n return entities.map((entity) => {\n const translatedFields = translationMap.get(entity.id)\n if (!translatedFields) return entity\n return { ...entity, ...translatedFields }\n })\n }\n\n /**\n * Save translation for an entity.\n * Each translatable field is a real column on the translation table.\n */\n async saveTranslation(\n entityId: string,\n locale: string,\n translations: Record<string, unknown>,\n ): Promise<void> {\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Saving translation')\n\n const translationTableName = `${this.entity.name}_translations`\n const translationTable = schemaRegistry.get(translationTableName)\n\n if (!translationTable) {\n throw new Error(`Translation table ${translationTableName} not found in schema registry`)\n }\n\n // Get translatable field names\n const translatableFields = Object.entries(this.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, config]) => config.translatable)\n .map(([name]) => name)\n\n if (translatableFields.length === 0) {\n throw new Error(`Entity ${this.entity.name} has no translatable fields`)\n }\n\n // Extract only translatable fields — these are real columns on the translation table\n const translationData: Record<string, unknown> = { entityId, locale }\n const updateData: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n if (translations[fieldName] !== undefined) {\n translationData[fieldName] = translations[fieldName]\n updateData[fieldName] = translations[fieldName]\n }\n }\n\n // Upsert: insert or update on conflict\n await this.db\n .insert(translationTable)\n .values(translationData)\n .onConflictDoUpdate({\n target: [translationTable.entityId, translationTable.locale],\n set: updateData,\n })\n\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Translation saved')\n }\n\n /**\n * PHASE 3: Delete translation(s) for an entity\n * If locale is provided, deletes specific locale; otherwise deletes all translations\n */\n async deleteTranslation(entityId: string, locale?: string): Promise<void> {\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Deleting translation')\n\n const translationTableName = `${this.entity.name}_translations`\n const translationTable = schemaRegistry.get(translationTableName)\n\n if (!translationTable) {\n throw new Error(`Translation table ${translationTableName} not found in schema registry`)\n }\n\n if (locale) {\n // Delete specific locale\n await this.db\n .delete(translationTable)\n .where(and(eq(translationTable.entityId, entityId), eq(translationTable.locale, locale)))\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Translation deleted')\n } else {\n // Delete all translations for entity\n await this.db.delete(translationTable).where(eq(translationTable.entityId, entityId))\n this.logger?.info({ entity: this.entity.name, entityId }, 'All translations deleted')\n }\n }\n\n /**\n * Save block-level translations for an entity.\n * For each block in each blocks field, extracts translatable field values\n * and upserts them into {entity}_layout_translations.\n *\n * Block _id must match an existing layout row ID.\n */\n async saveBlockTranslations(\n entityId: string,\n locale: string,\n data: Record<string, unknown>,\n ): Promise<void> {\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Saving block translations')\n\n const blocksFields = this.getBlocksFields()\n if (blocksFields.length === 0) return\n\n const layoutTransTable = schemaRegistry.get(`${this.entity.name}_layout_translations`)\n if (!layoutTransTable) return\n\n const layoutTable = schemaRegistry.get(`${this.entity.name}_layout`)\n if (!layoutTable) return\n\n for (const { name: fieldName, config } of blocksFields) {\n const blocks = data[fieldName]\n if (!Array.isArray(blocks)) continue\n\n // Get block definitions to identify translatable fields\n // biome-ignore lint/suspicious/noExplicitAny: blocks property exists on blocks-type FieldConfig but isn't in the base FieldConfig type\n const blockDefs = (config as any).blocks as\n | Array<{ slug: string; fields: Record<string, FieldConfig> }>\n | undefined\n if (!blockDefs) continue\n\n // Load actual layout row IDs from DB (ordered by sort_order to match request array order).\n // The _id from the request may be a Puck-generated ID (e.g. \"hero-abc123\") rather than\n // the real DB UUID, so we match by position instead.\n const layoutRows = await this.db\n .select({ id: layoutTable.id, blockType: layoutTable.blockType })\n .from(layoutTable)\n .where(\n and(\n eq(layoutTable.entityId, entityId),\n eq(layoutTable.fieldName, fieldName),\n isNull(layoutTable.locale),\n ),\n )\n .orderBy(layoutTable.sortOrder)\n\n for (let i = 0; i < (blocks as Record<string, unknown>[]).length; i++) {\n const block = (blocks as Record<string, unknown>[])[i]\n const blockType = block._block as string\n if (!blockType) continue\n\n // Match by position — layout rows and request blocks are in the same sort order\n const layoutRow = layoutRows[i]\n if (!layoutRow || layoutRow.blockType !== blockType) continue\n\n const blockDef = blockDefs.find((b) => b.slug === blockType)\n if (!blockDef) continue\n\n // Extract only translatable fields\n const translatedFields: Record<string, unknown> = {}\n for (const [fname, fconfig] of Object.entries(blockDef.fields)) {\n if (fconfig.translatable && block[fname] !== undefined) {\n translatedFields[fname] = block[fname]\n }\n }\n\n if (Object.keys(translatedFields).length === 0) continue\n\n // Upsert using the real DB layout row ID\n await this.db\n .insert(layoutTransTable)\n .values({ layoutId: layoutRow.id, locale, fields: translatedFields })\n .onConflictDoUpdate({\n target: [layoutTransTable.layoutId, layoutTransTable.locale],\n set: { fields: translatedFields },\n })\n }\n }\n\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Block translations saved')\n }\n\n /**\n * Save per-locale blocks for an entity.\n * Used for entities with `localized: true` on their blocks field — each locale gets\n * its own independent block layout rows in the layout table.\n */\n async saveLocalizedBlocks(\n entityId: string,\n locale: string,\n data: Record<string, unknown>,\n ): Promise<void> {\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Saving localized blocks')\n await this.saveBlocks(entityId, data, { locale })\n }\n\n // ---------------------------------------------------------------\n // Block CRUD (layout table operations)\n // ---------------------------------------------------------------\n\n /**\n * Get all blocks field names for this entity.\n */\n private getBlocksFields(): Array<{ name: string; config: FieldConfig }> {\n return Object.entries(this.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, config]) => config.type === 'blocks')\n .map(([name, config]) => ({ name, config }))\n }\n\n /**\n * Save blocks for an entity after create/update.\n * For each blocks field, writes rows to {entity}_layout table.\n */\n private async saveBlocks(\n entityId: string,\n data: Record<string, unknown>,\n options?: { locale?: string },\n ): Promise<void> {\n const blocksFields = this.getBlocksFields()\n if (blocksFields.length === 0) return\n\n const layoutTable = schemaRegistry.get(`${this.entity.name}_layout`)\n if (!layoutTable) return\n\n for (const { name: fieldName, config } of blocksFields) {\n const blocks = data[fieldName]\n if (!Array.isArray(blocks)) continue\n\n const isLocalized = 'localized' in config && config.localized === true\n const locale = isLocalized ? (options?.locale ?? null) : null\n\n // Delete existing layout rows for this field + locale\n const deleteConditions = [\n eq(layoutTable.entityId, entityId),\n eq(layoutTable.fieldName, fieldName),\n ]\n if (locale) {\n deleteConditions.push(eq(layoutTable.locale, locale))\n } else if (!isLocalized) {\n // For shared layout, delete rows where locale IS NULL\n deleteConditions.push(isNull(layoutTable.locale))\n }\n await this.db.delete(layoutTable).where(and(...deleteConditions))\n\n // Insert new layout rows\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i] as Record<string, unknown>\n const blockType = block._block as string\n if (!blockType) continue\n\n // Separate _block and _id from block data\n const { _block, _id, ...blockData } = block\n\n await this.db.insert(layoutTable).values({\n entityId,\n fieldName,\n blockType,\n sortOrder: i,\n data: blockData,\n locale,\n })\n }\n }\n }\n\n /**\n * Load blocks for one or more entities from the layout table.\n *\n * Handles both block translation modes:\n * - Shared layout (localized: false): loads locale=NULL rows, merges translations,\n * clears untranslated translatable fields to '' (strict mode for admin editing)\n * - Per-locale layout (localized: true): loads rows matching the provided locale only\n *\n * @param entityIds - Entity IDs to load blocks for\n * @param locale - Content locale (omit for default locale / base data)\n * @param options.defaultLocale - Default locale; NULL rows fall back only for this locale\n */\n private async loadBlocks(\n entityIds: string[],\n locale?: string,\n options?: { defaultLocale?: string },\n ): Promise<Map<string, Record<string, unknown[]>>> {\n const blocksFields = this.getBlocksFields()\n if (blocksFields.length === 0 || entityIds.length === 0) {\n return new Map()\n }\n\n const layoutTable = schemaRegistry.get(`${this.entity.name}_layout`)\n if (!layoutTable) return new Map()\n\n // Determine block field modes\n const sharedFields = blocksFields.filter(\n ({ config }) => !('localized' in config && config.localized),\n )\n const localizedFields = blocksFields.filter(\n ({ config }) => 'localized' in config && config.localized,\n )\n\n const result = new Map<string, Record<string, unknown[]>>()\n\n // ---- Shared blocks: locale IS NULL, translations from layout_translations ----\n if (sharedFields.length > 0) {\n const rows = await this.db\n .select()\n .from(layoutTable)\n .where(and(inArray(layoutTable.entityId, entityIds), isNull(layoutTable.locale)))\n .orderBy(layoutTable.sortOrder)\n\n // Load translations if locale provided\n let blockTransMap: Map<string, Record<string, unknown>> | undefined\n if (locale && rows.length > 0) {\n const layoutTransTable = schemaRegistry.get(`${this.entity.name}_layout_translations`)\n if (layoutTransTable) {\n const layoutIds = rows.map((r) => r.id as string)\n const translations = await this.db\n .select()\n .from(layoutTransTable)\n .where(\n and(\n inArray(layoutTransTable.layoutId, layoutIds),\n eq(layoutTransTable.locale, locale),\n ),\n )\n\n blockTransMap = new Map()\n for (const t of translations) {\n blockTransMap.set(t.layoutId as string, (t.fields as Record<string, unknown>) ?? {})\n }\n }\n }\n\n // Build block definition lookup for translatable field clearing\n const blockDefMap = new Map<string, Record<string, FieldConfig>>()\n for (const { config } of sharedFields) {\n // biome-ignore lint/suspicious/noExplicitAny: blocks property exists on blocks-type FieldConfig\n const blockDefs = (config as any).blocks as\n | Array<{ slug: string; fields: Record<string, FieldConfig> }>\n | undefined\n if (blockDefs) {\n for (const def of blockDefs) {\n blockDefMap.set(def.slug, def.fields)\n }\n }\n }\n\n for (const row of rows) {\n const eid = row.entityId as string\n const fname = row.fieldName as string\n\n if (!result.has(eid)) result.set(eid, {})\n const entityBlocks = result.get(eid)!\n if (!entityBlocks[fname]) entityBlocks[fname] = []\n\n const blockData = (row.data as Record<string, unknown>) ?? {}\n const translatedFields = blockTransMap?.get(row.id as string)\n\n // Build the block object\n const block: Record<string, unknown> = {\n _block: row.blockType,\n _id: row.id,\n ...blockData,\n ...(translatedFields ?? {}),\n }\n\n // Strict mode: clear untranslated translatable fields when loading for non-default locale\n if (locale) {\n const blockType = row.blockType as string\n const fieldDefs = blockDefMap.get(blockType)\n if (fieldDefs) {\n for (const [fieldName, fieldConfig] of Object.entries(fieldDefs)) {\n if (fieldConfig.translatable && !translatedFields?.[fieldName]) {\n block[fieldName] = ''\n }\n }\n }\n }\n\n entityBlocks[fname].push(block)\n }\n }\n\n // ---- Localized blocks: filter by locale column ----\n // NULL rows (from initial create) only fall back for the default locale.\n // Non-default locales without locale-specific rows get an empty array.\n if (localizedFields.length > 0) {\n const isDefault = !locale || locale === options?.defaultLocale\n const localeCondition = locale\n ? isDefault\n ? or(eq(layoutTable.locale, locale), isNull(layoutTable.locale))!\n : eq(layoutTable.locale, locale)\n : isNull(layoutTable.locale)\n\n const rows = await this.db\n .select()\n .from(layoutTable)\n .where(and(inArray(layoutTable.entityId, entityIds), localeCondition))\n .orderBy(layoutTable.sortOrder)\n\n // Group by entityId + fieldName, prefer locale-specific rows over NULL\n const grouped = new Map<string, { localeRows: typeof rows; nullRows: typeof rows }>()\n for (const row of rows) {\n const key = `${row.entityId}::${row.fieldName}`\n if (!grouped.has(key)) grouped.set(key, { localeRows: [], nullRows: [] })\n const group = grouped.get(key)!\n if (row.locale) {\n group.localeRows.push(row)\n } else {\n group.nullRows.push(row)\n }\n }\n\n for (const [, { localeRows, nullRows }] of grouped) {\n // Use locale-specific rows if available, otherwise fall back to NULL\n const effective = localeRows.length > 0 ? localeRows : nullRows\n\n for (const row of effective) {\n const eid = row.entityId as string\n const fname = row.fieldName as string\n\n if (!result.has(eid)) result.set(eid, {})\n const entityBlocks = result.get(eid)!\n if (!entityBlocks[fname]) entityBlocks[fname] = []\n\n const blockData = (row.data as Record<string, unknown>) ?? {}\n\n entityBlocks[fname].push({\n _block: row.blockType,\n _id: row.id,\n ...blockData,\n })\n }\n }\n }\n\n return result\n }\n\n /**\n * Attach loaded blocks to shaped DTOs.\n */\n private attachBlocks(\n entities: Record<string, unknown>[],\n blocksMap: Map<string, Record<string, unknown[]>>,\n ): void {\n const blocksFields = this.getBlocksFields()\n if (blocksFields.length === 0) return\n\n for (const entity of entities) {\n const eid = entity.id as string\n const entityBlocks = blocksMap.get(eid) ?? {}\n\n for (const { name } of blocksFields) {\n entity[name] = entityBlocks[name] ?? []\n }\n }\n }\n\n // ---------------------------------------------------------------\n // Reference tracking (entity_refs)\n // ---------------------------------------------------------------\n\n /**\n * Sync outgoing references in entity_refs after create/update.\n *\n * - 'create': inserts all refs (entity is new, no existing refs)\n * - 'update': deletes refs for changed ref-bearing fields, then inserts new ones\n *\n * Gracefully skips if entity_refs table is not registered (e.g. before migration).\n */\n private async syncRefs(\n entityId: string,\n data: Record<string, unknown>,\n mode: 'create' | 'update',\n ): Promise<void> {\n // Graceful degradation: skip if entity_refs table doesn't exist yet\n if (!schemaRegistry.has('entity_refs')) return\n\n const allFields = this.entity.allFields as Record<string, FieldConfig>\n\n if (mode === 'update') {\n // Only delete refs for fields present in the update data\n const changedRefFields = Object.keys(data).filter((k) => {\n const config = allFields[k]\n return (\n config &&\n (config.type === 'media' || config.type === 'reference' || config.type === 'blocks')\n )\n })\n if (changedRefFields.length > 0) {\n await this.db\n .delete(entityRefs)\n .where(\n and(\n eq(entityRefs.sourceEntity, this.entity.name),\n eq(entityRefs.sourceId, entityId),\n inArray(entityRefs.sourceField, changedRefFields),\n ),\n )\n }\n }\n\n // Extract refs from the data and insert\n const refs = extractRefs(allFields, data)\n if (refs.length > 0) {\n await this.db\n .insert(entityRefs)\n .values(\n refs.map((ref) => ({\n sourceEntity: this.entity.name,\n sourceId: entityId,\n sourceField: ref.sourceField,\n targetEntity: ref.targetEntity,\n targetId: ref.targetId,\n })),\n )\n .onConflictDoNothing()\n }\n }\n\n // ---------------------------------------------------------------\n // Count cache helpers\n // ---------------------------------------------------------------\n\n /**\n * Build a cache key for a count query.\n * Key format: `entityName` for unfiltered, `entityName:where_sql` for filtered.\n */\n private buildCountCacheKey(where?: SQL): string {\n if (!where) return this.entity.name\n // Use SQL's toString() representation as a stable key.\n // This is a display string, not executed — safe for cache keying.\n return `${this.entity.name}:${String(where)}`\n }\n\n /**\n * Invalidate all count cache entries for this entity.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OAAO,EAAW,CAClB,MACC,EACE,EAAG,EAAW,aAAc,KAAK,OAAO,KAAK,CAC7C,EAAG,EAAW,SAAU,EAAS,CACjC,EAAQ,EAAW,YAAa,EAAiB,CAClD,CACF,CAKP,IAAM,EAAO,EAAY,EAAW,EAAK,CACrC,EAAK,OAAS,GAChB,MAAM,KAAK,GACR,OAAO,EAAW,CAClB,OACC,EAAK,IAAK,IAAS,CACjB,aAAc,KAAK,OAAO,KAC1B,SAAU,EACV,YAAa,EAAI,YACjB,aAAc,EAAI,aAClB,SAAU,EAAI,SACf,EAAE,CACJ,CACA,qBAAqB,CAY5B,mBAA2B,EAAqB,CAI9C,OAHK,EAGE,GAAG,KAAK,OAAO,KAAK,GAAG,OAAO,EAAM,GAHxB,KAAK,OAAO,KASjC,sBAAqC,CACnC,KAAK,YAAY,WAAW,KAAK,OAAO,KAAK"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/cursor.ts","../../src/dto-shaper.ts","../../src/refs/errors.ts","../../src/refs/extract-refs.ts","../../src/refs/schema.ts","../../src/validation.ts","../../src/admin/client.ts"],"sourcesContent":["/**\n * Cursor-based (keyset) pagination utilities.\n *\n * Cursor pagination avoids the performance cliff of OFFSET at scale (1M+ rows).\n * Instead of `OFFSET N`, it uses a WHERE condition:\n * `WHERE (sortField < lastValue) OR (sortField = lastValue AND id < lastId)`\n * which Postgres can serve from an index in constant time.\n *\n * The cursor is opaque to the client — base64-encoded JSON.\n *\n * Security:\n * - `field` must be whitelisted against the entity's actual fields\n * - `id` must be a valid UUID\n * - `value` is parameterized (never interpolated into SQL)\n * - Malformed cursors return null (caller returns 400)\n */\n\nimport { and, eq, getTableColumns, gt, lt, or, type SQL } from 'drizzle-orm'\nimport type { PgTable } from 'drizzle-orm/pg-core'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Cursor input for keyset pagination. */\nexport interface CursorInput {\n /** Sort field name (e.g. 'createdAt'). Must be a real column on the entity. */\n field: string\n /** Last seen value of the sort field. */\n value: string | number\n /** Sort direction — must match the ORDER BY direction. */\n direction: 'asc' | 'desc'\n /** Tie-breaker: last seen entity ID. Required for non-unique sort fields. */\n id?: string\n}\n\n/** Decoded cursor (internal, after validation). */\ninterface DecodedCursor {\n field: string\n value: string | number\n direction: 'asc' | 'desc'\n id?: string\n}\n\n// ---------------------------------------------------------------------------\n// UUID validation (same format used throughout the toolkit)\n// ---------------------------------------------------------------------------\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n// ---------------------------------------------------------------------------\n// Encode / decode\n// ---------------------------------------------------------------------------\n\n/**\n * Encode a cursor for API transport (base64url).\n * Built from the last item in a result set.\n */\nexport function encodeCursor(\n item: Record<string, unknown>,\n sortField: string,\n direction: 'asc' | 'desc',\n): string {\n const payload: CursorInput = {\n field: sortField,\n value: item[sortField] as string | number,\n direction,\n id: item.id as string | undefined,\n }\n return btoa(JSON.stringify(payload))\n}\n\n/**\n * Decode and validate a cursor string from query params.\n * Returns null if the cursor is malformed, tampered, or invalid.\n *\n * Security: the `field` value is NOT validated here — the caller must\n * whitelist it against the entity's actual columns.\n */\nexport function decodeCursor(encoded: string): DecodedCursor | null {\n try {\n const json = atob(encoded)\n const parsed: unknown = JSON.parse(json)\n\n if (typeof parsed !== 'object' || parsed === null) return null\n const obj = parsed as Record<string, unknown>\n\n // Validate field\n if (typeof obj.field !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(obj.field)) {\n return null\n }\n\n // Validate value (string or number)\n if (typeof obj.value !== 'string' && typeof obj.value !== 'number') {\n return null\n }\n\n // Validate direction\n if (obj.direction !== 'asc' && obj.direction !== 'desc') {\n return null\n }\n\n // Validate id (optional, must be UUID if present)\n if (obj.id !== undefined) {\n if (typeof obj.id !== 'string' || !UUID_RE.test(obj.id)) {\n return null\n }\n }\n\n return {\n field: obj.field,\n value: obj.value,\n direction: obj.direction,\n id: obj.id as string | undefined,\n }\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// SQL condition builder\n// ---------------------------------------------------------------------------\n\n/**\n * Build the keyset WHERE condition from a decoded cursor.\n *\n * For DESC: `WHERE (field < value) OR (field = value AND id < cursorId)`\n * For ASC: `WHERE (field > value) OR (field = value AND id > cursorId)`\n *\n * The caller must verify that `cursor.field` exists on the table before calling.\n *\n * @param table - Drizzle table with columns\n * @param cursor - Decoded and validated cursor\n * @returns SQL condition, or null if the field doesn't exist on the table\n */\nexport function buildCursorCondition(\n table: PgTable,\n cursor: DecodedCursor,\n): SQL | null {\n const cols = getTableColumns(table)\n const column = cols[cursor.field]\n if (!column) return null\n\n const isDesc = cursor.direction === 'desc'\n const compare = isDesc ? lt : gt\n\n // Primary condition: sort field passes the cursor value\n const fieldCondition = compare(column, cursor.value)\n\n // Without tie-breaker ID, use simple comparison\n if (!cursor.id) {\n return fieldCondition\n }\n\n // With tie-breaker: (field < value) OR (field = value AND id < cursorId)\n const idColumn = cols.id\n if (!idColumn) return fieldCondition\n\n const idCondition = compare(idColumn, cursor.id)\n return or(fieldCondition, and(eq(column, cursor.value), idCondition))!\n}\n","/**\n * DTO Shaper\n * Transforms raw DB rows into clean DTOs.\n * All fields are real columns — just read from row directly.\n */\n\nimport type { Entity } from './define-entity.js'\nimport type { FieldConfig } from './fields/base.js'\nimport type { InferEntityDTO } from './types/infer.js'\n\nexport interface ShapeDtoOptions {\n select?: string[] // Explicit field selection\n includeInternal?: boolean // Include _version, _scopeId\n}\n\n/**\n * Shape a raw DB row into a typed DTO.\n * Every field is a real column — read directly from row.\n */\nexport function shapeDto<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n row: Record<string, unknown>,\n options?: ShapeDtoOptions,\n): InferEntityDTO<AllFields> | null {\n if (!row) return null\n\n const result: Record<string, unknown> = {}\n const fieldsToInclude = options?.select || Object.keys(entity.allFields)\n\n for (const fieldName of fieldsToInclude) {\n if (!options?.includeInternal && fieldName.startsWith('_')) continue\n\n const fieldConfig = (entity.allFields as Record<string, FieldConfig>)[fieldName]\n if (!fieldConfig) continue\n\n // Blocks are loaded separately from layout tables\n if (fieldConfig.type === 'blocks') continue\n\n result[fieldName] = row[fieldName]\n }\n\n return result as InferEntityDTO<AllFields>\n}\n\n/**\n * Shape multiple rows\n */\nexport function shapeDtos<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n rows: Record<string, unknown>[],\n options?: ShapeDtoOptions,\n): (InferEntityDTO<AllFields> | null)[] {\n return rows.map((row) => shapeDto(entity, row, options))\n}\n","/**\n * Error thrown when attempting to delete an entity that is still referenced.\n */\n\nimport type { EntityUsage } from './find-usages.js'\n\nexport class ReferencedEntityError extends Error {\n public readonly entityName: string\n public readonly entityId: string\n public readonly usages: EntityUsage[]\n\n constructor(entityName: string, entityId: string, usages: EntityUsage[]) {\n const count = usages.length\n super(\n `Cannot delete ${entityName} '${entityId}': referenced by ${count} other entit${count === 1 ? 'y' : 'ies'}`,\n )\n this.name = 'ReferencedEntityError'\n this.entityName = entityName\n this.entityId = entityId\n this.usages = usages\n }\n}\n","/**\n * Schema-aware reference extraction.\n *\n * Walks entity field definitions and data to find all outgoing references.\n * Handles:\n * - field.media() → target = 'media', single UUID\n * - field.reference() → target = config.entity, single UUID or UUID[]\n * - field.blocks() → inspects block instance data for media/reference fields\n */\n\nimport type { BlocksField, FieldConfig, ReferenceField } from '../fields/base.js'\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport interface ExtractedRef {\n sourceField: string\n targetEntity: string\n targetId: string\n}\n\n/**\n * Extract all outgoing references from entity data.\n *\n * @param allFields - The entity's complete field map (entity.allFields)\n * @param data - The entity data (full on create, partial on update)\n * @returns Deduplicated array of extracted references\n */\nexport function extractRefs(\n allFields: Record<string, FieldConfig>,\n data: Record<string, unknown>,\n): ExtractedRef[] {\n const refs: ExtractedRef[] = []\n const seen = new Set<string>()\n\n function add(sourceField: string, targetEntity: string, targetId: string) {\n if (!UUID_RE.test(targetId)) return\n const key = `${sourceField}|${targetEntity}|${targetId}`\n if (seen.has(key)) return\n seen.add(key)\n refs.push({ sourceField, targetEntity, targetId })\n }\n\n for (const [fieldName, config] of Object.entries(allFields)) {\n const value = data[fieldName]\n if (value == null) continue\n\n switch (config.type) {\n case 'media': {\n if (typeof value === 'string') {\n add(fieldName, 'media', value)\n }\n break\n }\n\n case 'reference': {\n const refConfig = config as ReferenceField\n if (refConfig.cardinality === 'many' && Array.isArray(value)) {\n for (const id of value) {\n if (typeof id === 'string') {\n add(fieldName, refConfig.entity, id)\n }\n }\n } else if (typeof value === 'string') {\n add(fieldName, refConfig.entity, value)\n }\n break\n }\n\n case 'blocks': {\n const blocksConfig = config as BlocksField\n if (!Array.isArray(value)) break\n\n for (const block of value) {\n const inst = block as Record<string, unknown>\n const blockType = inst._block as string | undefined\n if (!blockType) continue\n\n // Find the block definition to know its field types\n const blockDef = blocksConfig.blocks.find((b) => b.slug === blockType)\n if (!blockDef) continue\n\n // Scan block fields for media/reference values\n for (const [blockFieldName, blockFieldConfig] of Object.entries(blockDef.fields)) {\n const blockValue = inst[blockFieldName]\n if (blockValue == null) continue\n\n if (blockFieldConfig.type === 'media' && typeof blockValue === 'string') {\n add(fieldName, 'media', blockValue)\n }\n\n if (blockFieldConfig.type === 'reference') {\n const blockRefConfig = blockFieldConfig as ReferenceField\n if (blockRefConfig.cardinality === 'many' && Array.isArray(blockValue)) {\n for (const id of blockValue) {\n if (typeof id === 'string') {\n add(fieldName, blockRefConfig.entity, id)\n }\n }\n } else if (typeof blockValue === 'string') {\n add(fieldName, blockRefConfig.entity, blockValue)\n }\n }\n }\n }\n break\n }\n }\n }\n\n return refs\n}\n\n/**\n * Get the names of all ref-bearing fields in the entity.\n * Used to scope partial-update ref deletion.\n */\nexport function getRefBearingFields(allFields: Record<string, FieldConfig>): string[] {\n const names: string[] = []\n for (const [fieldName, config] of Object.entries(allFields)) {\n if (config.type === 'media' || config.type === 'reference' || config.type === 'blocks') {\n names.push(fieldName)\n }\n }\n return names\n}\n","/**\n * entity_refs — Universal reference tracking table.\n *\n * Every reference between entities (field.media(), field.reference(), block media fields)\n * gets a row here at write time. This enables:\n * - Instant \"where is this used?\" queries (one indexed lookup)\n * - Universal delete protection (can't delete referenced entities)\n * - Correct results (schema-aware, no LIKE text search)\n */\n\nimport { index, pgTable, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\nexport const entityRefs = pgTable(\n 'entity_refs',\n {\n sourceEntity: varchar('source_entity', { length: 100 }).notNull(),\n sourceId: uuid('source_id').notNull(),\n sourceField: varchar('source_field', { length: 100 }).notNull(),\n targetEntity: varchar('target_entity', { length: 100 }).notNull(),\n targetId: uuid('target_id').notNull(),\n },\n (t) => [\n unique('uq_entity_refs').on(\n t.sourceEntity,\n t.sourceId,\n t.sourceField,\n t.targetEntity,\n t.targetId,\n ),\n index('idx_entity_refs_target').on(t.targetEntity, t.targetId),\n index('idx_entity_refs_source').on(t.sourceEntity, t.sourceId),\n ],\n)\n","/**\n * Validation schema generator\n * Converts entity field definitions to Zod schemas for runtime validation\n */\n\nimport { z } from 'zod'\nimport type { Entity } from './define-entity.js'\nimport type { FieldConfig } from './fields/base.js'\n\n/**\n * Convert a field definition to a Zod schema\n */\nfunction fieldToZod(fieldConfig: FieldConfig): z.ZodType {\n let schema: z.ZodType\n\n switch (fieldConfig.type) {\n case 'id':\n schema = z.string().uuid()\n break\n\n case 'text':\n schema = z.string()\n if (fieldConfig.maxLength) {\n schema = (schema as z.ZodString).max(fieldConfig.maxLength)\n }\n if (fieldConfig.minLength) {\n schema = (schema as z.ZodString).min(fieldConfig.minLength)\n }\n if (fieldConfig.pattern) {\n schema = (schema as z.ZodString).regex(fieldConfig.pattern)\n }\n break\n\n case 'number':\n schema = z.number()\n if (fieldConfig.integer) {\n schema = (schema as z.ZodNumber).int()\n }\n if (fieldConfig.min !== undefined) {\n schema = (schema as z.ZodNumber).min(fieldConfig.min)\n }\n if (fieldConfig.max !== undefined) {\n schema = (schema as z.ZodNumber).max(fieldConfig.max)\n }\n break\n\n case 'boolean':\n schema = z.boolean()\n break\n\n case 'date':\n schema = z.date().or(z.string().datetime())\n // Allow either Date object or ISO string, coerce to Date\n break\n\n case 'select':\n schema = z.enum(fieldConfig.options as [string, ...string[]])\n break\n\n case 'reference':\n if (fieldConfig.cardinality === 'many') {\n schema = z.array(z.string().uuid())\n } else {\n schema = z.string().uuid()\n }\n break\n\n case 'media':\n schema = z.string().uuid() // Media entity ID\n break\n\n case 'richtext':\n // HTML string (TipTap/Puck) or Slate JSON array (Plate/entity forms)\n schema = z.union([z.string(), z.array(z.record(z.unknown()))])\n break\n\n case 'slug':\n schema = z.string().regex(/^[a-z0-9-]+$/)\n break\n\n case 'json':\n schema = z.record(z.unknown())\n break\n\n case 'blocks':\n // Array of block instances with _block discriminator.\n // .passthrough() is required because each block type has different dynamic props\n // (title, image, content, etc.) that can't be validated generically here.\n // Per-block-type validation happens in the block editor's converter layer.\n // Security: extra props are harmless at storage level since rendering maps to\n // known component definitions and ignores unknown fields.\n schema = z.array(\n z\n .object({\n _block: z.string(),\n })\n .passthrough(),\n )\n break\n\n default:\n schema = z.unknown()\n }\n\n // Apply required/optional — non-required fields accept both undefined and null\n if (!fieldConfig.required) {\n schema = schema.nullable().optional()\n }\n\n // Apply default value\n if (fieldConfig.default !== undefined) {\n schema = schema.default(fieldConfig.default)\n }\n\n return schema\n}\n\n/**\n * Generate complete validation schema for an entity\n */\nexport function generateValidationSchema(entity: Entity): z.AnyZodObject {\n const shape: Record<string, z.ZodType> = {}\n\n for (const [fieldName, fieldConfig] of Object.entries(entity.allFields)) {\n shape[fieldName] = fieldToZod(fieldConfig)\n }\n\n return z.object(shape)\n}\n\n/**\n * Generate schema for entity creation (omit auto-generated fields)\n */\nexport function generateCreateSchema(entity: Entity): z.AnyZodObject {\n const shape: Record<string, z.ZodType> = {}\n\n // Fields to omit from create schema (auto-generated + server-set behavior fields)\n const omitFields = new Set(['id', 'createdAt', 'updatedAt', 'createdBy', '_version'])\n\n for (const [fieldName, fieldConfig] of Object.entries(entity.allFields)) {\n if (!omitFields.has(fieldName)) {\n shape[fieldName] = fieldToZod(fieldConfig)\n }\n }\n\n return z.object(shape)\n}\n\n/**\n * Generate schema for entity updates (all fields optional, omit immutable fields)\n */\nexport function generateUpdateSchema(entity: Entity): z.AnyZodObject {\n const shape: Record<string, z.ZodType> = {}\n\n // Fields to omit from update schema (immutable + server-set behavior fields)\n const omitFields = new Set(['id', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy', '_version'])\n\n for (const [fieldName, fieldConfig] of Object.entries(entity.allFields)) {\n if (!omitFields.has(fieldName)) {\n // All fields optional for updates\n const fieldSchema = fieldToZod(fieldConfig)\n shape[fieldName] = fieldSchema.optional()\n }\n }\n\n return z.object(shape)\n}\n","/**\n * AdminClient - Full CRUD with server-only enforcement\n * CRITICAL: This file MUST NOT be imported in client code\n */\n\n// NOTE: We use runtime check instead of 'server-only' import to allow CLI scripts\n// The 'server-only' package blocks ALL non-Next.js contexts (including Node.js scripts)\n// Layer 3: Runtime check (catches what bundlers miss, allows CLI usage)\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport type { CountCacheLike } from '../count-cache.js'\nimport type { CursorInput } from '../cursor.js'\nimport { buildCursorCondition } from '../cursor.js'\nimport type { Entity } from '../define-entity.js'\nimport { shapeDto, shapeDtos } from '../dto-shaper.js'\nimport type { FieldConfig } from '../fields/base.js'\nimport { ReferencedEntityError } from '../refs/errors.js'\nimport { extractRefs } from '../refs/extract-refs.js'\nimport { entityRefs } from '../refs/schema.js'\nimport type { InferCreateInput, InferEntityDTO, InferUpdateInput } from '../types/infer.js'\nimport type { Logger } from '../types/logger.js'\nimport { generateCreateSchema, generateUpdateSchema } from '../validation.js'\n\nexport interface AdminClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n entity: Entity<AllFields>\n db: PostgresJsDatabase\n logger?: Logger\n /** Optional count cache for COUNT(*) query optimization. */\n countCache?: CountCacheLike\n}\n\nexport interface FindManyOptions {\n where?: SQL | undefined\n limit?: number\n offset?: number\n orderBy?: SQL | SQL[]\n locale?: string\n /** Default content locale. For localized blocks, NULL rows (from initial create)\n * are only returned as fallback when locale matches defaultLocale. */\n defaultLocale?: string\n /**\n * Cursor-based (keyset) pagination. When provided, replaces OFFSET with a\n * WHERE condition for O(1) page access at any depth. The `offset` option\n * is ignored when `cursor` is set.\n *\n * The cursor `field` must be a real column on the entity table.\n */\n cursor?: CursorInput\n}\n\nexport interface CountOptions {\n where?: SQL | undefined\n}\n\n/**\n * AdminClient - Full CRUD operations with security enforcement\n *\n * Security layers:\n * 1. Runtime check: typeof window !== 'undefined' → throw (allows CLI scripts)\n * 2. Uses read-write DB connection\n * 3. Validation with Zod before every write\n * 4. Hook execution (beforeCreate, afterCreate, etc.)\n *\n * Note: We don't use 'server-only' import because it blocks CLI scripts.\n * Next.js bundler protection comes from subpath exports (@murumets-ee/core/clients).\n *\n * Phase 1: Core CRUD + hooks + validation\n * Phase 2 (TODO): Access control, request context, scoping\n *\n * @typeParam AllFields - The entity's complete field map. Inferred automatically\n * when constructing via `createAdminClient(entity)`.\n */\nexport class AdminClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private entity: Entity<AllFields>\n private db: PostgresJsDatabase\n private logger?: Logger\n private createSchema: ZodType\n private updateSchema: ZodType\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any> for property access\n private table: PgTableWithColumns<any>\n private countCache?: CountCacheLike\n\n constructor(config: AdminClientConfig<AllFields>) {\n // Runtime enforcement: prevent usage in browser contexts\n if (typeof window !== 'undefined') {\n throw new Error(\n 'AdminClient cannot be used in browser code. ' +\n 'Use QueryClient for frontend data access.',\n )\n }\n\n this.entity = config.entity\n this.db = config.db\n this.logger = config.logger\n this.countCache = config.countCache\n\n // Pre-generate validation schemas for performance\n this.createSchema = generateCreateSchema(config.entity)\n this.updateSchema = generateUpdateSchema(config.entity)\n\n // Get table from schema registry\n const table = schemaRegistry.get(config.entity.name)\n if (!table) {\n throw new Error(\n `Schema for entity '${config.entity.name}' not found in registry. ` +\n 'Ensure schemas are generated and registered before creating AdminClient.',\n )\n }\n this.table = table\n }\n\n /**\n * Create a new entity\n *\n * Flow:\n * 1. Validate input with Zod\n * 2. Execute beforeCreate hooks\n * 3. Prepare data for insert\n * 4. Insert into database\n * 5. Execute afterCreate hooks\n * 6. Shape DTO and return\n */\n async create(data: InferCreateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n this.logger?.info({ entity: this.entity.name }, 'Creating entity')\n\n // TODO (Phase 2): Access control check\n // const ctx = getRequestContext()\n // if (!hasAccess(ctx.user, this.entity.access.create)) {\n // throw new ForbiddenError('User not authorized to create this entity')\n // }\n\n // Execute beforeCreate hooks BEFORE validation — hooks may populate required fields\n let dataToInsert = data as Record<string, unknown>\n for (const b of this.entity.behaviors ?? []) {\n if (b.hooks?.beforeCreate) {\n const hookResult = await b.hooks.beforeCreate(dataToInsert)\n if (hookResult !== undefined) dataToInsert = hookResult\n }\n }\n\n // Preserve server-set fields that hooks added but createSchema omits\n // (e.g. createdAt/updatedAt from timestamped(), createdBy/updatedBy from auditable())\n const serverFields: Record<string, unknown> = {}\n for (const key of ['createdAt', 'updatedAt', 'createdBy', 'updatedBy']) {\n if (dataToInsert[key] !== undefined) serverFields[key] = dataToInsert[key]\n }\n\n // Validate after hooks (hooks may add required fields like senderEmail)\n dataToInsert = { ...this.createSchema.parse(dataToInsert), ...serverFields }\n\n // TODO (Phase 2): Add scope if entity is scoped\n // if (this.entity.scope === 'team' || this.entity.scope === 'user') {\n // const ctx = getRequestContext()\n // dataToInsert._scopeId = ctx.scopeId\n // }\n\n // Prepare data for insert\n const columns = this.prepareDataForInsert(dataToInsert)\n\n // Insert into database\n const [row] = await this.db.insert(this.table).values(columns).returning()\n\n // Save blocks to layout table\n await this.saveBlocks(row.id, dataToInsert)\n\n // Track outgoing references (entity_refs)\n await this.syncRefs(row.id as string, dataToInsert, 'create')\n\n // Execute afterCreate hooks\n for (const b of this.entity.behaviors ?? []) {\n if (b.hooks?.afterCreate) await b.hooks.afterCreate(row)\n }\n\n // Invalidate count cache after creation\n this.invalidateCountCache()\n\n // Shape DTO and attach blocks\n const shaped = shapeDto(this.entity, row) as Record<string, unknown>\n if (shaped && this.getBlocksFields().length > 0) {\n const blocksMap = await this.loadBlocks([shaped.id as string])\n this.attachBlocks([shaped], blocksMap)\n }\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Find entity by ID\n */\n async findById(\n id: string,\n options?: { locale?: string; defaultLocale?: string },\n ): Promise<InferEntityDTO<AllFields> | null> {\n this.logger?.info({ entity: this.entity.name, id }, 'Finding entity by ID')\n\n // TODO (Phase 2): Access control check\n // const ctx = getRequestContext()\n // if (!hasAccess(ctx.user, this.entity.access.view)) {\n // throw new ForbiddenError('User not authorized to view this entity')\n // }\n\n // Query database\n const [row] = await this.db.select().from(this.table).where(eq(this.table.id, id))\n\n if (!row) return null\n\n // TODO (Phase 2): Scope check\n // if (this.entity.scope !== 'global') {\n // const ctx = getRequestContext()\n // if (row._scopeId !== ctx.scopeId) {\n // return null // Not in user's scope\n // }\n // }\n\n const shaped = shapeDto(this.entity, row) as Record<string, unknown>\n if (!shaped) return null\n\n // Attach blocks from layout table (with locale for block translations)\n if (this.getBlocksFields().length > 0) {\n const blocksMap = await this.loadBlocks([shaped.id as string], options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n this.attachBlocks([shaped], blocksMap)\n }\n\n if (options?.locale) {\n const [merged] = await this.mergeTranslations([shaped], options.locale)\n return merged as InferEntityDTO<AllFields>\n }\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Find multiple entities\n */\n async findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n this.logger?.info({ entity: this.entity.name, options }, 'Finding entities')\n\n // TODO (Phase 2): Access control check\n // const ctx = getRequestContext()\n // if (!hasAccess(ctx.user, this.entity.access.view)) {\n // throw new ForbiddenError('User not authorized to view this entity')\n // }\n\n // Build and execute query\n // TODO (Phase 2): Add scope filter\n let query = this.db.select().from(this.table).$dynamic()\n\n // Collect WHERE conditions\n const conditions: SQL[] = []\n\n if (options?.where) {\n conditions.push(options.where)\n }\n\n // Cursor-based pagination: add keyset WHERE condition (replaces OFFSET)\n if (options?.cursor) {\n // Whitelist: cursor field must be a real column on the entity\n const allFields = this.entity.allFields as Record<string, FieldConfig>\n if (!(options.cursor.field in allFields) && options.cursor.field !== 'id') {\n throw new Error(\n `Invalid cursor field: '${options.cursor.field}' is not a field on '${this.entity.name}'`,\n )\n }\n const cursorCondition = buildCursorCondition(this.table, options.cursor)\n if (cursorCondition) {\n conditions.push(cursorCondition)\n }\n }\n\n if (conditions.length > 0) {\n query = query.where(and(...conditions))\n }\n\n if (options?.limit) {\n query = query.limit(options.limit)\n }\n // Cursor takes precedence over offset — skip offset when cursor is active\n if (options?.offset && !options?.cursor) {\n query = query.offset(options.offset)\n }\n if (options?.orderBy) {\n const cols = Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy]\n query = query.orderBy(...cols)\n }\n\n const rows = await query\n\n const shaped = shapeDtos(this.entity, rows).filter(\n (e): e is NonNullable<typeof e> => e !== null,\n ) as Record<string, unknown>[]\n\n // Attach blocks from layout table (with locale for block translations)\n if (this.getBlocksFields().length > 0 && shaped.length > 0) {\n const entityIds = shaped.map((e) => e.id as string)\n const blocksMap = await this.loadBlocks(entityIds, options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n this.attachBlocks(shaped, blocksMap)\n }\n\n if (options?.locale) {\n return (await this.mergeTranslations(shaped, options.locale)) as InferEntityDTO<AllFields>[]\n }\n\n return shaped as InferEntityDTO<AllFields>[]\n }\n\n /**\n * Count entities matching optional conditions\n */\n async count(options?: CountOptions): Promise<number> {\n this.logger?.info({ entity: this.entity.name, options }, 'Counting entities')\n\n // Build cache key: entityName + serialized WHERE (or empty for unfiltered)\n const cacheKey = this.buildCountCacheKey(options?.where)\n if (this.countCache) {\n const cached = this.countCache.get(cacheKey)\n if (cached !== undefined) {\n this.logger?.debug?.({ entity: this.entity.name, cached }, 'Count cache hit')\n return cached\n }\n }\n\n let query = this.db.select({ count: sql<number>`count(*)` }).from(this.table).$dynamic()\n\n if (options?.where) {\n query = query.where(options.where)\n }\n\n const [result] = await query\n const count = Number(result.count)\n\n // Cache the result\n if (this.countCache) {\n this.countCache.set(cacheKey, count)\n }\n\n return count\n }\n\n /**\n * Update entity by ID\n *\n * Flow:\n * 1. Validate input with Zod\n * 2. Execute beforeUpdate hooks\n * 3. Prepare data for update\n * 4. Update in database\n * 5. Execute afterUpdate hooks\n * 6. Shape DTO and return\n */\n async update(\n id: string,\n data: InferUpdateInput<AllFields>,\n options?: { locale?: string },\n ): Promise<InferEntityDTO<AllFields>> {\n this.logger?.info({ entity: this.entity.name, id }, 'Updating entity')\n\n // TODO (Phase 2): Access control check\n // const ctx = getRequestContext()\n // if (!hasAccess(ctx.user, this.entity.access.update)) {\n // throw new ForbiddenError('User not authorized to update this entity')\n // }\n\n // Execute beforeUpdate hooks BEFORE validation — hooks may modify fields\n let dataToUpdate = data as Record<string, unknown>\n for (const b of this.entity.behaviors ?? []) {\n if (b.hooks?.beforeUpdate) {\n const hookResult = await b.hooks.beforeUpdate(id, dataToUpdate)\n if (hookResult !== undefined) dataToUpdate = hookResult\n }\n }\n\n // Validate after hooks\n dataToUpdate = this.updateSchema.parse(dataToUpdate)\n\n // Prepare data for update\n const columns = this.prepareDataForUpdate(dataToUpdate)\n\n // Update in database (only if there are non-blocks fields to update)\n let row: Record<string, unknown>\n if (Object.keys(columns).length > 0) {\n const [updated] = await this.db\n .update(this.table)\n .set(columns)\n .where(eq(this.table.id, id))\n .returning()\n row = updated\n } else {\n // Only blocks changed — fetch current row\n const [current] = await this.db.select().from(this.table).where(eq(this.table.id, id))\n row = current\n }\n\n // Update blocks in layout table (thread locale for per-locale blocks)\n await this.saveBlocks(id, dataToUpdate, options)\n\n // Update outgoing references (entity_refs) — only for changed fields\n await this.syncRefs(id, dataToUpdate, 'update')\n\n // Execute afterUpdate hooks\n for (const b of this.entity.behaviors ?? []) {\n if (b.hooks?.afterUpdate) await b.hooks.afterUpdate(row)\n }\n\n // Shape DTO and attach blocks\n const shaped = shapeDto(this.entity, row) as Record<string, unknown>\n if (shaped && this.getBlocksFields().length > 0) {\n const blocksMap = await this.loadBlocks([id])\n this.attachBlocks([shaped], blocksMap)\n }\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Delete entity by ID.\n *\n * Wraps cascade + delete in a transaction so cascaded deletes are rolled\n * back if the final entity delete fails (no partial data loss).\n *\n * Checks entity_refs for incoming references first — throws\n * ReferencedEntityError if this entity is still used somewhere.\n */\n async delete(id: string): Promise<void> {\n this.logger?.info({ entity: this.entity.name, id }, 'Deleting entity')\n\n await this.db.transaction(async (tx) => {\n // Handle incoming references — cascade or restrict based on field config\n await this.handleIncomingRefsForDelete(tx, [id])\n\n // Execute beforeDelete hooks\n for (const b of this.entity.behaviors ?? []) {\n if (b.hooks?.beforeDelete) await b.hooks.beforeDelete(id)\n }\n\n // Delete from database\n await tx.delete(this.table).where(eq(this.table.id, id))\n\n // Clean up outgoing references from entity_refs\n await tx\n .delete(entityRefs)\n .where(and(eq(entityRefs.sourceEntity, this.entity.name), eq(entityRefs.sourceId, id)))\n })\n\n // Execute afterDelete hooks (outside transaction — side effects should not block commit)\n for (const b of this.entity.behaviors ?? []) {\n if (b.hooks?.afterDelete) await b.hooks.afterDelete(id)\n }\n\n // Invalidate count cache after deletion\n this.invalidateCountCache()\n }\n\n /**\n * Delete multiple entities matching a WHERE condition.\n *\n * Wraps cascade + delete in a transaction so cascaded deletes are rolled\n * back if the final entity delete fails (no partial data loss).\n *\n * Respects `onDelete` config on referencing fields:\n * - `cascade`: recursively deletes referencing entities\n * - `set-null`: nullifies the reference column\n * - `restrict` (default): blocks deletion if references exist\n *\n * Runs beforeDelete/afterDelete hooks for each entity.\n *\n * @returns Number of rows deleted\n */\n async deleteMany(where: SQL): Promise<number> {\n this.logger?.info({ entity: this.entity.name }, 'Bulk deleting entities')\n\n // Get IDs first — needed for ref handling and hooks\n const rows = await this.db\n .select({ id: this.table.id })\n .from(this.table)\n .where(where)\n const ids = rows.map((r) => (r as Record<string, unknown>).id as string)\n if (ids.length === 0) return 0\n\n await this.db.transaction(async (tx) => {\n // Handle incoming references — cascade or restrict\n await this.handleIncomingRefsForDelete(tx, ids)\n\n // Run beforeDelete hooks\n for (const id of ids) {\n for (const b of this.entity.behaviors ?? []) {\n if (b.hooks?.beforeDelete) await b.hooks.beforeDelete(id)\n }\n }\n\n // Delete from database\n await tx.delete(this.table).where(inArray(this.table.id, ids))\n\n // Clean up outgoing references from entity_refs\n await tx\n .delete(entityRefs)\n .where(and(eq(entityRefs.sourceEntity, this.entity.name), inArray(entityRefs.sourceId, ids)))\n })\n\n // Run afterDelete hooks (outside transaction — side effects should not block commit)\n for (const id of ids) {\n for (const b of this.entity.behaviors ?? []) {\n if (b.hooks?.afterDelete) await b.hooks.afterDelete(id)\n }\n }\n\n this.invalidateCountCache()\n return ids.length\n }\n\n /** Maximum cascade depth to prevent infinite recursion from circular references. */\n private static readonly MAX_CASCADE_DEPTH = 10\n\n /**\n * Handle incoming references before deleting entities.\n *\n * For each referencing entity/field:\n * - `onDelete: 'cascade'` → recursively delete referencing entities\n * - `onDelete: 'set-null'` → nullify the FK column on referencing rows\n * - `onDelete: 'restrict'` → throw ReferencedEntityError\n *\n * Looks up referencing entity definitions from the app's entity registry\n * to determine the onDelete strategy. Falls back to 'restrict' if the\n * entity registry is unavailable.\n *\n * @param tx - Transaction handle for atomicity (cascade + delete in same tx)\n * @param ids - Entity IDs being deleted\n * @param depth - Current recursion depth (guards against circular references)\n */\n private async handleIncomingRefsForDelete(\n tx: PostgresJsDatabase,\n ids: string[],\n depth = 0,\n ): Promise<void> {\n if (depth >= AdminClient.MAX_CASCADE_DEPTH) {\n throw new Error(\n `Cascade delete exceeded maximum depth of ${AdminClient.MAX_CASCADE_DEPTH} ` +\n `while deleting '${this.entity.name}'. This likely indicates a circular reference chain.`,\n )\n }\n\n // Find all incoming references for all IDs in a single query\n const usages = await tx\n .select({\n sourceEntity: entityRefs.sourceEntity,\n sourceId: entityRefs.sourceId,\n sourceField: entityRefs.sourceField,\n })\n .from(entityRefs)\n .where(\n and(\n eq(entityRefs.targetEntity, this.entity.name),\n inArray(entityRefs.targetId, ids),\n ),\n )\n\n if (usages.length === 0) return\n\n // Group usages by source entity + field to determine strategy per group\n const groups = new Map<string, { sourceEntity: string; sourceField: string; sourceIds: string[] }>()\n for (const u of usages) {\n const key = `${u.sourceEntity}:${u.sourceField}`\n let group = groups.get(key)\n if (!group) {\n group = { sourceEntity: u.sourceEntity, sourceField: u.sourceField, sourceIds: [] }\n groups.set(key, group)\n }\n group.sourceIds.push(u.sourceId)\n }\n\n // Look up entity registry for onDelete config\n let entityMap: Map<string, Entity> | undefined\n try {\n const moduleName = ['@murumets-ee', 'core'].join('/')\n const core = await (import(moduleName) as Promise<{ getApp: () => { entities: Map<string, Entity> } }>)\n entityMap = core.getApp().entities\n } catch {\n // Entity registry unavailable — treat all as restrict\n }\n\n for (const [, group] of groups) {\n const refEntity = entityMap?.get(group.sourceEntity)\n const refField = refEntity?.fields[group.sourceField] as\n | { type: string; onDelete?: string }\n | undefined\n const strategy = refField?.onDelete ?? 'restrict'\n\n if (strategy === 'restrict') {\n throw new ReferencedEntityError(\n this.entity.name,\n ids[0],\n group.sourceIds.map((sid) => ({\n sourceEntity: group.sourceEntity,\n sourceId: sid,\n sourceField: group.sourceField,\n })),\n )\n }\n\n if (strategy === 'cascade') {\n // Recursively delete referencing entities via their own AdminClient\n // Uses the same transaction handle (tx) for atomicity\n const sourceTable = schemaRegistry.get(group.sourceEntity)\n if (sourceTable && refEntity) {\n const sourceClient = new AdminClient({\n entity: refEntity,\n db: tx,\n logger: this.logger,\n })\n await sourceClient.deleteManyInTx(tx, inArray(sourceTable.id, group.sourceIds), depth + 1)\n }\n } else if (strategy === 'set-null') {\n // Nullify the FK column on referencing rows\n const sourceTable = schemaRegistry.get(group.sourceEntity)\n if (sourceTable) {\n const col = sourceTable[group.sourceField]\n if (col) {\n await tx\n .update(sourceTable)\n .set({ [group.sourceField]: null })\n .where(inArray(sourceTable.id, group.sourceIds))\n // Clean up the ref rows\n await tx\n .delete(entityRefs)\n .where(\n and(\n eq(entityRefs.sourceEntity, group.sourceEntity),\n inArray(entityRefs.sourceId, group.sourceIds),\n eq(entityRefs.sourceField, group.sourceField),\n ),\n )\n }\n }\n }\n }\n }\n\n /**\n * Internal: delete within an existing transaction (used by cascade).\n * Skips wrapping in a new transaction — the caller already has one.\n */\n private async deleteManyInTx(tx: PostgresJsDatabase, where: SQL, depth: number): Promise<number> {\n const rows = await tx\n .select({ id: this.table.id })\n .from(this.table)\n .where(where)\n const ids = rows.map((r) => (r as Record<string, unknown>).id as string)\n if (ids.length === 0) return 0\n\n await this.handleIncomingRefsForDelete(tx, ids, depth)\n\n for (const id of ids) {\n for (const b of this.entity.behaviors ?? []) {\n if (b.hooks?.beforeDelete) await b.hooks.beforeDelete(id)\n }\n }\n\n await tx.delete(this.table).where(inArray(this.table.id, ids))\n await tx\n .delete(entityRefs)\n .where(and(eq(entityRefs.sourceEntity, this.entity.name), inArray(entityRefs.sourceId, ids)))\n\n // afterDelete hooks run outside the caller's transaction scope\n // (the caller — deleteMany — handles them after tx commits)\n\n this.invalidateCountCache()\n return ids.length\n }\n\n // -------------------------------------------------------------------------\n // Bulk operations\n // -------------------------------------------------------------------------\n\n /**\n * Update multiple entities matching a WHERE condition.\n *\n * Unlike `update(id, data)`, this does NOT run hooks (beforeUpdate/afterUpdate),\n * does NOT validate with Zod, and does NOT update blocks/translations.\n * It's a direct bulk column update — use for operational changes like\n * status transitions, assignments, and cleanup jobs.\n *\n * @returns Number of rows updated\n *\n * @example Close all resolved tickets older than 30 days\n * ```ts\n * const closed = await ticketClient.updateMany(\n * and(eq(table.status, 'resolved'), lte(table.updatedAt, cutoff)),\n * { status: 'closed', updatedAt: new Date() },\n * )\n * ```\n */\n async updateMany(\n where: SQL,\n data: Partial<InferUpdateInput<AllFields>>,\n ): Promise<number> {\n this.logger?.info({ entity: this.entity.name }, 'Bulk updating entities')\n\n const columns = this.prepareDataForUpdate(data as Record<string, unknown>)\n const result = await this.db\n .update(this.table)\n .set(columns)\n .where(where)\n .returning({ id: this.table.id })\n\n this.invalidateCountCache()\n return result.length\n }\n\n // -------------------------------------------------------------------------\n // Aggregation\n // -------------------------------------------------------------------------\n\n /**\n * Run an aggregate query on this entity's table.\n *\n * Supports GROUP BY with standard aggregate functions (count, sum, avg,\n * min, max). This is the entity-level equivalent of Drupal's\n * `EntityQueryAggregate` — standardized stats without raw SQL.\n *\n * @example Count tickets by status\n * ```ts\n * const stats = await ticketClient.aggregate({\n * select: { count: sql<number>`count(*)::int` },\n * groupBy: [table.status],\n * })\n * // → [{ status: 'open', count: 12 }, { status: 'closed', count: 45 }]\n * ```\n *\n * @example Dashboard stats with conditional counts\n * ```ts\n * const [stats] = await ticketClient.aggregate({\n * select: {\n * open: sql<number>`count(case when ${table.status} = ${'open'} then 1 end)::int`,\n * pending: sql<number>`count(case when ${table.status} = ${'pending'} then 1 end)::int`,\n * },\n * })\n * ```\n */\n async aggregate<TResult extends Record<string, unknown> = Record<string, unknown>>(options: {\n /** Named select expressions — each key becomes an output column. Use `sql<T>` for aggregates. */\n select: Record<string, SQL | ReturnType<typeof eq>>\n /** Columns to GROUP BY. */\n groupBy?: SQL[]\n /** WHERE filter applied before aggregation. */\n where?: SQL\n /** ORDER BY for the result. */\n orderBy?: SQL | SQL[]\n /** Limit the number of rows returned. */\n limit?: number\n }): Promise<TResult[]> {\n this.logger?.info({ entity: this.entity.name }, 'Aggregate query')\n\n let query = this.db.select(options.select).from(this.table).$dynamic()\n\n if (options.where) {\n query = query.where(options.where)\n }\n if (options.groupBy && options.groupBy.length > 0) {\n query = query.groupBy(...options.groupBy)\n }\n if (options.orderBy) {\n const cols = Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy]\n query = query.orderBy(...cols)\n }\n if (options.limit) {\n query = query.limit(options.limit)\n }\n\n return (await query) as TResult[]\n }\n\n /**\n * Expose the underlying Drizzle table for typed Drizzle queries.\n *\n * Use this when you need column references for `.where()`, `.orderBy()`,\n * aggregate expressions, or JOINs with other entity tables. This is the\n * standardized way to access entity columns — never use string table names\n * or `sql.identifier()`.\n *\n * @example\n * ```ts\n * const t = ticketClient.getTable()\n * const stats = await ticketClient.aggregate({\n * select: { count: sql<number>`count(*)::int` },\n * groupBy: [t.status],\n * })\n * ```\n */\n // biome-ignore lint/suspicious/noExplicitAny: entity tables have dynamic columns not known at compile time\n getTable(): PgTableWithColumns<any> {\n return this.table\n }\n\n /**\n * Prepare data for insert — every field is a real column.\n */\n private prepareDataForInsert(data: Record<string, unknown>): Record<string, unknown> {\n const columns: Record<string, unknown> = {}\n\n for (const [fieldName, value] of Object.entries(data)) {\n const fieldConfig = (this.entity.allFields as Record<string, FieldConfig>)[fieldName]\n if (!fieldConfig) continue\n if (fieldName === 'id') continue\n if (fieldConfig.type === 'blocks') continue\n columns[fieldName] = value\n }\n\n return columns\n }\n\n /**\n * Prepare data for update — every field is a real column.\n * Standard column SET, no JSONB merge needed.\n */\n private prepareDataForUpdate(data: Record<string, unknown>): Record<string, unknown> {\n const columns: Record<string, unknown> = {}\n\n for (const [fieldName, value] of Object.entries(data)) {\n const fieldConfig = (this.entity.allFields as Record<string, FieldConfig>)[fieldName]\n if (!fieldConfig) continue\n if (fieldName === 'id') continue\n if (fieldConfig.type === 'blocks') continue\n columns[fieldName] = value\n }\n\n return columns\n }\n\n /**\n * Merge translations into entities for the specified locale.\n * Reads translatable field values from real columns on the translation row.\n */\n private async mergeTranslations<T extends Record<string, unknown>>(\n entities: T[],\n locale: string,\n ): Promise<T[]> {\n if (!entities.length) return entities\n\n const translationTableName = `${this.entity.name}_translations`\n const translationTable = schemaRegistry.get(translationTableName)\n\n if (!translationTable) return entities\n\n const entityIds = entities.map((e) => e.id)\n\n const translations = await this.db\n .select()\n .from(translationTable)\n .where(\n and(inArray(translationTable.entityId, entityIds), eq(translationTable.locale, locale)),\n )\n\n // Get translatable field names\n const translatableFields = Object.entries(this.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, config]) => config.translatable)\n .map(([name]) => name)\n\n const translationMap = new Map<unknown, Record<string, unknown>>()\n for (const translation of translations) {\n const translatedValues: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n const value = (translation as Record<string, unknown>)[fieldName]\n if (value !== undefined && value !== null) {\n translatedValues[fieldName] = value\n }\n }\n translationMap.set(translation.entityId, translatedValues)\n }\n\n return entities.map((entity) => {\n const translatedFields = translationMap.get(entity.id)\n if (!translatedFields) return entity\n return { ...entity, ...translatedFields }\n })\n }\n\n /**\n * Save translation for an entity.\n * Each translatable field is a real column on the translation table.\n */\n async saveTranslation(\n entityId: string,\n locale: string,\n translations: Record<string, unknown>,\n ): Promise<void> {\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Saving translation')\n\n const translationTableName = `${this.entity.name}_translations`\n const translationTable = schemaRegistry.get(translationTableName)\n\n if (!translationTable) {\n throw new Error(`Translation table ${translationTableName} not found in schema registry`)\n }\n\n // Get translatable field names\n const translatableFields = Object.entries(this.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, config]) => config.translatable)\n .map(([name]) => name)\n\n if (translatableFields.length === 0) {\n throw new Error(`Entity ${this.entity.name} has no translatable fields`)\n }\n\n // Extract only translatable fields — these are real columns on the translation table\n const translationData: Record<string, unknown> = { entityId, locale }\n const updateData: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n if (translations[fieldName] !== undefined) {\n translationData[fieldName] = translations[fieldName]\n updateData[fieldName] = translations[fieldName]\n }\n }\n\n // Upsert: insert or update on conflict\n await this.db\n .insert(translationTable)\n .values(translationData)\n .onConflictDoUpdate({\n target: [translationTable.entityId, translationTable.locale],\n set: updateData,\n })\n\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Translation saved')\n }\n\n /**\n * PHASE 3: Delete translation(s) for an entity\n * If locale is provided, deletes specific locale; otherwise deletes all translations\n */\n async deleteTranslation(entityId: string, locale?: string): Promise<void> {\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Deleting translation')\n\n const translationTableName = `${this.entity.name}_translations`\n const translationTable = schemaRegistry.get(translationTableName)\n\n if (!translationTable) {\n throw new Error(`Translation table ${translationTableName} not found in schema registry`)\n }\n\n if (locale) {\n // Delete specific locale\n await this.db\n .delete(translationTable)\n .where(and(eq(translationTable.entityId, entityId), eq(translationTable.locale, locale)))\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Translation deleted')\n } else {\n // Delete all translations for entity\n await this.db.delete(translationTable).where(eq(translationTable.entityId, entityId))\n this.logger?.info({ entity: this.entity.name, entityId }, 'All translations deleted')\n }\n }\n\n /**\n * Save block-level translations for an entity.\n * For each block in each blocks field, extracts translatable field values\n * and upserts them into {entity}_layout_translations.\n *\n * Block _id must match an existing layout row ID.\n */\n async saveBlockTranslations(\n entityId: string,\n locale: string,\n data: Record<string, unknown>,\n ): Promise<void> {\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Saving block translations')\n\n const blocksFields = this.getBlocksFields()\n if (blocksFields.length === 0) return\n\n const layoutTransTable = schemaRegistry.get(`${this.entity.name}_layout_translations`)\n if (!layoutTransTable) return\n\n const layoutTable = schemaRegistry.get(`${this.entity.name}_layout`)\n if (!layoutTable) return\n\n for (const { name: fieldName, config } of blocksFields) {\n const blocks = data[fieldName]\n if (!Array.isArray(blocks)) continue\n\n // Get block definitions to identify translatable fields\n if (config.type !== 'blocks') continue\n const blockDefs = config.blocks\n if (!blockDefs) continue\n\n // Load actual layout row IDs from DB (ordered by sort_order to match request array order).\n // The _id from the request may be a Puck-generated ID (e.g. \"hero-abc123\") rather than\n // the real DB UUID, so we match by position instead.\n const layoutRows = await this.db\n .select({ id: layoutTable.id, blockType: layoutTable.blockType })\n .from(layoutTable)\n .where(\n and(\n eq(layoutTable.entityId, entityId),\n eq(layoutTable.fieldName, fieldName),\n isNull(layoutTable.locale),\n ),\n )\n .orderBy(layoutTable.sortOrder)\n\n for (let i = 0; i < (blocks as Record<string, unknown>[]).length; i++) {\n const block = (blocks as Record<string, unknown>[])[i]\n const blockType = block._block as string\n if (!blockType) continue\n\n // Match by position — layout rows and request blocks are in the same sort order\n const layoutRow = layoutRows[i]\n if (!layoutRow || layoutRow.blockType !== blockType) continue\n\n const blockDef = blockDefs.find((b) => b.slug === blockType)\n if (!blockDef) continue\n\n // Extract only translatable fields\n const translatedFields: Record<string, unknown> = {}\n for (const [fname, fconfig] of Object.entries(blockDef.fields)) {\n if (fconfig.translatable && block[fname] !== undefined) {\n translatedFields[fname] = block[fname]\n }\n }\n\n if (Object.keys(translatedFields).length === 0) continue\n\n // Upsert using the real DB layout row ID\n await this.db\n .insert(layoutTransTable)\n .values({ layoutId: layoutRow.id, locale, fields: translatedFields })\n .onConflictDoUpdate({\n target: [layoutTransTable.layoutId, layoutTransTable.locale],\n set: { fields: translatedFields },\n })\n }\n }\n\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Block translations saved')\n }\n\n /**\n * Save per-locale blocks for an entity.\n * Used for entities with `localized: true` on their blocks field — each locale gets\n * its own independent block layout rows in the layout table.\n */\n async saveLocalizedBlocks(\n entityId: string,\n locale: string,\n data: Record<string, unknown>,\n ): Promise<void> {\n this.logger?.info({ entity: this.entity.name, entityId, locale }, 'Saving localized blocks')\n await this.saveBlocks(entityId, data, { locale })\n }\n\n // ---------------------------------------------------------------\n // Block CRUD (layout table operations)\n // ---------------------------------------------------------------\n\n /**\n * Get all blocks field names for this entity.\n */\n private getBlocksFields(): Array<{ name: string; config: FieldConfig }> {\n return Object.entries(this.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, config]) => config.type === 'blocks')\n .map(([name, config]) => ({ name, config }))\n }\n\n /**\n * Save blocks for an entity after create/update.\n * For each blocks field, writes rows to {entity}_layout table.\n */\n private async saveBlocks(\n entityId: string,\n data: Record<string, unknown>,\n options?: { locale?: string },\n ): Promise<void> {\n const blocksFields = this.getBlocksFields()\n if (blocksFields.length === 0) return\n\n const layoutTable = schemaRegistry.get(`${this.entity.name}_layout`)\n if (!layoutTable) return\n\n for (const { name: fieldName, config } of blocksFields) {\n const blocks = data[fieldName]\n if (!Array.isArray(blocks)) continue\n\n const isLocalized = 'localized' in config && config.localized === true\n const locale = isLocalized ? (options?.locale ?? null) : null\n\n // Delete existing layout rows for this field + locale\n const deleteConditions = [\n eq(layoutTable.entityId, entityId),\n eq(layoutTable.fieldName, fieldName),\n ]\n if (locale) {\n deleteConditions.push(eq(layoutTable.locale, locale))\n } else if (!isLocalized) {\n // For shared layout, delete rows where locale IS NULL\n deleteConditions.push(isNull(layoutTable.locale))\n }\n await this.db.delete(layoutTable).where(and(...deleteConditions))\n\n // Insert new layout rows\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i] as Record<string, unknown>\n const blockType = block._block as string\n if (!blockType) continue\n\n // Separate _block and _id from block data\n const { _block, _id, ...blockData } = block\n\n await this.db.insert(layoutTable).values({\n entityId,\n fieldName,\n blockType,\n sortOrder: i,\n data: blockData,\n locale,\n })\n }\n }\n }\n\n /**\n * Load blocks for one or more entities from the layout table.\n *\n * Handles both block translation modes:\n * - Shared layout (localized: false): loads locale=NULL rows, merges translations,\n * clears untranslated translatable fields to '' (strict mode for admin editing)\n * - Per-locale layout (localized: true): loads rows matching the provided locale only\n *\n * @param entityIds - Entity IDs to load blocks for\n * @param locale - Content locale (omit for default locale / base data)\n * @param options.defaultLocale - Default locale; NULL rows fall back only for this locale\n */\n private async loadBlocks(\n entityIds: string[],\n locale?: string,\n options?: { defaultLocale?: string },\n ): Promise<Map<string, Record<string, unknown[]>>> {\n const blocksFields = this.getBlocksFields()\n if (blocksFields.length === 0 || entityIds.length === 0) {\n return new Map()\n }\n\n const layoutTable = schemaRegistry.get(`${this.entity.name}_layout`)\n if (!layoutTable) return new Map()\n\n // Determine block field modes\n const sharedFields = blocksFields.filter(\n ({ config }) => !('localized' in config && config.localized),\n )\n const localizedFields = blocksFields.filter(\n ({ config }) => 'localized' in config && config.localized,\n )\n\n const result = new Map<string, Record<string, unknown[]>>()\n\n // ---- Shared blocks: locale IS NULL, translations from layout_translations ----\n if (sharedFields.length > 0) {\n const rows = await this.db\n .select()\n .from(layoutTable)\n .where(and(inArray(layoutTable.entityId, entityIds), isNull(layoutTable.locale)))\n .orderBy(layoutTable.sortOrder)\n\n // Load translations if locale provided\n let blockTransMap: Map<string, Record<string, unknown>> | undefined\n if (locale && rows.length > 0) {\n const layoutTransTable = schemaRegistry.get(`${this.entity.name}_layout_translations`)\n if (layoutTransTable) {\n const layoutIds = rows.map((r) => r.id as string)\n const translations = await this.db\n .select()\n .from(layoutTransTable)\n .where(\n and(\n inArray(layoutTransTable.layoutId, layoutIds),\n eq(layoutTransTable.locale, locale),\n ),\n )\n\n blockTransMap = new Map()\n for (const t of translations) {\n blockTransMap.set(t.layoutId as string, (t.fields as Record<string, unknown>) ?? {})\n }\n }\n }\n\n // Build block definition lookup for translatable field clearing\n const blockDefMap = new Map<string, Record<string, FieldConfig>>()\n for (const { config } of sharedFields) {\n if (config.type !== 'blocks') continue\n for (const def of config.blocks) {\n blockDefMap.set(def.slug, def.fields)\n }\n }\n\n for (const row of rows) {\n const eid = row.entityId as string\n const fname = row.fieldName as string\n\n if (!result.has(eid)) result.set(eid, {})\n const entityBlocks = result.get(eid)!\n if (!entityBlocks[fname]) entityBlocks[fname] = []\n\n const blockData = (row.data as Record<string, unknown>) ?? {}\n const translatedFields = blockTransMap?.get(row.id as string)\n\n // Build the block object\n const block: Record<string, unknown> = {\n _block: row.blockType,\n _id: row.id,\n ...blockData,\n ...(translatedFields ?? {}),\n }\n\n // Strict mode: clear untranslated translatable fields when loading for non-default locale\n if (locale) {\n const blockType = row.blockType as string\n const fieldDefs = blockDefMap.get(blockType)\n if (fieldDefs) {\n for (const [fieldName, fieldConfig] of Object.entries(fieldDefs)) {\n if (fieldConfig.translatable && !translatedFields?.[fieldName]) {\n block[fieldName] = ''\n }\n }\n }\n }\n\n entityBlocks[fname].push(block)\n }\n }\n\n // ---- Localized blocks: filter by locale column ----\n // NULL rows (from initial create) only fall back for the default locale.\n // Non-default locales without locale-specific rows get an empty array.\n if (localizedFields.length > 0) {\n const isDefault = !locale || locale === options?.defaultLocale\n const localeCondition = locale\n ? isDefault\n ? or(eq(layoutTable.locale, locale), isNull(layoutTable.locale))!\n : eq(layoutTable.locale, locale)\n : isNull(layoutTable.locale)\n\n const rows = await this.db\n .select()\n .from(layoutTable)\n .where(and(inArray(layoutTable.entityId, entityIds), localeCondition))\n .orderBy(layoutTable.sortOrder)\n\n // Group by entityId + fieldName, prefer locale-specific rows over NULL\n const grouped = new Map<string, { localeRows: typeof rows; nullRows: typeof rows }>()\n for (const row of rows) {\n const key = `${row.entityId}::${row.fieldName}`\n if (!grouped.has(key)) grouped.set(key, { localeRows: [], nullRows: [] })\n const group = grouped.get(key)!\n if (row.locale) {\n group.localeRows.push(row)\n } else {\n group.nullRows.push(row)\n }\n }\n\n for (const [, { localeRows, nullRows }] of grouped) {\n // Use locale-specific rows if available, otherwise fall back to NULL\n const effective = localeRows.length > 0 ? localeRows : nullRows\n\n for (const row of effective) {\n const eid = row.entityId as string\n const fname = row.fieldName as string\n\n if (!result.has(eid)) result.set(eid, {})\n const entityBlocks = result.get(eid)!\n if (!entityBlocks[fname]) entityBlocks[fname] = []\n\n const blockData = (row.data as Record<string, unknown>) ?? {}\n\n entityBlocks[fname].push({\n _block: row.blockType,\n _id: row.id,\n ...blockData,\n })\n }\n }\n }\n\n return result\n }\n\n /**\n * Attach loaded blocks to shaped DTOs.\n */\n private attachBlocks(\n entities: Record<string, unknown>[],\n blocksMap: Map<string, Record<string, unknown[]>>,\n ): void {\n const blocksFields = this.getBlocksFields()\n if (blocksFields.length === 0) return\n\n for (const entity of entities) {\n const eid = entity.id as string\n const entityBlocks = blocksMap.get(eid) ?? {}\n\n for (const { name } of blocksFields) {\n entity[name] = entityBlocks[name] ?? []\n }\n }\n }\n\n // ---------------------------------------------------------------\n // Reference tracking (entity_refs)\n // ---------------------------------------------------------------\n\n /**\n * Sync outgoing references in entity_refs after create/update.\n *\n * - 'create': inserts all refs (entity is new, no existing refs)\n * - 'update': deletes refs for changed ref-bearing fields, then inserts new ones\n *\n * Gracefully skips if entity_refs table is not registered (e.g. before migration).\n */\n private async syncRefs(\n entityId: string,\n data: Record<string, unknown>,\n mode: 'create' | 'update',\n ): Promise<void> {\n // Graceful degradation: skip if entity_refs table doesn't exist yet\n if (!schemaRegistry.has('entity_refs')) return\n\n const allFields = this.entity.allFields as Record<string, FieldConfig>\n\n if (mode === 'update') {\n // Only delete refs for fields present in the update data\n const changedRefFields = Object.keys(data).filter((k) => {\n const config = allFields[k]\n return (\n config &&\n (config.type === 'media' || config.type === 'reference' || config.type === 'blocks')\n )\n })\n if (changedRefFields.length > 0) {\n await this.db\n .delete(entityRefs)\n .where(\n and(\n eq(entityRefs.sourceEntity, this.entity.name),\n eq(entityRefs.sourceId, entityId),\n inArray(entityRefs.sourceField, changedRefFields),\n ),\n )\n }\n }\n\n // Extract refs from the data and insert\n const refs = extractRefs(allFields, data)\n if (refs.length > 0) {\n await this.db\n .insert(entityRefs)\n .values(\n refs.map((ref) => ({\n sourceEntity: this.entity.name,\n sourceId: entityId,\n sourceField: ref.sourceField,\n targetEntity: ref.targetEntity,\n targetId: ref.targetId,\n })),\n )\n .onConflictDoNothing()\n }\n }\n\n // ---------------------------------------------------------------\n // Count cache helpers\n // ---------------------------------------------------------------\n\n /**\n * Build a cache key for a count query.\n * Key format: `entityName` for unfiltered, `entityName:where_sql` for filtered.\n */\n private buildCountCacheKey(where?: SQL): string {\n if (!where) return this.entity.name\n // Use SQL's toString() representation as a stable key.\n // This is a display string, not executed — safe for cache keying.\n return `${this.entity.name}:${String(where)}`\n }\n\n /**\n * Invalidate all count cache entries for this entity.\n */\n private invalidateCountCache(): void {\n this.countCache?.invalidate(this.entity.name)\n }\n}\n"],"mappings":"8RAwIA,SAAgB,EACd,EACA,EACY,CACZ,IAAM,EAAO,EAAgB,EAAM,CAC7B,EAAS,EAAK,EAAO,OAC3B,GAAI,CAAC,EAAQ,OAAO,KAGpB,IAAM,EADS,EAAO,YAAc,OACX,EAAK,EAGxB,EAAiB,EAAQ,EAAQ,EAAO,MAAM,CAGpD,GAAI,CAAC,EAAO,GACV,OAAO,EAIT,IAAM,EAAW,EAAK,GACtB,GAAI,CAAC,EAAU,OAAO,EAEtB,IAAM,EAAc,EAAQ,EAAU,EAAO,GAAG,CAChD,OAAO,EAAG,EAAgB,EAAI,EAAG,EAAQ,EAAO,MAAM,CAAE,EAAY,CAAC,CC7IvE,SAAgB,EACd,EACA,EACA,EACkC,CAClC,GAAI,CAAC,EAAK,OAAO,KAEjB,IAAM,EAAkC,EAAE,CACpC,EAAkB,GAAS,QAAU,OAAO,KAAK,EAAO,UAAU,CAExE,IAAK,IAAM,KAAa,EAAiB,CACvC,GAAI,CAAC,GAAS,iBAAmB,EAAU,WAAW,IAAI,CAAE,SAE5D,IAAM,EAAe,EAAO,UAA0C,GACjE,GAGD,EAAY,OAAS,WAEzB,EAAO,GAAa,EAAI,IAG1B,OAAO,EAMT,SAAgB,EACd,EACA,EACA,EACsC,CACtC,OAAO,EAAK,IAAK,GAAQ,EAAS,EAAQ,EAAK,EAAQ,CAAC,CC9C1D,IAAa,EAAb,cAA2C,KAAM,CAC/C,WACA,SACA,OAEA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izzle-orm";
2
2
  import { SQL } from "drizzle-orm";
3
3
  import * as _$drizzle_orm_pg_core0 from "drizzle-orm/pg-core";
4
- import { PgTable, PgTableWithColumns } from "drizzle-orm/pg-core";
4
+ import { PgTable } from "drizzle-orm/pg-core";
5
5
  import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
6
6
 
7
7
  //#region src/admin-config.d.ts
@@ -313,7 +313,9 @@ declare const field: {
313
313
  /**
314
314
  * Select field (enum)
315
315
  * Preserves literal option types for type inference.
316
+ * String options → varchar column, number options → integer column.
316
317
  * e.g. field.select({ options: ['news', 'tutorial'] }) infers 'news' | 'tutorial'
318
+ * e.g. field.select({ options: [0, 1, 2, 3] }) infers 0 | 1 | 2 | 3
317
319
  */
318
320
  select: <const O extends readonly string[], const C extends Omit<Partial<SelectField>, "options"> = {}>(config: {
319
321
  options: O;
@@ -491,7 +493,7 @@ declare function decodeCursor(encoded: string): DecodedCursor | null;
491
493
  * @param cursor - Decoded and validated cursor
492
494
  * @returns SQL condition, or null if the field doesn't exist on the table
493
495
  */
494
- declare function buildCursorCondition(table: PgTableWithColumns<any>, cursor: DecodedCursor): SQL | null;
496
+ declare function buildCursorCondition(table: PgTable, cursor: DecodedCursor): SQL | null;
495
497
  //#endregion
496
498
  //#region src/define-entity.d.ts
497
499
  /**
@@ -540,7 +542,6 @@ interface Entity<AllFields extends Record<string, FieldConfig> = Record<string,
540
542
  /** Admin UI configuration — controls sidebar, list, and form display */
541
543
  admin?: EntityAdminConfig;
542
544
  allFields: AllFields;
543
- hooks: Behavior['hooks'];
544
545
  }
545
546
  /**
546
547
  * Extract and intersect behavior field types from a behaviors tuple.
@@ -585,13 +586,6 @@ declare class ReferencedEntityError extends Error {
585
586
  }
586
587
  //#endregion
587
588
  //#region src/schema-generator.d.ts
588
- type AnyTable = PgTable<any>;
589
- /**
590
- * Convert a field config to a Drizzle column.
591
- *
592
- * @param nullable - When true, skips notNull and default constraints.
593
- * Used for translation table columns (translations are partial overrides).
594
- */
595
589
  /**
596
590
  * Generate a runtime Drizzle schema from an entity definition.
597
591
  * Every field becomes its own column — no JSONB.
@@ -629,7 +623,7 @@ declare function generateSchema(entity: Entity): _$drizzle_orm_pg_core0.PgTableW
629
623
  * DELETE CASCADE`. Callers that only need the table shape for query
630
624
  * building (core/app.ts, content/plugin.ts) can omit `parent`.
631
625
  */
632
- declare function generateTranslationSchema(entity: Entity, parent?: AnyTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
626
+ declare function generateTranslationSchema(entity: Entity, parent?: PgTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
633
627
  name: string;
634
628
  schema: undefined;
635
629
  columns: {
@@ -667,7 +661,7 @@ declare function hasBlocksFields(entity: Entity): boolean;
667
661
  * `parent` is optional — when provided, emits a `.references()` FK (for
668
662
  * migration generation); query-runtime callers can omit it.
669
663
  */
670
- declare function generateLayoutSchema(entity: Entity, parent?: AnyTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
664
+ declare function generateLayoutSchema(entity: Entity, parent?: PgTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
671
665
  name: string;
672
666
  schema: undefined;
673
667
  columns: {
@@ -813,7 +807,7 @@ declare function needsLocaleStatus(entity: Entity): boolean;
813
807
  */
814
808
  declare function isPublishable(entity: Entity): boolean;
815
809
  /** Per-locale publish status table for publishable + translatable entities. */
816
- declare function generateLocaleStatusSchema(entity: Entity, parent: AnyTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
810
+ declare function generateLocaleStatusSchema(entity: Entity, parent: PgTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
817
811
  name: string;
818
812
  schema: undefined;
819
813
  columns: {
@@ -910,7 +904,7 @@ declare function generateLocaleStatusSchema(entity: Entity, parent: AnyTable): _
910
904
  dialect: "pg";
911
905
  }>;
912
906
  /** Drafts overlay table for publishable entities. */
913
- declare function generateDraftsSchema(entity: Entity, parent: AnyTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
907
+ declare function generateDraftsSchema(entity: Entity, parent: PgTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
914
908
  name: string;
915
909
  schema: undefined;
916
910
  columns: {
@@ -1060,7 +1054,7 @@ declare function generateDraftsSchema(entity: Entity, parent: AnyTable): _$drizz
1060
1054
  dialect: "pg";
1061
1055
  }>;
1062
1056
  /** Versions history table for versionable entities. */
1063
- declare function generateVersionsSchema(entity: Entity, parent: AnyTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
1057
+ declare function generateVersionsSchema(entity: Entity, parent: PgTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
1064
1058
  name: string;
1065
1059
  schema: undefined;
1066
1060
  columns: {
@@ -1430,7 +1424,7 @@ declare function hasTranslatableBlocks(entity: Entity): boolean;
1430
1424
  * pointing at the corresponding `{entity}_layout` table (for migration
1431
1425
  * generation).
1432
1426
  */
1433
- declare function generateLayoutTranslationSchema(entity: Entity, layoutParent?: AnyTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
1427
+ declare function generateLayoutTranslationSchema(entity: Entity, layoutParent?: PgTable): _$drizzle_orm_pg_core0.PgTableWithColumns<{
1434
1428
  name: string;
1435
1429
  schema: undefined;
1436
1430
  columns: {
@@ -1521,7 +1515,7 @@ declare function generateLayoutTranslationSchema(entity: Entity, layoutParent?:
1521
1515
  * internal tables are added separately by reading each plugin's
1522
1516
  * `tables` field.
1523
1517
  */
1524
- declare function buildEntitySchemaMap(entities: Entity[]): Record<string, AnyTable>;
1518
+ declare function buildEntitySchemaMap(entities: Entity[]): Record<string, PgTable>;
1525
1519
  //#endregion
1526
1520
  export { type AuditableFields, type Behavior, type BehaviorFactory, type BlockDefinitionRef, type BlocksField, type BooleanField, CountCache, type CountCacheLike, type CursorInput, type DateField, type Entity, type EntityAdminConfig, type EntityDefinition, type EntityInput, type EntityUsage, type FieldConfig, type FieldToTS, type HierarchicalFields, type IdField, type InferCreateInput, type InferEntity, type InferEntityDTO, type InferUpdateInput, type JsonField, type MediaField, type NumberField, type PublishableFields, type ReferenceField, ReferencedEntityError, type RevisionableFields, type RichTextField, type SelectField, type SlugField, type SluggableFields, type SluggableOptions, type TextField, auditable, behavior, buildCursorCondition, buildEntitySchemaMap, decodeCursor, defineEntity, encodeCursor, estimateRowCount, field, generateContentLocksSchema, generateDraftsSchema, generateLayoutSchema, generateLayoutTranslationSchema, generateLocaleStatusSchema, generateSchema, generateTranslationSchema, generateVersionsSchema, hasBlocksFields, hasTranslatableBlocks, hierarchical, isPublishable, isVersionable, needsLocaleStatus, publishable, revisionable, sluggable, slugify, timestamped };
1527
1521
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/admin-config.ts","../src/fields/base.ts","../src/types/infer.ts","../src/behaviors/types.ts","../src/behaviors/auditable.ts","../src/behaviors/hierarchical.ts","../src/behaviors/publishable.ts","../src/behaviors/revisionable.ts","../src/behaviors/sluggable.ts","../src/fields/builders.ts","../src/behaviors/timestamped.ts","../src/behaviors/index.ts","../src/count-cache.ts","../src/count-estimate.ts","../src/cursor.ts","../src/define-entity.ts","../src/refs/find-usages.ts","../src/refs/errors.ts","../src/schema-generator.ts"],"mappings":";;;;;;;;;;;UAIiB,iBAAA;;EAEf,KAAA;EAFe;EAIf,KAAA;;EAEA,aAAA;EAJA;EAMA,IAAA;EAFA;EAIA,WAAA;EAAA;EAEA,MAAA;EAEA;EAAA,YAAA;EAIA;EAFA,aAAA;EAEkC;EAAlC,cAAA,GAAiB,MAAA;IAAiB,KAAA;IAAgB,WAAA;IAAsB,WAAA;EAAA;EAQxE;EANA,WAAA;EAUA;EARA,oBAAA;EAoBA;EAlBA,QAAA;EAuBiB;EArBjB,UAAA;;EAEA,aAAA;;EAEA,SAAA;EC7B8B;;;;;EDmC9B,MAAA;EC/BA;;;;;EDqCA,YAAA;ECjCM;AAIR;;;EDkCE,iBAAA;AAAA;;;;;;;UC9Ce,eAAA;EACf,QAAA;EACA,OAAA;EACA,YAAA;EACA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behaviors/hierarchical.ts","../src/behaviors/publishable.ts","../src/behaviors/revisionable.ts","../src/behaviors/sluggable.ts","../src/fields/builders.ts","../src/behaviors/timestamped.ts","../src/behaviors/index.ts","../src/count-cache.ts","../src/count-estimate.ts","../src/cursor.ts","../src/define-entity.ts","../src/refs/find-usages.ts","../src/refs/errors.ts","../src/schema-generator.ts"],"mappings":";;;;;;;;;;;UAIiB,iBAAA;;EAEf,KAAA;EAFe;EAIf,KAAA;;EAEA,aAAA;EAJA;EAMA,IAAA;EAFA;EAIA,WAAA;EAAA;EAEA,MAAA;EAEA;EAAA,YAAA;EAIA;EAFA,aAAA;EAEkC;EAAlC,cAAA,GAAiB,MAAA;IAAiB,KAAA;IAAgB,WAAA;IAAsB,WAAA;EAAA;EAQxE;EANA,WAAA;EAUA;EARA,oBAAA;EAoBA;EAlBA,QAAA;EAuBiB;EArBjB,UAAA;;EAEA,aAAA;;EAEA,SAAA;EC7B8B;;;;;EDmC9B,MAAA;EC/BA;;;;;EDqCA,YAAA;ECjCM;AAIR;;;EDkCE,iBAAA;AAAA;;;;;;;UC9Ce,eAAA;EACf,QAAA;EACA,OAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;EACA,MAAA;IACE,IAAA;IACA,IAAA;EAAA;AAAA;AAAA,UAIa,OAAA,SAAgB,eAAA;EAC/B,IAAA;AAAA;AAAA,UAGe,SAAA,SAAkB,eAAA;EACjC,IAAA;EACA,SAAA;EACA,SAAA;EACA,OAAA,GAAU,MAAA;AAAA;AAAA,UAGK,WAAA,SAAoB,eAAA;EACnC,IAAA;EACA,GAAA;EACA,GAAA;EACA,OAAA;AAAA;AAAA,UAGe,YAAA,SAAqB,eAAA;EACpC,IAAA;AAAA;AAAA,UAGe,SAAA,SAAkB,eAAA;EACjC,IAAA;EACA,OAAA,GAAU,IAAA;EACV,OAAA,GAAU,IAAA;AAAA;AAAA,UAGK,WAAA,SAAoB,eAAA;EACnC,IAAA;EACA,OAAA;AAAA;AAAA,UAGe,cAAA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