@murumets-ee/entity 0.8.0 → 0.9.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/shared/entity-data-ops.ts","../../src/query/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 * Shared entity data operations.\n *\n * Extracted from AdminClient and QueryClient to eliminate duplication.\n * These are standalone functions that take an EntityContext — both clients\n * satisfy this interface via `this`.\n */\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, inArray, isNull, or, type SQL } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { Entity } from '../define-entity.js'\nimport type { FieldConfig } from '../fields/base.js'\n\n// ---------------------------------------------------------------------------\n// Context interface — satisfied by both AdminClient and QueryClient via `this`\n// ---------------------------------------------------------------------------\n\n/**\n * Security context resolved per-request. Provided by the consumer\n * (e.g., via React.cache() in Next.js, or runAsCli for CLI).\n * The entity package has zero knowledge of how this is resolved.\n */\nexport interface SecurityContext {\n user: { id: string; groups: string[] }\n checker: (role: string, resource: string, action: string) => boolean\n scope?: { type: string; id: string }\n}\n\n/**\n * Function that resolves the current request's security context.\n * Injected at construction time — the entity package never imports\n * @murumets-ee/core or any framework-specific code.\n *\n * Returns undefined only when intentionally skipping enforcement\n * (should not happen in production — throw ForbiddenError instead).\n */\nexport type ContextResolver = () => SecurityContext | undefined | Promise<SecurityContext | undefined>\n\nexport interface EntityContext {\n entity: Entity\n db: PostgresJsDatabase\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any>\n table: PgTableWithColumns<any>\n /** Resolves the current request's security context. */\n resolveContext?: ContextResolver\n}\n\n// ---------------------------------------------------------------------------\n// Field accessors\n// ---------------------------------------------------------------------------\n\n/** Get the entity's full field map with proper typing. Eliminates repeated casts. */\nexport function getAllFields(ctx: EntityContext): Record<string, FieldConfig> {\n return ctx.entity.allFields as Record<string, FieldConfig>\n}\n\n/** Get all blocks field definitions for this entity. */\nexport function getBlocksFields(ctx: EntityContext): Array<{ name: string; config: FieldConfig }> {\n return Object.entries(getAllFields(ctx))\n .filter(([_, config]) => config.type === 'blocks')\n .map(([name, config]) => ({ name, config }))\n}\n\n// ---------------------------------------------------------------------------\n// Translation merging\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 */\nexport async function mergeTranslations<T extends Record<string, unknown>>(\n ctx: EntityContext,\n entities: T[],\n locale: string,\n): Promise<T[]> {\n if (!entities.length) return entities\n\n const translationTableName = `${ctx.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 ctx.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(getAllFields(ctx))\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// Block loading\n// ---------------------------------------------------------------------------\n\nexport interface LoadBlocksOptions {\n defaultLocale?: string\n /**\n * When true (admin editing), clears untranslated translatable block fields\n * to empty string — signals incomplete translation in the editing UI.\n * When false (visitor-facing), preserves base data as fallback.\n */\n strictTranslations?: boolean\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 * - Per-locale layout (localized: true): loads rows matching the provided locale only\n */\nexport async function loadBlocks(\n ctx: EntityContext,\n entityIds: string[],\n locale?: string,\n options?: LoadBlocksOptions,\n): Promise<Map<string, Record<string, unknown[]>>> {\n const blocksFields = getBlocksFields(ctx)\n if (blocksFields.length === 0 || entityIds.length === 0) {\n return new Map()\n }\n\n const layoutTable = schemaRegistry.get(`${ctx.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 ctx.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(`${ctx.entity.name}_layout_translations`)\n if (layoutTransTable) {\n const layoutIds = rows.map((r) => r.id as string)\n const translations = await ctx.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 (strict mode only)\n let blockDefMap: Map<string, Record<string, FieldConfig>> | undefined\n if (options?.strictTranslations) {\n blockDefMap = new Map()\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\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 && blockDefMap) {\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 ctx.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 */\nexport function attachBlocks(\n ctx: EntityContext,\n entities: Record<string, unknown>[],\n blocksMap: Map<string, Record<string, unknown[]>>,\n): void {\n const blocksFields = getBlocksFields(ctx)\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// Count cache key\n// ---------------------------------------------------------------------------\n\n/**\n * Build a cache key for a count query.\n * @param prefix - Optional namespace prefix (e.g. 'query' for QueryClient)\n * @param scopeId - Optional scope ID for multi-tenant isolation\n */\nexport function buildCountCacheKey(\n entityName: string,\n where?: SQL,\n prefix?: string,\n scopeId?: string,\n): string {\n let base = prefix ? `${prefix}:${entityName}` : entityName\n if (scopeId) base = `${base}@${scopeId}`\n if (!where) return base\n // Use SQL's toString() representation as a stable key.\n // This is a display string, not executed — safe for cache keying.\n return `${base}:${String(where)}`\n}\n\n// ---------------------------------------------------------------------------\n// ForbiddenError\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a user lacks permission for an entity operation.\n * Consumers (api-handler) catch this and return HTTP 403.\n */\nexport class ForbiddenError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ForbiddenError'\n }\n}\n\n// ---------------------------------------------------------------------------\n// Context helpers — dynamic imports to avoid entity → core circular dep\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Context resolution — framework-agnostic\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the security context from the resolver on EntityContext.\n * Throws ForbiddenError if no resolver is configured or if it returns undefined.\n */\nasync function resolveSecurityContext(resolver: ContextResolver | undefined): Promise<SecurityContext> {\n if (!resolver) {\n throw new ForbiddenError(\n 'No context resolver configured on AdminClient/QueryClient. ' +\n 'Use createAdminClient() from @murumets-ee/core/clients, or pass a contextResolver in config.',\n )\n }\n\n const ctx = await resolver()\n\n if (!ctx) {\n throw new ForbiddenError(\n 'Context resolver returned no context. ' +\n 'Ensure auth is configured in your request handler, or use runAsCli() for CLI scripts.',\n )\n }\n\n return ctx\n}\n\n// ---------------------------------------------------------------------------\n// Permission enforcement\n// ---------------------------------------------------------------------------\n\n/**\n * Assert the current user has permission for the given action on the entity.\n * Uses the PermissionChecker from the resolved SecurityContext.\n */\nexport async function assertEntityAccess(\n entity: Entity,\n resolver: ContextResolver | undefined,\n action: 'view' | 'create' | 'update' | 'delete',\n): Promise<void> {\n const ctx = await resolveSecurityContext(resolver)\n\n const role = ctx.user.groups[0]\n if (!role) {\n throw new ForbiddenError(`User '${ctx.user.id}' has no role assigned.`)\n }\n\n if (!ctx.checker(role, entity.name, action)) {\n throw new ForbiddenError(\n `Forbidden: role '${role}' cannot ${action} '${entity.name}'`,\n )\n }\n}\n\n// ---------------------------------------------------------------------------\n// Scope filtering\n// ---------------------------------------------------------------------------\n\n/**\n * Get the current scope ID for a scoped entity.\n * Returns undefined for global entities.\n */\nexport async function getScopeId(\n entity: Entity,\n resolver: ContextResolver | undefined,\n): Promise<string | undefined> {\n if (!entity.scope || entity.scope === 'global') return undefined\n\n const ctx = await resolveSecurityContext(resolver)\n return ctx.scope?.id\n}\n\n/**\n * Build a WHERE condition for scope filtering.\n */\nexport function buildScopeCondition(\n ctx: EntityContext,\n scopeId: string,\n): SQL {\n return eq(ctx.table._scopeId, scopeId)\n}\n\n/**\n * Require scope for a scoped entity. Throws if no scope is in context.\n * Returns undefined for global entities.\n */\nexport async function requireScopeForEntity(\n entity: Entity,\n resolver: ContextResolver | undefined,\n): Promise<string | undefined> {\n if (!entity.scope || entity.scope === 'global') return undefined\n\n const ctx = await resolveSecurityContext(resolver)\n const scopeId = ctx.scope?.id\n\n if (!scopeId) {\n throw new ForbiddenError(\n `Entity '${entity.name}' requires scope '${entity.scope}' but no scope is set in context.`,\n )\n }\n\n return scopeId\n}\n","/**\n * QueryClient - Read-only client for frontend use\n * SAFE for client bundles - NO 'server-only' import\n */\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, type SQL, sql } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\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 {\n assertEntityAccess,\n attachBlocks,\n buildCountCacheKey,\n buildScopeCondition,\n getAllFields,\n getBlocksFields,\n getScopeId,\n loadBlocks,\n mergeTranslations,\n type ContextResolver,\n type EntityContext,\n} from '../shared/entity-data-ops.js'\nimport type { InferEntityDTO } from '../types/infer.js'\nimport type { Logger } from '../types/logger.js'\n\nexport interface QueryClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n entity: Entity<AllFields>\n db: PostgresJsDatabase // Read-only connection (enforced at PostgreSQL level)\n logger?: Logger\n /** Optional count cache for COUNT(*) query optimization. */\n countCache?: CountCacheLike\n /** Resolves the current request's security context. */\n contextResolver?: ContextResolver\n}\n\nexport interface FindByIdOptions {\n select?: string[]\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\nexport interface FindManyOptions {\n where?: SQL | undefined\n limit?: number\n offset?: number\n orderBy?: SQL | SQL[]\n select?: string[]\n locale?: string\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 * QueryClient - Read-only entity access for frontends\n *\n * **Requires RequestContext.** All operations check permissions and scope via\n * the context established by `runWithContextAsync()`. CLI scripts use `runAsCli()`.\n *\n * Security & integrity layers:\n * 1. Permission enforcement: `assertEntityAccess()` checks `checker(role, entity, 'view')` from context\n * 2. Scope filtering: scoped entities auto-filter by `_scopeId` from context\n * 3. Publish filtering: publishable entities auto-filter to `status = 'published'`\n * 4. Read-only DB connection (PostgreSQL enforces with `default_transaction_read_only=on`)\n * 5. NO mutation methods on TypeScript type (create/update/delete don't exist)\n *\n * @typeParam AllFields - The entity's complete field map. Inferred automatically\n * when constructing via `createQueryClient(entity)`.\n */\nexport class QueryClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private entity: Entity<AllFields>\n private db: PostgresJsDatabase\n private logger?: Logger\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any> for property access\n private table: PgTableWithColumns<any>\n private isPublishable: boolean\n private countCache?: CountCacheLike\n private contextResolver?: ContextResolver\n\n /** Shared context for entity-data-ops functions. */\n private get ctx(): EntityContext {\n return { entity: this.entity, db: this.db, table: this.table, resolveContext: this.contextResolver }\n }\n\n constructor(config: QueryClientConfig<AllFields>) {\n this.entity = config.entity\n this.db = config.db // Assumes read-only connection passed from outside\n this.logger = config.logger\n this.countCache = config.countCache\n this.contextResolver = config.contextResolver\n\n // Detect if entity has publishable behavior\n this.isPublishable = config.entity.behaviors?.some((b) => b.name === 'publishable') ?? false\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 QueryClient.',\n )\n }\n this.table = table\n }\n\n /**\n * Find entity by ID\n * Auto-filters to published if entity has publishable() behavior\n * PHASE 3: Merges translations if locale is provided\n */\n async findById(id: string, options?: FindByIdOptions): Promise<InferEntityDTO<AllFields> | null> {\n this.logger?.info(\n { entity: this.entity.name, id, locale: options?.locale },\n 'Query: Finding entity by ID',\n )\n\n // Permission + scope enforcement\n await assertEntityAccess(this.entity, this.contextResolver, 'view')\n const scopeId = await getScopeId(this.entity, this.contextResolver)\n\n // Query database\n const whereConditions = [eq(this.table.id, id)]\n\n // Scope filter\n if (scopeId) whereConditions.push(buildScopeCondition(this.ctx, scopeId))\n\n // Auto-filter to published if entity has publishable behavior\n if (this.isPublishable) {\n whereConditions.push(this.buildPublishFilter(options?.locale))\n }\n\n const [row] = await this.db\n .select()\n .from(this.table)\n .where(and(...whereConditions))\n\n if (!row) return null\n\n // Shape DTO (row is non-null here, so shaped result will be non-null)\n const shaped = shapeDto(this.entity, row, { select: options?.select }) as Record<\n string,\n unknown\n >\n if (!shaped) return null\n\n // Attach blocks from layout table (with locale for block translations)\n if (getBlocksFields(this.ctx).length > 0) {\n const blocksMap = await loadBlocks(this.ctx, [shaped.id as string], options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n attachBlocks(this.ctx, [shaped], blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n const merged = await mergeTranslations(this.ctx,[shaped], options.locale)\n return merged[0] as InferEntityDTO<AllFields>\n }\n\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Find multiple entities\n * Auto-filters to published if entity has publishable() behavior\n * PHASE 3: Merges translations if locale is provided\n */\n async findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n this.logger?.info(\n { entity: this.entity.name, options, locale: options?.locale },\n 'Query: Finding entities',\n )\n\n // Permission + scope enforcement\n await assertEntityAccess(this.entity, this.contextResolver, 'view')\n const scopeId = await getScopeId(this.entity, this.contextResolver)\n\n // Build query\n let query = this.db.select().from(this.table).$dynamic()\n\n // Collect WHERE conditions\n const conditions: SQL[] = []\n\n // Scope filter\n if (scopeId) conditions.push(buildScopeCondition(this.ctx, scopeId))\n\n // Auto-filter to published if entity has publishable behavior\n if (this.isPublishable) {\n conditions.push(this.buildPublishFilter(options?.locale))\n }\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 = getAllFields(this.ctx)\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 // Shape DTOs (filter out null results)\n const shaped = shapeDtos(this.entity, rows, { select: options?.select }).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 (getBlocksFields(this.ctx).length > 0 && shaped.length > 0) {\n const entityIds = shaped.map((e) => e.id as string)\n const blocksMap = await loadBlocks(this.ctx, entityIds, options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n attachBlocks(this.ctx, shaped, blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n return (await mergeTranslations(this.ctx,shaped, options.locale)) as InferEntityDTO<AllFields>[]\n }\n\n return shaped as InferEntityDTO<AllFields>[]\n }\n\n /**\n * Count entities\n * Auto-filters to published if entity has publishable() behavior\n */\n async count(options?: CountOptions): Promise<number> {\n this.logger?.info({ entity: this.entity.name, options }, 'Query: Counting entities')\n\n // Permission + scope enforcement\n await assertEntityAccess(this.entity, this.contextResolver, 'view')\n const scopeId = await getScopeId(this.entity, this.contextResolver)\n\n // Build cache key: entityName + serialized WHERE (or empty for unfiltered)\n const cacheKey = buildCountCacheKey(this.entity.name, options?.where, 'query', scopeId)\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 // Build count query\n let query = this.db.select({ count: sql<number>`count(*)` }).from(this.table).$dynamic()\n\n // Collect conditions: scope + publish filter + user-provided WHERE\n const conditions: SQL[] = []\n if (scopeId) conditions.push(buildScopeCondition(this.ctx, scopeId))\n if (this.isPublishable) conditions.push(this.buildPublishFilter())\n if (options?.where) conditions.push(options.where)\n if (conditions.length > 0) query = query.where(and(...conditions))\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 * Build publish filter SQL condition.\n * When a locale is provided and a locale_status table exists,\n * uses COALESCE to check locale-specific status first, falling back to base status.\n */\n private buildPublishFilter(locale?: string): SQL {\n if (locale) {\n const localeStatusTable = schemaRegistry.get(`${this.entity.name}_locale_status`)\n if (localeStatusTable) {\n return sql`COALESCE(\n (SELECT ${localeStatusTable.status} FROM ${localeStatusTable}\n WHERE ${localeStatusTable.entityId} = ${this.table.id}\n AND ${localeStatusTable.locale} = ${locale}),\n ${this.table.status}\n ) = 'published'`\n }\n }\n return eq(this.table.status, 'published')\n }\n\n // mergeTranslations, getBlocksFields, loadBlocks, attachBlocks, buildCountCacheKey\n // → extracted to ../shared/entity-data-ops.ts (shared with AdminClient)\n\n // NO create/update/delete methods\n // These physically don't exist on the TypeScript type - security by design\n}\n"],"mappings":"0KAwIA,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,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OAAQ,YAAY"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/cursor.ts","../../src/dto-shaper.ts","../../src/shared/entity-data-ops.ts","../../src/query/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 * Shared entity data operations.\n *\n * Extracted from AdminClient and QueryClient to eliminate duplication.\n * These are standalone functions that take an EntityContext — both clients\n * satisfy this interface via `this`.\n */\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, inArray, isNull, or, type SQL } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { Entity } from '../define-entity.js'\nimport type { FieldConfig } from '../fields/base.js'\n\n// ---------------------------------------------------------------------------\n// Context interface — satisfied by both AdminClient and QueryClient via `this`\n// ---------------------------------------------------------------------------\n\n/**\n * Security context resolved per-request. Provided by the consumer\n * (e.g., via React.cache() in Next.js, or runAsCli for CLI).\n * The entity package has zero knowledge of how this is resolved.\n */\nexport interface SecurityContext {\n user: { id: string; groups: string[]; name?: string; email?: string }\n checker: (role: string, resource: string, action: string) => boolean\n scope?: { type: string; id: string }\n}\n\n/**\n * Function that resolves the current request's security context.\n * Injected at construction time — the entity package never imports\n * @murumets-ee/core or any framework-specific code.\n *\n * Returns undefined only when intentionally skipping enforcement\n * (should not happen in production — throw ForbiddenError instead).\n */\nexport type ContextResolver = () => SecurityContext | undefined | Promise<SecurityContext | undefined>\n\nexport interface EntityContext {\n entity: Entity\n db: PostgresJsDatabase\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any>\n table: PgTableWithColumns<any>\n /** Resolves the current request's security context. */\n resolveContext?: ContextResolver\n}\n\n// ---------------------------------------------------------------------------\n// Field accessors\n// ---------------------------------------------------------------------------\n\n/** Get the entity's full field map with proper typing. Eliminates repeated casts. */\nexport function getAllFields(ctx: EntityContext): Record<string, FieldConfig> {\n return ctx.entity.allFields as Record<string, FieldConfig>\n}\n\n/** Get all blocks field definitions for this entity. */\nexport function getBlocksFields(ctx: EntityContext): Array<{ name: string; config: FieldConfig }> {\n return Object.entries(getAllFields(ctx))\n .filter(([_, config]) => config.type === 'blocks')\n .map(([name, config]) => ({ name, config }))\n}\n\n// ---------------------------------------------------------------------------\n// Translation merging\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 */\nexport async function mergeTranslations<T extends Record<string, unknown>>(\n ctx: EntityContext,\n entities: T[],\n locale: string,\n): Promise<T[]> {\n if (!entities.length) return entities\n\n const translationTableName = `${ctx.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 ctx.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(getAllFields(ctx))\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// Block loading\n// ---------------------------------------------------------------------------\n\nexport interface LoadBlocksOptions {\n defaultLocale?: string\n /**\n * When true (admin editing), clears untranslated translatable block fields\n * to empty string — signals incomplete translation in the editing UI.\n * When false (visitor-facing), preserves base data as fallback.\n */\n strictTranslations?: boolean\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 * - Per-locale layout (localized: true): loads rows matching the provided locale only\n */\nexport async function loadBlocks(\n ctx: EntityContext,\n entityIds: string[],\n locale?: string,\n options?: LoadBlocksOptions,\n): Promise<Map<string, Record<string, unknown[]>>> {\n const blocksFields = getBlocksFields(ctx)\n if (blocksFields.length === 0 || entityIds.length === 0) {\n return new Map()\n }\n\n const layoutTable = schemaRegistry.get(`${ctx.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 ctx.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(`${ctx.entity.name}_layout_translations`)\n if (layoutTransTable) {\n const layoutIds = rows.map((r) => r.id as string)\n const translations = await ctx.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 (strict mode only)\n let blockDefMap: Map<string, Record<string, FieldConfig>> | undefined\n if (options?.strictTranslations) {\n blockDefMap = new Map()\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\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 && blockDefMap) {\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 ctx.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 */\nexport function attachBlocks(\n ctx: EntityContext,\n entities: Record<string, unknown>[],\n blocksMap: Map<string, Record<string, unknown[]>>,\n): void {\n const blocksFields = getBlocksFields(ctx)\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// Count cache key\n// ---------------------------------------------------------------------------\n\n/**\n * Build a cache key for a count query.\n * @param prefix - Optional namespace prefix (e.g. 'query' for QueryClient)\n * @param scopeId - Optional scope ID for multi-tenant isolation\n */\nexport function buildCountCacheKey(\n entityName: string,\n where?: SQL,\n prefix?: string,\n scopeId?: string,\n): string {\n let base = prefix ? `${prefix}:${entityName}` : entityName\n if (scopeId) base = `${base}@${scopeId}`\n if (!where) return base\n // Use SQL's toString() representation as a stable key.\n // This is a display string, not executed — safe for cache keying.\n return `${base}:${String(where)}`\n}\n\n// ---------------------------------------------------------------------------\n// ForbiddenError\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a user lacks permission for an entity operation.\n * Consumers (api-handler) catch this and return HTTP 403.\n */\nexport class ForbiddenError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ForbiddenError'\n }\n}\n\n// ---------------------------------------------------------------------------\n// Context helpers — dynamic imports to avoid entity → core circular dep\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Context resolution — framework-agnostic\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the security context from the resolver on EntityContext.\n * Throws ForbiddenError if no resolver is configured or if it returns undefined.\n */\nasync function resolveSecurityContext(resolver: ContextResolver | undefined): Promise<SecurityContext> {\n if (!resolver) {\n throw new ForbiddenError(\n 'No context resolver configured on AdminClient/QueryClient. ' +\n 'Use createAdminClient() from @murumets-ee/core/clients, or pass a contextResolver in config.',\n )\n }\n\n const ctx = await resolver()\n\n if (!ctx) {\n throw new ForbiddenError(\n 'Context resolver returned no context. ' +\n 'Ensure auth is configured in your request handler, or use runAsCli() for CLI scripts.',\n )\n }\n\n return ctx\n}\n\n// ---------------------------------------------------------------------------\n// Permission enforcement\n// ---------------------------------------------------------------------------\n\n/**\n * Assert the current user has permission for the given action on the entity.\n * Uses the PermissionChecker from the resolved SecurityContext.\n */\nexport async function assertEntityAccess(\n entity: Entity,\n resolver: ContextResolver | undefined,\n action: 'view' | 'create' | 'update' | 'delete',\n): Promise<void> {\n const ctx = await resolveSecurityContext(resolver)\n\n const role = ctx.user.groups[0]\n if (!role) {\n throw new ForbiddenError(`User '${ctx.user.id}' has no role assigned.`)\n }\n\n if (!ctx.checker(role, entity.name, action)) {\n throw new ForbiddenError(\n `Forbidden: role '${role}' cannot ${action} '${entity.name}'`,\n )\n }\n}\n\n// ---------------------------------------------------------------------------\n// Scope filtering\n// ---------------------------------------------------------------------------\n\n/**\n * Get the current scope ID for a scoped entity.\n * Returns undefined for global entities.\n */\nexport async function getScopeId(\n entity: Entity,\n resolver: ContextResolver | undefined,\n): Promise<string | undefined> {\n if (!entity.scope || entity.scope === 'global') return undefined\n\n const ctx = await resolveSecurityContext(resolver)\n return ctx.scope?.id\n}\n\n/**\n * Build a WHERE condition for scope filtering.\n */\nexport function buildScopeCondition(\n ctx: EntityContext,\n scopeId: string,\n): SQL {\n return eq(ctx.table._scopeId, scopeId)\n}\n\n/**\n * Require scope for a scoped entity. Throws if no scope is in context.\n * Returns undefined for global entities.\n */\nexport async function requireScopeForEntity(\n entity: Entity,\n resolver: ContextResolver | undefined,\n): Promise<string | undefined> {\n if (!entity.scope || entity.scope === 'global') return undefined\n\n const ctx = await resolveSecurityContext(resolver)\n const scopeId = ctx.scope?.id\n\n if (!scopeId) {\n throw new ForbiddenError(\n `Entity '${entity.name}' requires scope '${entity.scope}' but no scope is set in context.`,\n )\n }\n\n return scopeId\n}\n","/**\n * QueryClient - Read-only client for frontend use\n * SAFE for client bundles - NO 'server-only' import\n */\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, type SQL, sql } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\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 {\n assertEntityAccess,\n attachBlocks,\n buildCountCacheKey,\n buildScopeCondition,\n getAllFields,\n getBlocksFields,\n getScopeId,\n loadBlocks,\n mergeTranslations,\n type ContextResolver,\n type EntityContext,\n} from '../shared/entity-data-ops.js'\nimport type { InferEntityDTO } from '../types/infer.js'\nimport type { Logger } from '../types/logger.js'\n\nexport interface QueryClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n entity: Entity<AllFields>\n db: PostgresJsDatabase // Read-only connection (enforced at PostgreSQL level)\n logger?: Logger\n /** Optional count cache for COUNT(*) query optimization. */\n countCache?: CountCacheLike\n /** Resolves the current request's security context. */\n contextResolver?: ContextResolver\n}\n\nexport interface FindByIdOptions {\n select?: string[]\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\nexport interface FindManyOptions {\n where?: SQL | undefined\n limit?: number\n offset?: number\n orderBy?: SQL | SQL[]\n select?: string[]\n locale?: string\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 * QueryClient - Read-only entity access for frontends\n *\n * **Requires RequestContext.** All operations check permissions and scope via\n * the context established by `runWithContextAsync()`. CLI scripts use `runAsCli()`.\n *\n * Security & integrity layers:\n * 1. Permission enforcement: `assertEntityAccess()` checks `checker(role, entity, 'view')` from context\n * 2. Scope filtering: scoped entities auto-filter by `_scopeId` from context\n * 3. Publish filtering: publishable entities auto-filter to `status = 'published'`\n * 4. Read-only DB connection (PostgreSQL enforces with `default_transaction_read_only=on`)\n * 5. NO mutation methods on TypeScript type (create/update/delete don't exist)\n *\n * @typeParam AllFields - The entity's complete field map. Inferred automatically\n * when constructing via `createQueryClient(entity)`.\n */\nexport class QueryClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private entity: Entity<AllFields>\n private db: PostgresJsDatabase\n private logger?: Logger\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any> for property access\n private table: PgTableWithColumns<any>\n private isPublishable: boolean\n private countCache?: CountCacheLike\n private contextResolver?: ContextResolver\n\n /** Shared context for entity-data-ops functions. */\n private get ctx(): EntityContext {\n return { entity: this.entity, db: this.db, table: this.table, resolveContext: this.contextResolver }\n }\n\n constructor(config: QueryClientConfig<AllFields>) {\n this.entity = config.entity\n this.db = config.db // Assumes read-only connection passed from outside\n this.logger = config.logger\n this.countCache = config.countCache\n this.contextResolver = config.contextResolver\n\n // Detect if entity has publishable behavior\n this.isPublishable = config.entity.behaviors?.some((b) => b.name === 'publishable') ?? false\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 QueryClient.',\n )\n }\n this.table = table\n }\n\n /**\n * Find entity by ID\n * Auto-filters to published if entity has publishable() behavior\n * PHASE 3: Merges translations if locale is provided\n */\n async findById(id: string, options?: FindByIdOptions): Promise<InferEntityDTO<AllFields> | null> {\n this.logger?.info(\n { entity: this.entity.name, id, locale: options?.locale },\n 'Query: Finding entity by ID',\n )\n\n // Permission + scope enforcement\n await assertEntityAccess(this.entity, this.contextResolver, 'view')\n const scopeId = await getScopeId(this.entity, this.contextResolver)\n\n // Query database\n const whereConditions = [eq(this.table.id, id)]\n\n // Scope filter\n if (scopeId) whereConditions.push(buildScopeCondition(this.ctx, scopeId))\n\n // Auto-filter to published if entity has publishable behavior\n if (this.isPublishable) {\n whereConditions.push(this.buildPublishFilter(options?.locale))\n }\n\n const [row] = await this.db\n .select()\n .from(this.table)\n .where(and(...whereConditions))\n\n if (!row) return null\n\n // Shape DTO (row is non-null here, so shaped result will be non-null)\n const shaped = shapeDto(this.entity, row, { select: options?.select }) as Record<\n string,\n unknown\n >\n if (!shaped) return null\n\n // Attach blocks from layout table (with locale for block translations)\n if (getBlocksFields(this.ctx).length > 0) {\n const blocksMap = await loadBlocks(this.ctx, [shaped.id as string], options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n attachBlocks(this.ctx, [shaped], blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n const merged = await mergeTranslations(this.ctx,[shaped], options.locale)\n return merged[0] as InferEntityDTO<AllFields>\n }\n\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Find multiple entities\n * Auto-filters to published if entity has publishable() behavior\n * PHASE 3: Merges translations if locale is provided\n */\n async findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n this.logger?.info(\n { entity: this.entity.name, options, locale: options?.locale },\n 'Query: Finding entities',\n )\n\n // Permission + scope enforcement\n await assertEntityAccess(this.entity, this.contextResolver, 'view')\n const scopeId = await getScopeId(this.entity, this.contextResolver)\n\n // Build query\n let query = this.db.select().from(this.table).$dynamic()\n\n // Collect WHERE conditions\n const conditions: SQL[] = []\n\n // Scope filter\n if (scopeId) conditions.push(buildScopeCondition(this.ctx, scopeId))\n\n // Auto-filter to published if entity has publishable behavior\n if (this.isPublishable) {\n conditions.push(this.buildPublishFilter(options?.locale))\n }\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 = getAllFields(this.ctx)\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 // Shape DTOs (filter out null results)\n const shaped = shapeDtos(this.entity, rows, { select: options?.select }).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 (getBlocksFields(this.ctx).length > 0 && shaped.length > 0) {\n const entityIds = shaped.map((e) => e.id as string)\n const blocksMap = await loadBlocks(this.ctx, entityIds, options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n attachBlocks(this.ctx, shaped, blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n return (await mergeTranslations(this.ctx,shaped, options.locale)) as InferEntityDTO<AllFields>[]\n }\n\n return shaped as InferEntityDTO<AllFields>[]\n }\n\n /**\n * Count entities\n * Auto-filters to published if entity has publishable() behavior\n */\n async count(options?: CountOptions): Promise<number> {\n this.logger?.info({ entity: this.entity.name, options }, 'Query: Counting entities')\n\n // Permission + scope enforcement\n await assertEntityAccess(this.entity, this.contextResolver, 'view')\n const scopeId = await getScopeId(this.entity, this.contextResolver)\n\n // Build cache key: entityName + serialized WHERE (or empty for unfiltered)\n const cacheKey = buildCountCacheKey(this.entity.name, options?.where, 'query', scopeId)\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 // Build count query\n let query = this.db.select({ count: sql<number>`count(*)` }).from(this.table).$dynamic()\n\n // Collect conditions: scope + publish filter + user-provided WHERE\n const conditions: SQL[] = []\n if (scopeId) conditions.push(buildScopeCondition(this.ctx, scopeId))\n if (this.isPublishable) conditions.push(this.buildPublishFilter())\n if (options?.where) conditions.push(options.where)\n if (conditions.length > 0) query = query.where(and(...conditions))\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 * Build publish filter SQL condition.\n * When a locale is provided and a locale_status table exists,\n * uses COALESCE to check locale-specific status first, falling back to base status.\n */\n private buildPublishFilter(locale?: string): SQL {\n if (locale) {\n const localeStatusTable = schemaRegistry.get(`${this.entity.name}_locale_status`)\n if (localeStatusTable) {\n return sql`COALESCE(\n (SELECT ${localeStatusTable.status} FROM ${localeStatusTable}\n WHERE ${localeStatusTable.entityId} = ${this.table.id}\n AND ${localeStatusTable.locale} = ${locale}),\n ${this.table.status}\n ) = 'published'`\n }\n }\n return eq(this.table.status, 'published')\n }\n\n // mergeTranslations, getBlocksFields, loadBlocks, attachBlocks, buildCountCacheKey\n // → extracted to ../shared/entity-data-ops.ts (shared with AdminClient)\n\n // NO create/update/delete methods\n // These physically don't exist on the TypeScript type - security by design\n}\n"],"mappings":"0KAwIA,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,KA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3
+ "version": "0.9.0",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -28,7 +28,7 @@
28
28
  "drizzle-orm": "^0.45.2",
29
29
  "zod": "^3.24.1",
30
30
  "server-only": "^0.0.1",
31
- "@murumets-ee/db": "0.8.0"
31
+ "@murumets-ee/db": "0.9.0"
32
32
  },
33
33
  "devDependencies": {
34
34
  "tsdown": "^0.21.7",