@open-mercato/shared 0.10.1-develop.8274.1.c8f0850146 → 0.10.1-develop.8275.1.44b856bbe6
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,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/data/engine.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityData, EntityName, FilterQuery, RequiredEntityData } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { type Kysely, sql } from 'kysely'\nimport { encryptCustomEntityRecordDocument, setRecordCustomFields } from '@open-mercato/core/modules/entities/lib/helpers'\nimport { validateCustomFieldValuesServer } from '@open-mercato/core/modules/entities/lib/validation'\nimport { sanitizeCustomFieldHtmlRichTextValuesServer } from '@open-mercato/core/modules/entities/lib/htmlRichTextSanitizer'\nimport type { EventBus } from '@open-mercato/events/types'\nimport {\n CRUD_QUERY_INDEX_MANAGED_PAYLOAD_KEY,\n type CrudEventAction,\n type CrudEventsConfig,\n type CrudIndexerConfig,\n type CrudEntityIdentifiers,\n} from '../crud/types'\nimport type { BulkImportSuppression } from '../commands/types'\nimport { conflict, CrudHttpError, isUniqueViolation, notFound } from '../crud/errors'\nimport { AdvisoryLockUnavailableError, withAdvisoryXactLock } from '../db/advisoryLock'\nimport { resolveRegisteredEntityTableName } from '../query/engine'\nimport { getEntityIds } from '../encryption/entityIds'\nimport { normalizeCustomFieldValues } from '../custom-fields/normalize'\nimport { parseBooleanToken } from '../boolean'\nimport { isReadProjectionAlwaysConsistent } from './consistency'\nimport { isEventDeclared } from '../../modules/events'\nimport { createLogger } from '../logger'\nimport { createBoundedTtlMemo } from '../query/bounded-ttl-memo'\nimport type { TenantDataEncryptionService } from '../encryption/tenantDataEncryptionService'\n\nconst logger = createLogger('shared').child({ component: 'data-engine' })\n\nconst undeclaredEventWarned = new Set<string>()\n\nfunction warnIfUndeclaredEvent(eventName: string, context: string): void {\n if (isEventDeclared(eventName)) return\n if (undeclaredEventWarned.has(eventName)) return\n undeclaredEventWarned.add(eventName)\n logger.warn('Emitting undeclared event \u2014 declare it in the owning module events.ts (createModuleEvents) so the event registry stays authoritative', { context, eventName })\n}\n\n/** Internal: clear the undeclared-event warning cache. Exposed for tests. */\nexport function __resetUndeclaredEventWarningsForTests(): void {\n undeclaredEventWarned.clear()\n}\n\n/** Only `true` is cached: a cached `false` would keep this failing after a migration creates the table. */\nconst tableExistsCache = createBoundedTtlMemo<true>({\n ttlEnv: 'OM_DATA_ENGINE_TABLE_EXISTS_CACHE_MS',\n defaultTtlMs: 3_600_000,\n defaultMaxEntries: 1_000,\n})\n\n/** Test-only: the module-scoped memo would otherwise leak state across specs. */\nexport function clearDataEngineTableExistsCache(): void {\n tableExistsCache.clear()\n}\n\nconst COVERAGE_REFRESH_INTERVAL_MS = 5 * 60 * 1000\nconst coverageRefreshTracker = new Map<string, number>()\n\nfunction shouldTriggerCoverageRefresh(entityType: string | undefined, tenantId: string | null): boolean {\n if (!entityType) return false\n const key = `${entityType}|${tenantId ?? '__null__'}`\n const now = Date.now()\n const last = coverageRefreshTracker.get(key) ?? 0\n if (now - last < COVERAGE_REFRESH_INTERVAL_MS) return false\n coverageRefreshTracker.set(key, now)\n return true\n}\n\ntype CustomEntityValues = Record<string, unknown>\n\ntype CustomEntityStorageDatabase = {\n custom_entities_storage: {\n entity_type: string\n entity_id: string\n organization_id: string | null\n tenant_id: string | null\n doc: CustomEntityValues\n updated_at: Date\n created_at: Date\n deleted_at: Date | null\n }\n}\n\ntype QueuedCrudSideEffect = {\n action: CrudEventAction\n entity: unknown\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n events?: CrudEventsConfig<unknown>\n indexer?: CrudIndexerConfig<unknown>\n}\n\n/**\n * A `makeCrudRoute` route-level `indexer:` declaration, handed to the data engine for the\n * duration of one command-bus write. Command handlers own the side-effect mark on the\n * `actions.*` path, and most of them mark `events:` only \u2014 without this the route's\n * declaration would reach no code at all. `entityClass` scopes the default to the route's\n * own ORM entity so a handler that also marks a sibling entity in the same request (a tag\n * assignment alongside a tag, say) is never indexed under the route's `entityType`.\n */\nexport type DefaultCrudIndexerConfig = {\n indexer: CrudIndexerConfig<unknown>\n entityClass: abstract new (...args: never[]) => object\n}\n\nexport interface DataEngine {\n setCustomFields(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: Record<string, string | number | boolean | null | undefined | Array<string | number | boolean | null | undefined>>\n /**\n * Default true: emits the entity-keyed custom-field change signal `<module>.<entity>.updated`,\n * derived from `entityId` (e.g. `catalog:catalog_product` \u2192 `catalog.catalog_product.updated`).\n * It is not a module domain event \u2014 the query_index bridge subscribes to the same derivation for\n * every entity carrying custom fields, including runtime custom entities \u2014 so it is deliberately\n * not checked against the `events.ts` registry.\n */\n notify?: boolean\n // Forwarded to `setRecordCustomFields` \u2014 see its doc for when a caller must pass\n // true (a recordId that is not unique across organizations for this entityId).\n pinOrganizationId?: boolean\n }): Promise<void>\n\n // Storage for user-defined entities (doc-based)\n createCustomEntityRecord(opts: {\n entityId: string // '<module>:<entity>'\n recordId?: string // optional; auto-generate if not provided\n createOnly?: boolean\n organizationId?: string | null\n tenantId?: string | null\n values: CustomEntityValues\n notify?: boolean // keep event emitting as it is via setCustomFields (updated)\n }): Promise<{ id: string }>\n\n updateCustomEntityRecord(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: CustomEntityValues\n notify?: boolean // keep event emitting as it is via setCustomFields (updated)\n requireActive?: boolean\n }): Promise<void>\n\n deleteCustomEntityRecord(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n soft?: boolean // default true: sets deleted_at\n notify?: boolean // keep event emitting as it is (no extra events here)\n }): Promise<void>\n\n // Generic ORM-backed entity operations used by CrudFactory\n createOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n data: EntityData<T>\n }): Promise<T>\n\n updateOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n apply: (current: T) => Promise<void> | void\n }): Promise<T | null>\n\n deleteOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n soft?: boolean\n softDeleteField?: keyof T & string\n }): Promise<T | null>\n\n emitOrmEntityEvent<T>(opts: {\n action: CrudEventAction\n entity: T\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n /** Bulk-import deferral: skip the domain event and/or inline reindex for this emit. */\n suppress?: BulkImportSuppression\n }): Promise<void>\n\n markOrmEntityChange<T>(opts: {\n action: CrudEventAction\n entity: T | null | undefined\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n }): void\n\n /**\n * Drain queued side effects. When `suppress` is passed (a bulk-import backfill), the\n * flagged per-record events / reindex are skipped for every drained entry; the caller\n * is responsible for rebuilding the `query_index` afterwards.\n */\n flushOrmEntityChanges(suppress?: BulkImportSuppression): Promise<void>\n\n /**\n * Declare the indexer a CRUD route configured, for marks made during one command-bus\n * write that do not carry an indexer of their own. Pass `null` to clear it. Optional so\n * third-party `DataEngine` implementations stay valid; callers invoke it with `?.`.\n */\n setDefaultIndexerConfig?(config: DefaultCrudIndexerConfig | null): void\n\n /**\n * Whether any side effect drained since the current default was declared carried an\n * indexer for that default's entity class \u2014 false means the declared query-index\n * obligation was discharged by nobody. Optional for the same reason as the setter.\n */\n hasIndexedDefaultEntityClass?(): boolean\n}\n\nexport const SYSTEM_ENTITY_RECORDS_BLOCKED_CODE = 'system_entity_records_blocked'\n\n/**\n * A system entity for doc-storage purposes is an id that modules declare in the\n * generated entity-id registry AND that resolves to a registered ORM table. Both\n * conditions matter: `resolveRegisteredEntityTableName` matches class-name candidates\n * from the entity segment alone, so a runtime-registered custom entity whose name\n * happens to collide with some ORM class (e.g. `user:todo` vs the example module's\n * `Todo`) must never be classified as system. When the registry is not populated\n * (exotic bootstraps, unit harnesses) the check conservatively falls back to the\n * ORM-table match alone so the #2939 protection never switches off.\n */\nexport function isOrmBackedSystemEntityId(em: EntityManager, entityId: string): boolean {\n const registry = getEntityIds(false)\n const moduleIds = Object.values(registry).flatMap((moduleEntities) => Object.values(moduleEntities ?? {}))\n if (moduleIds.length > 0 && !moduleIds.includes(entityId)) return false\n return resolveRegisteredEntityTableName(em, entityId) !== null\n}\n\n/**\n * Doc storage (`custom_entities_storage`) is for custom entities only. A system\n * entity's records live in its own module tables/APIs \u2014 writing doc rows for it\n * poisons read-path classification (#2939) and must be rejected at the deepest\n * seam so no caller (API, AI tool, workflow) can do it.\n */\nexport function assertCustomEntityStorageEntityId(em: EntityManager, entityId: string): void {\n if (isOrmBackedSystemEntityId(em, entityId)) {\n throw new CrudHttpError(400, {\n error: 'Records are available for custom entities only',\n code: SYSTEM_ENTITY_RECORDS_BLOCKED_CODE,\n entityId,\n })\n }\n}\n\nexport class DefaultDataEngine implements DataEngine {\n private pendingSideEffects = new Map<string, QueuedCrudSideEffect>()\n private defaultIndexer: DefaultCrudIndexerConfig | null = null\n private indexedDefaultEntityClass = false\n constructor(private em: EntityManager, private container: AwilixContainer) {}\n\n /**\n * Per-command state, deliberately held on the engine instance rather than threaded through\n * `CommandRuntimeContext` the way the bulk-import flags are. That is sound only because\n * `createRequestContainer()` registers `dataEngine` per request (`lib/di/container.ts`), so\n * one engine instance never spans two requests, and no `makeCrudRoute` verb runs two commands\n * concurrently against it. An application that re-registers `dataEngine` as a transient would\n * break both assumptions: the command would mark on a different instance than the route\n * declared on, so nothing is indexed and every write logs the undischarged-declaration warning.\n */\n setDefaultIndexerConfig(config: DefaultCrudIndexerConfig | null): void {\n this.defaultIndexer = config\n this.indexedDefaultEntityClass = false\n }\n\n hasIndexedDefaultEntityClass(): boolean {\n return this.indexedDefaultEntityClass\n }\n\n private matchesDefaultEntityClass(entity: unknown): boolean {\n const declared = this.defaultIndexer?.entityClass\n // `OrmEntityConfig.entity` is `any` and this repository treats `EntitySchema` instances as a\n // first-class entity shape (`lib/bootstrap/types.ts`). An `EntitySchema` is an object rather\n // than a constructor, so `instanceof` against it throws \u2014 and it would throw inside\n // `markOrmEntityChange`, outside the best-effort try/catch that guards the flush, turning\n // every write on such a route into a 500.\n if (typeof declared !== 'function') return false\n return entity instanceof declared\n }\n\n private resolveDefaultIndexer(entity: unknown): CrudIndexerConfig<unknown> | undefined {\n return this.matchesDefaultEntityClass(entity) ? this.defaultIndexer?.indexer : undefined\n }\n\n async setCustomFields(opts: Parameters<DataEngine['setCustomFields']>[0]): Promise<void> {\n const { entityId, recordId, organizationId = null, tenantId = null, values } = opts\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId,\n organizationId,\n tenantId,\n values,\n })\n await this.validateCustomFieldValues(entityId, organizationId, tenantId, sanitizedValues as Record<string, unknown>)\n let encryptionService: any = null\n try {\n encryptionService = this.container.resolve('tenantEncryptionService') as any\n } catch {\n encryptionService = null\n }\n await setRecordCustomFields(this.em, {\n entityId,\n recordId,\n organizationId,\n tenantId,\n values: sanitizedValues,\n encryptionService,\n pinOrganizationId: opts.pinOrganizationId === true,\n })\n if (opts.notify !== false) {\n let bus: EventBus | null = null\n try {\n bus = (this.container.resolve('eventBus') as EventBus)\n } catch {\n bus = null\n }\n if (bus) {\n const [mod, ent] = (entityId || '').split(':')\n if (mod && ent) {\n const eventName = `${mod}.${ent}.updated`\n try {\n await bus.emitEvent(eventName, { id: recordId, organizationId, tenantId }, {\n persistent: true,\n tenantId,\n organizationId,\n emitterModuleId: mod,\n })\n } catch {\n // non-blocking\n }\n }\n }\n }\n }\n\n private normalizeDocValues(values: CustomEntityValues): CustomEntityValues {\n const out: CustomEntityValues = {}\n for (const [k, v] of Object.entries(values || {})) {\n // Never allow callers to override reserved identifiers in the doc\n if (k === 'id' || k === 'entity_id' || k === 'entityId') continue\n // Accept both 'cf_<key>' and 'cf:<key>' inputs and normalize to 'cf:<key>'\n if (k.startsWith('cf_')) out[`cf:${k.slice(3)}`] = v\n else out[k] = v\n }\n return out\n }\n\n private backcompatEavEnabled(): boolean {\n try {\n return parseBooleanToken(process.env.ENTITIES_BACKCOMPAT_EAV_FOR_CUSTOM ?? '') === true\n } catch { return false }\n }\n\n private resolveCustomEntityEncryptionService(): TenantDataEncryptionService | null {\n try {\n return this.container.resolve<TenantDataEncryptionService>('tenantEncryptionService')\n } catch {\n return null\n }\n }\n\n private getKysely(): Kysely<any> {\n return this.em.getKysely<any>()\n }\n\n private async ensureStorageTableExists(): Promise<void> {\n const cacheKey = 'custom_entities_storage'\n if (tableExistsCache.get(cacheKey)) return\n const db = this.getKysely()\n const exists = await db\n .selectFrom('information_schema.tables' as any)\n .select(sql`1`.as('present'))\n .where('table_name' as any, '=', 'custom_entities_storage')\n .executeTakeFirst()\n if (!exists) {\n throw new Error('custom_entities_storage table is missing. Run migrations (yarn db:migrate).')\n }\n tableExistsCache.set(cacheKey, true)\n }\n\n private normalizeValuesForValidation(values: Record<string, unknown> | undefined | null): Record<string, unknown> {\n if (!values) return {}\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n if (key.startsWith('cf_') || key.startsWith('cf:')) {\n const normalized = key.slice(3)\n if (normalized) out[normalized] = value\n continue\n }\n out[key] = value\n }\n return out\n }\n\n private async validateCustomFieldValues(\n entityId: string,\n organizationId: string | null,\n tenantId: string | null,\n values: Record<string, unknown> | undefined | null,\n ): Promise<void> {\n const prepared = this.normalizeValuesForValidation(values)\n if (!entityId || Object.keys(prepared).length === 0) return\n const result = await validateCustomFieldValuesServer(this.em, {\n entityId,\n organizationId,\n tenantId,\n values: prepared,\n })\n if (!result.ok) {\n throw new CrudHttpError(400, { error: 'Validation failed', fields: result.fieldErrors })\n }\n }\n\n private async withCustomEntityStorageLock<T>(lockKey: string, work: (txEm: EntityManager) => Promise<T>): Promise<T> {\n if (!this.em.isInTransaction?.()) return withAdvisoryXactLock(this.em, lockKey, work)\n const deadlineAt = Date.now() + 15_000\n while (true) {\n const rows = await this.em.execute<Array<{ locked: boolean }>>(\n 'select pg_try_advisory_xact_lock(hashtextextended(?, 0)) as locked',\n [lockKey],\n )\n if (rows[0]?.locked) return work(this.em)\n const remainingMs = deadlineAt - Date.now()\n if (remainingMs <= 0) throw new AdvisoryLockUnavailableError('deadline', lockKey)\n await new Promise<void>((resolve) => setTimeout(resolve, Math.min(50, remainingMs)))\n }\n }\n\n private async writeCustomEntityStorageDoc(target: {\n entityType: string\n entityId: string\n organizationId: string | null\n tenantId: string | null\n doc: Record<string, unknown>\n requireActive?: boolean\n }): Promise<void> {\n const lockKey = `custom_entity_create:${JSON.stringify([target.tenantId, target.organizationId, target.entityType, target.entityId.toLowerCase()])}`\n await this.withCustomEntityStorageLock(lockKey, async (txEm) => {\n const db = txEm.getKysely<CustomEntityStorageDatabase>()\n const doc = sql<CustomEntityValues>`${JSON.stringify(target.doc)}::jsonb`\n let update = db\n .updateTable('custom_entities_storage')\n .set({ doc, updated_at: sql<Date>`now()`, deleted_at: null })\n .where('entity_type', '=', target.entityType)\n .where('entity_id', '=', target.entityId)\n .where('organization_id', target.organizationId === null ? 'is' : '=', target.organizationId)\n .where('tenant_id', target.tenantId === null ? 'is' : '=', target.tenantId)\n if (target.requireActive) update = update.where('deleted_at', 'is', null)\n const updated = await update.executeTakeFirst()\n if (Number(updated.numUpdatedRows) > 0) return\n if (target.requireActive) throw notFound()\n await db.insertInto('custom_entities_storage').values({\n entity_type: target.entityType,\n entity_id: target.entityId,\n organization_id: target.organizationId,\n tenant_id: target.tenantId,\n doc,\n created_at: sql<Date>`now()`,\n updated_at: sql<Date>`now()`,\n deleted_at: null,\n }).execute()\n })\n }\n\n async createCustomEntityRecord(opts: Parameters<DataEngine['createCustomEntityRecord']>[0]): Promise<{ id: string }> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n await this.ensureStorageTableExists()\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId: opts.entityId,\n organizationId: opts.organizationId ?? null,\n tenantId: opts.tenantId ?? null,\n values: opts.values || {},\n })\n await this.validateCustomFieldValues(opts.entityId, opts.organizationId ?? null, opts.tenantId ?? null, sanitizedValues)\n const rawId = String(opts.recordId ?? '').trim()\n const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(rawId)\n const sentinel = rawId.toLowerCase()\n const shouldGenerate = !rawId || !isUuid || sentinel === 'create' || sentinel === 'new' || sentinel === 'null' || sentinel === 'undefined'\n const id = shouldGenerate ? ((): string => {\n const g = globalThis as { crypto?: { randomUUID?: () => string } }\n if (g.crypto?.randomUUID) return g.crypto.randomUUID()\n // Fallback UUIDv4 generator\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0\n const v = c === 'x' ? r : (r & 0x3) | 0x8\n return v.toString(16)\n })\n })() : rawId\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const doc = await encryptCustomEntityRecordDocument(this.em, {\n entityId: opts.entityId, organizationId: orgId, tenantId,\n doc: { id, ...this.normalizeDocValues(sanitizedValues || {}) },\n encryptionService: this.resolveCustomEntityEncryptionService(),\n })\n\n const now = sql<Date>`now()`\n const payload = {\n entity_type: opts.entityId,\n entity_id: id,\n organization_id: orgId,\n tenant_id: tenantId,\n doc: sql<CustomEntityValues>`${JSON.stringify(doc)}::jsonb`,\n updated_at: now,\n created_at: now,\n deleted_at: null,\n }\n\n if (opts.createOnly) {\n const duplicateError = () => {\n const error = conflict('[internal] Custom entity record already exists')\n error.body.code = 'custom_entity_record_exists'\n return error\n }\n const lockKey = `custom_entity_create:${JSON.stringify([tenantId, orgId, opts.entityId, id.toLowerCase()])}`\n await withAdvisoryXactLock(this.em, lockKey, async (txEm) => {\n const storage = txEm.getKysely<CustomEntityStorageDatabase>()\n const existing = await storage\n .selectFrom('custom_entities_storage')\n .select('entity_id')\n .where('entity_type', '=', opts.entityId)\n .where(sql<string>`lower(entity_id::text)`, '=', id.toLowerCase())\n .where('organization_id', orgId === null ? 'is' : '=', orgId)\n .where('tenant_id', tenantId === null ? 'is' : '=', tenantId)\n .executeTakeFirst()\n if (existing) throw duplicateError()\n try {\n await storage.insertInto('custom_entities_storage').values(payload).execute()\n } catch (error) {\n if (isUniqueViolation(error, 'custom_entities_storage_unique_idx')) throw duplicateError()\n throw error\n }\n })\n } else {\n await this.writeCustomEntityStorageDoc({ entityType: opts.entityId, entityId: id, organizationId: orgId, tenantId, doc })\n }\n\n // Optional EAV backward compatibility (disabled by default)\n if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {\n await this.setCustomFields({\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: tenantId,\n values: normalizeCustomFieldValues(sanitizedValues),\n notify: opts.notify, // defaults to true\n // custom_entities_storage upserts on (entity_type, entity_id, organization_id),\n // so `id` is unique only within this organization, not across organizations \u2014\n // pin the reconciling delete/lookup to this organization (#6034 review).\n pinOrganizationId: true,\n })\n }\n\n return { id }\n }\n\n async updateCustomEntityRecord(opts: Parameters<DataEngine['updateCustomEntityRecord']>[0]): Promise<void> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n const db = this.getKysely()\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId: opts.entityId,\n organizationId: opts.organizationId ?? null,\n tenantId: opts.tenantId ?? null,\n values: opts.values || {},\n })\n await this.validateCustomFieldValues(opts.entityId, opts.organizationId ?? null, opts.tenantId ?? null, sanitizedValues)\n const id = String(opts.recordId)\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const requireActive = opts.requireActive === true\n\n // Merge doc shallowly: load existing doc and overlay\n await this.ensureStorageTableExists()\n const applyScope = <T extends { where: (col: any, op: any, val?: any) => T }>(q: T) => {\n let chain = q.where('entity_type' as any, '=', opts.entityId)\n chain = chain.where('entity_id' as any, '=', id)\n chain = orgId === null\n ? chain.where('organization_id' as any, 'is', null as any)\n : chain.where('organization_id' as any, '=', orgId)\n chain = tenantId === null\n ? chain.where('tenant_id' as any, 'is', null as any)\n : chain.where('tenant_id' as any, '=', tenantId)\n if (requireActive) chain = chain.where('deleted_at', 'is', null)\n return chain\n }\n const row = await applyScope(\n db.selectFrom('custom_entities_storage' as any).select(['doc' as any])\n ).executeTakeFirst()\n if (requireActive && !row) throw notFound()\n const prevDoc: Record<string, unknown> = (row as any)?.doc || { id }\n const nextDoc = await encryptCustomEntityRecordDocument(this.em, {\n entityId: opts.entityId, organizationId: orgId, tenantId,\n doc: { ...prevDoc, ...this.normalizeDocValues(sanitizedValues || {}), id },\n encryptionService: this.resolveCustomEntityEncryptionService(),\n })\n await this.writeCustomEntityStorageDoc({ entityType: opts.entityId, entityId: id, organizationId: orgId, tenantId, doc: nextDoc, requireActive })\n\n // Optional EAV backward compatibility (disabled by default)\n if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {\n await this.setCustomFields({\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: tenantId,\n values: normalizeCustomFieldValues(sanitizedValues),\n notify: opts.notify, // defaults to true\n // custom_entities_storage upserts on (entity_type, entity_id, organization_id),\n // so `id` is unique only within this organization, not across organizations \u2014\n // pin the reconciling delete/lookup to this organization (#6034 review).\n pinOrganizationId: true,\n })\n }\n }\n\n async deleteCustomEntityRecord(opts: Parameters<DataEngine['deleteCustomEntityRecord']>[0]): Promise<void> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n const db = this.getKysely()\n const id = String(opts.recordId)\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const soft = opts.soft !== false\n\n const applyScope = <T extends { where: (col: any, op: any, val?: any) => T }>(q: T) => {\n let chain = q.where('entity_type' as any, '=', opts.entityId)\n chain = chain.where('entity_id' as any, '=', id)\n chain = orgId === null\n ? chain.where('organization_id' as any, 'is', null as any)\n : chain.where('organization_id' as any, '=', orgId)\n chain = tenantId === null\n ? chain.where('tenant_id' as any, 'is', null as any)\n : chain.where('tenant_id' as any, '=', tenantId)\n return chain\n }\n\n if (soft) {\n await applyScope(\n db.updateTable('custom_entities_storage' as any).set({\n deleted_at: sql`now()`,\n updated_at: sql`now()`,\n } as any) as any\n ).execute()\n } else {\n await applyScope(db.deleteFrom('custom_entities_storage' as any) as any).execute()\n }\n\n // Soft-delete EAV values to preserve current behavior\n try {\n const { CustomFieldValue } = await import('@open-mercato/core/modules/entities/data/entities')\n const values = await this.em.find(CustomFieldValue, {\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: opts.tenantId ?? null,\n })\n const now = new Date()\n const mutated = values.filter((record) => {\n if (record.deletedAt) return false\n record.deletedAt = now\n return true\n })\n if (mutated.length) {\n for (const record of values) this.em.persist(record)\n await this.em.flush()\n }\n } catch { /* non-blocking */ }\n }\n\n async createOrmEntity<T extends object>(opts: { entity: EntityName<T>; data: EntityData<T> }): Promise<T> {\n const entity = this.em.create(\n opts.entity as EntityName<T>,\n opts.data as unknown as RequiredEntityData<T>\n )\n await this.em.persist(entity).flush()\n return entity\n }\n\n async updateOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n apply: (current: T) => Promise<void> | void\n }): Promise<T | null> {\n const current = await this.em.findOne(opts.entity as EntityName<T>, opts.where as FilterQuery<NoInfer<T>>)\n if (!current) return null\n await opts.apply(current)\n await this.em.persist(current).flush()\n return current\n }\n\n async deleteOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n soft?: boolean\n softDeleteField?: keyof T & string\n }): Promise<T | null> {\n const current = await this.em.findOne(opts.entity as EntityName<T>, opts.where as FilterQuery<NoInfer<T>>)\n if (!current) return null\n if (opts.soft !== false) {\n const field = opts.softDeleteField || ('deletedAt' as keyof T & string)\n if (typeof current === 'object' && current !== null) {\n ;(current as Record<string, unknown>)[field] = new Date()\n await this.em.persist(current).flush()\n }\n } else {\n await this.em.remove(current).flush()\n }\n return current\n }\n\n async emitOrmEntityEvent<T>(opts: {\n action: CrudEventAction\n entity: T\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n suppress?: BulkImportSuppression\n }): Promise<void> {\n const { action, entity, events, indexer, identifiers, syncOrigin, suppress } = opts\n // Bulk-import deferral: an entry may suppress its domain event and/or inline reindex. When both\n // the config is absent AND (for the present one) suppressed, there is nothing left to do.\n const emitEvents = !!events && !suppress?.skipEvents\n const runIndexer = !!indexer && !suppress?.skipReindex\n if (!emitEvents && !runIndexer) return\n if (!identifiers?.id) return\n\n let bus: EventBus | null = null\n try {\n bus = (this.container.resolve('eventBus') as EventBus)\n } catch {\n bus = null\n }\n if (!bus) return\n\n const ctx = {\n action,\n entity,\n identifiers: {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n },\n syncOrigin: syncOrigin ?? null,\n actorUserId: opts.actorUserId ?? null,\n }\n\n if (events && !suppress?.skipEvents) {\n const eventName = `${events.module}.${events.entity}.${action}`\n warnIfUndeclaredEvent(eventName, 'emitOrmEntityEvent')\n const builtPayload = events.buildPayload\n ? events.buildPayload(ctx)\n : {\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n ...(ctx.syncOrigin ? { syncOrigin: ctx.syncOrigin } : {}),\n }\n // A configured indexer means this data-engine call owns the query-index\n // decision, including an explicit skipReindex suppression. Mark object\n // payloads so the legacy domain-event bridge does not enqueue the same\n // record a second time. Keep the marker non-enumerable so client broadcasts\n // and persisted domain payloads retain their existing public shape.\n // Primitive custom payloads cannot be bridged in any case because they do\n // not expose the record id.\n const payload = indexer && builtPayload && typeof builtPayload === 'object' && !Array.isArray(builtPayload)\n ? Object.defineProperty(\n { ...(builtPayload as Record<string, unknown>) },\n CRUD_QUERY_INDEX_MANAGED_PAYLOAD_KEY,\n { value: true, enumerable: false },\n )\n : builtPayload\n try {\n await bus.emitEvent(eventName, payload, {\n persistent: !!events.persistent,\n tenantId: ctx.identifiers.tenantId ?? null,\n organizationId: ctx.identifiers.organizationId ?? null,\n emitterModuleId: events.module,\n })\n } catch {\n // non-blocking\n }\n }\n\n if (indexer && !suppress?.skipReindex) {\n const alwaysConsistent = isReadProjectionAlwaysConsistent()\n const resolveCoverageBaseDelta = (): number | undefined => {\n if (action === 'created') return 1\n if (action === 'deleted') return -1\n return undefined\n }\n const coverageBaseDelta = resolveCoverageBaseDelta()\n\n if (action === 'deleted') {\n const payload = indexer.buildDeletePayload\n ? indexer.buildDeletePayload(ctx)\n : {\n entityType: indexer.entityType,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }\n const enrichedPayload = payload as Record<string, unknown>\n enrichedPayload.crudAction = action\n if (coverageBaseDelta !== undefined) enrichedPayload.coverageBaseDelta = coverageBaseDelta\n if (ctx.syncOrigin) enrichedPayload.syncOrigin = ctx.syncOrigin\n // Await the index update so query-index reads (the `customValues`/scalar\n // projection that list endpoints serve) are consistent the moment the write\n // returns. The subscriber removes the projection row + tokens synchronously and\n // defers the coverage recompute + fulltext delete, so this stays bounded.\n // Errors are logged, not thrown \u2014 index drift never fails the originating write.\n // Always-consistent mode rethrows so drift is loud and retryable.\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.delete_one', enrichedPayload, { rethrowHandlerErrors: true })\n } else {\n await bus.emitEvent('query_index.delete_one', enrichedPayload).catch((err: unknown) => {\n logger.error('query_index.delete_one emit failed', { err })\n })\n }\n } else {\n const payload = indexer.buildUpsertPayload\n ? indexer.buildUpsertPayload(ctx)\n : {\n entityType: indexer.entityType,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }\n const enrichedPayload = payload as Record<string, unknown>\n enrichedPayload.crudAction = action\n if (coverageBaseDelta !== undefined) enrichedPayload.coverageBaseDelta = coverageBaseDelta\n if (ctx.syncOrigin) enrichedPayload.syncOrigin = ctx.syncOrigin\n // Await the projection upsert so list reads observe the new doc immediately\n // (see delete_one above). The subscriber updates `entity_indexes` synchronously\n // and defers the heavy token-reindex pipeline (build doc + encrypt + decrypt +\n // tokenize + DELETE + chunked INSERT) so write latency stays bounded.\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.upsert_one', enrichedPayload, { rethrowHandlerErrors: true })\n } else {\n await bus.emitEvent('query_index.upsert_one', enrichedPayload).catch((err: unknown) => {\n logger.error('query_index.upsert_one emit failed', { err })\n })\n }\n }\n\n if (alwaysConsistent || shouldTriggerCoverageRefresh(indexer.entityType, ctx.identifiers.tenantId ?? null)) {\n const coveragePayload = {\n entityType: indexer.entityType,\n tenantId: ctx.identifiers.tenantId ?? null,\n organizationId: null,\n delayMs: 0,\n }\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.coverage.refresh', coveragePayload, { rethrowHandlerErrors: true })\n } else {\n void bus.emitEvent('query_index.coverage.refresh', coveragePayload).catch(() => undefined)\n }\n }\n }\n }\n\n markOrmEntityChange<T>(opts: {\n action: CrudEventAction\n entity: T | null | undefined\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n }): void {\n const { entity, identifiers } = opts\n if (!entity) return\n if (!identifiers?.id) return\n // A command handler that marks `events:` only still discharges the route's declared\n // query-index obligation \u2014 the route hands its `indexer:` down as the default so the\n // handler's own entity and identifiers (the accurate ones) drive the projection write.\n const indexer = opts.indexer ?? this.resolveDefaultIndexer(entity)\n const key = this.buildSideEffectKey(opts.action, identifiers)\n const existing = this.pendingSideEffects.get(key)\n if (existing) {\n existing.entity = entity\n existing.identifiers = {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n }\n existing.syncOrigin = opts.syncOrigin ?? null\n existing.actorUserId = opts.actorUserId ?? null\n if (opts.events) existing.events = opts.events as CrudEventsConfig<unknown>\n // Explicit always wins, on the merge branch too: a second `events:`-only mark on the same\n // key must not let the route default overwrite the `indexer:` an earlier mark installed,\n // which would silently drop that handler's own `buildUpsertPayload`.\n if (opts.indexer) existing.indexer = opts.indexer as CrudIndexerConfig<unknown>\n else if (!existing.indexer && indexer) existing.indexer = indexer\n this.pendingSideEffects.set(key, existing)\n return\n }\n const entry: QueuedCrudSideEffect = {\n action: opts.action,\n entity,\n identifiers: {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n },\n syncOrigin: opts.syncOrigin ?? null,\n actorUserId: opts.actorUserId ?? null,\n }\n if (opts.events) entry.events = opts.events as CrudEventsConfig<unknown>\n if (indexer) entry.indexer = indexer\n this.pendingSideEffects.set(key, entry)\n }\n\n async flushOrmEntityChanges(suppress?: BulkImportSuppression): Promise<void> {\n if (!this.pendingSideEffects.size) return\n const entries = Array.from(this.pendingSideEffects.values())\n this.pendingSideEffects.clear()\n for (const entry of entries) {\n if (entry.indexer && !suppress?.skipReindex && this.matchesDefaultEntityClass(entry.entity)) {\n this.indexedDefaultEntityClass = true\n }\n try {\n await this.emitOrmEntityEvent({\n action: entry.action,\n entity: entry.entity,\n identifiers: entry.identifiers,\n syncOrigin: entry.syncOrigin ?? null,\n actorUserId: entry.actorUserId ?? null,\n events: entry.events as CrudEventsConfig<unknown>,\n indexer: entry.indexer as CrudIndexerConfig<unknown>,\n suppress,\n })\n } catch (error) {\n if (isReadProjectionAlwaysConsistent()) {\n throw error\n }\n // best-effort; continue with remaining side effects\n }\n }\n }\n\n private buildSideEffectKey(action: CrudEventAction, identifiers: CrudEntityIdentifiers): string {\n const id = identifiers.id ?? ''\n const org = identifiers.organizationId ?? ''\n const tenant = identifiers.tenantId ?? ''\n return [action, id, org, tenant].join('|')\n }\n}\n"],
|
|
5
|
-
"mappings": "AAGA,SAAsB,WAAW;AACjC,SAAS,mCAAmC,6BAA6B;AACzE,SAAS,uCAAuC;AAChD,SAAS,mDAAmD;AAE5D;AAAA,EACE;AAAA,OAKK;AAEP,SAAS,UAAU,eAAe,mBAAmB,gBAAgB;AACrE,SAAS,8BAA8B,4BAA4B;AACnE,SAAS,wCAAwC;AACjD,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAC3C,SAAS,yBAAyB;AAClC,SAAS,wCAAwC;AACjD,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AAGrC,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,cAAc,CAAC;AAExE,MAAM,wBAAwB,oBAAI,IAAY;AAE9C,SAAS,sBAAsB,WAAmB,SAAuB;AACvE,MAAI,gBAAgB,SAAS,EAAG;AAChC,MAAI,sBAAsB,IAAI,SAAS,EAAG;AAC1C,wBAAsB,IAAI,SAAS;AACnC,SAAO,KAAK,6IAAwI,EAAE,SAAS,UAAU,CAAC;AAC5K;AAGO,SAAS,yCAA+C;AAC7D,wBAAsB,MAAM;AAC9B;AAGA,MAAM,mBAAmB,qBAA2B;AAAA,EAClD,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,mBAAmB;AACrB,CAAC;AAGM,SAAS,kCAAwC;AACtD,mBAAiB,MAAM;AACzB;AAEA,MAAM,+BAA+B,IAAI,KAAK;AAC9C,MAAM,yBAAyB,oBAAI,IAAoB;AAEvD,SAAS,6BAA6B,YAAgC,UAAkC;AACtG,MAAI,CAAC,WAAY,QAAO;AACxB,QAAM,MAAM,GAAG,UAAU,IAAI,YAAY,UAAU;AACnD,QAAM,MAAM,KAAK,IAAI;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ACF;AAAA,EACF;AAAA,EAEQ,mBAAmB,QAAyB,aAA4C;AAC9F,UAAM,KAAK,YAAY,MAAM;AAC7B,UAAM,MAAM,YAAY,kBAAkB;AAC1C,UAAM,SAAS,YAAY,YAAY;AACvC,WAAO,CAAC,QAAQ,IAAI,KAAK,MAAM,EAAE,KAAK,GAAG;AAAA,EAC3C;AACF;",
|
|
4
|
+
"sourcesContent": ["import type { EntityData, EntityName, FilterQuery, RequiredEntityData } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { type Kysely, sql } from 'kysely'\nimport { encryptCustomEntityRecordDocument, setRecordCustomFields } from '@open-mercato/core/modules/entities/lib/helpers'\nimport { validateCustomFieldValuesServer } from '@open-mercato/core/modules/entities/lib/validation'\nimport { sanitizeCustomFieldHtmlRichTextValuesServer } from '@open-mercato/core/modules/entities/lib/htmlRichTextSanitizer'\nimport type { EventBus } from '@open-mercato/events/types'\nimport {\n CRUD_QUERY_INDEX_MANAGED_PAYLOAD_KEY,\n type CrudEventAction,\n type CrudEventsConfig,\n type CrudIndexerConfig,\n type CrudEntityIdentifiers,\n} from '../crud/types'\nimport type { BulkImportSuppression } from '../commands/types'\nimport { conflict, CrudHttpError, isUniqueViolation, notFound } from '../crud/errors'\nimport { AdvisoryLockUnavailableError, withAdvisoryXactLock } from '../db/advisoryLock'\nimport { resolveRegisteredEntityTableName } from '../query/engine'\nimport { getEntityIds } from '../encryption/entityIds'\nimport { normalizeCustomFieldValues } from '../custom-fields/normalize'\nimport { parseBooleanToken } from '../boolean'\nimport { isReadProjectionAlwaysConsistent } from './consistency'\nimport { isEventDeclared } from '../../modules/events'\nimport { createLogger } from '../logger'\nimport { createBoundedTtlMemo } from '../query/bounded-ttl-memo'\nimport type { TenantDataEncryptionService } from '../encryption/tenantDataEncryptionService'\n\nconst logger = createLogger('shared').child({ component: 'data-engine' })\n\nconst undeclaredEventWarned = new Set<string>()\n\nfunction warnIfUndeclaredEvent(eventName: string, context: string): void {\n if (isEventDeclared(eventName)) return\n if (undeclaredEventWarned.has(eventName)) return\n undeclaredEventWarned.add(eventName)\n logger.warn('Emitting undeclared event \u2014 declare it in the owning module events.ts (createModuleEvents) so the event registry stays authoritative', { context, eventName })\n}\n\n/** Internal: clear the undeclared-event warning cache. Exposed for tests. */\nexport function __resetUndeclaredEventWarningsForTests(): void {\n undeclaredEventWarned.clear()\n}\n\n/** Only `true` is cached: a cached `false` would keep this failing after a migration creates the table. */\nconst tableExistsCache = createBoundedTtlMemo<true>({\n ttlEnv: 'OM_DATA_ENGINE_TABLE_EXISTS_CACHE_MS',\n defaultTtlMs: 3_600_000,\n defaultMaxEntries: 1_000,\n})\n\n/** Test-only: the module-scoped memo would otherwise leak state across specs. */\nexport function clearDataEngineTableExistsCache(): void {\n tableExistsCache.clear()\n}\n\nconst COVERAGE_REFRESH_INTERVAL_MS = 5 * 60 * 1000\nconst coverageRefreshTracker = new Map<string, number>()\n\nfunction shouldTriggerCoverageRefresh(entityType: string | undefined, tenantId: string | null): boolean {\n if (!entityType) return false\n const key = `${entityType}|${tenantId ?? '__null__'}`\n const now = Date.now()\n const last = coverageRefreshTracker.get(key) ?? 0\n if (now - last < COVERAGE_REFRESH_INTERVAL_MS) return false\n coverageRefreshTracker.set(key, now)\n return true\n}\n\ntype CustomEntityValues = Record<string, unknown>\n\ntype CustomEntityStorageDatabase = {\n custom_entities_storage: {\n entity_type: string\n entity_id: string\n organization_id: string | null\n tenant_id: string | null\n doc: CustomEntityValues\n updated_at: Date\n created_at: Date\n deleted_at: Date | null\n }\n}\n\ntype QueuedCrudSideEffect = {\n action: CrudEventAction\n entity: unknown\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n events?: CrudEventsConfig<unknown>\n indexer?: CrudIndexerConfig<unknown>\n}\n\n/**\n * A `makeCrudRoute` route-level `indexer:` declaration, handed to the data engine for the\n * duration of one command-bus write. Command handlers own the side-effect mark on the\n * `actions.*` path, and most of them mark `events:` only \u2014 without this the route's\n * declaration would reach no code at all. `entityClass` scopes the default to the route's\n * own ORM entity so a handler that also marks a sibling entity in the same request (a tag\n * assignment alongside a tag, say) is never indexed under the route's `entityType`.\n */\nexport type DefaultCrudIndexerConfig = {\n indexer: CrudIndexerConfig<unknown>\n entityClass: abstract new (...args: never[]) => object\n}\n\nexport interface DataEngine {\n setCustomFields(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: Record<string, string | number | boolean | null | undefined | Array<string | number | boolean | null | undefined>>\n /**\n * Default true: emits the entity-keyed custom-field change signal `<module>.<entity>.updated`,\n * derived from `entityId` (e.g. `catalog:catalog_product` \u2192 `catalog.catalog_product.updated`).\n * It is not a module domain event \u2014 the query_index bridge subscribes to the same derivation for\n * every entity carrying custom fields, including runtime custom entities \u2014 so it is deliberately\n * not checked against the `events.ts` registry.\n */\n notify?: boolean\n // Forwarded to `setRecordCustomFields` \u2014 see its doc for when a caller must pass\n // true (a recordId that is not unique across organizations for this entityId).\n pinOrganizationId?: boolean\n }): Promise<void>\n\n // Storage for user-defined entities (doc-based)\n createCustomEntityRecord(opts: {\n entityId: string // '<module>:<entity>'\n recordId?: string // optional; auto-generate if not provided\n createOnly?: boolean\n organizationId?: string | null\n tenantId?: string | null\n values: CustomEntityValues\n notify?: boolean // keep event emitting as it is via setCustomFields (updated)\n }): Promise<{ id: string }>\n\n updateCustomEntityRecord(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: CustomEntityValues\n notify?: boolean // keep event emitting as it is via setCustomFields (updated)\n requireActive?: boolean\n }): Promise<void>\n\n deleteCustomEntityRecord(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n soft?: boolean // default true: sets deleted_at\n notify?: boolean // keep event emitting as it is (no extra events here)\n }): Promise<void>\n\n // Generic ORM-backed entity operations used by CrudFactory\n createOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n data: EntityData<T>\n }): Promise<T>\n\n updateOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n apply: (current: T) => Promise<void> | void\n }): Promise<T | null>\n\n deleteOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n soft?: boolean\n softDeleteField?: keyof T & string\n }): Promise<T | null>\n\n emitOrmEntityEvent<T>(opts: {\n action: CrudEventAction\n entity: T\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n /** Bulk-import deferral: skip the domain event and/or inline reindex for this emit. */\n suppress?: BulkImportSuppression\n }): Promise<void>\n\n markOrmEntityChange<T>(opts: {\n action: CrudEventAction\n entity: T | null | undefined\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n }): void\n\n /**\n * Drain queued side effects. When `suppress` is passed (a bulk-import backfill), the\n * flagged per-record events / reindex are skipped for every drained entry; the caller\n * is responsible for rebuilding the `query_index` afterwards.\n */\n flushOrmEntityChanges(suppress?: BulkImportSuppression): Promise<void>\n\n /**\n * Declare the indexer a CRUD route configured, for marks made during one command-bus\n * write that do not carry an indexer of their own. Pass `null` to clear it. Optional so\n * third-party `DataEngine` implementations stay valid; callers invoke it with `?.`.\n */\n setDefaultIndexerConfig?(config: DefaultCrudIndexerConfig | null): void\n\n /**\n * Whether any side effect drained since the current default was declared carried an\n * indexer for that default's entity class \u2014 false means the declared query-index\n * obligation was discharged by nobody. Optional for the same reason as the setter.\n */\n hasIndexedDefaultEntityClass?(): boolean\n}\n\nexport const SYSTEM_ENTITY_RECORDS_BLOCKED_CODE = 'system_entity_records_blocked'\n\n/**\n * A system entity for doc-storage purposes is an id that modules declare in the\n * generated entity-id registry AND that resolves to a registered ORM table. Both\n * conditions matter: `resolveRegisteredEntityTableName` matches class-name candidates\n * from the entity segment alone, so a runtime-registered custom entity whose name\n * happens to collide with some ORM class (e.g. `user:todo` vs the example module's\n * `Todo`) must never be classified as system. When the registry is not populated\n * (exotic bootstraps, unit harnesses) the check conservatively falls back to the\n * ORM-table match alone so the #2939 protection never switches off.\n */\nexport function isOrmBackedSystemEntityId(em: EntityManager, entityId: string): boolean {\n const registry = getEntityIds(false)\n const moduleIds = Object.values(registry).flatMap((moduleEntities) => Object.values(moduleEntities ?? {}))\n if (moduleIds.length > 0 && !moduleIds.includes(entityId)) return false\n return resolveRegisteredEntityTableName(em, entityId) !== null\n}\n\n/**\n * Doc storage (`custom_entities_storage`) is for custom entities only. A system\n * entity's records live in its own module tables/APIs \u2014 writing doc rows for it\n * poisons read-path classification (#2939) and must be rejected at the deepest\n * seam so no caller (API, AI tool, workflow) can do it.\n */\nexport function assertCustomEntityStorageEntityId(em: EntityManager, entityId: string): void {\n if (isOrmBackedSystemEntityId(em, entityId)) {\n throw new CrudHttpError(400, {\n error: 'Records are available for custom entities only',\n code: SYSTEM_ENTITY_RECORDS_BLOCKED_CODE,\n entityId,\n })\n }\n}\n\nexport class DefaultDataEngine implements DataEngine {\n private pendingSideEffects = new Map<string, QueuedCrudSideEffect>()\n private defaultIndexer: DefaultCrudIndexerConfig | null = null\n private indexedDefaultEntityClass = false\n constructor(private em: EntityManager, private container: AwilixContainer) {}\n\n /**\n * Per-command state, deliberately held on the engine instance rather than threaded through\n * `CommandRuntimeContext` the way the bulk-import flags are. That is sound only because\n * `createRequestContainer()` registers `dataEngine` per request (`lib/di/container.ts`), so\n * one engine instance never spans two requests, and no `makeCrudRoute` verb runs two commands\n * concurrently against it. An application that re-registers `dataEngine` as a transient would\n * break both assumptions: the command would mark on a different instance than the route\n * declared on, so nothing is indexed and every write logs the undischarged-declaration warning.\n */\n setDefaultIndexerConfig(config: DefaultCrudIndexerConfig | null): void {\n this.defaultIndexer = config\n this.indexedDefaultEntityClass = false\n }\n\n hasIndexedDefaultEntityClass(): boolean {\n return this.indexedDefaultEntityClass\n }\n\n private matchesDefaultEntityClass(entity: unknown): boolean {\n const declared = this.defaultIndexer?.entityClass\n // `OrmEntityConfig.entity` is `any` and this repository treats `EntitySchema` instances as a\n // first-class entity shape (`lib/bootstrap/types.ts`). An `EntitySchema` is an object rather\n // than a constructor, so `instanceof` against it throws \u2014 and it would throw inside\n // `markOrmEntityChange`, outside the best-effort try/catch that guards the flush, turning\n // every write on such a route into a 500.\n if (typeof declared !== 'function') return false\n return entity instanceof declared\n }\n\n private resolveDefaultIndexer(entity: unknown): CrudIndexerConfig<unknown> | undefined {\n return this.matchesDefaultEntityClass(entity) ? this.defaultIndexer?.indexer : undefined\n }\n\n async setCustomFields(opts: Parameters<DataEngine['setCustomFields']>[0]): Promise<void> {\n const { entityId, recordId, organizationId = null, tenantId = null, values } = opts\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId,\n organizationId,\n tenantId,\n values,\n })\n await this.validateCustomFieldValues(entityId, organizationId, tenantId, sanitizedValues as Record<string, unknown>)\n let encryptionService: any = null\n try {\n encryptionService = this.container.resolve('tenantEncryptionService') as any\n } catch {\n encryptionService = null\n }\n await setRecordCustomFields(this.em, {\n entityId,\n recordId,\n organizationId,\n tenantId,\n values: sanitizedValues,\n encryptionService,\n pinOrganizationId: opts.pinOrganizationId === true,\n })\n if (opts.notify !== false) {\n let bus: EventBus | null = null\n try {\n bus = (this.container.resolve('eventBus') as EventBus)\n } catch {\n bus = null\n }\n if (bus) {\n const [mod, ent] = (entityId || '').split(':')\n if (mod && ent) {\n const eventName = `${mod}.${ent}.updated`\n try {\n await bus.emitEvent(eventName, { id: recordId, organizationId, tenantId }, {\n persistent: true,\n tenantId,\n organizationId,\n emitterModuleId: mod,\n })\n } catch {\n // non-blocking\n }\n }\n }\n }\n }\n\n private normalizeDocValues(values: CustomEntityValues): CustomEntityValues {\n const out: CustomEntityValues = {}\n for (const [k, v] of Object.entries(values || {})) {\n // Never allow callers to override reserved identifiers in the doc\n if (k === 'id' || k === 'entity_id' || k === 'entityId') continue\n // Accept both 'cf_<key>' and 'cf:<key>' inputs and normalize to 'cf:<key>'\n if (k.startsWith('cf_')) out[`cf:${k.slice(3)}`] = v\n else out[k] = v\n }\n return out\n }\n\n private backcompatEavEnabled(): boolean {\n try {\n return parseBooleanToken(process.env.ENTITIES_BACKCOMPAT_EAV_FOR_CUSTOM ?? '') === true\n } catch { return false }\n }\n\n private resolveCustomEntityEncryptionService(): TenantDataEncryptionService | null {\n try {\n return this.container.resolve<TenantDataEncryptionService>('tenantEncryptionService')\n } catch {\n return null\n }\n }\n\n private getKysely(): Kysely<any> {\n return this.em.getKysely<any>()\n }\n\n private async ensureStorageTableExists(): Promise<void> {\n const cacheKey = 'custom_entities_storage'\n if (tableExistsCache.get(cacheKey)) return\n const db = this.getKysely()\n const exists = await db\n .selectFrom('information_schema.tables' as any)\n .select(sql`1`.as('present'))\n .where('table_name' as any, '=', 'custom_entities_storage')\n .executeTakeFirst()\n if (!exists) {\n throw new Error('custom_entities_storage table is missing. Run migrations (yarn db:migrate).')\n }\n tableExistsCache.set(cacheKey, true)\n }\n\n private normalizeValuesForValidation(values: Record<string, unknown> | undefined | null): Record<string, unknown> {\n if (!values) return {}\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n if (key.startsWith('cf_') || key.startsWith('cf:')) {\n const normalized = key.slice(3)\n if (normalized) out[normalized] = value\n continue\n }\n out[key] = value\n }\n return out\n }\n\n private async validateCustomFieldValues(\n entityId: string,\n organizationId: string | null,\n tenantId: string | null,\n values: Record<string, unknown> | undefined | null,\n ): Promise<void> {\n const prepared = this.normalizeValuesForValidation(values)\n if (!entityId || Object.keys(prepared).length === 0) return\n const result = await validateCustomFieldValuesServer(this.em, {\n entityId,\n organizationId,\n tenantId,\n values: prepared,\n })\n if (!result.ok) {\n throw new CrudHttpError(400, { error: 'Validation failed', fields: result.fieldErrors })\n }\n }\n\n private async withCustomEntityStorageLock<T>(lockKey: string, work: (txEm: EntityManager) => Promise<T>): Promise<T> {\n if (!this.em.isInTransaction?.()) return withAdvisoryXactLock(this.em, lockKey, work)\n const deadlineAt = Date.now() + 15_000\n while (true) {\n const rows = await this.em.execute<Array<{ locked: boolean }>>(\n 'select pg_try_advisory_xact_lock(hashtextextended(?, 0)) as locked',\n [lockKey],\n )\n if (rows[0]?.locked) return work(this.em)\n const remainingMs = deadlineAt - Date.now()\n if (remainingMs <= 0) throw new AdvisoryLockUnavailableError('deadline', lockKey)\n await new Promise<void>((resolve) => setTimeout(resolve, Math.min(50, remainingMs)))\n }\n }\n\n private async writeCustomEntityStorageDoc(target: {\n entityType: string\n entityId: string\n organizationId: string | null\n tenantId: string | null\n doc: Record<string, unknown>\n requireActive?: boolean\n }): Promise<void> {\n const lockKey = `custom_entity_create:${JSON.stringify([target.tenantId, target.organizationId, target.entityType, target.entityId.toLowerCase()])}`\n await this.withCustomEntityStorageLock(lockKey, async (txEm) => {\n const db = txEm.getKysely<CustomEntityStorageDatabase>()\n const doc = sql<CustomEntityValues>`${JSON.stringify(target.doc)}::jsonb`\n let update = db\n .updateTable('custom_entities_storage')\n .set({ doc, updated_at: sql<Date>`now()`, deleted_at: null })\n .where('entity_type', '=', target.entityType)\n .where('entity_id', '=', target.entityId)\n .where('organization_id', target.organizationId === null ? 'is' : '=', target.organizationId)\n .where('tenant_id', target.tenantId === null ? 'is' : '=', target.tenantId)\n if (target.requireActive) update = update.where('deleted_at', 'is', null)\n const updated = await update.executeTakeFirst()\n if (Number(updated.numUpdatedRows) > 0) return\n if (target.requireActive) throw notFound()\n await db.insertInto('custom_entities_storage').values({\n entity_type: target.entityType,\n entity_id: target.entityId,\n organization_id: target.organizationId,\n tenant_id: target.tenantId,\n doc,\n created_at: sql<Date>`now()`,\n updated_at: sql<Date>`now()`,\n deleted_at: null,\n }).execute()\n })\n }\n\n async createCustomEntityRecord(opts: Parameters<DataEngine['createCustomEntityRecord']>[0]): Promise<{ id: string }> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n await this.ensureStorageTableExists()\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId: opts.entityId,\n organizationId: opts.organizationId ?? null,\n tenantId: opts.tenantId ?? null,\n values: opts.values || {},\n })\n await this.validateCustomFieldValues(opts.entityId, opts.organizationId ?? null, opts.tenantId ?? null, sanitizedValues)\n const rawId = String(opts.recordId ?? '').trim()\n const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(rawId)\n const sentinel = rawId.toLowerCase()\n const shouldGenerate = !rawId || !isUuid || sentinel === 'create' || sentinel === 'new' || sentinel === 'null' || sentinel === 'undefined'\n const id = shouldGenerate ? ((): string => {\n const g = globalThis as { crypto?: { randomUUID?: () => string } }\n if (g.crypto?.randomUUID) return g.crypto.randomUUID()\n // Fallback UUIDv4 generator\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0\n const v = c === 'x' ? r : (r & 0x3) | 0x8\n return v.toString(16)\n })\n })() : rawId\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const doc = await encryptCustomEntityRecordDocument(this.em, {\n entityId: opts.entityId, organizationId: orgId, tenantId,\n doc: { id, ...this.normalizeDocValues(sanitizedValues || {}) },\n encryptionService: this.resolveCustomEntityEncryptionService(),\n })\n\n const now = sql<Date>`now()`\n const payload = {\n entity_type: opts.entityId,\n entity_id: id,\n organization_id: orgId,\n tenant_id: tenantId,\n doc: sql<CustomEntityValues>`${JSON.stringify(doc)}::jsonb`,\n updated_at: now,\n created_at: now,\n deleted_at: null,\n }\n\n if (opts.createOnly) {\n const duplicateError = () => {\n const error = conflict('[internal] Custom entity record already exists')\n error.body.code = 'custom_entity_record_exists'\n return error\n }\n const lockKey = `custom_entity_create:${JSON.stringify([tenantId, orgId, opts.entityId, id.toLowerCase()])}`\n await withAdvisoryXactLock(this.em, lockKey, async (txEm) => {\n const storage = txEm.getKysely<CustomEntityStorageDatabase>()\n const existing = await storage\n .selectFrom('custom_entities_storage')\n .select('entity_id')\n .where('entity_type', '=', opts.entityId)\n .where(sql<string>`lower(entity_id::text)`, '=', id.toLowerCase())\n .where('organization_id', orgId === null ? 'is' : '=', orgId)\n .where('tenant_id', tenantId === null ? 'is' : '=', tenantId)\n .executeTakeFirst()\n if (existing) throw duplicateError()\n try {\n await storage.insertInto('custom_entities_storage').values(payload).execute()\n } catch (error) {\n if (isUniqueViolation(error, 'custom_entities_storage_unique_idx')) throw duplicateError()\n throw error\n }\n })\n } else {\n await this.writeCustomEntityStorageDoc({ entityType: opts.entityId, entityId: id, organizationId: orgId, tenantId, doc })\n }\n\n // Optional EAV backward compatibility (disabled by default)\n if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {\n await this.setCustomFields({\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: tenantId,\n values: normalizeCustomFieldValues(sanitizedValues),\n notify: opts.notify, // defaults to true\n // custom_entities_storage upserts on (entity_type, entity_id, organization_id),\n // so `id` is unique only within this organization, not across organizations \u2014\n // pin the reconciling delete/lookup to this organization (#6034 review).\n pinOrganizationId: true,\n })\n }\n\n return { id }\n }\n\n async updateCustomEntityRecord(opts: Parameters<DataEngine['updateCustomEntityRecord']>[0]): Promise<void> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n const db = this.getKysely()\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId: opts.entityId,\n organizationId: opts.organizationId ?? null,\n tenantId: opts.tenantId ?? null,\n values: opts.values || {},\n })\n await this.validateCustomFieldValues(opts.entityId, opts.organizationId ?? null, opts.tenantId ?? null, sanitizedValues)\n const id = String(opts.recordId)\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const requireActive = opts.requireActive === true\n\n // Merge doc shallowly: load existing doc and overlay\n await this.ensureStorageTableExists()\n const applyScope = <T extends { where: (col: any, op: any, val?: any) => T }>(q: T) => {\n let chain = q.where('entity_type' as any, '=', opts.entityId)\n chain = chain.where('entity_id' as any, '=', id)\n chain = orgId === null\n ? chain.where('organization_id' as any, 'is', null as any)\n : chain.where('organization_id' as any, '=', orgId)\n chain = tenantId === null\n ? chain.where('tenant_id' as any, 'is', null as any)\n : chain.where('tenant_id' as any, '=', tenantId)\n if (requireActive) chain = chain.where('deleted_at', 'is', null)\n return chain\n }\n const row = await applyScope(\n db.selectFrom('custom_entities_storage' as any).select(['doc' as any])\n ).executeTakeFirst()\n if (requireActive && !row) throw notFound()\n const prevDoc: Record<string, unknown> = (row as any)?.doc || { id }\n const nextDoc = await encryptCustomEntityRecordDocument(this.em, {\n entityId: opts.entityId, organizationId: orgId, tenantId,\n doc: { ...prevDoc, ...this.normalizeDocValues(sanitizedValues || {}), id },\n encryptionService: this.resolveCustomEntityEncryptionService(),\n })\n await this.writeCustomEntityStorageDoc({ entityType: opts.entityId, entityId: id, organizationId: orgId, tenantId, doc: nextDoc, requireActive })\n\n // Optional EAV backward compatibility (disabled by default)\n if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {\n await this.setCustomFields({\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: tenantId,\n values: normalizeCustomFieldValues(sanitizedValues),\n notify: opts.notify, // defaults to true\n // custom_entities_storage upserts on (entity_type, entity_id, organization_id),\n // so `id` is unique only within this organization, not across organizations \u2014\n // pin the reconciling delete/lookup to this organization (#6034 review).\n pinOrganizationId: true,\n })\n }\n }\n\n async deleteCustomEntityRecord(opts: Parameters<DataEngine['deleteCustomEntityRecord']>[0]): Promise<void> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n const db = this.getKysely()\n const id = String(opts.recordId)\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const soft = opts.soft !== false\n\n const applyScope = <T extends { where: (col: any, op: any, val?: any) => T }>(q: T) => {\n let chain = q.where('entity_type' as any, '=', opts.entityId)\n chain = chain.where('entity_id' as any, '=', id)\n chain = orgId === null\n ? chain.where('organization_id' as any, 'is', null as any)\n : chain.where('organization_id' as any, '=', orgId)\n chain = tenantId === null\n ? chain.where('tenant_id' as any, 'is', null as any)\n : chain.where('tenant_id' as any, '=', tenantId)\n return chain\n }\n\n if (soft) {\n await applyScope(\n db.updateTable('custom_entities_storage' as any).set({\n deleted_at: sql`now()`,\n updated_at: sql`now()`,\n } as any) as any\n ).execute()\n } else {\n await applyScope(db.deleteFrom('custom_entities_storage' as any) as any).execute()\n }\n\n // Soft-delete EAV values to preserve current behavior\n try {\n const { CustomFieldValue } = await import('@open-mercato/core/modules/entities/data/entities')\n const values = await this.em.find(CustomFieldValue, {\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: opts.tenantId ?? null,\n })\n const now = new Date()\n const mutated = values.filter((record) => {\n if (record.deletedAt) return false\n record.deletedAt = now\n return true\n })\n if (mutated.length) {\n for (const record of values) this.em.persist(record)\n await this.em.flush()\n }\n } catch { /* non-blocking */ }\n }\n\n async createOrmEntity<T extends object>(opts: { entity: EntityName<T>; data: EntityData<T> }): Promise<T> {\n const entity = this.em.create(\n opts.entity as EntityName<T>,\n opts.data as unknown as RequiredEntityData<T>\n )\n await this.em.persist(entity).flush()\n return entity\n }\n\n async updateOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n apply: (current: T) => Promise<void> | void\n }): Promise<T | null> {\n const current = await this.em.findOne<T>(opts.entity, opts.where as Parameters<typeof this.em.findOne<T>>[1])\n if (!current) return null\n await opts.apply(current)\n await this.em.persist(current).flush()\n return current\n }\n\n async deleteOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n soft?: boolean\n softDeleteField?: keyof T & string\n }): Promise<T | null> {\n const current = await this.em.findOne<T>(opts.entity, opts.where as Parameters<typeof this.em.findOne<T>>[1])\n if (!current) return null\n if (opts.soft !== false) {\n const field = opts.softDeleteField || ('deletedAt' as keyof T & string)\n if (typeof current === 'object' && current !== null) {\n ;(current as Record<string, unknown>)[field] = new Date()\n await this.em.persist(current).flush()\n }\n } else {\n await this.em.remove(current).flush()\n }\n return current\n }\n\n async emitOrmEntityEvent<T>(opts: {\n action: CrudEventAction\n entity: T\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n suppress?: BulkImportSuppression\n }): Promise<void> {\n const { action, entity, events, indexer, identifiers, syncOrigin, suppress } = opts\n // Bulk-import deferral: an entry may suppress its domain event and/or inline reindex. When both\n // the config is absent AND (for the present one) suppressed, there is nothing left to do.\n const emitEvents = !!events && !suppress?.skipEvents\n const runIndexer = !!indexer && !suppress?.skipReindex\n if (!emitEvents && !runIndexer) return\n if (!identifiers?.id) return\n\n let bus: EventBus | null = null\n try {\n bus = (this.container.resolve('eventBus') as EventBus)\n } catch {\n bus = null\n }\n if (!bus) return\n\n const ctx = {\n action,\n entity,\n identifiers: {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n },\n syncOrigin: syncOrigin ?? null,\n actorUserId: opts.actorUserId ?? null,\n }\n\n if (events && !suppress?.skipEvents) {\n const eventName = `${events.module}.${events.entity}.${action}`\n warnIfUndeclaredEvent(eventName, 'emitOrmEntityEvent')\n const builtPayload = events.buildPayload\n ? events.buildPayload(ctx)\n : {\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n ...(ctx.syncOrigin ? { syncOrigin: ctx.syncOrigin } : {}),\n }\n // A configured indexer means this data-engine call owns the query-index\n // decision, including an explicit skipReindex suppression. Mark object\n // payloads so the legacy domain-event bridge does not enqueue the same\n // record a second time. Keep the marker non-enumerable so client broadcasts\n // and persisted domain payloads retain their existing public shape.\n // Primitive custom payloads cannot be bridged in any case because they do\n // not expose the record id.\n const payload = indexer && builtPayload && typeof builtPayload === 'object' && !Array.isArray(builtPayload)\n ? Object.defineProperty(\n { ...(builtPayload as Record<string, unknown>) },\n CRUD_QUERY_INDEX_MANAGED_PAYLOAD_KEY,\n { value: true, enumerable: false },\n )\n : builtPayload\n try {\n await bus.emitEvent(eventName, payload, {\n persistent: !!events.persistent,\n tenantId: ctx.identifiers.tenantId ?? null,\n organizationId: ctx.identifiers.organizationId ?? null,\n emitterModuleId: events.module,\n })\n } catch {\n // non-blocking\n }\n }\n\n if (indexer && !suppress?.skipReindex) {\n const alwaysConsistent = isReadProjectionAlwaysConsistent()\n const resolveCoverageBaseDelta = (): number | undefined => {\n if (action === 'created') return 1\n if (action === 'deleted') return -1\n return undefined\n }\n const coverageBaseDelta = resolveCoverageBaseDelta()\n\n if (action === 'deleted') {\n const payload = indexer.buildDeletePayload\n ? indexer.buildDeletePayload(ctx)\n : {\n entityType: indexer.entityType,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }\n const enrichedPayload = payload as Record<string, unknown>\n enrichedPayload.crudAction = action\n if (coverageBaseDelta !== undefined) enrichedPayload.coverageBaseDelta = coverageBaseDelta\n if (ctx.syncOrigin) enrichedPayload.syncOrigin = ctx.syncOrigin\n // Await the index update so query-index reads (the `customValues`/scalar\n // projection that list endpoints serve) are consistent the moment the write\n // returns. The subscriber removes the projection row + tokens synchronously and\n // defers the coverage recompute + fulltext delete, so this stays bounded.\n // Errors are logged, not thrown \u2014 index drift never fails the originating write.\n // Always-consistent mode rethrows so drift is loud and retryable.\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.delete_one', enrichedPayload, { rethrowHandlerErrors: true })\n } else {\n await bus.emitEvent('query_index.delete_one', enrichedPayload).catch((err: unknown) => {\n logger.error('query_index.delete_one emit failed', { err })\n })\n }\n } else {\n const payload = indexer.buildUpsertPayload\n ? indexer.buildUpsertPayload(ctx)\n : {\n entityType: indexer.entityType,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }\n const enrichedPayload = payload as Record<string, unknown>\n enrichedPayload.crudAction = action\n if (coverageBaseDelta !== undefined) enrichedPayload.coverageBaseDelta = coverageBaseDelta\n if (ctx.syncOrigin) enrichedPayload.syncOrigin = ctx.syncOrigin\n // Await the projection upsert so list reads observe the new doc immediately\n // (see delete_one above). The subscriber updates `entity_indexes` synchronously\n // and defers the heavy token-reindex pipeline (build doc + encrypt + decrypt +\n // tokenize + DELETE + chunked INSERT) so write latency stays bounded.\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.upsert_one', enrichedPayload, { rethrowHandlerErrors: true })\n } else {\n await bus.emitEvent('query_index.upsert_one', enrichedPayload).catch((err: unknown) => {\n logger.error('query_index.upsert_one emit failed', { err })\n })\n }\n }\n\n if (alwaysConsistent || shouldTriggerCoverageRefresh(indexer.entityType, ctx.identifiers.tenantId ?? null)) {\n const coveragePayload = {\n entityType: indexer.entityType,\n tenantId: ctx.identifiers.tenantId ?? null,\n organizationId: null,\n delayMs: 0,\n }\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.coverage.refresh', coveragePayload, { rethrowHandlerErrors: true })\n } else {\n void bus.emitEvent('query_index.coverage.refresh', coveragePayload).catch(() => undefined)\n }\n }\n }\n }\n\n markOrmEntityChange<T>(opts: {\n action: CrudEventAction\n entity: T | null | undefined\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n }): void {\n const { entity, identifiers } = opts\n if (!entity) return\n if (!identifiers?.id) return\n // A command handler that marks `events:` only still discharges the route's declared\n // query-index obligation \u2014 the route hands its `indexer:` down as the default so the\n // handler's own entity and identifiers (the accurate ones) drive the projection write.\n const indexer = opts.indexer ?? this.resolveDefaultIndexer(entity)\n const key = this.buildSideEffectKey(opts.action, identifiers)\n const existing = this.pendingSideEffects.get(key)\n if (existing) {\n existing.entity = entity\n existing.identifiers = {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n }\n existing.syncOrigin = opts.syncOrigin ?? null\n existing.actorUserId = opts.actorUserId ?? null\n if (opts.events) existing.events = opts.events as CrudEventsConfig<unknown>\n // Explicit always wins, on the merge branch too: a second `events:`-only mark on the same\n // key must not let the route default overwrite the `indexer:` an earlier mark installed,\n // which would silently drop that handler's own `buildUpsertPayload`.\n if (opts.indexer) existing.indexer = opts.indexer as CrudIndexerConfig<unknown>\n else if (!existing.indexer && indexer) existing.indexer = indexer\n this.pendingSideEffects.set(key, existing)\n return\n }\n const entry: QueuedCrudSideEffect = {\n action: opts.action,\n entity,\n identifiers: {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n },\n syncOrigin: opts.syncOrigin ?? null,\n actorUserId: opts.actorUserId ?? null,\n }\n if (opts.events) entry.events = opts.events as CrudEventsConfig<unknown>\n if (indexer) entry.indexer = indexer\n this.pendingSideEffects.set(key, entry)\n }\n\n async flushOrmEntityChanges(suppress?: BulkImportSuppression): Promise<void> {\n if (!this.pendingSideEffects.size) return\n const entries = Array.from(this.pendingSideEffects.values())\n this.pendingSideEffects.clear()\n for (const entry of entries) {\n if (entry.indexer && !suppress?.skipReindex && this.matchesDefaultEntityClass(entry.entity)) {\n this.indexedDefaultEntityClass = true\n }\n try {\n await this.emitOrmEntityEvent({\n action: entry.action,\n entity: entry.entity,\n identifiers: entry.identifiers,\n syncOrigin: entry.syncOrigin ?? null,\n actorUserId: entry.actorUserId ?? null,\n events: entry.events as CrudEventsConfig<unknown>,\n indexer: entry.indexer as CrudIndexerConfig<unknown>,\n suppress,\n })\n } catch (error) {\n if (isReadProjectionAlwaysConsistent()) {\n throw error\n }\n // best-effort; continue with remaining side effects\n }\n }\n }\n\n private buildSideEffectKey(action: CrudEventAction, identifiers: CrudEntityIdentifiers): string {\n const id = identifiers.id ?? ''\n const org = identifiers.organizationId ?? ''\n const tenant = identifiers.tenantId ?? ''\n return [action, id, org, tenant].join('|')\n }\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAsB,WAAW;AACjC,SAAS,mCAAmC,6BAA6B;AACzE,SAAS,uCAAuC;AAChD,SAAS,mDAAmD;AAE5D;AAAA,EACE;AAAA,OAKK;AAEP,SAAS,UAAU,eAAe,mBAAmB,gBAAgB;AACrE,SAAS,8BAA8B,4BAA4B;AACnE,SAAS,wCAAwC;AACjD,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAC3C,SAAS,yBAAyB;AAClC,SAAS,wCAAwC;AACjD,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AAGrC,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,cAAc,CAAC;AAExE,MAAM,wBAAwB,oBAAI,IAAY;AAE9C,SAAS,sBAAsB,WAAmB,SAAuB;AACvE,MAAI,gBAAgB,SAAS,EAAG;AAChC,MAAI,sBAAsB,IAAI,SAAS,EAAG;AAC1C,wBAAsB,IAAI,SAAS;AACnC,SAAO,KAAK,6IAAwI,EAAE,SAAS,UAAU,CAAC;AAC5K;AAGO,SAAS,yCAA+C;AAC7D,wBAAsB,MAAM;AAC9B;AAGA,MAAM,mBAAmB,qBAA2B;AAAA,EAClD,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,mBAAmB;AACrB,CAAC;AAGM,SAAS,kCAAwC;AACtD,mBAAiB,MAAM;AACzB;AAEA,MAAM,+BAA+B,IAAI,KAAK;AAC9C,MAAM,yBAAyB,oBAAI,IAAoB;AAEvD,SAAS,6BAA6B,YAAgC,UAAkC;AACtG,MAAI,CAAC,WAAY,QAAO;AACxB,QAAM,MAAM,GAAG,UAAU,IAAI,YAAY,UAAU;AACnD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,OAAO,uB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EAEQ,mBAAmB,QAAyB,aAA4C;AAC9F,UAAM,KAAK,YAAY,MAAM;AAC7B,UAAM,MAAM,YAAY,kBAAkB;AAC1C,UAAM,SAAS,YAAY,YAAY;AACvC,WAAO,CAAC,QAAQ,IAAI,KAAK,MAAM,EAAE,KAAK,GAAG;AAAA,EAC3C;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/lib/version.js
CHANGED
package/dist/lib/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/version.ts"],
|
|
4
|
-
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.
|
|
4
|
+
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8275.1.44b856bbe6';\nexport const appVersion = APP_VERSION;\n"],
|
|
5
5
|
"mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/shared",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8275.1.44b856bbe6",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -130,7 +130,7 @@
|
|
|
130
130
|
"@mikro-orm/core": "^7.1.14",
|
|
131
131
|
"@mikro-orm/decorators": "^7.1.14",
|
|
132
132
|
"@mikro-orm/postgresql": "^7.1.14",
|
|
133
|
-
"@open-mercato/cache": "0.10.1-develop.
|
|
133
|
+
"@open-mercato/cache": "0.10.1-develop.8275.1.44b856bbe6",
|
|
134
134
|
"@types/html-to-text": "^9.0.4",
|
|
135
135
|
"@types/sanitize-html": "^2.16.1",
|
|
136
136
|
"dotenv": "^17.4.2",
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import ts from 'typescript-js'
|
|
4
|
+
|
|
5
|
+
const enginePath = join(__dirname, '..', 'engine.ts')
|
|
6
|
+
const engineSource = ts.createSourceFile(enginePath, readFileSync(enginePath, 'utf8'), ts.ScriptTarget.Latest, true)
|
|
7
|
+
const engineClass = engineSource.statements.find(
|
|
8
|
+
(statement): statement is ts.ClassDeclaration => ts.isClassDeclaration(statement) && statement.name?.text === 'DefaultDataEngine',
|
|
9
|
+
)
|
|
10
|
+
if (!engineClass) throw new Error('[internal] DefaultDataEngine class not found')
|
|
11
|
+
|
|
12
|
+
const methodNames = ['updateOrmEntity', 'deleteOrmEntity']
|
|
13
|
+
const methods = engineClass.members.filter(
|
|
14
|
+
(member): member is ts.MethodDeclaration => ts.isMethodDeclaration(member) && methodNames.includes(member.name.getText(engineSource)),
|
|
15
|
+
)
|
|
16
|
+
const probePath = join(__dirname, 'orm-query-probe.ts')
|
|
17
|
+
const probeSource = `
|
|
18
|
+
import type { EntityName, FilterQuery } from '@mikro-orm/core'
|
|
19
|
+
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
20
|
+
class OrmQueryProbe {
|
|
21
|
+
constructor(private readonly em: EntityManager) {}
|
|
22
|
+
${methods.map((method) => method.getText(engineSource)).join('\n')}
|
|
23
|
+
}
|
|
24
|
+
`
|
|
25
|
+
|
|
26
|
+
const managerPath = join(dirname(require.resolve('@mikro-orm/core')), 'EntityManager.d.ts')
|
|
27
|
+
const managerText = readFileSync(managerPath, 'utf8')
|
|
28
|
+
const managerSource = ts.createSourceFile(managerPath, managerText, ts.ScriptTarget.Latest, true)
|
|
29
|
+
const managerClass = managerSource.statements.find(
|
|
30
|
+
(statement): statement is ts.ClassDeclaration => ts.isClassDeclaration(statement) && statement.name?.text === 'EntityManager',
|
|
31
|
+
)
|
|
32
|
+
const findOne = managerClass?.members.find(
|
|
33
|
+
(member): member is ts.MethodDeclaration => ts.isMethodDeclaration(member) && member.name.getText(managerSource) === 'findOne',
|
|
34
|
+
)
|
|
35
|
+
const whereType = findOne?.parameters.find((parameter) => parameter.name.getText(managerSource) === 'where')?.type
|
|
36
|
+
if (!whereType) throw new Error('[internal] EntityManager.findOne query type not found')
|
|
37
|
+
|
|
38
|
+
describe('DataEngine ORM query compatibility', () => {
|
|
39
|
+
test.each([
|
|
40
|
+
['MikroORM 7.1 / 7.2.8', '[Using] extends [never] ? FilterQuery<NoInfer<Entity>> : IndexFilterQuery<NoInfer<Entity>, Using>'],
|
|
41
|
+
['MikroORM 7.2.9', 'NoInfer<[Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>>'],
|
|
42
|
+
])('update and delete compile with the %s findOne signature', (_version, queryType) => {
|
|
43
|
+
expect(methods.map((method) => method.name.getText(engineSource))).toEqual(methodNames)
|
|
44
|
+
const declaration = managerText.slice(0, whereType.getStart(managerSource)) + queryType + managerText.slice(whereType.end)
|
|
45
|
+
const options: ts.CompilerOptions = {
|
|
46
|
+
strict: true,
|
|
47
|
+
noEmit: true,
|
|
48
|
+
skipLibCheck: true,
|
|
49
|
+
target: ts.ScriptTarget.ES2022,
|
|
50
|
+
module: ts.ModuleKind.ESNext,
|
|
51
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
52
|
+
types: [],
|
|
53
|
+
}
|
|
54
|
+
const host = ts.createCompilerHost(options)
|
|
55
|
+
const readFile = host.readFile.bind(host)
|
|
56
|
+
host.readFile = (filePath) => filePath === probePath ? probeSource : filePath === managerPath ? declaration : readFile(filePath)
|
|
57
|
+
const fileExists = host.fileExists.bind(host)
|
|
58
|
+
host.fileExists = (filePath) => filePath === probePath || fileExists(filePath)
|
|
59
|
+
|
|
60
|
+
const program = ts.createProgram([probePath], options, host)
|
|
61
|
+
const errors = ts.getPreEmitDiagnostics(program).filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error)
|
|
62
|
+
expect(errors.map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))).toEqual([])
|
|
63
|
+
})
|
|
64
|
+
})
|
package/src/lib/data/engine.ts
CHANGED
|
@@ -689,7 +689,7 @@ export class DefaultDataEngine implements DataEngine {
|
|
|
689
689
|
where: FilterQuery<T>
|
|
690
690
|
apply: (current: T) => Promise<void> | void
|
|
691
691
|
}): Promise<T | null> {
|
|
692
|
-
const current = await this.em.findOne(opts.entity
|
|
692
|
+
const current = await this.em.findOne<T>(opts.entity, opts.where as Parameters<typeof this.em.findOne<T>>[1])
|
|
693
693
|
if (!current) return null
|
|
694
694
|
await opts.apply(current)
|
|
695
695
|
await this.em.persist(current).flush()
|
|
@@ -702,7 +702,7 @@ export class DefaultDataEngine implements DataEngine {
|
|
|
702
702
|
soft?: boolean
|
|
703
703
|
softDeleteField?: keyof T & string
|
|
704
704
|
}): Promise<T | null> {
|
|
705
|
-
const current = await this.em.findOne(opts.entity
|
|
705
|
+
const current = await this.em.findOne<T>(opts.entity, opts.where as Parameters<typeof this.em.findOne<T>>[1])
|
|
706
706
|
if (!current) return null
|
|
707
707
|
if (opts.soft !== false) {
|
|
708
708
|
const field = opts.softDeleteField || ('deletedAt' as keyof T & string)
|