@burdenoff/be-sdk 2026.1114.1 → 2026.1116.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/{EventQueueFactory-9NGZV9jl.js → EventQueueFactory-BhNJE93c.js} +82 -8
  2. package/dist/EventQueueFactory-BhNJE93c.js.map +1 -0
  3. package/dist/event-queue/index.d.ts +1 -1
  4. package/dist/event-queue/index.js +3 -3
  5. package/dist/{event-queue-Cw-YJPY_.js → event-queue-CKvgAqF3.js} +3 -3
  6. package/dist/{event-queue-Cw-YJPY_.js.map → event-queue-CKvgAqF3.js.map} +1 -1
  7. package/dist/graph/index.d.ts +1 -1
  8. package/dist/graph/index.js +2 -2
  9. package/dist/{graph-CR7u4lpl.js → graph-Egewc_K7.js} +4 -4
  10. package/dist/{graph-CR7u4lpl.js.map → graph-Egewc_K7.js.map} +1 -1
  11. package/dist/{graph-emitter-CdOXP7Tn.js → graph-emitter-DpaWxRBp.js} +2 -2
  12. package/dist/{graph-emitter-CdOXP7Tn.js.map → graph-emitter-DpaWxRBp.js.map} +1 -1
  13. package/dist/{index-CEtULfb_.d.ts → index-B1bHk4Rq.d.ts} +6 -0
  14. package/dist/{index-9MJVKzWA.d.ts → index-DMeQh75K.d.ts} +1 -1
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +5 -5
  17. package/dist/init/index.js +1 -1
  18. package/dist/{init-D814LeLF.js → init-BCLZQ1Gz.js} +2 -2
  19. package/dist/{init-D814LeLF.js.map → init-BCLZQ1Gz.js.map} +1 -1
  20. package/dist/{middleware-CUxJVUpD.js → middleware-B9eyLP7A.js} +2 -2
  21. package/dist/{middleware-CUxJVUpD.js.map → middleware-B9eyLP7A.js.map} +1 -1
  22. package/dist/prisma/index.js +2 -2
  23. package/dist/{prisma-BzOOdt79.js → prisma-CML_Prrn.js} +3 -3
  24. package/dist/{prisma-BzOOdt79.js.map → prisma-CML_Prrn.js.map} +1 -1
  25. package/package.json +1 -1
  26. package/dist/EventQueueFactory-9NGZV9jl.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"prisma-BzOOdt79.js","names":[],"sources":["../src/prisma/factory.ts","../src/prisma/manager.ts","../src/prisma/health.ts","../src/prisma/fields.ts","../src/prisma/context.ts","../src/prisma/index.ts"],"sourcesContent":["/**\n * Database Client Factory\n *\n * Provides a unified factory for creating fully-configured database clients\n * with Prisma 7, PostgreSQL adapter, graph extension, and graceful shutdown.\n *\n * This module consolidates all database setup into a single call, reducing\n * boilerplate across all backend services.\n *\n * @module prisma/factory\n * @category Database\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createPrismaClient,\n ensureServiceApplicationName,\n type PrismaClientBase,\n type PrismaClientWrapper,\n type PrismaClientConstructorOptions,\n} from './client.js';\nimport type { PrismaClientConfig } from './types.js';\nimport { addGraphExtension, type GraphMiddlewareConfig, type GraphEventEmitter } from '../graph/middleware/index.js';\nimport { getGraphEventEmitter } from '../event-queue/graph-emitter.js';\nimport { addWorkspaceExtension, type WorkspaceExtensionConfig } from './workspace-extension.js';\n\n/**\n * Configuration for creating a database client\n */\nexport interface DatabaseClientConfig extends PrismaClientConfig {\n /**\n * Product name for graph events (e.g., 'module-tags', 'workspaces')\n */\n productName: string;\n\n /**\n * Enable graph extension for entity sync\n * @default true (reads from GRAPH_MIDDLEWARE_ENABLED env var)\n */\n enableGraphExtension?: boolean;\n\n /**\n * Custom graph event emitter (defaults to NATS-based emitter)\n */\n graphEventEmitter?: GraphEventEmitter;\n\n /**\n * Enable workspace extension for automatic workspaceId injection.\n *\n * Default is layer-aware:\n * - Global-layer services (`productName` starting with `global-` or `global_`,\n * or `WORKSPACE_LAYER=global`) default to `false`. Global-layer tables\n * (Tenant, Organization, Workspace, PlatformProduct, etc.) are intentionally\n * not workspace-scoped — enforcing workspaceId on them would block legitimate\n * queries like `myOrganizations`, `myWorkspaces`, `myAccessibleProducts`.\n * - All other services (wspace layer, product backends) default to `true`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` env var always wins when explicitly set\n * (`true` or `false`). Pass the field on `config` for code-level override.\n */\n enableWorkspaceExtension?: boolean;\n\n /**\n * Configuration for the workspace extension\n */\n workspaceExtensionConfig?: WorkspaceExtensionConfig;\n\n /**\n * Register process shutdown handlers for graceful shutdown\n * @default true\n */\n registerShutdownHandlers?: boolean;\n}\n\n/**\n * Result of creating a database client\n */\nexport interface DatabaseClient<T extends PrismaClientBase> {\n /**\n * The extended Prisma client for database operations\n * Use this for all queries: db.model.operation()\n */\n db: T & { client: T };\n\n /**\n * The Prisma client wrapper with connection management utilities\n */\n wrapper: PrismaClientWrapper<T>;\n\n /**\n * Connect to the database with retry logic\n */\n connect: (retries?: number, delay?: number) => Promise<void>;\n\n /**\n * Disconnect from the database\n */\n disconnect: () => Promise<void>;\n}\n\n/**\n * Layer-aware default for the workspace extension.\n *\n * Global-layer services (productName starting with `global-`/`global_`, or\n * `WORKSPACE_LAYER=global`) opt out by default because their tables don't carry\n * a workspaceId column — enforcement would break queries like `myOrganizations`,\n * `myAccessibleProducts`, `contentPages`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` is respected as an explicit override.\n */\nfunction resolveWorkspaceExtensionDefault(productName: string): boolean {\n const explicit = process.env['WORKSPACE_EXTENSION_ENABLED'];\n if (explicit === 'true') return true;\n if (explicit === 'false') return false;\n\n const layer = process.env['WORKSPACE_LAYER']?.toLowerCase();\n if (layer === 'global') return false;\n if (layer === 'wspace') return true;\n\n const name = productName.toLowerCase();\n if (name.startsWith('global-') || name.startsWith('global_')) return false;\n return true;\n}\n\n/**\n * Create a fully-configured database client with graph extension\n *\n * This is the recommended way to create a database connection in all backend services.\n * It handles:\n * - Prisma client creation with PostgreSQL adapter\n * - Connection pooling configuration\n * - Query logging (in development)\n * - Graph extension for entity sync (via NATS or in-memory)\n * - Graceful shutdown handlers\n *\n * @example\n * ```typescript\n * // In your service's db.ts\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClient } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = createDatabaseClient(PrismaClient, {\n * productName: 'my-service',\n * databaseUrl: process.env.DATABASE_URL!,\n * });\n *\n * export { db, wrapper, connect, disconnect };\n * export type ExtendedPrismaClient = typeof db;\n * ```\n *\n * @example\n * ```typescript\n * // With custom configuration\n * const { db } = createDatabaseClient(PrismaClient, {\n * productName: 'workspaces',\n * databaseUrl: process.env.DATABASE_URL!,\n * maxConnections: 50,\n * enableQueryLogging: true,\n * slowQueryThreshold: 200,\n * enableGraphExtension: true,\n * registerShutdownHandlers: true,\n * });\n * ```\n */\nexport function createDatabaseClient<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const {\n productName,\n enableGraphExtension = process.env['GRAPH_MIDDLEWARE_ENABLED'] !== 'false',\n graphEventEmitter,\n enableWorkspaceExtension = resolveWorkspaceExtensionDefault(productName),\n workspaceExtensionConfig,\n registerShutdownHandlers = true,\n ...prismaConfig\n } = config;\n\n // Tag every service's pool with `svc=<productName>` by default so its\n // connections are attributable in pg_stat_activity / pg_stat_statements\n // (the on-ramp to per-workspace observability and shard routing). This is\n // pure diagnostic metadata with no effect on behavior; explicit\n // `applicationName` on the config always wins.\n const prismaConfigWithDefaults: PrismaClientConfig = {\n ...prismaConfig,\n applicationName: prismaConfig.applicationName ?? `svc=${productName}`,\n };\n\n // Belt-and-suspenders: also set the PGAPPNAME env fallback so any additional\n // pools this service opens outside be-sdk still carry the per-service tag.\n ensureServiceApplicationName(productName);\n\n // Create Prisma client wrapper\n const wrapper = createPrismaClient(PrismaClientConstructor, prismaConfigWithDefaults);\n\n // Get the base client\n const baseClient = wrapper.getClient();\n\n // Extension chaining order:\n // 1. Graph extension (event emission on CRUD) - runs first\n // 2. Workspace extension (auto-inject workspaceId) - runs second\n //\n // The workspace extension should run BEFORE graph extension in the\n // interception chain so that graph events include the injected workspaceId.\n // In Prisma $extends, the LAST extension added runs FIRST (outermost wrapper).\n // So we add graph first, then workspace on top.\n\n let extendedClient: T;\n\n // Step 1: Add graph extension\n if (enableGraphExtension) {\n const eventEmitter = graphEventEmitter ?? getGraphEventEmitter();\n\n const graphConfig: GraphMiddlewareConfig = {\n enabled: true,\n productName,\n eventEmitter,\n };\n\n extendedClient = addGraphExtension(baseClient, graphConfig);\n\n logger.info('[Database] Graph extension enabled', { productName });\n } else {\n extendedClient = baseClient;\n logger.info('[Database] Graph extension disabled');\n }\n\n // Step 2: Add workspace extension (wraps on top of graph)\n if (enableWorkspaceExtension) {\n extendedClient = addWorkspaceExtension(extendedClient, workspaceExtensionConfig);\n\n logger.info('[Database] Workspace extension enabled', { productName });\n } else {\n logger.info('[Database] Workspace extension disabled');\n }\n\n // Add backwards compatibility alias\n const db = extendedClient as T & { client: T };\n (db as unknown as Record<string, unknown>)['client'] = db;\n\n // Register shutdown handlers if requested\n if (registerShutdownHandlers) {\n wrapper.registerShutdownHandlers();\n logger.debug('[Database] Shutdown handlers registered');\n }\n\n return {\n db,\n wrapper,\n connect: (retries?: number, delay?: number) => wrapper.connect(retries, delay),\n disconnect: () => wrapper.disconnect(),\n };\n}\n\n/**\n * Pool-tuning options resolved from environment variables.\n */\nexport interface PoolTuningEnv {\n /** Postgres application_name (defaults to `svc=<productName>`). */\n applicationName: string;\n /** Client-side node-postgres query_timeout in ms, if opted in (pooler-safe). */\n queryTimeoutMillis?: number;\n /** Server-side statement_timeout in ms, if opted in. */\n statementTimeoutMillis?: number;\n /** Server-side idle_in_transaction_session_timeout in ms, if opted in. */\n idleInTransactionTimeoutMillis?: number;\n /** Server-side lock_timeout in ms, if opted in. */\n lockTimeoutMillis?: number;\n}\n\n/**\n * Parse a strictly-positive integer environment variable.\n *\n * Returns `undefined` for unset, empty, non-numeric, zero, or negative values —\n * so a misconfigured or absent env var can never silently enable an aggressive\n * (or nonsensical) timeout. This is what keeps the DB-enforced timeouts OFF by\n * default and therefore behavior-preserving.\n */\nfunction parsePositiveIntEnv(name: string): number | undefined {\n const raw = process.env[name];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n const parsed = Number.parseInt(raw.trim(), 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/**\n * Resolve pool tuning (application_name + opt-in DB timeouts) from env vars:\n * - DATABASE_APPLICATION_NAME: overrides the default `svc=<productName>` tag\n * - DATABASE_QUERY_TIMEOUT: client-side node-postgres query_timeout in ms (opt-in, pooler-safe)\n * - DATABASE_STATEMENT_TIMEOUT: server-side statement_timeout in ms (opt-in; DIRECT :5432 only — see note)\n * - DATABASE_IDLE_IN_TRANSACTION_TIMEOUT: idle_in_transaction_session_timeout in ms (opt-in)\n * - DATABASE_LOCK_TIMEOUT: lock_timeout in ms (opt-in)\n *\n * Timeouts are omitted entirely unless explicitly set to a positive integer, so\n * the default is exactly today's behavior (no timeouts).\n *\n * NOTE: prefer `DATABASE_QUERY_TIMEOUT` for services whose `DATABASE_URL` points\n * at the built-in PgBouncer (`:6432`). `DATABASE_STATEMENT_TIMEOUT` and friends\n * are Postgres startup parameters that Azure PgBouncer does not pass through, so\n * they silently have no effect (or fail the connection) on the pooled path.\n */\nexport function resolvePoolTuningFromEnv(productName: string): PoolTuningEnv {\n const tuning: PoolTuningEnv = {\n applicationName: process.env['DATABASE_APPLICATION_NAME']?.trim() || `svc=${productName}`,\n };\n\n const queryTimeout = parsePositiveIntEnv('DATABASE_QUERY_TIMEOUT');\n if (queryTimeout !== undefined) {\n tuning.queryTimeoutMillis = queryTimeout;\n }\n\n const statementTimeout = parsePositiveIntEnv('DATABASE_STATEMENT_TIMEOUT');\n if (statementTimeout !== undefined) {\n tuning.statementTimeoutMillis = statementTimeout;\n }\n\n const idleInTransactionTimeout = parsePositiveIntEnv('DATABASE_IDLE_IN_TRANSACTION_TIMEOUT');\n if (idleInTransactionTimeout !== undefined) {\n tuning.idleInTransactionTimeoutMillis = idleInTransactionTimeout;\n }\n\n const lockTimeout = parsePositiveIntEnv('DATABASE_LOCK_TIMEOUT');\n if (lockTimeout !== undefined) {\n tuning.lockTimeoutMillis = lockTimeout;\n }\n\n return tuning;\n}\n\n/**\n * Create a database client from environment variables\n *\n * Convenience function that reads configuration from standard environment variables:\n * - DATABASE_URL: Connection string (required)\n * - DATABASE_MAX_CONNECTIONS: Max pool connections (default: 20)\n * - DATABASE_APPLICATION_NAME: Postgres application_name (default: `svc=<productName>`)\n * - DATABASE_QUERY_TIMEOUT: opt-in client-side query timeout in ms — the\n * PgBouncer-safe query bound (default: OFF, preserving current behavior)\n * - DATABASE_STATEMENT_TIMEOUT / DATABASE_IDLE_IN_TRANSACTION_TIMEOUT / DATABASE_LOCK_TIMEOUT:\n * opt-in server-side timeouts in ms (default: OFF; DIRECT :5432 only — not\n * honored through the built-in PgBouncer :6432 runtime path)\n * - NODE_ENV: Environment for logging settings\n * - GRAPH_MIDDLEWARE_ENABLED: Enable graph sync (default: true)\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClientFromEnv } from '@burdenoff/be-sdk/prisma';\n *\n * const { db } = createDatabaseClientFromEnv(PrismaClient, 'module-tags');\n * export { db };\n * ```\n */\nexport function createDatabaseClientFromEnv<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n overrides?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n const databaseUrl = process.env['DATABASE_URL'];\n if (!databaseUrl) {\n throw new Error('DATABASE_URL environment variable is required');\n }\n\n const isDevelopment = process.env['NODE_ENV'] === 'development';\n\n const config: DatabaseClientConfig = {\n productName,\n databaseUrl,\n maxConnections: parseInt(process.env['DATABASE_MAX_CONNECTIONS'] || '20', 10),\n idleTimeoutMillis: parseInt(process.env['DATABASE_IDLE_TIMEOUT'] || '30000', 10),\n connectionTimeoutMillis: parseInt(process.env['DATABASE_CONNECTION_TIMEOUT'] || '10000', 10),\n ...resolvePoolTuningFromEnv(productName),\n enableQueryLogging: isDevelopment,\n slowQueryThreshold: isDevelopment ? 100 : 500,\n ...overrides,\n };\n\n // Transient acquire retry — env-tunable, and unlike the fields above zero is\n // meaningful (DATABASE_ACQUIRE_RETRIES=0 disables the retry entirely).\n const acquireRetriesRaw = process.env['DATABASE_ACQUIRE_RETRIES']?.trim();\n if (acquireRetriesRaw !== undefined && acquireRetriesRaw !== '' && config.acquireRetries === undefined) {\n const parsed = Number.parseInt(acquireRetriesRaw, 10);\n if (Number.isFinite(parsed) && parsed >= 0) {\n config.acquireRetries = parsed;\n }\n }\n const acquireRetryDelay = parsePositiveIntEnv('DATABASE_ACQUIRE_RETRY_DELAY');\n if (acquireRetryDelay !== undefined && config.acquireRetryDelayMillis === undefined) {\n config.acquireRetryDelayMillis = acquireRetryDelay;\n }\n\n return createDatabaseClient(PrismaClientConstructor, config);\n}\n","/**\n * Database Singleton Manager\n *\n * Provides a singleton pattern for database connections across microservices.\n * Services initialize once at startup and access the db instance globally.\n *\n * This eliminates the need for individual db.ts files in each microservice.\n *\n * @module prisma/manager\n * @category Database\n *\n * @example\n * ```typescript\n * // In your service's index.ts (startup)\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * // Initialize once at startup\n * const { db, connect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n *\n * // In any other file\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n * const db = getDb();\n * await db.client.user.findMany();\n * ```\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createDatabaseClient,\n createDatabaseClientFromEnv,\n type DatabaseClient,\n type DatabaseClientConfig,\n} from './factory.js';\nimport type { PrismaClientBase, PrismaClientConstructorOptions, DatabaseReturnType } from './client.js';\n\n/**\n * Global database manager state\n */\ninterface DatabaseManagerState {\n initialized: boolean;\n productName: string | null;\n client: DatabaseClient<PrismaClientBase> | null;\n}\n\n/**\n * Singleton state for the database manager\n */\nconst state: DatabaseManagerState = {\n initialized: false,\n productName: null,\n client: null,\n};\n\n/**\n * Initialize the database singleton\n *\n * Call this once at application startup with your service's PrismaClient.\n * After initialization, use `getDb()` to access the database anywhere.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class from your service\n * @param productName - Product name for graph events (e.g., 'module-tags', 'workspaces')\n * @param config - Optional configuration overrides\n * @returns The database client with db, wrapper, connect, disconnect\n *\n * @throws Error if already initialized with a different product\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, connect, disconnect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n * ```\n */\nexport function initializeDatabase<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n config?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client using env-based factory\n const client = createDatabaseClientFromEnv(PrismaClientConstructor, productName, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized', { productName });\n\n return client;\n}\n\n/**\n * Initialize the database with explicit configuration\n *\n * Use this when you need full control over database configuration\n * rather than reading from environment variables.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class\n * @param config - Full database configuration\n * @returns The database client\n *\n * @example\n * ```typescript\n * const { db } = initializeDatabaseWithConfig(PrismaClient, {\n * productName: 'module-tags',\n * databaseUrl: 'postgresql://...',\n * maxConnections: 50,\n * enableGraphExtension: false,\n * });\n * ```\n */\nexport function initializeDatabaseWithConfig<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const { productName } = config;\n\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client\n const client = createDatabaseClient(PrismaClientConstructor, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized with custom config', { productName });\n\n return client;\n}\n\n/**\n * Get the initialized database client\n *\n * Use this anywhere in your application to access the database.\n * Must call `initializeDatabase()` first at application startup.\n *\n * The returned client provides dynamic model access - you can access any\n * model property (e.g., `db.client.user`, `db.client.universalTag`) and\n * TypeScript will allow common Prisma operations (findMany, create, etc.).\n *\n * @returns The extended Prisma client (db) with dynamic model access\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n *\n * const db = getDb();\n * // Dynamic model access works without importing service-specific types\n * const tags = await db.client.universalTag.findMany();\n * const users = await db.client.user.findMany({ where: { active: true } });\n * ```\n */\nexport function getDb<T extends PrismaClientBase = PrismaClientBase>(): DatabaseReturnType<T> {\n if (!state.initialized || !state.client) {\n throw new Error('Database not initialized. Call initializeDatabase() at application startup before using getDb().');\n }\n return state.client.db as unknown as DatabaseReturnType<T>;\n}\n\n/**\n * Get the full database manager\n *\n * Returns the complete database client including wrapper, connect, and disconnect functions.\n * Useful when you need access to connection management utilities.\n *\n * @returns The full database client\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDatabaseManager } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = getDatabaseManager();\n * await connect();\n * ```\n */\nexport function getDatabaseManager<T extends PrismaClientBase = PrismaClientBase>(): DatabaseClient<T> {\n if (!state.initialized || !state.client) {\n throw new Error(\n 'Database not initialized. Call initializeDatabase() at application startup before using getDatabaseManager().'\n );\n }\n return state.client as DatabaseClient<T>;\n}\n\n/**\n * Check if database is initialized\n *\n * @returns True if database has been initialized\n *\n * @example\n * ```typescript\n * if (!isDatabaseInitialized()) {\n * await initializeDatabase(PrismaClient, 'my-service');\n * }\n * ```\n */\nexport function isDatabaseInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Get the product name of the initialized database\n *\n * @returns The product name or null if not initialized\n */\nexport function getDatabaseProductName(): string | null {\n return state.productName;\n}\n\n/**\n * Reset the database manager (for testing purposes only)\n *\n * WARNING: This disconnects and resets the database manager.\n * Only use this in test environments for cleanup between tests.\n *\n * @internal\n */\nexport async function resetDatabaseManager(): Promise<void> {\n if (state.client) {\n try {\n await state.client.disconnect();\n } catch (error) {\n logger.warn('[DatabaseManager] Error during disconnect on reset', { error });\n }\n }\n\n state.initialized = false;\n state.productName = null;\n state.client = null;\n\n logger.debug('[DatabaseManager] Database manager reset');\n}\n","/**\n * Prisma Health Check Utilities\n */\n\nimport { logger } from '../logger/index.js';\nimport type { DatabaseHealth } from './types.js';\nimport type { PrismaClientBase } from './client.js';\n\n/**\n * Check database health\n */\nexport async function checkDatabaseHealth<T extends PrismaClientBase>(client: T): Promise<DatabaseHealth> {\n try {\n const start = Date.now();\n await client.$queryRaw`SELECT 1`;\n const latency = Date.now() - start;\n\n return { healthy: true, latency };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error('[Prisma] Health check failed', { error: errorMessage });\n\n return {\n healthy: false,\n error: errorMessage,\n };\n }\n}\n\n/**\n * Test database connection\n */\nexport async function testConnection<T extends PrismaClientBase>(client: T): Promise<boolean> {\n try {\n await client.$queryRaw`SELECT 1`;\n return true;\n } catch (error) {\n logger.error('[Prisma] Connection test failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Get database version\n */\nexport async function getDatabaseVersion<T extends PrismaClientBase>(client: T): Promise<string | null> {\n try {\n const result = await client.$queryRaw<Array<{ version?: string }>>`SELECT version()`;\n return result[0]?.version ?? null;\n } catch (error) {\n logger.error('[Prisma] Failed to get database version', {\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n}\n\n/**\n * Get database stats\n */\nexport async function getDatabaseStats<T extends PrismaClientBase>(\n client: T\n): Promise<{\n health: DatabaseHealth;\n version: string | null;\n timestamp: Date;\n}> {\n const [health, version] = await Promise.all([checkDatabaseHealth(client), getDatabaseVersion(client)]);\n\n return {\n health,\n version,\n timestamp: new Date(),\n };\n}\n","/**\n * Prisma Field Extraction Utilities\n *\n * Provides utilities for extracting model fields from Prisma schema.\n * In Prisma 7, DMMF is not available at runtime, so this module provides\n * build-time field extraction through a generator.\n *\n * @module prisma/fields\n */\n\nimport { createRequire } from 'node:module';\nimport { logger } from '../logger/index.js';\n\nconst requireFn = createRequire(import.meta.url);\n\n/**\n * Field extraction options\n */\nexport interface FieldExtractionOptions {\n /** Fields to exclude from extraction */\n excludeFields?: string[];\n /** Whether to include relation fields */\n includeRelations?: boolean;\n /** Custom filter function */\n customFilter?: (field: { name: string; type: string; isRelation: boolean }) => boolean;\n}\n\n/**\n * Field extraction result\n */\nexport interface FieldExtractionResult {\n /** Extracted field names */\n fields: string[];\n /** Metadata about the extraction */\n metadata: {\n /** Total number of fields found */\n totalFields: number;\n /** Number of fields excluded */\n excludedCount: number;\n /** Names of excluded fields */\n excludedFields: string[];\n /** Number of relation fields */\n relationFields: number;\n };\n}\n\n/**\n * Model fields mapping\n * This will be generated at build time by the Prisma generator\n */\nexport type ModelFieldsMap = Record<\n string,\n {\n fields: string[];\n relations: string[];\n }\n>;\n\n/**\n * Import generated fields from the consuming package\n * This function should be used by backends to load their generated fields\n */\nexport function loadGeneratedFields(generatedFieldsPath: string): ModelFieldsMap {\n try {\n // Dynamic import of generated fields using createRequire\n const generated = requireFn(generatedFieldsPath) as { default: ModelFieldsMap };\n return generated.default || generated;\n } catch (error) {\n logger.error('[Prisma] Failed to load generated fields', {\n error: error instanceof Error ? error.message : String(error),\n path: generatedFieldsPath,\n });\n throw new Error(`Failed to load generated fields from ${generatedFieldsPath}`);\n }\n}\n\n/**\n * Extract fields from generated model fields with options\n */\nexport function extractFieldsFromModel(\n modelName: string,\n modelFieldsMap: ModelFieldsMap,\n options: FieldExtractionOptions = {}\n): FieldExtractionResult {\n const modelFields = modelFieldsMap[modelName];\n\n if (!modelFields) {\n throw new Error(\n `Model \"${modelName}\" not found in generated fields. ` +\n `Available models: ${Object.keys(modelFieldsMap).join(', ')}`\n );\n }\n\n const { excludeFields = [], includeRelations = false, customFilter } = options;\n\n // Start with scalar fields\n let fields = [...modelFields.fields];\n\n // Add relations if requested\n if (includeRelations) {\n fields = [...fields, ...modelFields.relations];\n }\n\n // Track excluded fields\n const excluded: string[] = [];\n\n // Apply exclusions\n if (excludeFields.length > 0) {\n fields = fields.filter((field) => {\n if (excludeFields.includes(field)) {\n excluded.push(field);\n return false;\n }\n return true;\n });\n }\n\n // Apply custom filter\n if (customFilter) {\n fields = fields.filter((fieldName) => {\n const isRelation = modelFields.relations.includes(fieldName);\n const shouldInclude = customFilter({\n name: fieldName,\n type: 'unknown', // Type information not available without full DMMF\n isRelation,\n });\n\n if (!shouldInclude) {\n excluded.push(fieldName);\n }\n\n return shouldInclude;\n });\n }\n\n return {\n fields,\n metadata: {\n totalFields: modelFields.fields.length + modelFields.relations.length,\n excludedCount: excluded.length,\n excludedFields: excluded,\n relationFields: modelFields.relations.length,\n },\n };\n}\n\n/**\n * Get all field names for a model (without options)\n */\nexport function getModelFields(modelName: string, modelFieldsMap: ModelFieldsMap, includeRelations = false): string[] {\n const result = extractFieldsFromModel(modelName, modelFieldsMap, { includeRelations });\n return result.fields;\n}\n\n/**\n * Check if a model exists in the generated fields\n */\nexport function hasModel(modelName: string, modelFieldsMap: ModelFieldsMap): boolean {\n return modelName in modelFieldsMap;\n}\n\n/**\n * Get all available model names\n */\nexport function getAllModelNames(modelFieldsMap: ModelFieldsMap): string[] {\n return Object.keys(modelFieldsMap);\n}\n","/**\n * Prisma Context Filtering Utilities\n *\n * Utilities for handling operation context in queries, mutations, and filtering.\n * Context JSON enables multi-dimensional data isolation across workspaces, users, projects, etc.\n *\n * @module prisma/context\n * @category Database\n */\n\nimport { isSameProductSlug, productSlugVariants } from '../product-alias/index.js';\n\n/**\n * Context filter input for querying entities by context\n */\nexport interface ContextFilterInput {\n workspaceId?: string | null;\n userId?: string | null;\n projectId?: string | null;\n appId?: string | null;\n /** Product identifier (e.g. \"vibecontrols\", \"workspaces\"). Stamped on cross-product\n * records so admin filters can scope by originating product. */\n productId?: string | null;\n /** Organization identifier within the tenant. */\n organizationId?: string | null;\n}\n\n/**\n * Operation context for create/update operations\n */\nexport interface OperationContext extends ContextFilterInput {\n custom?: Record<string, unknown> | null;\n}\n\n/**\n * Prisma JSON filter type (simplified for context filtering)\n * This type is designed to be compatible with Prisma's JsonNullableFilter\n * Uses Record<string, unknown> for maximum compatibility with various Prisma versions\n */\nexport type PrismaJsonFilter = Record<string, unknown>;\n\n/**\n * One entry of {@link buildContextWhereConditions}: a JSON-path predicate on `context`,\n * or an `OR` of them (used for a renamed product's slug twins).\n */\nexport type ContextWhereCondition = { context: PrismaJsonFilter } | { OR: Array<{ context: PrismaJsonFilter }> };\n\n/**\n * JSON value type for Prisma (includes null for reading from DB)\n */\nexport type JsonValue = string | number | boolean | null | { [key: string]: JsonValue } | JsonValue[];\n\n/**\n * Input JSON value type for Prisma (excludes null for writing to DB)\n * Compatible with Prisma's InputJsonValue type\n */\nexport type InputJsonValue = string | number | boolean | { [key: string]: InputJsonValue } | InputJsonValue[];\n\n/**\n * Build Prisma where condition for context filtering.\n * Uses PostgreSQL JSONB containment operators for efficient queries.\n *\n * @param contextFilter - The context filter input\n * @returns Prisma where clause for context field, or undefined if no filter provided\n *\n * @example\n * ```typescript\n * const contextWhere = buildContextWhereClause({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Returns: { path: ['workspaceId'], equals: '123' }\n * ```\n */\nexport function buildContextWhereClause(\n contextFilter: ContextFilterInput | null | undefined\n): PrismaJsonFilter | undefined {\n if (!contextFilter) {\n return undefined;\n }\n\n // Build array of path conditions for each non-null field\n const conditions: PrismaJsonFilter[] = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n path: ['userId'],\n equals: contextFilter.userId,\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n path: ['projectId'],\n equals: contextFilter.projectId,\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n path: ['appId'],\n equals: contextFilter.appId,\n });\n }\n\n if (contextFilter.productId != null) {\n conditions.push({\n path: ['productId'],\n equals: contextFilter.productId,\n });\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n });\n }\n\n // If no conditions, return undefined\n if (conditions.length === 0) {\n return undefined;\n }\n\n // If single condition, return it directly\n if (conditions.length === 1) {\n return conditions[0];\n }\n\n // For multiple conditions, return the first one\n // Caller should use buildContextWhereConditions for multiple AND conditions\n return conditions[0];\n}\n\n/**\n * Build context where conditions as an array for use in AND clause.\n * This is useful when you need to filter by multiple context fields.\n *\n * @param contextFilter - The context filter input\n * @returns Array of Prisma where conditions, each targeting the context field\n *\n * @example\n * ```typescript\n * const conditions = buildContextWhereConditions({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Use in Prisma query:\n * prisma.entity.findMany({\n * where: { AND: conditions }\n * });\n * ```\n */\nexport function buildContextWhereConditions(\n contextFilter: ContextFilterInput | null | undefined\n): ContextWhereCondition[] {\n if (!contextFilter) {\n return [];\n }\n\n const conditions: ContextWhereCondition[] = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n context: {\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n },\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n context: {\n path: ['userId'],\n equals: contextFilter.userId,\n },\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n context: {\n path: ['projectId'],\n equals: contextFilter.projectId,\n },\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n context: {\n path: ['appId'],\n equals: contextFilter.appId,\n },\n });\n }\n\n if (contextFilter.productId != null) {\n // A renamed product (botlit → botmanor) matches rows stored under either slug while\n // they are migrated; every other product keeps the exact single-slug predicate.\n const slugs = productSlugVariants(contextFilter.productId);\n if (slugs.length > 1) {\n conditions.push({\n OR: slugs.map((slug) => ({ context: { path: ['productId'], equals: slug } })),\n });\n } else {\n conditions.push({\n context: {\n path: ['productId'],\n equals: contextFilter.productId,\n },\n });\n }\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n context: {\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n },\n });\n }\n\n return conditions;\n}\n\n/**\n * Convert context input to Prisma JSON format for create/update operations.\n *\n * @param contextInput - The context input\n * @returns JSON value for the context field, or undefined if empty\n *\n * @example\n * ```typescript\n * const contextJson = toContextJson({\n * workspaceId: '123',\n * userId: '456'\n * });\n * // Use in Prisma create:\n * prisma.entity.create({\n * data: { context: contextJson }\n * });\n * ```\n */\nexport function toContextJson(contextInput: OperationContext | null | undefined): InputJsonValue | undefined {\n if (!contextInput) {\n return undefined;\n }\n\n // Remove null values and build clean context object\n const context: Record<string, InputJsonValue> = {};\n\n if (contextInput.workspaceId != null) {\n context['workspaceId'] = contextInput.workspaceId;\n }\n if (contextInput.userId != null) {\n context['userId'] = contextInput.userId;\n }\n if (contextInput.projectId != null) {\n context['projectId'] = contextInput.projectId;\n }\n if (contextInput.appId != null) {\n context['appId'] = contextInput.appId;\n }\n if (contextInput.productId != null) {\n context['productId'] = contextInput.productId;\n }\n if (contextInput.organizationId != null) {\n context['organizationId'] = contextInput.organizationId;\n }\n if (contextInput.custom != null) {\n context['custom'] = contextInput.custom as InputJsonValue;\n }\n\n // Return undefined if no fields set\n if (Object.keys(context).length === 0) {\n return undefined;\n }\n\n return context;\n}\n\n/**\n * Filter out null values from an object for Prisma compatibility\n */\nfunction filterNullValues(obj: Record<string, unknown>): Record<string, InputJsonValue> {\n const filtered: Record<string, InputJsonValue> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== null) {\n filtered[key] = value as InputJsonValue;\n }\n }\n return filtered;\n}\n\n/**\n * Merge a single field into the merged context object\n */\nfunction mergeContextField(\n merged: Record<string, InputJsonValue>,\n fieldName: string,\n fieldValue: string | Record<string, unknown> | null | undefined\n): void {\n if (fieldValue === undefined) {\n return; // Don't touch this field\n }\n\n if (fieldValue === null) {\n delete merged[fieldName]; // Explicitly remove\n } else {\n merged[fieldName] = fieldValue as InputJsonValue; // Set new value\n }\n}\n\n/**\n * Merge existing context with new context input.\n * New values override existing ones, but undefined values are preserved from existing.\n *\n * @param existingContext - The existing context JSON from database\n * @param newContext - The new context input\n * @returns Merged context as InputJsonValue (suitable for Prisma writes)\n *\n * @example\n * ```typescript\n * const merged = mergeContext(\n * { workspaceId: '123', userId: 'old' },\n * { userId: 'new', projectId: '456' }\n * );\n * // Result: { workspaceId: '123', userId: 'new', projectId: '456' }\n * ```\n */\nexport function mergeContext(\n existingContext: JsonValue | null | undefined,\n newContext: OperationContext | null | undefined\n): InputJsonValue | undefined {\n // If no new context, return existing (excluding null values)\n if (!newContext) {\n if (!existingContext) {\n return undefined;\n }\n // Filter out null values from existing context for Prisma compatibility\n if (typeof existingContext === 'object' && !Array.isArray(existingContext)) {\n const filtered = filterNullValues(existingContext);\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n }\n return existingContext as InputJsonValue;\n }\n\n // If no existing context, convert new to JSON\n if (!existingContext || typeof existingContext !== 'object' || Array.isArray(existingContext)) {\n return toContextJson(newContext);\n }\n\n // Merge existing with new\n const merged = filterNullValues(existingContext);\n\n // Merge each field from new context\n mergeContextField(merged, 'workspaceId', newContext.workspaceId);\n mergeContextField(merged, 'userId', newContext.userId);\n mergeContextField(merged, 'projectId', newContext.projectId);\n mergeContextField(merged, 'appId', newContext.appId);\n mergeContextField(merged, 'productId', newContext.productId);\n mergeContextField(merged, 'organizationId', newContext.organizationId);\n mergeContextField(merged, 'custom', newContext.custom);\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n/**\n * Parse context JSON from database to OperationContext interface.\n *\n * @param contextJson - The context JSON from database\n * @returns Parsed OperationContext or null\n *\n * @example\n * ```typescript\n * const context = parseContext(entity.context);\n * if (context?.workspaceId) {\n * // Use workspace-specific logic\n * }\n * ```\n */\nexport function parseContext(contextJson: JsonValue | null | undefined): OperationContext | null {\n if (!contextJson || typeof contextJson !== 'object' || Array.isArray(contextJson)) {\n return null;\n }\n\n const ctx = contextJson as Record<string, unknown>;\n\n return {\n workspaceId: typeof ctx['workspaceId'] === 'string' ? ctx['workspaceId'] : null,\n userId: typeof ctx['userId'] === 'string' ? ctx['userId'] : null,\n projectId: typeof ctx['projectId'] === 'string' ? ctx['projectId'] : null,\n appId: typeof ctx['appId'] === 'string' ? ctx['appId'] : null,\n productId: typeof ctx['productId'] === 'string' ? ctx['productId'] : null,\n organizationId: typeof ctx['organizationId'] === 'string' ? ctx['organizationId'] : null,\n custom: typeof ctx['custom'] === 'object' ? (ctx['custom'] as Record<string, unknown>) : null,\n };\n}\n\n/**\n * Check if context matches filter criteria\n *\n * @param context - The context to check\n * @param filter - The filter criteria\n * @returns True if context matches all filter criteria\n */\nexport function contextMatches(context: OperationContext | null | undefined, filter: ContextFilterInput): boolean {\n if (!context) {\n return false;\n }\n\n if (filter.workspaceId != null && context.workspaceId !== filter.workspaceId) {\n return false;\n }\n if (filter.userId != null && context.userId !== filter.userId) {\n return false;\n }\n if (filter.projectId != null && context.projectId !== filter.projectId) {\n return false;\n }\n if (filter.appId != null && context.appId !== filter.appId) {\n return false;\n }\n // Renamed products (botlit → botmanor) match under either slug while rows are migrated.\n if (filter.productId != null && !isSameProductSlug(context.productId, filter.productId)) {\n return false;\n }\n if (filter.organizationId != null && context.organizationId !== filter.organizationId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Create a default context from SDK context\n *\n * @param sdkContext - The SDK context (from AsyncLocalStorage)\n * @returns Operation context with workspace and user info\n */\nexport function createContextFromSDK(sdkContext: {\n workspaceId?: string;\n userId?: string;\n projectId?: string;\n appId?: string;\n productId?: string;\n organizationId?: string;\n}): OperationContext {\n return {\n workspaceId: sdkContext.workspaceId ?? null,\n userId: sdkContext.userId ?? null,\n projectId: sdkContext.projectId ?? null,\n appId: sdkContext.appId ?? null,\n productId: sdkContext.productId ?? null,\n organizationId: sdkContext.organizationId ?? null,\n };\n}\n","/**\n * Prisma Module for Burdenoff Backend SDK\n *\n * Provides Prisma 7 utilities including:\n * - Singleton database manager for microservices\n * - Unified database client factory with graph extension\n * - Prisma client configuration with PostgreSQL adapter\n * - Connection pooling and management\n * - Health checks and monitoring\n * - Graceful shutdown handling\n * - Field extraction utilities for graph sync\n * - Context filtering utilities for multi-tenant queries\n * - Workspace extension for automatic workspaceId injection\n *\n * @module prisma\n * @category Database\n */\n\nexport * from './manager.js';\nexport * from './factory.js';\nexport * from './client.js';\nexport type * from './types.js';\nexport * from './health.js';\nexport * from './fields.js';\nexport * from './context.js';\nexport * from './workspace-extension.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8GA,SAAS,iCAAiC,aAA8B;CACtE,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,QAAQ,OAAO;CAChC,IAAI,aAAa,SAAS,OAAO;CAEjC,MAAM,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,YAAY;CAC1D,IAAI,UAAU,UAAU,OAAO;CAC/B,IAAI,UAAU,UAAU,OAAO;CAE/B,MAAM,OAAO,YAAY,YAAY;CACrC,IAAI,KAAK,WAAW,SAAS,KAAK,KAAK,WAAW,SAAS,GAAG,OAAO;CACrE,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,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aAAa;EACnC,gBAAgB,WAAW,kBAAkB;CAC/C;AACF"}
1
+ {"version":3,"file":"prisma-CML_Prrn.js","names":[],"sources":["../src/prisma/factory.ts","../src/prisma/manager.ts","../src/prisma/health.ts","../src/prisma/fields.ts","../src/prisma/context.ts","../src/prisma/index.ts"],"sourcesContent":["/**\n * Database Client Factory\n *\n * Provides a unified factory for creating fully-configured database clients\n * with Prisma 7, PostgreSQL adapter, graph extension, and graceful shutdown.\n *\n * This module consolidates all database setup into a single call, reducing\n * boilerplate across all backend services.\n *\n * @module prisma/factory\n * @category Database\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createPrismaClient,\n ensureServiceApplicationName,\n type PrismaClientBase,\n type PrismaClientWrapper,\n type PrismaClientConstructorOptions,\n} from './client.js';\nimport type { PrismaClientConfig } from './types.js';\nimport { addGraphExtension, type GraphMiddlewareConfig, type GraphEventEmitter } from '../graph/middleware/index.js';\nimport { getGraphEventEmitter } from '../event-queue/graph-emitter.js';\nimport { addWorkspaceExtension, type WorkspaceExtensionConfig } from './workspace-extension.js';\n\n/**\n * Configuration for creating a database client\n */\nexport interface DatabaseClientConfig extends PrismaClientConfig {\n /**\n * Product name for graph events (e.g., 'module-tags', 'workspaces')\n */\n productName: string;\n\n /**\n * Enable graph extension for entity sync\n * @default true (reads from GRAPH_MIDDLEWARE_ENABLED env var)\n */\n enableGraphExtension?: boolean;\n\n /**\n * Custom graph event emitter (defaults to NATS-based emitter)\n */\n graphEventEmitter?: GraphEventEmitter;\n\n /**\n * Enable workspace extension for automatic workspaceId injection.\n *\n * Default is layer-aware:\n * - Global-layer services (`productName` starting with `global-` or `global_`,\n * or `WORKSPACE_LAYER=global`) default to `false`. Global-layer tables\n * (Tenant, Organization, Workspace, PlatformProduct, etc.) are intentionally\n * not workspace-scoped — enforcing workspaceId on them would block legitimate\n * queries like `myOrganizations`, `myWorkspaces`, `myAccessibleProducts`.\n * - All other services (wspace layer, product backends) default to `true`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` env var always wins when explicitly set\n * (`true` or `false`). Pass the field on `config` for code-level override.\n */\n enableWorkspaceExtension?: boolean;\n\n /**\n * Configuration for the workspace extension\n */\n workspaceExtensionConfig?: WorkspaceExtensionConfig;\n\n /**\n * Register process shutdown handlers for graceful shutdown\n * @default true\n */\n registerShutdownHandlers?: boolean;\n}\n\n/**\n * Result of creating a database client\n */\nexport interface DatabaseClient<T extends PrismaClientBase> {\n /**\n * The extended Prisma client for database operations\n * Use this for all queries: db.model.operation()\n */\n db: T & { client: T };\n\n /**\n * The Prisma client wrapper with connection management utilities\n */\n wrapper: PrismaClientWrapper<T>;\n\n /**\n * Connect to the database with retry logic\n */\n connect: (retries?: number, delay?: number) => Promise<void>;\n\n /**\n * Disconnect from the database\n */\n disconnect: () => Promise<void>;\n}\n\n/**\n * Layer-aware default for the workspace extension.\n *\n * Global-layer services (productName starting with `global-`/`global_`, or\n * `WORKSPACE_LAYER=global`) opt out by default because their tables don't carry\n * a workspaceId column — enforcement would break queries like `myOrganizations`,\n * `myAccessibleProducts`, `contentPages`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` is respected as an explicit override.\n */\nfunction resolveWorkspaceExtensionDefault(productName: string): boolean {\n const explicit = process.env['WORKSPACE_EXTENSION_ENABLED'];\n if (explicit === 'true') return true;\n if (explicit === 'false') return false;\n\n const layer = process.env['WORKSPACE_LAYER']?.toLowerCase();\n if (layer === 'global') return false;\n if (layer === 'wspace') return true;\n\n const name = productName.toLowerCase();\n if (name.startsWith('global-') || name.startsWith('global_')) return false;\n return true;\n}\n\n/**\n * Create a fully-configured database client with graph extension\n *\n * This is the recommended way to create a database connection in all backend services.\n * It handles:\n * - Prisma client creation with PostgreSQL adapter\n * - Connection pooling configuration\n * - Query logging (in development)\n * - Graph extension for entity sync (via NATS or in-memory)\n * - Graceful shutdown handlers\n *\n * @example\n * ```typescript\n * // In your service's db.ts\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClient } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = createDatabaseClient(PrismaClient, {\n * productName: 'my-service',\n * databaseUrl: process.env.DATABASE_URL!,\n * });\n *\n * export { db, wrapper, connect, disconnect };\n * export type ExtendedPrismaClient = typeof db;\n * ```\n *\n * @example\n * ```typescript\n * // With custom configuration\n * const { db } = createDatabaseClient(PrismaClient, {\n * productName: 'workspaces',\n * databaseUrl: process.env.DATABASE_URL!,\n * maxConnections: 50,\n * enableQueryLogging: true,\n * slowQueryThreshold: 200,\n * enableGraphExtension: true,\n * registerShutdownHandlers: true,\n * });\n * ```\n */\nexport function createDatabaseClient<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const {\n productName,\n enableGraphExtension = process.env['GRAPH_MIDDLEWARE_ENABLED'] !== 'false',\n graphEventEmitter,\n enableWorkspaceExtension = resolveWorkspaceExtensionDefault(productName),\n workspaceExtensionConfig,\n registerShutdownHandlers = true,\n ...prismaConfig\n } = config;\n\n // Tag every service's pool with `svc=<productName>` by default so its\n // connections are attributable in pg_stat_activity / pg_stat_statements\n // (the on-ramp to per-workspace observability and shard routing). This is\n // pure diagnostic metadata with no effect on behavior; explicit\n // `applicationName` on the config always wins.\n const prismaConfigWithDefaults: PrismaClientConfig = {\n ...prismaConfig,\n applicationName: prismaConfig.applicationName ?? `svc=${productName}`,\n };\n\n // Belt-and-suspenders: also set the PGAPPNAME env fallback so any additional\n // pools this service opens outside be-sdk still carry the per-service tag.\n ensureServiceApplicationName(productName);\n\n // Create Prisma client wrapper\n const wrapper = createPrismaClient(PrismaClientConstructor, prismaConfigWithDefaults);\n\n // Get the base client\n const baseClient = wrapper.getClient();\n\n // Extension chaining order:\n // 1. Graph extension (event emission on CRUD) - runs first\n // 2. Workspace extension (auto-inject workspaceId) - runs second\n //\n // The workspace extension should run BEFORE graph extension in the\n // interception chain so that graph events include the injected workspaceId.\n // In Prisma $extends, the LAST extension added runs FIRST (outermost wrapper).\n // So we add graph first, then workspace on top.\n\n let extendedClient: T;\n\n // Step 1: Add graph extension\n if (enableGraphExtension) {\n const eventEmitter = graphEventEmitter ?? getGraphEventEmitter();\n\n const graphConfig: GraphMiddlewareConfig = {\n enabled: true,\n productName,\n eventEmitter,\n };\n\n extendedClient = addGraphExtension(baseClient, graphConfig);\n\n logger.info('[Database] Graph extension enabled', { productName });\n } else {\n extendedClient = baseClient;\n logger.info('[Database] Graph extension disabled');\n }\n\n // Step 2: Add workspace extension (wraps on top of graph)\n if (enableWorkspaceExtension) {\n extendedClient = addWorkspaceExtension(extendedClient, workspaceExtensionConfig);\n\n logger.info('[Database] Workspace extension enabled', { productName });\n } else {\n logger.info('[Database] Workspace extension disabled');\n }\n\n // Add backwards compatibility alias\n const db = extendedClient as T & { client: T };\n (db as unknown as Record<string, unknown>)['client'] = db;\n\n // Register shutdown handlers if requested\n if (registerShutdownHandlers) {\n wrapper.registerShutdownHandlers();\n logger.debug('[Database] Shutdown handlers registered');\n }\n\n return {\n db,\n wrapper,\n connect: (retries?: number, delay?: number) => wrapper.connect(retries, delay),\n disconnect: () => wrapper.disconnect(),\n };\n}\n\n/**\n * Pool-tuning options resolved from environment variables.\n */\nexport interface PoolTuningEnv {\n /** Postgres application_name (defaults to `svc=<productName>`). */\n applicationName: string;\n /** Client-side node-postgres query_timeout in ms, if opted in (pooler-safe). */\n queryTimeoutMillis?: number;\n /** Server-side statement_timeout in ms, if opted in. */\n statementTimeoutMillis?: number;\n /** Server-side idle_in_transaction_session_timeout in ms, if opted in. */\n idleInTransactionTimeoutMillis?: number;\n /** Server-side lock_timeout in ms, if opted in. */\n lockTimeoutMillis?: number;\n}\n\n/**\n * Parse a strictly-positive integer environment variable.\n *\n * Returns `undefined` for unset, empty, non-numeric, zero, or negative values —\n * so a misconfigured or absent env var can never silently enable an aggressive\n * (or nonsensical) timeout. This is what keeps the DB-enforced timeouts OFF by\n * default and therefore behavior-preserving.\n */\nfunction parsePositiveIntEnv(name: string): number | undefined {\n const raw = process.env[name];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n const parsed = Number.parseInt(raw.trim(), 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/**\n * Resolve pool tuning (application_name + opt-in DB timeouts) from env vars:\n * - DATABASE_APPLICATION_NAME: overrides the default `svc=<productName>` tag\n * - DATABASE_QUERY_TIMEOUT: client-side node-postgres query_timeout in ms (opt-in, pooler-safe)\n * - DATABASE_STATEMENT_TIMEOUT: server-side statement_timeout in ms (opt-in; DIRECT :5432 only — see note)\n * - DATABASE_IDLE_IN_TRANSACTION_TIMEOUT: idle_in_transaction_session_timeout in ms (opt-in)\n * - DATABASE_LOCK_TIMEOUT: lock_timeout in ms (opt-in)\n *\n * Timeouts are omitted entirely unless explicitly set to a positive integer, so\n * the default is exactly today's behavior (no timeouts).\n *\n * NOTE: prefer `DATABASE_QUERY_TIMEOUT` for services whose `DATABASE_URL` points\n * at the built-in PgBouncer (`:6432`). `DATABASE_STATEMENT_TIMEOUT` and friends\n * are Postgres startup parameters that Azure PgBouncer does not pass through, so\n * they silently have no effect (or fail the connection) on the pooled path.\n */\nexport function resolvePoolTuningFromEnv(productName: string): PoolTuningEnv {\n const tuning: PoolTuningEnv = {\n applicationName: process.env['DATABASE_APPLICATION_NAME']?.trim() || `svc=${productName}`,\n };\n\n const queryTimeout = parsePositiveIntEnv('DATABASE_QUERY_TIMEOUT');\n if (queryTimeout !== undefined) {\n tuning.queryTimeoutMillis = queryTimeout;\n }\n\n const statementTimeout = parsePositiveIntEnv('DATABASE_STATEMENT_TIMEOUT');\n if (statementTimeout !== undefined) {\n tuning.statementTimeoutMillis = statementTimeout;\n }\n\n const idleInTransactionTimeout = parsePositiveIntEnv('DATABASE_IDLE_IN_TRANSACTION_TIMEOUT');\n if (idleInTransactionTimeout !== undefined) {\n tuning.idleInTransactionTimeoutMillis = idleInTransactionTimeout;\n }\n\n const lockTimeout = parsePositiveIntEnv('DATABASE_LOCK_TIMEOUT');\n if (lockTimeout !== undefined) {\n tuning.lockTimeoutMillis = lockTimeout;\n }\n\n return tuning;\n}\n\n/**\n * Create a database client from environment variables\n *\n * Convenience function that reads configuration from standard environment variables:\n * - DATABASE_URL: Connection string (required)\n * - DATABASE_MAX_CONNECTIONS: Max pool connections (default: 20)\n * - DATABASE_APPLICATION_NAME: Postgres application_name (default: `svc=<productName>`)\n * - DATABASE_QUERY_TIMEOUT: opt-in client-side query timeout in ms — the\n * PgBouncer-safe query bound (default: OFF, preserving current behavior)\n * - DATABASE_STATEMENT_TIMEOUT / DATABASE_IDLE_IN_TRANSACTION_TIMEOUT / DATABASE_LOCK_TIMEOUT:\n * opt-in server-side timeouts in ms (default: OFF; DIRECT :5432 only — not\n * honored through the built-in PgBouncer :6432 runtime path)\n * - NODE_ENV: Environment for logging settings\n * - GRAPH_MIDDLEWARE_ENABLED: Enable graph sync (default: true)\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClientFromEnv } from '@burdenoff/be-sdk/prisma';\n *\n * const { db } = createDatabaseClientFromEnv(PrismaClient, 'module-tags');\n * export { db };\n * ```\n */\nexport function createDatabaseClientFromEnv<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n overrides?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n const databaseUrl = process.env['DATABASE_URL'];\n if (!databaseUrl) {\n throw new Error('DATABASE_URL environment variable is required');\n }\n\n const isDevelopment = process.env['NODE_ENV'] === 'development';\n\n const config: DatabaseClientConfig = {\n productName,\n databaseUrl,\n maxConnections: parseInt(process.env['DATABASE_MAX_CONNECTIONS'] || '20', 10),\n idleTimeoutMillis: parseInt(process.env['DATABASE_IDLE_TIMEOUT'] || '30000', 10),\n connectionTimeoutMillis: parseInt(process.env['DATABASE_CONNECTION_TIMEOUT'] || '10000', 10),\n ...resolvePoolTuningFromEnv(productName),\n enableQueryLogging: isDevelopment,\n slowQueryThreshold: isDevelopment ? 100 : 500,\n ...overrides,\n };\n\n // Transient acquire retry — env-tunable, and unlike the fields above zero is\n // meaningful (DATABASE_ACQUIRE_RETRIES=0 disables the retry entirely).\n const acquireRetriesRaw = process.env['DATABASE_ACQUIRE_RETRIES']?.trim();\n if (acquireRetriesRaw !== undefined && acquireRetriesRaw !== '' && config.acquireRetries === undefined) {\n const parsed = Number.parseInt(acquireRetriesRaw, 10);\n if (Number.isFinite(parsed) && parsed >= 0) {\n config.acquireRetries = parsed;\n }\n }\n const acquireRetryDelay = parsePositiveIntEnv('DATABASE_ACQUIRE_RETRY_DELAY');\n if (acquireRetryDelay !== undefined && config.acquireRetryDelayMillis === undefined) {\n config.acquireRetryDelayMillis = acquireRetryDelay;\n }\n\n return createDatabaseClient(PrismaClientConstructor, config);\n}\n","/**\n * Database Singleton Manager\n *\n * Provides a singleton pattern for database connections across microservices.\n * Services initialize once at startup and access the db instance globally.\n *\n * This eliminates the need for individual db.ts files in each microservice.\n *\n * @module prisma/manager\n * @category Database\n *\n * @example\n * ```typescript\n * // In your service's index.ts (startup)\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * // Initialize once at startup\n * const { db, connect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n *\n * // In any other file\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n * const db = getDb();\n * await db.client.user.findMany();\n * ```\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createDatabaseClient,\n createDatabaseClientFromEnv,\n type DatabaseClient,\n type DatabaseClientConfig,\n} from './factory.js';\nimport type { PrismaClientBase, PrismaClientConstructorOptions, DatabaseReturnType } from './client.js';\n\n/**\n * Global database manager state\n */\ninterface DatabaseManagerState {\n initialized: boolean;\n productName: string | null;\n client: DatabaseClient<PrismaClientBase> | null;\n}\n\n/**\n * Singleton state for the database manager\n */\nconst state: DatabaseManagerState = {\n initialized: false,\n productName: null,\n client: null,\n};\n\n/**\n * Initialize the database singleton\n *\n * Call this once at application startup with your service's PrismaClient.\n * After initialization, use `getDb()` to access the database anywhere.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class from your service\n * @param productName - Product name for graph events (e.g., 'module-tags', 'workspaces')\n * @param config - Optional configuration overrides\n * @returns The database client with db, wrapper, connect, disconnect\n *\n * @throws Error if already initialized with a different product\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, connect, disconnect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n * ```\n */\nexport function initializeDatabase<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n config?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client using env-based factory\n const client = createDatabaseClientFromEnv(PrismaClientConstructor, productName, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized', { productName });\n\n return client;\n}\n\n/**\n * Initialize the database with explicit configuration\n *\n * Use this when you need full control over database configuration\n * rather than reading from environment variables.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class\n * @param config - Full database configuration\n * @returns The database client\n *\n * @example\n * ```typescript\n * const { db } = initializeDatabaseWithConfig(PrismaClient, {\n * productName: 'module-tags',\n * databaseUrl: 'postgresql://...',\n * maxConnections: 50,\n * enableGraphExtension: false,\n * });\n * ```\n */\nexport function initializeDatabaseWithConfig<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const { productName } = config;\n\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client\n const client = createDatabaseClient(PrismaClientConstructor, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized with custom config', { productName });\n\n return client;\n}\n\n/**\n * Get the initialized database client\n *\n * Use this anywhere in your application to access the database.\n * Must call `initializeDatabase()` first at application startup.\n *\n * The returned client provides dynamic model access - you can access any\n * model property (e.g., `db.client.user`, `db.client.universalTag`) and\n * TypeScript will allow common Prisma operations (findMany, create, etc.).\n *\n * @returns The extended Prisma client (db) with dynamic model access\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n *\n * const db = getDb();\n * // Dynamic model access works without importing service-specific types\n * const tags = await db.client.universalTag.findMany();\n * const users = await db.client.user.findMany({ where: { active: true } });\n * ```\n */\nexport function getDb<T extends PrismaClientBase = PrismaClientBase>(): DatabaseReturnType<T> {\n if (!state.initialized || !state.client) {\n throw new Error('Database not initialized. Call initializeDatabase() at application startup before using getDb().');\n }\n return state.client.db as unknown as DatabaseReturnType<T>;\n}\n\n/**\n * Get the full database manager\n *\n * Returns the complete database client including wrapper, connect, and disconnect functions.\n * Useful when you need access to connection management utilities.\n *\n * @returns The full database client\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDatabaseManager } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = getDatabaseManager();\n * await connect();\n * ```\n */\nexport function getDatabaseManager<T extends PrismaClientBase = PrismaClientBase>(): DatabaseClient<T> {\n if (!state.initialized || !state.client) {\n throw new Error(\n 'Database not initialized. Call initializeDatabase() at application startup before using getDatabaseManager().'\n );\n }\n return state.client as DatabaseClient<T>;\n}\n\n/**\n * Check if database is initialized\n *\n * @returns True if database has been initialized\n *\n * @example\n * ```typescript\n * if (!isDatabaseInitialized()) {\n * await initializeDatabase(PrismaClient, 'my-service');\n * }\n * ```\n */\nexport function isDatabaseInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Get the product name of the initialized database\n *\n * @returns The product name or null if not initialized\n */\nexport function getDatabaseProductName(): string | null {\n return state.productName;\n}\n\n/**\n * Reset the database manager (for testing purposes only)\n *\n * WARNING: This disconnects and resets the database manager.\n * Only use this in test environments for cleanup between tests.\n *\n * @internal\n */\nexport async function resetDatabaseManager(): Promise<void> {\n if (state.client) {\n try {\n await state.client.disconnect();\n } catch (error) {\n logger.warn('[DatabaseManager] Error during disconnect on reset', { error });\n }\n }\n\n state.initialized = false;\n state.productName = null;\n state.client = null;\n\n logger.debug('[DatabaseManager] Database manager reset');\n}\n","/**\n * Prisma Health Check Utilities\n */\n\nimport { logger } from '../logger/index.js';\nimport type { DatabaseHealth } from './types.js';\nimport type { PrismaClientBase } from './client.js';\n\n/**\n * Check database health\n */\nexport async function checkDatabaseHealth<T extends PrismaClientBase>(client: T): Promise<DatabaseHealth> {\n try {\n const start = Date.now();\n await client.$queryRaw`SELECT 1`;\n const latency = Date.now() - start;\n\n return { healthy: true, latency };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error('[Prisma] Health check failed', { error: errorMessage });\n\n return {\n healthy: false,\n error: errorMessage,\n };\n }\n}\n\n/**\n * Test database connection\n */\nexport async function testConnection<T extends PrismaClientBase>(client: T): Promise<boolean> {\n try {\n await client.$queryRaw`SELECT 1`;\n return true;\n } catch (error) {\n logger.error('[Prisma] Connection test failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Get database version\n */\nexport async function getDatabaseVersion<T extends PrismaClientBase>(client: T): Promise<string | null> {\n try {\n const result = await client.$queryRaw<Array<{ version?: string }>>`SELECT version()`;\n return result[0]?.version ?? null;\n } catch (error) {\n logger.error('[Prisma] Failed to get database version', {\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n}\n\n/**\n * Get database stats\n */\nexport async function getDatabaseStats<T extends PrismaClientBase>(\n client: T\n): Promise<{\n health: DatabaseHealth;\n version: string | null;\n timestamp: Date;\n}> {\n const [health, version] = await Promise.all([checkDatabaseHealth(client), getDatabaseVersion(client)]);\n\n return {\n health,\n version,\n timestamp: new Date(),\n };\n}\n","/**\n * Prisma Field Extraction Utilities\n *\n * Provides utilities for extracting model fields from Prisma schema.\n * In Prisma 7, DMMF is not available at runtime, so this module provides\n * build-time field extraction through a generator.\n *\n * @module prisma/fields\n */\n\nimport { createRequire } from 'node:module';\nimport { logger } from '../logger/index.js';\n\nconst requireFn = createRequire(import.meta.url);\n\n/**\n * Field extraction options\n */\nexport interface FieldExtractionOptions {\n /** Fields to exclude from extraction */\n excludeFields?: string[];\n /** Whether to include relation fields */\n includeRelations?: boolean;\n /** Custom filter function */\n customFilter?: (field: { name: string; type: string; isRelation: boolean }) => boolean;\n}\n\n/**\n * Field extraction result\n */\nexport interface FieldExtractionResult {\n /** Extracted field names */\n fields: string[];\n /** Metadata about the extraction */\n metadata: {\n /** Total number of fields found */\n totalFields: number;\n /** Number of fields excluded */\n excludedCount: number;\n /** Names of excluded fields */\n excludedFields: string[];\n /** Number of relation fields */\n relationFields: number;\n };\n}\n\n/**\n * Model fields mapping\n * This will be generated at build time by the Prisma generator\n */\nexport type ModelFieldsMap = Record<\n string,\n {\n fields: string[];\n relations: string[];\n }\n>;\n\n/**\n * Import generated fields from the consuming package\n * This function should be used by backends to load their generated fields\n */\nexport function loadGeneratedFields(generatedFieldsPath: string): ModelFieldsMap {\n try {\n // Dynamic import of generated fields using createRequire\n const generated = requireFn(generatedFieldsPath) as { default: ModelFieldsMap };\n return generated.default || generated;\n } catch (error) {\n logger.error('[Prisma] Failed to load generated fields', {\n error: error instanceof Error ? error.message : String(error),\n path: generatedFieldsPath,\n });\n throw new Error(`Failed to load generated fields from ${generatedFieldsPath}`);\n }\n}\n\n/**\n * Extract fields from generated model fields with options\n */\nexport function extractFieldsFromModel(\n modelName: string,\n modelFieldsMap: ModelFieldsMap,\n options: FieldExtractionOptions = {}\n): FieldExtractionResult {\n const modelFields = modelFieldsMap[modelName];\n\n if (!modelFields) {\n throw new Error(\n `Model \"${modelName}\" not found in generated fields. ` +\n `Available models: ${Object.keys(modelFieldsMap).join(', ')}`\n );\n }\n\n const { excludeFields = [], includeRelations = false, customFilter } = options;\n\n // Start with scalar fields\n let fields = [...modelFields.fields];\n\n // Add relations if requested\n if (includeRelations) {\n fields = [...fields, ...modelFields.relations];\n }\n\n // Track excluded fields\n const excluded: string[] = [];\n\n // Apply exclusions\n if (excludeFields.length > 0) {\n fields = fields.filter((field) => {\n if (excludeFields.includes(field)) {\n excluded.push(field);\n return false;\n }\n return true;\n });\n }\n\n // Apply custom filter\n if (customFilter) {\n fields = fields.filter((fieldName) => {\n const isRelation = modelFields.relations.includes(fieldName);\n const shouldInclude = customFilter({\n name: fieldName,\n type: 'unknown', // Type information not available without full DMMF\n isRelation,\n });\n\n if (!shouldInclude) {\n excluded.push(fieldName);\n }\n\n return shouldInclude;\n });\n }\n\n return {\n fields,\n metadata: {\n totalFields: modelFields.fields.length + modelFields.relations.length,\n excludedCount: excluded.length,\n excludedFields: excluded,\n relationFields: modelFields.relations.length,\n },\n };\n}\n\n/**\n * Get all field names for a model (without options)\n */\nexport function getModelFields(modelName: string, modelFieldsMap: ModelFieldsMap, includeRelations = false): string[] {\n const result = extractFieldsFromModel(modelName, modelFieldsMap, { includeRelations });\n return result.fields;\n}\n\n/**\n * Check if a model exists in the generated fields\n */\nexport function hasModel(modelName: string, modelFieldsMap: ModelFieldsMap): boolean {\n return modelName in modelFieldsMap;\n}\n\n/**\n * Get all available model names\n */\nexport function getAllModelNames(modelFieldsMap: ModelFieldsMap): string[] {\n return Object.keys(modelFieldsMap);\n}\n","/**\n * Prisma Context Filtering Utilities\n *\n * Utilities for handling operation context in queries, mutations, and filtering.\n * Context JSON enables multi-dimensional data isolation across workspaces, users, projects, etc.\n *\n * @module prisma/context\n * @category Database\n */\n\nimport { isSameProductSlug, productSlugVariants } from '../product-alias/index.js';\n\n/**\n * Context filter input for querying entities by context\n */\nexport interface ContextFilterInput {\n workspaceId?: string | null;\n userId?: string | null;\n projectId?: string | null;\n appId?: string | null;\n /** Product identifier (e.g. \"vibecontrols\", \"workspaces\"). Stamped on cross-product\n * records so admin filters can scope by originating product. */\n productId?: string | null;\n /** Organization identifier within the tenant. */\n organizationId?: string | null;\n}\n\n/**\n * Operation context for create/update operations\n */\nexport interface OperationContext extends ContextFilterInput {\n custom?: Record<string, unknown> | null;\n}\n\n/**\n * Prisma JSON filter type (simplified for context filtering)\n * This type is designed to be compatible with Prisma's JsonNullableFilter\n * Uses Record<string, unknown> for maximum compatibility with various Prisma versions\n */\nexport type PrismaJsonFilter = Record<string, unknown>;\n\n/**\n * One entry of {@link buildContextWhereConditions}: a JSON-path predicate on `context`,\n * or an `OR` of them (used for a renamed product's slug twins).\n */\nexport type ContextWhereCondition = { context: PrismaJsonFilter } | { OR: Array<{ context: PrismaJsonFilter }> };\n\n/**\n * JSON value type for Prisma (includes null for reading from DB)\n */\nexport type JsonValue = string | number | boolean | null | { [key: string]: JsonValue } | JsonValue[];\n\n/**\n * Input JSON value type for Prisma (excludes null for writing to DB)\n * Compatible with Prisma's InputJsonValue type\n */\nexport type InputJsonValue = string | number | boolean | { [key: string]: InputJsonValue } | InputJsonValue[];\n\n/**\n * Build Prisma where condition for context filtering.\n * Uses PostgreSQL JSONB containment operators for efficient queries.\n *\n * @param contextFilter - The context filter input\n * @returns Prisma where clause for context field, or undefined if no filter provided\n *\n * @example\n * ```typescript\n * const contextWhere = buildContextWhereClause({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Returns: { path: ['workspaceId'], equals: '123' }\n * ```\n */\nexport function buildContextWhereClause(\n contextFilter: ContextFilterInput | null | undefined\n): PrismaJsonFilter | undefined {\n if (!contextFilter) {\n return undefined;\n }\n\n // Build array of path conditions for each non-null field\n const conditions: PrismaJsonFilter[] = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n path: ['userId'],\n equals: contextFilter.userId,\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n path: ['projectId'],\n equals: contextFilter.projectId,\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n path: ['appId'],\n equals: contextFilter.appId,\n });\n }\n\n if (contextFilter.productId != null) {\n conditions.push({\n path: ['productId'],\n equals: contextFilter.productId,\n });\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n });\n }\n\n // If no conditions, return undefined\n if (conditions.length === 0) {\n return undefined;\n }\n\n // If single condition, return it directly\n if (conditions.length === 1) {\n return conditions[0];\n }\n\n // For multiple conditions, return the first one\n // Caller should use buildContextWhereConditions for multiple AND conditions\n return conditions[0];\n}\n\n/**\n * Build context where conditions as an array for use in AND clause.\n * This is useful when you need to filter by multiple context fields.\n *\n * @param contextFilter - The context filter input\n * @returns Array of Prisma where conditions, each targeting the context field\n *\n * @example\n * ```typescript\n * const conditions = buildContextWhereConditions({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Use in Prisma query:\n * prisma.entity.findMany({\n * where: { AND: conditions }\n * });\n * ```\n */\nexport function buildContextWhereConditions(\n contextFilter: ContextFilterInput | null | undefined\n): ContextWhereCondition[] {\n if (!contextFilter) {\n return [];\n }\n\n const conditions: ContextWhereCondition[] = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n context: {\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n },\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n context: {\n path: ['userId'],\n equals: contextFilter.userId,\n },\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n context: {\n path: ['projectId'],\n equals: contextFilter.projectId,\n },\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n context: {\n path: ['appId'],\n equals: contextFilter.appId,\n },\n });\n }\n\n if (contextFilter.productId != null) {\n // A renamed product (botlit → botmanor) matches rows stored under either slug while\n // they are migrated; every other product keeps the exact single-slug predicate.\n const slugs = productSlugVariants(contextFilter.productId);\n if (slugs.length > 1) {\n conditions.push({\n OR: slugs.map((slug) => ({ context: { path: ['productId'], equals: slug } })),\n });\n } else {\n conditions.push({\n context: {\n path: ['productId'],\n equals: contextFilter.productId,\n },\n });\n }\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n context: {\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n },\n });\n }\n\n return conditions;\n}\n\n/**\n * Convert context input to Prisma JSON format for create/update operations.\n *\n * @param contextInput - The context input\n * @returns JSON value for the context field, or undefined if empty\n *\n * @example\n * ```typescript\n * const contextJson = toContextJson({\n * workspaceId: '123',\n * userId: '456'\n * });\n * // Use in Prisma create:\n * prisma.entity.create({\n * data: { context: contextJson }\n * });\n * ```\n */\nexport function toContextJson(contextInput: OperationContext | null | undefined): InputJsonValue | undefined {\n if (!contextInput) {\n return undefined;\n }\n\n // Remove null values and build clean context object\n const context: Record<string, InputJsonValue> = {};\n\n if (contextInput.workspaceId != null) {\n context['workspaceId'] = contextInput.workspaceId;\n }\n if (contextInput.userId != null) {\n context['userId'] = contextInput.userId;\n }\n if (contextInput.projectId != null) {\n context['projectId'] = contextInput.projectId;\n }\n if (contextInput.appId != null) {\n context['appId'] = contextInput.appId;\n }\n if (contextInput.productId != null) {\n context['productId'] = contextInput.productId;\n }\n if (contextInput.organizationId != null) {\n context['organizationId'] = contextInput.organizationId;\n }\n if (contextInput.custom != null) {\n context['custom'] = contextInput.custom as InputJsonValue;\n }\n\n // Return undefined if no fields set\n if (Object.keys(context).length === 0) {\n return undefined;\n }\n\n return context;\n}\n\n/**\n * Filter out null values from an object for Prisma compatibility\n */\nfunction filterNullValues(obj: Record<string, unknown>): Record<string, InputJsonValue> {\n const filtered: Record<string, InputJsonValue> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== null) {\n filtered[key] = value as InputJsonValue;\n }\n }\n return filtered;\n}\n\n/**\n * Merge a single field into the merged context object\n */\nfunction mergeContextField(\n merged: Record<string, InputJsonValue>,\n fieldName: string,\n fieldValue: string | Record<string, unknown> | null | undefined\n): void {\n if (fieldValue === undefined) {\n return; // Don't touch this field\n }\n\n if (fieldValue === null) {\n delete merged[fieldName]; // Explicitly remove\n } else {\n merged[fieldName] = fieldValue as InputJsonValue; // Set new value\n }\n}\n\n/**\n * Merge existing context with new context input.\n * New values override existing ones, but undefined values are preserved from existing.\n *\n * @param existingContext - The existing context JSON from database\n * @param newContext - The new context input\n * @returns Merged context as InputJsonValue (suitable for Prisma writes)\n *\n * @example\n * ```typescript\n * const merged = mergeContext(\n * { workspaceId: '123', userId: 'old' },\n * { userId: 'new', projectId: '456' }\n * );\n * // Result: { workspaceId: '123', userId: 'new', projectId: '456' }\n * ```\n */\nexport function mergeContext(\n existingContext: JsonValue | null | undefined,\n newContext: OperationContext | null | undefined\n): InputJsonValue | undefined {\n // If no new context, return existing (excluding null values)\n if (!newContext) {\n if (!existingContext) {\n return undefined;\n }\n // Filter out null values from existing context for Prisma compatibility\n if (typeof existingContext === 'object' && !Array.isArray(existingContext)) {\n const filtered = filterNullValues(existingContext);\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n }\n return existingContext as InputJsonValue;\n }\n\n // If no existing context, convert new to JSON\n if (!existingContext || typeof existingContext !== 'object' || Array.isArray(existingContext)) {\n return toContextJson(newContext);\n }\n\n // Merge existing with new\n const merged = filterNullValues(existingContext);\n\n // Merge each field from new context\n mergeContextField(merged, 'workspaceId', newContext.workspaceId);\n mergeContextField(merged, 'userId', newContext.userId);\n mergeContextField(merged, 'projectId', newContext.projectId);\n mergeContextField(merged, 'appId', newContext.appId);\n mergeContextField(merged, 'productId', newContext.productId);\n mergeContextField(merged, 'organizationId', newContext.organizationId);\n mergeContextField(merged, 'custom', newContext.custom);\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n/**\n * Parse context JSON from database to OperationContext interface.\n *\n * @param contextJson - The context JSON from database\n * @returns Parsed OperationContext or null\n *\n * @example\n * ```typescript\n * const context = parseContext(entity.context);\n * if (context?.workspaceId) {\n * // Use workspace-specific logic\n * }\n * ```\n */\nexport function parseContext(contextJson: JsonValue | null | undefined): OperationContext | null {\n if (!contextJson || typeof contextJson !== 'object' || Array.isArray(contextJson)) {\n return null;\n }\n\n const ctx = contextJson as Record<string, unknown>;\n\n return {\n workspaceId: typeof ctx['workspaceId'] === 'string' ? ctx['workspaceId'] : null,\n userId: typeof ctx['userId'] === 'string' ? ctx['userId'] : null,\n projectId: typeof ctx['projectId'] === 'string' ? ctx['projectId'] : null,\n appId: typeof ctx['appId'] === 'string' ? ctx['appId'] : null,\n productId: typeof ctx['productId'] === 'string' ? ctx['productId'] : null,\n organizationId: typeof ctx['organizationId'] === 'string' ? ctx['organizationId'] : null,\n custom: typeof ctx['custom'] === 'object' ? (ctx['custom'] as Record<string, unknown>) : null,\n };\n}\n\n/**\n * Check if context matches filter criteria\n *\n * @param context - The context to check\n * @param filter - The filter criteria\n * @returns True if context matches all filter criteria\n */\nexport function contextMatches(context: OperationContext | null | undefined, filter: ContextFilterInput): boolean {\n if (!context) {\n return false;\n }\n\n if (filter.workspaceId != null && context.workspaceId !== filter.workspaceId) {\n return false;\n }\n if (filter.userId != null && context.userId !== filter.userId) {\n return false;\n }\n if (filter.projectId != null && context.projectId !== filter.projectId) {\n return false;\n }\n if (filter.appId != null && context.appId !== filter.appId) {\n return false;\n }\n // Renamed products (botlit → botmanor) match under either slug while rows are migrated.\n if (filter.productId != null && !isSameProductSlug(context.productId, filter.productId)) {\n return false;\n }\n if (filter.organizationId != null && context.organizationId !== filter.organizationId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Create a default context from SDK context\n *\n * @param sdkContext - The SDK context (from AsyncLocalStorage)\n * @returns Operation context with workspace and user info\n */\nexport function createContextFromSDK(sdkContext: {\n workspaceId?: string;\n userId?: string;\n projectId?: string;\n appId?: string;\n productId?: string;\n organizationId?: string;\n}): OperationContext {\n return {\n workspaceId: sdkContext.workspaceId ?? null,\n userId: sdkContext.userId ?? null,\n projectId: sdkContext.projectId ?? null,\n appId: sdkContext.appId ?? null,\n productId: sdkContext.productId ?? null,\n organizationId: sdkContext.organizationId ?? null,\n };\n}\n","/**\n * Prisma Module for Burdenoff Backend SDK\n *\n * Provides Prisma 7 utilities including:\n * - Singleton database manager for microservices\n * - Unified database client factory with graph extension\n * - Prisma client configuration with PostgreSQL adapter\n * - Connection pooling and management\n * - Health checks and monitoring\n * - Graceful shutdown handling\n * - Field extraction utilities for graph sync\n * - Context filtering utilities for multi-tenant queries\n * - Workspace extension for automatic workspaceId injection\n *\n * @module prisma\n * @category Database\n */\n\nexport * from './manager.js';\nexport * from './factory.js';\nexport * from './client.js';\nexport type * from './types.js';\nexport * from './health.js';\nexport * from './fields.js';\nexport * from './context.js';\nexport * from './workspace-extension.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8GA,SAAS,iCAAiC,aAA8B;CACtE,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,QAAQ,OAAO;CAChC,IAAI,aAAa,SAAS,OAAO;CAEjC,MAAM,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,YAAY;CAC1D,IAAI,UAAU,UAAU,OAAO;CAC/B,IAAI,UAAU,UAAU,OAAO;CAE/B,MAAM,OAAO,YAAY,YAAY;CACrC,IAAI,KAAK,WAAW,SAAS,KAAK,KAAK,WAAW,SAAS,GAAG,OAAO;CACrE,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,qBACd,yBACA,QACmB;CACnB,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W,kBAAkB;CAC/C;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/be-sdk",
3
- "version": "2026.1114.1",
3
+ "version": "2026.1116.1",
4
4
  "description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1 +0,0 @@
1
- {"version":3,"file":"EventQueueFactory-9NGZV9jl.js","names":[],"sources":["../src/event-queue/types/config.ts","../src/event-queue/implementations/redis-streams/trace-context.ts","../src/event-queue/implementations/redis-streams/settlement.ts","../src/event-queue/implementations/dispatch-limiter.ts","../src/event-queue/implementations/redis-streams/RedisStreamsEventConsumer.ts","../src/event-queue/implementations/redis-streams/serialize.ts","../src/event-queue/implementations/redis-streams/RedisStreamsEventPublisher.ts","../src/event-queue/factory/EventQueueFactory.ts"],"sourcesContent":["/**\n * Event Queue Configuration Types\n */\n\n/**\n * Queue type enum\n */\nexport enum QueueType {\n REDIS_STREAMS = 'redis-streams',\n RABBITMQ = 'rabbitmq',\n KAFKA = 'kafka',\n SQS = 'sqs',\n}\n\n/**\n * Base configuration for event queue\n */\nexport interface BaseQueueConfig {\n /** Queue type */\n type: QueueType | string;\n /** Connection URL */\n url: string;\n /** Optional username */\n user?: string;\n /** Optional password */\n password?: string;\n /** Optional auth token */\n token?: string;\n /** Optional credentials file contents (auth payload for the backend) */\n creds?: string;\n /** Optional path to a credentials file */\n credsFile?: string;\n /** Maximum reconnection attempts (-1 for infinite) */\n maxReconnectAttempts?: number;\n /** Time to wait between reconnection attempts (ms) */\n reconnectTimeWait?: number;\n /** Connection timeout (ms) */\n connectionTimeout?: number;\n /** Connection name/identifier */\n name?: string;\n /**\n * Redis Streams only: connection-local key scope prepended to every event\n * key (streams, registry, dedup, delay queue, DLQ, replies). Omit it to derive\n * the scope from the URL's DB index (`db14:` for `.../14`, empty for DB 0),\n * which is the historical key layout. An empty string selects the unscoped\n * shared bus regardless of the URL.\n */\n keyScope?: string;\n}\n\n/**\n * Publisher-specific configuration\n */\nexport interface PublisherConfig extends BaseQueueConfig {\n /** Default message TTL (ms) */\n defaultTTL?: number;\n /** Enable message deduplication */\n enableDeduplication?: boolean;\n /** Default priority for messages */\n defaultPriority?: 'low' | 'normal' | 'high';\n}\n\n/**\n * Consumer-specific configuration\n */\nexport interface ConsumerConfig extends Partial<BaseQueueConfig> {\n /** Stream name to consume from */\n stream: string;\n /** Consumer name (durable) */\n consumer: string;\n /** Subject filter pattern */\n filterSubject?: string;\n /**\n * Read batch size: the XREADGROUP COUNT used by a serial (`concurrency: 1`)\n * subscription. Despite the historical name this does NOT run handlers in\n * parallel; use `concurrency` for that.\n */\n maxConcurrent?: number;\n /**\n * Handlers of one subscription that may run at the same time. Default 1\n * (strictly serial, in stream order). With N > 1 each entry is acked or\n * nak'd independently and ordering across entries is not guaranteed.\n */\n concurrency?: number;\n /**\n * How long unsubscribe/disconnect waits for in-flight handlers before\n * closing (ms). Default: the ack wait. Entries still running at the\n * deadline stay pending so another replica reclaims them.\n */\n drainTimeoutMs?: number;\n /** Maximum delivery attempts */\n maxDeliver?: number;\n /** Acknowledgment wait time (nanoseconds) */\n ackWait?: number;\n /** Acknowledgment policy */\n ackPolicy?: 'explicit' | 'all' | 'none';\n /** Delivery policy */\n deliverPolicy?: 'all' | 'last' | 'new' | 'byStartSequence' | 'byStartTime';\n /** Maximum pending acknowledgments */\n maxAckPending?: number;\n}\n\n/**\n * Health check result\n */\nexport interface EventQueueHealthCheckResult {\n /** Overall health status */\n status: 'healthy' | 'unhealthy' | 'degraded';\n /** Timestamp of health check */\n timestamp: string;\n /** Connection status */\n connected?: boolean;\n /** Latency in milliseconds */\n latencyMs?: number;\n /** Additional details */\n details?: Record<string, unknown>;\n /** Error message if unhealthy */\n error?: string;\n}\n\n/**\n * Statistics\n */\nexport interface QueueStatistics {\n /** Total messages published */\n messagesPublished?: number;\n /** Total messages consumed */\n messagesConsumed?: number;\n /** Messages currently pending */\n messagesPending?: number;\n /** Messages in queue */\n queueSize?: number;\n /** Failed message count */\n messagesFailed?: number;\n /** Active consumers count */\n activeConsumers?: number;\n /** Active publishers count */\n activePublishers?: number;\n /** Average processing time (ms) */\n avgProcessingTimeMs?: number;\n /** Last activity timestamp */\n lastActivity?: string | null;\n /** Custom metrics */\n details?: Record<string, unknown>;\n}\n","/**\n * W3C trace context propagation for Redis Streams entries.\n *\n * Stream entries carry trace context as ordinary fields (`traceparent`,\n * `tracestate`, `baggage`). When `@opentelemetry/api` isn't installed at the\n * consumer, these helpers degrade to no-ops.\n */\nimport { logger } from '../../../logger/index.js';\n\ntype OtelApi = {\n propagation: {\n inject: (\n ctx: unknown,\n carrier: Record<string, string>,\n setter: { set: (c: Record<string, string>, k: string, v: string) => void }\n ) => void;\n extract: (\n ctx: unknown,\n carrier: Record<string, string>,\n getter: {\n get: (c: Record<string, string>, k: string) => string | undefined;\n keys: (c: Record<string, string>) => string[];\n }\n ) => unknown;\n };\n context: { active: () => unknown; with: <T>(ctx: unknown, fn: () => T) => T };\n trace: { getTracer: (name: string, version?: string) => { startActiveSpan: (...args: unknown[]) => unknown } };\n};\n\nlet otelApiPromise: Promise<OtelApi | null> | null = null;\n\nasync function loadOtelApi(): Promise<OtelApi | null> {\n if (otelApiPromise) return otelApiPromise;\n otelApiPromise = (async () => {\n try {\n const mod = (await import('@opentelemetry/api')) as unknown as OtelApi;\n return mod;\n } catch {\n logger.debug('[redis-streams/trace-context] @opentelemetry/api not available; tracing disabled');\n return null;\n }\n })();\n return otelApiPromise;\n}\n\nconst TRACE_KEYS = ['traceparent', 'tracestate', 'baggage'] as const;\n\n/** Inject the active OTel context into a plain record of stream fields. */\nexport async function injectTraceFields(): Promise<Record<string, string>> {\n const api = await loadOtelApi();\n if (!api) return {};\n const carrier: Record<string, string> = {};\n try {\n api.propagation.inject(api.context.active(), carrier, {\n set(c, k, v) {\n c[k] = v;\n },\n });\n } catch (err) {\n logger.debug('[redis-streams/trace-context] inject failed', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n return carrier;\n}\n\n/** Extract OTel context from stream-entry fields. */\nexport async function extractTraceContext(fields: Record<string, string>): Promise<unknown> {\n const api = await loadOtelApi();\n if (!api) return undefined;\n const carrier: Record<string, string> = {};\n for (const key of TRACE_KEYS) {\n const value = fields[key];\n if (value) carrier[key] = value;\n }\n try {\n return api.propagation.extract(api.context.active(), carrier, {\n get(c, k) {\n return c[k];\n },\n keys(c) {\n return Object.keys(c);\n },\n });\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wrap a consumer handler in a CONSUMER-kind span rooted at the carried trace.\n *\n * The handler runs exactly once. If the tracing setup itself fails before the\n * handler started, it runs untraced; a handler failure is always propagated\n * and never retried here (retrying would execute a non-idempotent handler\n * twice for one delivery).\n */\nexport async function runWithConsumerSpan<T>(\n subject: string,\n fields: Record<string, string>,\n handler: () => Promise<T>\n): Promise<T> {\n const api = await loadOtelApi();\n if (!api) return handler();\n let started = false;\n const once = (): Promise<T> => {\n started = true;\n return handler();\n };\n try {\n const parentCtx = await extractTraceContext(fields);\n const tracer = api.trace.getTracer('@burdenoff/be-sdk/redis-streams');\n return await new Promise<T>((resolve, reject) => {\n tracer.startActiveSpan(\n `redis-streams.consume ${subject}`,\n {\n kind: 5,\n attributes: { 'messaging.system': 'redis', 'messaging.destination.name': subject },\n },\n parentCtx,\n async (span: {\n setStatus: (status: { code: number; message?: string }) => void;\n recordException: (err: Error) => void;\n end: () => void;\n }) => {\n try {\n const result = await once();\n span.setStatus({ code: 1 });\n span.end();\n resolve(result);\n } catch (err) {\n span.recordException(err instanceof Error ? err : new Error(String(err)));\n span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });\n span.end();\n reject(err);\n }\n }\n );\n });\n } catch (err) {\n if (started) throw err;\n return handler();\n }\n}\n","/** Per-message, per-consumer-group confirmation. No durable publication deduplication is claimed. */\nexport interface SettlementTransport {\n acknowledge(): Promise<void>;\n delay(milliseconds: number): Promise<void>;\n terminate(reason?: 'max-deliver-exceeded'): Promise<void>;\n confirmed(): void;\n}\n\nexport interface SettlementActions {\n ack(): Promise<void>;\n nak(delay?: number): Promise<void>;\n term(reason?: 'max-deliver-exceeded'): Promise<void>;\n}\n\n/** Serializes concurrent operations; only an idempotent XACK may retry after an uncertain response. */\nexport function messageSettlement(transport: SettlementTransport): SettlementActions {\n let tail: Promise<void> = Promise.resolve();\n let confirmed = false;\n let publication: string | null = null;\n let published = false;\n let held = false;\n const serial = (operation: () => Promise<void>): Promise<void> => {\n const result = tail.then(operation);\n tail = result.catch(() => undefined);\n return result;\n };\n const acknowledge = async (): Promise<void> => {\n await transport.acknowledge();\n confirmed = true;\n transport.confirmed();\n };\n const settle = (intent: string, publish?: () => Promise<void>): Promise<void> =>\n serial(async () => {\n if (confirmed) return;\n if (held) throw new Error('EVENT_SETTLEMENT_PUBLICATION_UNKNOWN');\n if (publication && intent !== publication && intent !== 'ACK')\n throw new Error('EVENT_SETTLEMENT_INTENT_CONFLICT');\n publication ??= intent;\n if (publish && !published) {\n publication = intent;\n // A rejected enqueue may already have reached Redis. Do not publish it again blindly.\n held = true;\n try {\n await publish();\n published = true;\n held = false;\n } catch {\n throw new Error('EVENT_SETTLEMENT_PUBLICATION_UNKNOWN');\n }\n }\n await acknowledge();\n });\n return {\n ack: () => settle('ACK'),\n nak: (delay = 0) => {\n if (!Number.isSafeInteger(delay) || delay < 0) return Promise.reject(new Error('EVENT_SETTLEMENT_DELAY_INVALID'));\n // Leave the original PEL entry pending for normal reclaim; this is not an ACK.\n if (delay === 0)\n return serial(async () => {\n if (held) throw new Error('EVENT_SETTLEMENT_PUBLICATION_UNKNOWN');\n if (publication && !confirmed) throw new Error('EVENT_SETTLEMENT_INTENT_CONFLICT');\n });\n return settle(`DELAY:${delay}`, () => transport.delay(delay));\n },\n term: (reason) => settle(`TERM:${reason ?? 'explicit'}`, () => transport.terminate(reason)),\n };\n}\n","/**\n * Bounded dispatch for event-queue consumers.\n *\n * A {@link DispatchLimiter} hands out at most `concurrency` slots. A consumer\n * loop acquires a slot before it starts a handler and the slot is released\n * when the handler settles, so no more than `concurrency` handlers of one\n * subscription run at the same time. `drain()` waits for every started\n * handler, bounded by a timeout, which is what graceful shutdown needs.\n *\n * Shared by the Redis Streams and in-memory consumers so both transports\n * dispatch with the same semantics.\n */\n\n/** Validates a `concurrency` value; `undefined` yields the default of 1. */\nexport function resolveConcurrency(value: number | undefined, label = 'concurrency'): number {\n if (value === undefined) return 1;\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`[event-queue] ${label} must be a positive integer, got ${String(value)}`);\n }\n return value;\n}\n\n/** Validates a `drainTimeoutMs` value; `undefined` yields `fallbackMs`. */\nexport function resolveDrainTimeout(value: number | undefined, fallbackMs: number): number {\n if (value === undefined) return fallbackMs;\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`[event-queue] drainTimeoutMs must be a non-negative number, got ${String(value)}`);\n }\n return value;\n}\n\nexport class DispatchLimiter {\n private active = 0;\n private readonly waiters: Array<() => void> = [];\n private readonly running = new Set<Promise<void>>();\n\n constructor(readonly concurrency: number) {\n resolveConcurrency(concurrency);\n }\n\n /** Slots not currently held. */\n get freeSlots(): number {\n return this.concurrency - this.active;\n }\n\n /** Handlers started through {@link run} that have not settled yet. */\n get inFlight(): number {\n return this.running.size;\n }\n\n /** Waits for a slot and takes it. Waiters are served in FIFO order. */\n acquire(): Promise<void> {\n if (this.active < this.concurrency) {\n this.active++;\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n this.waiters.push(() => {\n this.active++;\n resolve();\n });\n });\n }\n\n /** Takes a slot only if one is free right now. */\n tryAcquire(): boolean {\n if (this.active >= this.concurrency) return false;\n this.active++;\n return true;\n }\n\n /** Returns a slot taken with {@link acquire} or {@link tryAcquire} that was not passed to {@link run}. */\n release(): void {\n if (this.active === 0) return;\n this.active--;\n const next = this.waiters.shift();\n next?.();\n }\n\n /**\n * Runs `task` on a slot the caller already holds and releases the slot when\n * the task settles. The task must handle its own errors; a rejection is\n * swallowed here so one failure never affects its siblings.\n */\n run(task: () => Promise<void>): void {\n const promise: Promise<void> = Promise.resolve()\n .then(task)\n .catch(() => undefined)\n .finally(() => {\n this.running.delete(promise);\n this.release();\n });\n this.running.add(promise);\n }\n\n /**\n * Waits for every running task, at most `timeoutMs`. Resolves `true` when\n * everything settled in time and `false` on timeout (the tasks keep running).\n */\n async drain(timeoutMs: number): Promise<boolean> {\n if (this.running.size === 0) return true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs);\n timer.unref?.();\n });\n const settled = (async (): Promise<true> => {\n // Tasks started while draining are awaited too.\n while (this.running.size > 0) await Promise.allSettled([...this.running]);\n return true;\n })();\n try {\n return await Promise.race([settled, timedOut]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n}\n","/**\n * Redis Streams implementation of IEventConsumer.\n *\n * One ioredis client per active subscription handles `XREADGROUP BLOCK` in a\n * background loop, with a small ZSET-based delay queue draining NAK'd messages\n * back into the stream when their delay expires.\n *\n * Dispatch is bounded per subscription by `concurrency` (default 1, serial).\n * Every entry this process has read and not yet settled is \"held\": a heartbeat\n * re-claims held ids with `XCLAIM … JUSTID` every ackWait/2 so their idle time\n * never reaches ackWait, which keeps this process's and other replicas' sweeps\n * away from live work. The sweep only reclaims entries idle longer than\n * ackWait that are not held here, re-dispatches them through the same bounded\n * dispatcher while their delivery count is within maxDeliver, and\n * dead-letters them past it. Unsubscribe and disconnect stop reading, wait for\n * in-flight handlers (bounded by `drainTimeoutMs`) and only then close.\n *\n * A delayed nak re-adds the payload as a new stream entry, which starts with a\n * fresh delivery count. The attempts already used travel with it in the\n * `delivery-attempts` field, so `getDeliveryAttempt()` keeps counting and the\n * entry is dead-lettered once it would exceed maxDeliver (BOFF-11323).\n */\nimport { randomUUID } from 'node:crypto';\nimport { hostname } from 'node:os';\nimport { logger } from '../../../logger/index.js';\nimport type { IEventConsumer, ISubscription } from '../../interfaces/IEventConsumer.js';\nimport type { ConsumerConfig, EventQueueHealthCheckResult, QueueStatistics } from '../../types/config.js';\nimport type {\n AcknowledgeableEvent,\n EventHandler,\n EventMetadata,\n StreamConfig,\n SubscriptionOptions,\n} from '../../types/events.js';\nimport { RedisStreamsConnection, type IoRedis } from './RedisStreamsConnection.js';\nimport {\n boundaryOf,\n delayLockKey,\n delayQueueKey,\n dlqKey,\n isWildcard,\n matchSubject,\n registryKey,\n streamKey,\n} from './keyspace.js';\nimport { runWithConsumerSpan } from './trace-context.js';\nimport { messageSettlement, type SettlementActions } from './settlement.js';\nimport { registerDisposable, unregisterDisposable, type ShutdownDisposable } from '../../../lifecycle/index.js';\nimport { DispatchLimiter, resolveConcurrency, resolveDrainTimeout } from '../dispatch-limiter.js';\n\ninterface ParsedEntry<T = unknown> {\n id: string;\n stream: string;\n subject: string;\n data: T;\n metadata: EventMetadata;\n timestamp: string;\n fields: Record<string, string>;\n /** Deliveries of this message so far, this one included, across delayed re-adds. */\n deliveryCount: number;\n}\n\nconst DEFAULT_BLOCK_MS = 5000;\nconst DEFAULT_BATCH = 10;\nconst REGISTRY_REFRESH_MS = 10_000;\nconst DEFAULT_ACK_WAIT_MS = 30_000;\nconst DEFAULT_MAX_DELIVER = 3;\nconst SWEEP_INTERVAL_MS = 15_000;\nconst SWEEP_BATCH = 50;\nconst HEARTBEAT_MIN_INTERVAL_MS = 250;\nconst HEARTBEAT_CHUNK = 100;\nconst DELAYQ_INTERVAL_MS = 1_000;\n/**\n * Field carried by an entry that a delayed nak re-added: how many deliveries\n * the message had already used before it was parked. Read back by parseEntry.\n */\nconst DELIVERY_ATTEMPTS_FIELD = 'delivery-attempts';\n\ntype StreamReadReply = Array<[string, Array<[string, string[]]>]>;\n\n/** One stream loop of a subscription: what the sweep needs to re-dispatch a reclaimed entry. */\ninterface StreamWorker {\n sub: RedisStreamsSubscription;\n subject: string;\n handler: EventHandler<unknown>;\n limiter: DispatchLimiter;\n /** Deliveries allowed before an entry is dead-lettered (the subscription's maxDeliver). */\n maxDeliver: number;\n /** Reclaimed entries waiting for a slot. */\n queued: number;\n}\n\n/** A row of the extended XPENDING reply: id, owning consumer, idle ms, delivery count. */\ninterface PendingRow {\n id: string;\n deliveries: number;\n}\n\nfunction parsePendingRows(reply: unknown): PendingRow[] {\n if (!Array.isArray(reply)) return [];\n const rows: PendingRow[] = [];\n for (const row of reply) {\n if (!Array.isArray(row)) continue;\n const id: unknown = row[0];\n const deliveries = Number(row[3]);\n if (typeof id !== 'string' || !Number.isFinite(deliveries)) continue;\n rows.push({ id, deliveries });\n }\n return rows;\n}\n\nfunction parseClaimedEntries(reply: unknown): Map<string, string[]> {\n const out = new Map<string, string[]>();\n if (!Array.isArray(reply)) return out;\n for (const entry of reply) {\n // Entries deleted from the stream come back as null (or not at all).\n if (!Array.isArray(entry)) continue;\n const id: unknown = entry[0];\n const fields: unknown = entry[1];\n if (typeof id !== 'string' || !Array.isArray(fields)) continue;\n out.set(\n id,\n fields.filter((f): f is string => typeof f === 'string')\n );\n }\n return out;\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Deliveries used before a delayed nak re-added this entry; 0 for an entry published normally. */\nfunction priorAttempts(fields: Record<string, string>): number {\n const raw = fields[DELIVERY_ATTEMPTS_FIELD];\n if (raw === undefined) return 0;\n const n = Number(raw);\n return Number.isSafeInteger(n) && n > 0 ? n : 0;\n}\n\n/** A subscription's maxDeliver, falling back to the consumer's; rejects anything but a positive integer. */\nfunction resolveMaxDeliver(value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`[RedisStreamsEventConsumer] maxDeliver must be a positive integer, got ${String(value)}`);\n }\n return value;\n}\n\nclass RedisStreamsSubscription implements ISubscription {\n readonly id = randomUUID();\n private active = true;\n private receivedCount = 0;\n private processedCount = 0;\n private failedCount = 0;\n private lastActivity = new Date().toISOString();\n\n constructor(\n readonly subject: string,\n private readonly unsubscribeFn: () => Promise<void>\n ) {}\n\n async unsubscribe(): Promise<void> {\n if (!this.active) return;\n this.active = false;\n await this.unsubscribeFn();\n }\n\n isActive(): boolean {\n return this.active;\n }\n\n getStats(): {\n messagesReceived: number;\n messagesProcessed: number;\n messagesFailed: number;\n lastActivity: string;\n } {\n return {\n messagesReceived: this.receivedCount,\n messagesProcessed: this.processedCount,\n messagesFailed: this.failedCount,\n lastActivity: this.lastActivity,\n };\n }\n\n recordReceived(): void {\n this.receivedCount++;\n this.lastActivity = new Date().toISOString();\n }\n recordProcessed(): void {\n this.processedCount++;\n this.lastActivity = new Date().toISOString();\n }\n recordFailed(): void {\n this.failedCount++;\n this.lastActivity = new Date().toISOString();\n }\n}\n\nexport interface RedisStreamsConsumerConfig extends ConsumerConfig {\n keyPrefix?: string;\n}\n\nexport class RedisStreamsEventConsumer implements IEventConsumer, ShutdownDisposable {\n public readonly shutdownName: string;\n private readonly connection: RedisStreamsConnection;\n private subscriptions: RedisStreamsSubscription[] = [];\n private readonly subscriptionLoops: Set<() => Promise<void>> = new Set();\n private readonly keyPrefix: string;\n private readonly consumerName: string;\n private readonly group: string;\n private readonly maxDeliver: number;\n private readonly ackWaitMs: number;\n /** XREADGROUP COUNT for serial subscriptions (historical name; not a concurrency limit). */\n private readonly maxConcurrent: number;\n private readonly concurrency: number;\n private readonly drainTimeoutMs: number;\n private consumedCount = 0;\n private failedCount = 0;\n private lastActivity: Date | null = null;\n private stopped = false;\n private sweepTimer: ReturnType<typeof setInterval> | null = null;\n private delayqTimer: ReturnType<typeof setInterval> | null = null;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n /** stream -> the subscription loop consuming it (used to re-dispatch reclaimed entries). */\n private readonly workers = new Map<string, StreamWorker>();\n /** Every stream loop a subscription started, for drain and cleanup. */\n private readonly subWorkers = new Map<RedisStreamsSubscription, Array<{ stream: string; worker: StreamWorker }>>();\n /** stream -> ids read by this process and not yet settled by their handler. */\n private readonly held = new Map<string, Set<string>>();\n /** Blocking clients per subscription, closed on unsubscribe to abort a pending XREADGROUP BLOCK. */\n private readonly blockingClients = new Map<RedisStreamsSubscription, Set<IoRedis>>();\n private readonly settlements = new Map<\n string,\n { actions: SettlementActions; entry: ParsedEntry; serializedFieldsBytes: number }\n >();\n private retainedSerializedFieldsBytes = 0;\n private knownStreams: Map<string, string> = new Map(); // streamKey -> subject\n\n constructor(config: RedisStreamsConsumerConfig) {\n this.connection = new RedisStreamsConnection({\n type: 'redis-streams',\n url: config.url ?? process.env['REDIS_URL'] ?? 'redis://localhost:6379',\n user: config.user,\n password: config.password,\n name: config.name,\n connectionTimeout: config.connectionTimeout,\n keyScope: config.keyScope,\n });\n this.keyPrefix = config.keyPrefix ?? process.env['REDIS_STREAMS_KEY_PREFIX'] ?? 'boff:events';\n this.group = config.consumer || config.name || 'default-consumer';\n this.consumerName = `${this.group}:${hostname()}:${process.pid}`;\n this.maxDeliver = config.maxDeliver ?? DEFAULT_MAX_DELIVER;\n this.ackWaitMs = config.ackWait ? Math.max(1000, Math.round(config.ackWait / 1_000_000)) : DEFAULT_ACK_WAIT_MS;\n this.maxConcurrent = config.maxConcurrent ?? 5;\n this.concurrency = resolveConcurrency(config.concurrency);\n this.drainTimeoutMs = resolveDrainTimeout(config.drainTimeoutMs, this.ackWaitMs);\n this.shutdownName = `redis-streams-consumer:${config.name ?? this.group}`;\n // The consumer holds one blocking ioredis client per subscribed stream —\n // the bulk of the event-bus connections. Ensure they are all closed on\n // graceful shutdown even if the owner never calls disconnect().\n registerDisposable(this);\n }\n\n /** Close underlying connections on graceful shutdown. */\n dispose(): Promise<void> {\n return this.disconnect();\n }\n\n async connect(): Promise<void> {\n await this.connection.connect();\n if (!this.sweepTimer) {\n const t = setInterval(() => {\n void this.sweepPending().catch((err) => {\n logger.debug('[RedisStreamsEventConsumer] sweep error', {\n error: err instanceof Error ? err.message : String(err),\n });\n });\n }, SWEEP_INTERVAL_MS);\n t.unref?.();\n this.sweepTimer = t;\n }\n if (!this.delayqTimer) {\n const t = setInterval(() => {\n void this.drainDelayQueues().catch(() => undefined);\n }, DELAYQ_INTERVAL_MS);\n t.unref?.();\n this.delayqTimer = t;\n }\n if (!this.heartbeatTimer) {\n const t = setInterval(\n () => {\n void this.heartbeat().catch(() => undefined);\n },\n Math.max(HEARTBEAT_MIN_INTERVAL_MS, Math.floor(this.ackWaitMs / 2))\n );\n t.unref?.();\n this.heartbeatTimer = t;\n }\n }\n\n /**\n * Stops reading, waits for in-flight handlers (bounded by `drainTimeoutMs`)\n * so they can still ack, then closes the connection. The heartbeat keeps\n * running during the drain so live entries are not reclaimed meanwhile.\n */\n async disconnect(): Promise<void> {\n unregisterDisposable(this);\n this.stopped = true;\n if (this.sweepTimer) clearInterval(this.sweepTimer);\n if (this.delayqTimer) clearInterval(this.delayqTimer);\n this.sweepTimer = null;\n this.delayqTimer = null;\n await this.unsubscribeAll();\n if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n await this.connection.disconnect();\n }\n\n isConnected(): boolean {\n return this.connection.isConnected();\n }\n\n async healthCheck(): Promise<EventQueueHealthCheckResult> {\n try {\n const t0 = Date.now();\n const pong = await this.connection.ping();\n return {\n status: pong === 'PONG' ? 'healthy' : 'degraded',\n timestamp: new Date().toISOString(),\n connected: this.isConnected(),\n latencyMs: Date.now() - t0,\n details: {\n type: 'redis-streams',\n subscriptions: this.subscriptions.length,\n },\n };\n } catch (err) {\n return {\n status: 'unhealthy',\n timestamp: new Date().toISOString(),\n connected: false,\n details: { type: 'redis-streams' },\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n async getStatistics(): Promise<QueueStatistics> {\n return Promise.resolve({\n messagesConsumed: this.consumedCount,\n messagesFailed: this.failedCount,\n messagesPublished: 0,\n activeConsumers: this.subscriptions.length,\n lastActivity: this.lastActivity?.toISOString() ?? null,\n details: { type: 'redis-streams', group: this.group },\n });\n }\n\n async ensureStream(_config: StreamConfig): Promise<void> {\n return Promise.resolve();\n }\n\n async ensureConsumer(_config: ConsumerConfig): Promise<void> {\n return Promise.resolve();\n }\n\n async subscribe<T = unknown>(opts: {\n subject: string;\n handler: EventHandler<T>;\n options?: SubscriptionOptions;\n }): Promise<ISubscription> {\n await this.connect();\n // Validate up front so a bad value fails the subscribe call, not a background loop.\n const concurrency = resolveConcurrency(opts.options?.concurrency ?? this.concurrency);\n const drainTimeoutMs = resolveDrainTimeout(opts.options?.drainTimeoutMs, this.drainTimeoutMs);\n // The subscription's maxDeliver (EventsManager passes its own, default 5)\n // overrides the consumer config's (env QUEUE_MAX_DELIVER, default 3).\n const maxDeliver = resolveMaxDeliver(opts.options?.maxDeliver, this.maxDeliver);\n // One limiter per stream loop: a wildcard subscription runs one loop per\n // matched stream, and a shared limiter would let one loop's blocking read\n // starve the others. `concurrency` therefore applies per stream.\n const limiter = (): DispatchLimiter => new DispatchLimiter(concurrency);\n const sub = new RedisStreamsSubscription(opts.subject, async () => {\n this.subscriptions = this.subscriptions.filter((s) => s !== sub);\n this.abortReads(sub);\n await this.drainSubscription(sub, opts.subject, drainTimeoutMs);\n this.releaseStreams(sub);\n });\n this.subscriptions.push(sub);\n\n const startId = this.resolveStartId(opts.options?.deliverPolicy);\n const wildcard = isWildcard(opts.subject);\n const handlerFn = opts.handler as EventHandler<unknown>;\n\n // When the caller provides an explicit stream name (e.g. 'WSPACE_GRAPH_EVENTS'),\n // pin the consumer to that single aggregated stream and filter by subject locally.\n // This mirrors the publisher's stream override logic so both sides use the same key.\n if (opts.options?.stream) {\n const stream = streamKey(opts.options.stream, { prefix: this.keyPrefix, scope: this.connection.keyScope });\n await this.ensureGroup(stream, startId);\n this.knownStreams.set(stream, opts.subject);\n const subjectFilter = wildcard ? opts.subject : null;\n const filteredHandler: EventHandler<unknown> = subjectFilter\n ? async (evt) => {\n if (matchSubject(subjectFilter, evt.subject)) {\n await handlerFn(evt);\n } else {\n await evt.ack();\n }\n }\n : handlerFn;\n this.spawnLoop(sub, stream, opts.subject, filteredHandler, limiter(), maxDeliver);\n return sub;\n }\n\n if (!wildcard) {\n const stream = streamKey(opts.subject, { prefix: this.keyPrefix, scope: this.connection.keyScope });\n await this.ensureGroup(stream, startId);\n this.knownStreams.set(stream, opts.subject);\n this.spawnLoop(sub, stream, opts.subject, handlerFn, limiter(), maxDeliver);\n } else {\n const boundary = boundaryOf(opts.subject);\n const refresh = async (): Promise<void> => {\n const client = this.connection.getClient();\n const subjects = await client.smembers(registryKey(boundary, this.connection.keyScope));\n for (const s of subjects) {\n if (!matchSubject(opts.subject, s)) continue;\n const stream = streamKey(s, { prefix: this.keyPrefix, scope: this.connection.keyScope });\n if (this.knownStreams.has(stream)) continue;\n await this.ensureGroup(stream, startId);\n this.knownStreams.set(stream, s);\n this.spawnLoop(sub, stream, s, handlerFn, limiter(), maxDeliver);\n }\n };\n await refresh();\n const t = setInterval(() => {\n if (this.stopped || !sub.isActive()) {\n clearInterval(t);\n return;\n }\n void refresh().catch(() => undefined);\n }, REGISTRY_REFRESH_MS);\n t.unref?.();\n }\n\n return sub;\n }\n\n async subscribeMultiple<T = unknown>(\n subjects: string[],\n handler: EventHandler<T>,\n options?: SubscriptionOptions\n ): Promise<ISubscription[]> {\n const out: ISubscription[] = [];\n for (const subject of subjects) {\n out.push(await this.subscribe({ subject, handler, options }));\n }\n return out;\n }\n\n async pull<T = unknown>(opts: {\n subject: string;\n batch?: number;\n timeout?: number;\n }): Promise<AcknowledgeableEvent<T>[]> {\n await this.connect();\n const stream = streamKey(opts.subject, { prefix: this.keyPrefix, scope: this.connection.keyScope });\n await this.ensureGroup(stream, '$');\n const client = this.connection.getClient();\n const raw = (await client.xreadgroup(\n 'GROUP',\n this.group,\n this.consumerName,\n 'COUNT',\n opts.batch ?? DEFAULT_BATCH,\n 'BLOCK',\n opts.timeout ?? DEFAULT_BLOCK_MS,\n 'STREAMS',\n stream,\n '>'\n )) as Array<[string, Array<[string, string[]]>]> | null;\n if (!raw) return [];\n const out: AcknowledgeableEvent<T>[] = [];\n for (const [streamName, entries] of raw) {\n for (const [id, rawFields] of entries) {\n const parsed = this.parseEntry<T>(streamName, id, rawFields);\n out.push(this.toAcknowledgeable(streamName, id, parsed));\n }\n }\n return out;\n }\n\n async unsubscribeAll(): Promise<void> {\n // Drain every subscription at once so shutdown waits for the slowest handler, not the sum.\n await Promise.all([...this.subscriptions].map((sub) => sub.unsubscribe()));\n this.subscriptions = [];\n this.subscriptionLoops.clear();\n }\n\n getSubscriptions(): ISubscription[] {\n return [...this.subscriptions];\n }\n\n async processDLQ<T = unknown>(handler: EventHandler<T>): Promise<void> {\n await this.connect();\n const client = this.connection.getClient();\n const dlqGroup = `${this.group}-dlq`;\n for (const [stream] of this.knownStreams) {\n const dlq = dlqKey(stream, this.connection.keyScope);\n try {\n await client.xgroup('CREATE', dlq, dlqGroup, '0', 'MKSTREAM');\n } catch {\n /* already exists */\n }\n const res = (await client.xreadgroup(\n 'GROUP',\n dlqGroup,\n this.consumerName,\n 'COUNT',\n 50,\n 'BLOCK',\n 100,\n 'STREAMS',\n dlq,\n '>'\n )) as Array<[string, Array<[string, string[]]>]> | null;\n if (!res) continue;\n for (const [, entries] of res) {\n for (const [id, rawFields] of entries) {\n const parsed = this.parseEntry<T>(dlq, id, rawFields);\n const evt = this.toAcknowledgeable<T>(dlq, id, parsed, dlqGroup);\n try {\n await handler(evt);\n } catch (err) {\n logger.error('[RedisStreamsEventConsumer] DLQ handler error', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n }\n }\n }\n\n async listSubjects(_stream?: string): Promise<string[]> {\n await this.connect();\n const client = this.connection.getClient();\n const seen = new Set<string>();\n for (const subject of this.knownStreams.values()) {\n const members = await client.smembers(registryKey(boundaryOf(subject), this.connection.keyScope));\n for (const m of members) seen.add(m);\n }\n return [...seen];\n }\n\n // ---- internals ----\n\n private resolveStartId(policy: SubscriptionOptions['deliverPolicy'] | undefined): string {\n switch (policy) {\n case 'all':\n return '0';\n case 'new':\n return '$';\n case 'last':\n return '$';\n default:\n return '$';\n }\n }\n\n private async ensureGroup(stream: string, startId: string): Promise<void> {\n const client = this.connection.getClient();\n try {\n await client.xgroup('CREATE', stream, this.group, startId, 'MKSTREAM');\n logger.debug('[RedisStreamsEventConsumer] group created', {\n stream,\n group: this.group,\n startId,\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (!msg.includes('BUSYGROUP')) {\n throw err;\n }\n }\n }\n\n private heldFor(stream: string): Set<string> {\n let ids = this.held.get(stream);\n if (!ids) {\n ids = new Set();\n this.held.set(stream, ids);\n }\n return ids;\n }\n\n /** Closes the subscription's blocking clients so a pending XREADGROUP BLOCK returns now. */\n private abortReads(sub: RedisStreamsSubscription): void {\n for (const client of this.blockingClients.get(sub) ?? []) {\n try {\n client.disconnect();\n } catch {\n /* already closed */\n }\n }\n }\n\n /** Waits for the in-flight handlers of every stream loop of `sub`, at most `timeoutMs` in total. */\n private async drainSubscription(sub: RedisStreamsSubscription, subject: string, timeoutMs: number): Promise<void> {\n const limiters = (this.subWorkers.get(sub) ?? []).map(({ worker }) => worker.limiter);\n const results = await Promise.all(limiters.map((l) => l.drain(timeoutMs)));\n if (results.every(Boolean)) return;\n logger.warn('[RedisStreamsEventConsumer] drain timed out; unfinished entries stay pending for reclaim', {\n subject,\n inFlight: limiters.reduce((sum, l) => sum + l.inFlight, 0),\n drainTimeoutMs: timeoutMs,\n });\n }\n\n /** Forgets the streams a finished subscription consumed so the sweep and heartbeat stop touching them. */\n private releaseStreams(sub: RedisStreamsSubscription): void {\n for (const { stream, worker } of this.subWorkers.get(sub) ?? []) {\n // Another subscription may have taken the stream over; leave its state alone.\n if (this.workers.get(stream) !== worker) continue;\n this.workers.delete(stream);\n this.knownStreams.delete(stream);\n // Anything still held belongs to a handler that outlived the drain; stop\n // heartbeating it so another replica can reclaim it after ackWait.\n this.held.delete(stream);\n }\n this.subWorkers.delete(sub);\n this.blockingClients.delete(sub);\n }\n\n private spawnLoop(\n sub: RedisStreamsSubscription,\n stream: string,\n subject: string,\n handler: EventHandler<unknown>,\n limiter: DispatchLimiter,\n maxDeliver: number\n ): void {\n const worker: StreamWorker = { sub, subject, handler, limiter, maxDeliver, queued: 0 };\n this.workers.set(stream, worker);\n const started = this.subWorkers.get(sub) ?? [];\n started.push({ stream, worker });\n this.subWorkers.set(sub, started);\n void this.runLoop(stream, worker).catch((err) => {\n logger.error('[RedisStreamsEventConsumer] loop crashed', {\n stream,\n error: errorMessage(err),\n });\n });\n }\n\n private isRunning(worker: StreamWorker): boolean {\n return !this.stopped && worker.sub.isActive();\n }\n\n private async runLoop(stream: string, worker: StreamWorker): Promise<void> {\n const client = await this.connection.makeBlockingClient();\n let clients = this.blockingClients.get(worker.sub);\n if (!clients) {\n clients = new Set();\n this.blockingClients.set(worker.sub, clients);\n }\n clients.add(client);\n try {\n while (this.isRunning(worker)) {\n // Hold a slot before reading so this replica never claims an entry it cannot start.\n await worker.limiter.acquire();\n if (!this.isRunning(worker)) {\n worker.limiter.release();\n break;\n }\n const entries = await this.readBatch(client, stream, worker);\n if (entries.length === 0) {\n worker.limiter.release();\n continue;\n }\n await this.dispatchBatch(stream, worker, entries);\n }\n } finally {\n clients.delete(client);\n try {\n client.disconnect();\n } catch {\n /* ignore */\n }\n }\n }\n\n /**\n * One XREADGROUP. A serial subscription reads `maxConcurrent` (the batch\n * size); a parallel one reads only as many entries as it has slots for.\n * Read errors are logged and yield an empty batch.\n */\n private async readBatch(client: IoRedis, stream: string, worker: StreamWorker): Promise<Array<[string, string[]]>> {\n const { limiter } = worker;\n const count = limiter.concurrency === 1 ? this.maxConcurrent : 1 + limiter.freeSlots;\n try {\n const raw = (await client.xreadgroup(\n 'GROUP',\n this.group,\n this.consumerName,\n 'COUNT',\n count,\n 'BLOCK',\n DEFAULT_BLOCK_MS,\n 'STREAMS',\n stream,\n '>'\n )) as StreamReadReply | null;\n return (raw ?? []).flatMap(([, batch]) => batch);\n } catch (err) {\n if (!this.isRunning(worker)) return [];\n const msg = errorMessage(err);\n if (msg.includes('NOGROUP')) {\n await this.ensureGroup(stream, '$');\n return [];\n }\n logger.warn('[RedisStreamsEventConsumer] read error', { stream, error: msg });\n await new Promise((res) => setTimeout(res, 1000));\n return [];\n }\n }\n\n /**\n * Starts each entry of a batch on its own slot, in stream order. The caller\n * already holds the slot for the first entry. Every entry is held (and so\n * heartbeated) from the moment it is read until its handler settles.\n */\n private async dispatchBatch(stream: string, worker: StreamWorker, entries: Array<[string, string[]]>): Promise<void> {\n const { limiter } = worker;\n const held = this.heldFor(stream);\n for (const [id] of entries) held.add(id);\n for (let index = 0; index < entries.length; index++) {\n if (index > 0) await limiter.acquire();\n if (!this.isRunning(worker)) {\n limiter.release();\n // Leave the unstarted entries pending and stop heartbeating them so they are reclaimed elsewhere.\n for (const [rest] of entries.slice(index)) held.delete(rest);\n return;\n }\n const [id, rawFields] = entries[index] ?? ['', []];\n limiter.run(() => this.dispatchEntry(worker, stream, id, rawFields, 1).finally(() => held.delete(id)));\n }\n }\n\n /**\n * Runs one entry's handler. Never rejects: a throw is logged and the entry\n * nak'd (left pending). `streamDeliveries` is the entry's own delivery count\n * in the group (1 on a first read); an entry a delayed nak re-added past the\n * subscription's maxDeliver is dead-lettered without running the handler.\n */\n private async dispatchEntry(\n worker: StreamWorker,\n stream: string,\n id: string,\n rawFields: string[],\n streamDeliveries: number\n ): Promise<void> {\n const { sub, subject, handler } = worker;\n sub.recordReceived();\n this.consumedCount++;\n this.lastActivity = new Date();\n let evt: AcknowledgeableEvent<unknown> | null = null;\n let fields: Record<string, string> = {};\n try {\n const parsed = this.parseEntry(stream, id, rawFields, streamDeliveries);\n if (parsed.deliveryCount > worker.maxDeliver) {\n await this.deadLetter(stream, parsed);\n return;\n }\n fields = parsed.fields;\n evt = this.toAcknowledgeable(stream, id, parsed);\n const event = evt;\n await runWithConsumerSpan(subject, fields, () => handler(event));\n sub.recordProcessed();\n } catch (err) {\n sub.recordFailed();\n this.failedCount++;\n logger.error('[RedisStreamsEventConsumer] handler error', {\n subject,\n id,\n error: errorMessage(err),\n });\n // Auto-nak on uncaught throw: the entry stays pending and the sweep\n // re-dispatches it once it has been idle for ackWait.\n if (evt) {\n try {\n await evt.nak();\n } catch {\n /* ignore */\n }\n }\n }\n }\n\n /** Resets the idle time of every held entry without bumping its delivery count. */\n private async heartbeat(): Promise<void> {\n if (this.held.size === 0) return;\n const client = this.connection.getClient();\n for (const [stream, ids] of this.held) {\n if (ids.size === 0) continue;\n const list = [...ids];\n try {\n for (let i = 0; i < list.length; i += HEARTBEAT_CHUNK) {\n await client.xclaim(\n stream,\n this.group,\n this.consumerName,\n 0,\n ...list.slice(i, i + HEARTBEAT_CHUNK),\n 'JUSTID'\n );\n }\n } catch (err) {\n logger.debug('[RedisStreamsEventConsumer] heartbeat error', { stream, error: errorMessage(err) });\n }\n }\n }\n\n /**\n * `streamDeliveries` is the entry's delivery count in the group (1 on a\n * first read); attempts used before a delayed nak re-added it are added on.\n */\n private parseEntry<T>(stream: string, id: string, rawFields: string[], streamDeliveries = 1): ParsedEntry<T> {\n const fields: Record<string, string> = {};\n for (let i = 0; i + 1 < rawFields.length; i += 2) {\n const key = rawFields[i];\n const val = rawFields[i + 1];\n if (key === undefined || val === undefined) continue;\n fields[key] = val;\n }\n let data: T;\n try {\n data = JSON.parse(fields['payload'] ?? 'null') as T;\n } catch {\n data = fields['payload'] as unknown as T;\n }\n let metadata: EventMetadata;\n try {\n metadata = JSON.parse(fields['metadata'] ?? '{}') as EventMetadata;\n } catch {\n metadata = { correlationId: fields['correlation-id'] ?? '' };\n }\n if (!metadata.correlationId) metadata.correlationId = fields['correlation-id'] ?? '';\n return {\n id,\n stream,\n subject: fields['subject'] ?? '',\n data,\n metadata,\n timestamp: fields['timestamp'] ?? new Date().toISOString(),\n fields,\n deliveryCount: priorAttempts(fields) + streamDeliveries,\n };\n }\n\n private toAcknowledgeable<T>(\n stream: string,\n id: string,\n parsed: ParsedEntry<T>,\n group: string = this.group\n ): AcknowledgeableEvent<T> {\n const actions = this.settlement(stream, id, parsed, group);\n return {\n id,\n subject: parsed.subject,\n data: parsed.data,\n metadata: parsed.metadata,\n timestamp: parsed.timestamp,\n ack: actions.ack,\n nak: actions.nak,\n term: () => actions.term(),\n isRedelivered(): boolean {\n return parsed.deliveryCount > 1;\n },\n getDeliveryAttempt(): number {\n return parsed.deliveryCount;\n },\n };\n }\n\n private settlement<T>(stream: string, id: string, parsed: ParsedEntry<T>, group: string): SettlementActions {\n const key = JSON.stringify([stream, group, id]);\n const existing = this.settlements.get(key);\n if (existing) {\n existing.entry.deliveryCount = Math.max(existing.entry.deliveryCount, parsed.deliveryCount);\n return existing.actions;\n }\n // Unknown publications are retained for this consumer lifetime, never evicted into a blind retry.\n const serializedFieldsBytes = new TextEncoder().encode(JSON.stringify(parsed.fields)).byteLength;\n if (this.settlements.size >= 10000 || this.retainedSerializedFieldsBytes + serializedFieldsBytes > 64 * 1024 * 1024)\n throw new Error('EVENT_SETTLEMENT_CAPACITY_HELD');\n const actions = messageSettlement({\n acknowledge: async () => {\n await this.connection.getClient().xack(stream, group, id);\n // XACK is group-local. Keep the stream entry available to independent groups.\n },\n delay: async (milliseconds) => {\n const score = Date.now() + milliseconds;\n if (!Number.isSafeInteger(score)) throw new Error('EVENT_SETTLEMENT_DELAY_INVALID');\n // The re-added entry starts a fresh delivery count; carry the attempts used so far with it.\n const carried = { ...parsed.fields, [DELIVERY_ATTEMPTS_FIELD]: String(parsed.deliveryCount) };\n await this.connection\n .getClient()\n .zadd(delayQueueKey(stream, this.connection.keyScope), score, `${id}|${JSON.stringify(carried)}`);\n },\n terminate: async (reason) => {\n const flat: string[] = [];\n for (const [k, v] of Object.entries(parsed.fields)) flat.push(k, v);\n if (reason) flat.push('dlq-reason', reason, 'dlq-deliveries', String(parsed.deliveryCount));\n await this.connection\n .getClient()\n .xadd(dlqKey(stream, this.connection.keyScope), 'MAXLEN', '~', 10000, '*', ...flat);\n },\n confirmed: () => {\n const retained = this.settlements.get(key);\n if (retained) this.retainedSerializedFieldsBytes -= retained.serializedFieldsBytes;\n this.settlements.delete(key);\n },\n });\n this.settlements.set(key, { actions, entry: parsed, serializedFieldsBytes });\n this.retainedSerializedFieldsBytes += serializedFieldsBytes;\n return actions;\n }\n\n /**\n * Reclaims entries idle longer than ackWait that this process is not\n * handling. Within maxDeliver they are re-dispatched through the stream's\n * bounded dispatcher; past it they are dead-lettered.\n */\n private async sweepPending(): Promise<void> {\n if (this.stopped || this.knownStreams.size === 0) return;\n for (const [stream] of this.knownStreams) {\n try {\n await this.sweepStream(stream);\n } catch (err) {\n const msg = errorMessage(err);\n if (msg.includes('NOGROUP')) continue;\n logger.debug('[RedisStreamsEventConsumer] sweep iteration error', { stream, error: msg });\n }\n }\n }\n\n private async sweepStream(stream: string): Promise<void> {\n const client = this.connection.getClient();\n const rows = parsePendingRows(\n await client.xpending(stream, this.group, 'IDLE', this.ackWaitMs, '-', '+', SWEEP_BATCH)\n );\n const worker = this.workers.get(stream);\n const live = worker && this.isRunning(worker) ? worker : undefined;\n const maxDeliver = live?.maxDeliver ?? this.maxDeliver;\n const picked = this.pickReclaimable(stream, rows, live, maxDeliver);\n if (picked.length === 0) return;\n // min-idle = ackWait: another replica that claimed or heartbeated an entry since XPENDING wins.\n const claimed = parseClaimedEntries(\n await client.xclaim(stream, this.group, this.consumerName, this.ackWaitMs, ...picked.map((r) => r.id))\n );\n for (const row of picked) {\n const rawFields = claimed.get(row.id);\n // Not returned: settled, deleted or claimed elsewhere since XPENDING.\n if (!rawFields) continue;\n // XCLAIM increments the delivery count of every entry it returns.\n const streamDeliveries = row.deliveries + 1;\n const parsed = this.parseEntry(stream, row.id, rawFields, streamDeliveries);\n if (parsed.deliveryCount > maxDeliver) await this.deadLetter(stream, parsed);\n else if (live) this.redispatch(stream, live, row.id, rawFields, streamDeliveries);\n }\n }\n\n /**\n * Chooses which idle entries to claim: never one this process is handling;\n * every one past maxDeliver (to dead-letter it); and, within maxDeliver, no\n * more than the live dispatcher can run alongside what it already runs, so\n * a replica never hoards reclaimed work it cannot start soon.\n */\n private pickReclaimable(\n stream: string,\n rows: PendingRow[],\n live: StreamWorker | undefined,\n maxDeliver: number\n ): PendingRow[] {\n const held = this.held.get(stream);\n let budget = live ? live.limiter.concurrency - live.limiter.inFlight - live.queued : 0;\n const picked: PendingRow[] = [];\n for (const row of rows) {\n if (held?.has(row.id)) continue;\n if (row.deliveries + 1 > maxDeliver) {\n picked.push(row);\n } else if (budget > 0) {\n budget--;\n picked.push(row);\n }\n }\n return picked;\n }\n\n private async deadLetter(stream: string, parsed: ParsedEntry): Promise<void> {\n const { id, deliveryCount } = parsed;\n try {\n await this.settlement(stream, id, parsed, this.group).term('max-deliver-exceeded');\n logger.warn('[RedisStreamsEventConsumer] message moved to DLQ', { stream, id, deliveryCount });\n } catch (err) {\n logger.debug('[RedisStreamsEventConsumer] dead-letter failed; retried on next sweep', {\n stream,\n id,\n error: errorMessage(err),\n });\n }\n }\n\n /**\n * Runs a reclaimed entry on the stream's dispatcher. It is held (and so\n * heartbeated) while it waits for a slot; if the subscription stops first\n * it is left pending for another replica.\n */\n private redispatch(\n stream: string,\n worker: StreamWorker,\n id: string,\n rawFields: string[],\n streamDeliveries: number\n ): void {\n const held = this.heldFor(stream);\n held.add(id);\n worker.queued++;\n void worker.limiter.acquire().then(() => {\n worker.queued--;\n if (!this.isRunning(worker)) {\n worker.limiter.release();\n held.delete(id);\n return;\n }\n worker.limiter.run(() =>\n this.dispatchEntry(worker, stream, id, rawFields, streamDeliveries).finally(() => held.delete(id))\n );\n });\n }\n\n private async drainDelayQueues(): Promise<void> {\n if (this.stopped || this.knownStreams.size === 0) return;\n const client = this.connection.getClient();\n for (const [stream] of this.knownStreams) {\n const lockKey = delayLockKey(stream, this.connection.keyScope);\n const got = await client.set(lockKey, this.consumerName, 'NX', 'EX', 30).catch(() => null);\n if (got !== 'OK') continue;\n try {\n const due = await client.zrangebyscore(\n delayQueueKey(stream, this.connection.keyScope),\n 0,\n Date.now(),\n 'LIMIT',\n 0,\n 50\n );\n for (const member of due) {\n const split = member.indexOf('|');\n if (split < 0) continue;\n const payload = member.slice(split + 1);\n let fields: Record<string, string> = {};\n try {\n fields = JSON.parse(payload) as Record<string, string>;\n } catch {\n continue;\n }\n const flat: string[] = [];\n for (const [k, v] of Object.entries(fields)) flat.push(k, v);\n await client.xadd(stream, 'MAXLEN', '~', 100_000, '*', ...flat);\n await client.zrem(delayQueueKey(stream, this.connection.keyScope), member);\n }\n } finally {\n await client.del(lockKey).catch(() => undefined);\n }\n }\n }\n}\n\nexport type { IoRedis };\n","/**\n * Serialization helpers for the Redis Streams backend.\n *\n * @module event-queue/implementations/redis-streams/serialize\n */\n\n/**\n * `JSON.stringify` that does not throw on BigInt values.\n *\n * Event payloads frequently originate from Prisma rows, which expose BigInt\n * columns (e.g. counters / durations) as native `bigint`. The standard\n * `JSON.stringify` throws `TypeError: Do not know how to serialize a BigInt`,\n * which would drop the entire event — an entity would then silently never reach\n * the graph / search index. We serialize BigInt as its decimal string so the\n * value is preserved and the event is published.\n */\nexport function safeStringify(value: unknown): string {\n return JSON.stringify(value ?? null, (_key, val) => (typeof val === 'bigint' ? val.toString() : val));\n}\n","/**\n * Redis Streams implementation of IEventPublisher.\n *\n * Each subject is its own stream (`boff:events:<subject-with-colons>`); MAXLEN\n * trimming keeps each stream bounded; dedup is enforced by `SET NX EX` on a\n * per-message-id key before XADD.\n */\nimport { randomUUID } from 'node:crypto';\nimport { logger } from '../../../logger/index.js';\nimport type { IEventPublisher, PublishOptions } from '../../interfaces/IEventPublisher.js';\nimport type { PublisherConfig, EventQueueHealthCheckResult, QueueStatistics } from '../../types/config.js';\nimport type { EventMetadata, StreamConfig } from '../../types/events.js';\nimport { RedisStreamsConnection, type IoRedis } from './RedisStreamsConnection.js';\nimport { boundaryOf, dedupKey, registryKey, replyKey, streamKey } from './keyspace.js';\nimport { safeStringify } from './serialize.js';\nimport { injectTraceFields } from './trace-context.js';\nimport { registerDisposable, unregisterDisposable, type ShutdownDisposable } from '../../../lifecycle/index.js';\n\nexport interface RedisStreamsPublisherConfig extends PublisherConfig {\n /** Approximate MAXLEN trim threshold per stream. Default 100_000. */\n maxLen?: number;\n /** Dedup TTL window in seconds. Default 120. */\n dedupTtlSeconds?: number;\n /** Key namespace override. Default `boff:events`. */\n keyPrefix?: string;\n}\n\nexport class RedisStreamsEventPublisher implements IEventPublisher, ShutdownDisposable {\n private connection: RedisStreamsConnection;\n private publishCount = 0;\n private lastPublishTime: Date | null = null;\n private readonly maxLen: number;\n private readonly dedupTtl: number;\n private readonly keyPrefix: string;\n public readonly shutdownName: string;\n\n constructor(private config: RedisStreamsPublisherConfig) {\n this.connection = new RedisStreamsConnection(config);\n this.maxLen = config.maxLen ?? parseInt(process.env['REDIS_STREAMS_MAXLEN'] ?? '100000', 10);\n this.dedupTtl = config.dedupTtlSeconds ?? parseInt(process.env['REDIS_STREAMS_DEDUP_TTL'] ?? '120', 10);\n this.keyPrefix = config.keyPrefix ?? process.env['REDIS_STREAMS_KEY_PREFIX'] ?? 'boff:events';\n this.shutdownName = `redis-streams-publisher:${config.name ?? 'default'}`;\n // Ensure the socket is closed on graceful shutdown even if the owner never\n // calls disconnect() (see lifecycle/shutdown-registry).\n registerDisposable(this);\n }\n\n /** Close underlying connections on graceful shutdown. */\n dispose(): Promise<void> {\n return this.disconnect();\n }\n\n async connect(): Promise<void> {\n await this.connection.connect();\n }\n\n async disconnect(): Promise<void> {\n unregisterDisposable(this);\n await this.connection.disconnect();\n }\n\n isConnected(): boolean {\n return this.connection.isConnected();\n }\n\n async healthCheck(): Promise<EventQueueHealthCheckResult> {\n try {\n const t0 = Date.now();\n const pong = await this.connection.ping();\n return {\n status: pong === 'PONG' ? 'healthy' : 'degraded',\n timestamp: new Date().toISOString(),\n connected: this.isConnected(),\n latencyMs: Date.now() - t0,\n details: { type: 'redis-streams', url: this.config.url },\n };\n } catch (err) {\n return {\n status: 'unhealthy',\n timestamp: new Date().toISOString(),\n connected: false,\n details: { type: 'redis-streams' },\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n async getStatistics(): Promise<QueueStatistics> {\n return {\n messagesPublished: this.publishCount,\n messagesConsumed: 0,\n messagesFailed: 0,\n activePublishers: 1,\n activeConsumers: 0,\n lastActivity: this.lastPublishTime?.toISOString() ?? null,\n details: { type: 'redis-streams' },\n };\n }\n\n async ensureStream(_config: StreamConfig): Promise<void> {\n // Streams are created lazily by XADD; no-op here.\n return Promise.resolve();\n }\n\n async publish<T = unknown>(options: {\n subject: string;\n data: T;\n metadata?: Partial<EventMetadata>;\n options?: PublishOptions;\n }): Promise<number | string> {\n return this.publishInternal(options);\n }\n\n private async publishInternal<T>(opts: {\n subject: string;\n data: T;\n metadata?: Partial<EventMetadata>;\n options?: PublishOptions;\n }): Promise<string> {\n await this.connect();\n const client = this.connection.getClient();\n // When the caller provides an explicit stream name (e.g. 'WSPACE_GRAPH_EVENTS'),\n // use it as the Redis stream key so all events land in one aggregated stream that\n // a single consumer can read. Fall back to the per-subject stream when no override.\n const streamName = opts.options?.stream ?? opts.subject;\n const stream = streamKey(streamName, { prefix: this.keyPrefix, scope: this.connection.keyScope });\n const msgId = opts.options?.messageId ?? randomUUID();\n const correlationId = opts.metadata?.correlationId ?? randomUUID();\n const enableDedup = this.config.enableDeduplication === true || opts.options?.messageId !== undefined;\n\n if (enableDedup) {\n const ok = await client.set(dedupKey(stream, msgId, this.connection.keyScope), '1', 'NX', 'EX', this.dedupTtl);\n if (ok !== 'OK') {\n logger.debug('[RedisStreamsEventPublisher] dedup hit; skipping publish', {\n subject: opts.subject,\n msgId,\n });\n return msgId;\n }\n }\n\n const trace = await injectTraceFields();\n const fields: Record<string, string> = {\n 'msg-id': msgId,\n subject: opts.subject,\n 'correlation-id': correlationId,\n timestamp: new Date().toISOString(),\n priority: opts.options?.priority ?? this.config.defaultPriority ?? 'normal',\n source: opts.metadata?.source ?? this.config.name ?? 'unknown',\n payload: safeStringify(opts.data ?? null),\n metadata: safeStringify(opts.metadata ?? {}),\n ...trace,\n };\n if (opts.metadata?.userId) fields['user-id'] = String(opts.metadata.userId);\n if (opts.metadata?.workspaceId) fields['workspace-id'] = String(opts.metadata.workspaceId);\n if (opts.metadata?.tenantId) fields['tenant-id'] = String(opts.metadata.tenantId);\n\n const flat: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n flat.push(k, v);\n }\n\n const id = await client.xadd(stream, 'MAXLEN', '~', this.maxLen, '*', ...flat);\n\n // Async fire-and-forget registry update\n void client\n .sadd(registryKey(boundaryOf(opts.subject), this.connection.keyScope), opts.subject)\n .catch(() => undefined);\n\n this.publishCount++;\n this.lastPublishTime = new Date();\n logger.debug('[RedisStreamsEventPublisher] published', {\n subject: opts.subject,\n stream,\n id,\n });\n return id;\n }\n\n async publishBatch<T = unknown>(\n events: Array<{\n subject: string;\n data: T;\n metadata?: Partial<EventMetadata>;\n options?: PublishOptions;\n }>\n ): Promise<Array<number | string>> {\n const out: string[] = [];\n for (const e of events) {\n out.push(await this.publishInternal(e));\n }\n return out;\n }\n\n /**\n * Emulated request/response: writer XADDs onto its own subject, then\n * blocks on a one-shot reply stream keyed by correlationId.\n */\n async publishWithAck<T = unknown, R = unknown>(opts: {\n subject: string;\n data: T;\n metadata?: Partial<EventMetadata>;\n timeout?: number;\n }): Promise<R> {\n await this.connect();\n const client = this.connection.getClient();\n const correlationId = opts.metadata?.correlationId ?? randomUUID();\n const reply = replyKey(correlationId, this.connection.keyScope);\n await this.publishInternal({\n subject: opts.subject,\n data: opts.data,\n metadata: { ...opts.metadata, correlationId, replyTo: reply },\n });\n\n const timeoutMs = opts.timeout ?? 5000;\n const t0 = Date.now();\n while (Date.now() - t0 < timeoutMs) {\n const entries = (await client.xrange(reply, '-', '+')) as Array<[string, string[]]>;\n if (Array.isArray(entries) && entries.length > 0) {\n const last = entries[entries.length - 1];\n if (!last) break;\n const rawFields = last[1];\n const payloadIdx = rawFields.indexOf('payload');\n const payload = payloadIdx >= 0 ? rawFields[payloadIdx + 1] : '{}';\n await client.del(reply);\n return JSON.parse(payload ?? '{}') as R;\n }\n await new Promise((res) => setTimeout(res, 50));\n }\n await client.del(reply).catch(() => undefined);\n throw new Error(`[RedisStreamsEventPublisher] publishWithAck timed out for subject=${opts.subject}`);\n }\n\n /** Internal helper used by the consumer's reply path. */\n async sendReply(correlationId: string, data: unknown): Promise<void> {\n await this.connect();\n const client = this.connection.getClient();\n const key = replyKey(correlationId, this.connection.keyScope);\n await client.xadd(key, '*', 'payload', safeStringify(data ?? null));\n await client.expire(key, 60);\n }\n}\n\nexport type { IoRedis };\n","/**\n * Event Queue Factory\n *\n * Single-backend wrapper around the Redis Streams publisher/consumer.\n * NATS support was removed on 2026-05-16 — Redis is the canonical fleet\n * event-bus. Other backends (RabbitMQ, Kafka, SQS) are listed in\n * `QueueType` for future extension; today only `redis-streams` is wired.\n */\nimport { logger } from '../../logger/index.js';\nimport type { ServiceLayer } from '../../types/layer.js';\n\nimport { RedisStreamsEventConsumer } from '../implementations/redis-streams/RedisStreamsEventConsumer.js';\nimport { RedisStreamsEventPublisher } from '../implementations/redis-streams/RedisStreamsEventPublisher.js';\nimport type { IEventConsumer } from '../interfaces/IEventConsumer.js';\nimport type { IEventPublisher } from '../interfaces/IEventPublisher.js';\nimport { type ConsumerConfig, type PublisherConfig, QueueType } from '../types/config.js';\nimport { resolveEventStreamsUrl } from '../env.js';\n\nconst DEFAULT_STREAMS_URL = 'redis://localhost:6379';\n\nfunction streamsUrlFromEnv(): string {\n return resolveEventStreamsUrl() ?? DEFAULT_STREAMS_URL;\n}\n\n/**\n * Reads an optional integer env var. Unset or empty yields `undefined` (the\n * consumer default applies); anything else is parsed and validated by the\n * consumer, so a malformed value fails fast at startup instead of silently\n * falling back.\n */\nfunction optionalIntEnv(name: string): number | undefined {\n const raw = process.env[name];\n if (raw === undefined || raw.trim() === '') return undefined;\n return Number(raw.trim());\n}\n\nfunction resolveQueueType(): QueueType {\n // Kept for the API contract — always returns REDIS_STREAMS now.\n return QueueType.REDIS_STREAMS;\n}\n\nfunction redactConnectionUrl(url: string | undefined): string | undefined {\n if (!url) return url;\n try {\n const parsed = new URL(url);\n const rendered = parsed.toString();\n const authorityStart = rendered.indexOf('//') + 2;\n const authorityEnd = rendered.indexOf('@', authorityStart);\n if (authorityStart < 2 || authorityEnd < 0) return rendered;\n return `${rendered.slice(0, authorityStart)}:***@${rendered.slice(authorityEnd + 1)}`;\n } catch {\n const schemeEnd = url.indexOf('://');\n if (schemeEnd < 0) return url;\n const authorityStart = schemeEnd + 3;\n const authorityEnd = url.indexOf('@', authorityStart);\n if (authorityEnd < 0) return url;\n return `${url.slice(0, authorityStart)}:***@${url.slice(authorityEnd + 1)}`;\n }\n}\n\n/**\n * Factory for creating event queue instances\n */\nexport class EventQueueFactory {\n /**\n * Create an event publisher based on configuration\n */\n static createPublisher(config: PublisherConfig): IEventPublisher {\n logger.info('[EventQueueFactory] Creating event publisher', {\n type: config.type,\n url: redactConnectionUrl(config.url),\n });\n\n if (config.type === QueueType.REDIS_STREAMS) {\n return new RedisStreamsEventPublisher(config);\n }\n\n throw new Error(`Unsupported queue type: ${config.type}. NATS was retired on 2026-05-16; use 'redis-streams'.`);\n }\n\n /**\n * Create an event consumer based on configuration\n */\n static createConsumer(config: ConsumerConfig): IEventConsumer {\n logger.info('[EventQueueFactory] Creating event consumer', {\n type: config.type,\n url: redactConnectionUrl(config.url),\n stream: config.stream,\n consumer: config.consumer,\n });\n\n if (config.type === QueueType.REDIS_STREAMS) {\n return new RedisStreamsEventConsumer(config);\n }\n\n throw new Error(`Unsupported queue type: ${config.type}. NATS was retired on 2026-05-16; use 'redis-streams'.`);\n }\n\n /**\n * Create a publisher from environment variables.\n * Reads `REDIS_STREAMS_URL` (else `REDIS_URL`), `REDIS_PASSWORD`, and\n * standard queue options.\n */\n static createPublisherFromEnv(): IEventPublisher {\n return EventQueueFactory.createPublisher({\n type: QueueType.REDIS_STREAMS,\n url: streamsUrlFromEnv(),\n password: process.env['REDIS_PASSWORD'],\n name: process.env['QUEUE_CLIENT_NAME'] ?? process.env['SERVICE_NAME'] ?? 'be-sdk-publisher',\n enableDeduplication: process.env['QUEUE_ENABLE_DEDUPLICATION'] === 'true',\n defaultPriority: (process.env['QUEUE_DEFAULT_PRIORITY'] as 'low' | 'normal' | 'high') ?? 'normal',\n });\n }\n\n /**\n * Create a consumer from environment variables.\n */\n static createConsumerFromEnv(stream: string, consumer: string): IEventConsumer {\n return EventQueueFactory.createConsumer({\n type: QueueType.REDIS_STREAMS,\n url: streamsUrlFromEnv(),\n password: process.env['REDIS_PASSWORD'],\n name: process.env['QUEUE_CLIENT_NAME'] ?? process.env['SERVICE_NAME'] ?? consumer,\n stream,\n consumer,\n maxConcurrent: process.env['QUEUE_MAX_CONCURRENT'] ? parseInt(process.env['QUEUE_MAX_CONCURRENT'], 10) : 5,\n concurrency: optionalIntEnv('QUEUE_CONCURRENCY'),\n drainTimeoutMs: optionalIntEnv('QUEUE_DRAIN_TIMEOUT_MS'),\n maxDeliver: process.env['QUEUE_MAX_DELIVER'] ? parseInt(process.env['QUEUE_MAX_DELIVER'], 10) : 3,\n ackWait: process.env['QUEUE_ACK_WAIT']\n ? parseInt(process.env['QUEUE_ACK_WAIT'], 10) * 1_000_000_000\n : 30_000_000_000,\n });\n }\n\n // ========================================================================\n // Layer-Aware Factory Methods\n // ========================================================================\n\n /**\n * Create a publisher for a specific layer.\n * The layer is preserved on the publisher name; otherwise identical to\n * `createPublisherFromEnv()`.\n */\n static createPublisherForLayer(_layer: ServiceLayer, serviceName: string): IEventPublisher {\n return EventQueueFactory.createPublisher({\n type: QueueType.REDIS_STREAMS,\n url: streamsUrlFromEnv(),\n password: process.env['REDIS_PASSWORD'],\n name: serviceName,\n enableDeduplication: process.env['QUEUE_ENABLE_DEDUPLICATION'] === 'true',\n defaultPriority: (process.env['QUEUE_DEFAULT_PRIORITY'] as 'low' | 'normal' | 'high') ?? 'normal',\n });\n }\n\n /**\n * Create a consumer for a specific layer.\n */\n static createConsumerForLayer(\n _layer: ServiceLayer,\n serviceName: string,\n stream: string,\n consumer: string\n ): IEventConsumer {\n return EventQueueFactory.createConsumer({\n type: QueueType.REDIS_STREAMS,\n url: streamsUrlFromEnv(),\n password: process.env['REDIS_PASSWORD'],\n name: serviceName,\n stream,\n consumer,\n maxConcurrent: process.env['QUEUE_MAX_CONCURRENT'] ? parseInt(process.env['QUEUE_MAX_CONCURRENT'], 10) : 5,\n concurrency: optionalIntEnv('QUEUE_CONCURRENCY'),\n drainTimeoutMs: optionalIntEnv('QUEUE_DRAIN_TIMEOUT_MS'),\n maxDeliver: process.env['QUEUE_MAX_DELIVER'] ? parseInt(process.env['QUEUE_MAX_DELIVER'], 10) : 3,\n ackWait: process.env['QUEUE_ACK_WAIT']\n ? parseInt(process.env['QUEUE_ACK_WAIT'], 10) * 1_000_000_000\n : 30_000_000_000,\n });\n }\n}\n\n// Internal helper kept exported for callers that imported it previously.\nexport { resolveQueueType };\n"],"mappings":";;;;;;;;;;;;;;;AAOA,IAAY,YAAL;CACL;CACA;CACA;CACA;;AACF;;;;;;;;;;ACiBA,IAAI,iBAAiD;AAErD,eAAe,cAAuC;CACpD,IAAI,gBAAgB,OAAO;CAC3B,kBAAkB,YAAY;EAC5B,IAAI;GAEF,OAAO,MADY,OAAO;EAE5B,QAAQ;GACN,OAAO,MAAM,kFAAkF;GAC/F,OAAO;EACT;CACF,EAAC,CAAE;CACH,OAAO;AACT;AAEA,MAAM,aAAa;CAAC;CAAe;CAAc;AAAS;;AAG1D,eAAsB,oBAAqD;CACzE,MAAM,MAAM,MAAM,YAAY;CAC9B,IAAI,CAAC,KAAK,OAAO,CAAC;CAClB,MAAM,UAAkC,CAAC;CACzC,IAAI;EACF,IAAI,YAAY,OAAO,IAAI,QAAQ,OAAO,GAAG,SAAS,EACpD,IAAI,GAAG,GAAG,GAAG;GACX,EAAE,KAAK;EACT,EACF,CAAC;CACH,SAAS,KAAK;EACZ,OAAO,MAAM,+CAA+C,EA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