@burdenoff/be-sdk 2026.1202.4 → 2026.1202.6

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 (70) hide show
  1. package/dist/{EventQueueFactory-DbLEV5h_.js → EventQueueFactory-0XHOTKEv.js} +19 -13
  2. package/dist/{EventQueueFactory-DbLEV5h_.js.map → EventQueueFactory-0XHOTKEv.js.map} +1 -1
  3. package/dist/activity/index.d.ts +2 -2
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/{backoff-Di7sEjSw.js → backoff-Ck5QMdig.js} +2 -2
  6. package/dist/{backoff-Di7sEjSw.js.map → backoff-Ck5QMdig.js.map} +1 -1
  7. package/dist/bootstrap/index.d.ts +1 -1
  8. package/dist/context/index.d.ts +1 -1
  9. package/dist/env-cCfoPZ7m.js +122 -0
  10. package/dist/env-cCfoPZ7m.js.map +1 -0
  11. package/dist/event-queue/index.d.ts +2 -2
  12. package/dist/event-queue/index.js +6 -6
  13. package/dist/{event-queue-ANzylLK1.js → event-queue-CpVi7BET.js} +11 -8
  14. package/dist/event-queue-CpVi7BET.js.map +1 -0
  15. package/dist/feature-flags/index.d.ts +1 -1
  16. package/dist/graph/index.d.ts +1 -1
  17. package/dist/graph/index.js +2 -2
  18. package/dist/{graph-emitter-CwSyGt3g.js → graph-emitter-CtfPpHxL.js} +8 -4
  19. package/dist/{graph-emitter-CwSyGt3g.js.map → graph-emitter-CtfPpHxL.js.map} +1 -1
  20. package/dist/{graph-BTaqvVYQ.js → graph-hPqNRoKC.js} +4 -4
  21. package/dist/{graph-BTaqvVYQ.js.map → graph-hPqNRoKC.js.map} +1 -1
  22. package/dist/graphql/index.js +1 -1
  23. package/dist/{graphql-D_DkedFZ.js → graphql-Cn-OBnyu.js} +2 -2
  24. package/dist/{graphql-D_DkedFZ.js.map → graphql-Cn-OBnyu.js.map} +1 -1
  25. package/dist/{graphql-DcZAKC6p.d.ts → graphql-DPkc5IMZ.d.ts} +1 -1
  26. package/dist/{index-UQSbAERe.d.ts → index--w3AsbqC.d.ts} +2 -2
  27. package/dist/{index-BMy-d2_f.d.ts → index-12QwfPvR.d.ts} +3 -3
  28. package/dist/{index-GzZunmGS.d.ts → index-B30y7Yry.d.ts} +3 -3
  29. package/dist/{index-C96mNrLW.d.ts → index-C4MFjzOT.d.ts} +2 -2
  30. package/dist/{index-CQ3vxT5P.d.ts → index-CDdrBQom.d.ts} +1 -0
  31. package/dist/{index-CeaJcbar.d.ts → index-ChJqXbVL.d.ts} +8 -4
  32. package/dist/{index-B4ckqUZX.d.ts → index-Cx77z1cc.d.ts} +1 -1
  33. package/dist/{index-Cl3Xiw1O.d.ts → index-DM5zS9TT.d.ts} +2 -2
  34. package/dist/{index-Cs426iRP.d.ts → index-DMKCyeBm.d.ts} +4 -4
  35. package/dist/{index-BmL-JjQK.d.ts → index-DMq2xPV7.d.ts} +1 -1
  36. package/dist/{index-C4hRRihw.d.ts → index-Dl32yXnZ.d.ts} +1 -1
  37. package/dist/{index-j1B6eYHc.d.ts → index-Ds_V1Crj.d.ts} +2 -2
  38. package/dist/{index-CZWopQsh.d.ts → index-PvHsCusi.d.ts} +1 -1
  39. package/dist/index.d.ts +14 -14
  40. package/dist/index.js +12 -8
  41. package/dist/index.js.map +1 -1
  42. package/dist/init/index.js +1 -1
  43. package/dist/{init-knkrqVvJ.js → init-CsfDrW9M.js} +3 -3
  44. package/dist/{init-knkrqVvJ.js.map → init-CsfDrW9M.js.map} +1 -1
  45. package/dist/instrumentation/index.d.ts +2 -2
  46. package/dist/logger/index.d.ts +1 -1
  47. package/dist/{middleware-InVCyjUX.js → middleware-aO50bLUO.js} +2 -2
  48. package/dist/{middleware-InVCyjUX.js.map → middleware-aO50bLUO.js.map} +1 -1
  49. package/dist/notifications/index.d.ts +1 -1
  50. package/dist/payments/index.d.ts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +2 -2
  53. package/dist/{prisma-DcMrbj7W.js → prisma-BlB0aalN.js} +3 -3
  54. package/dist/{prisma-DcMrbj7W.js.map → prisma-BlB0aalN.js.map} +1 -1
  55. package/dist/rbac/index.d.ts +1 -1
  56. package/dist/resource-caps/index.d.ts +1 -1
  57. package/dist/search/index.d.ts +2 -2
  58. package/dist/server/index.d.ts +2 -2
  59. package/dist/telemetry/index.d.ts +2 -2
  60. package/dist/tracker/index.d.ts +2 -2
  61. package/dist/translation/index.d.ts +2 -2
  62. package/dist/types/index.d.ts +1 -1
  63. package/dist/types/index.js.map +1 -1
  64. package/dist/{types-C36JkwDg.d.ts → types-BxZmaW3v.d.ts} +1 -1
  65. package/dist/usage/index.d.ts +1 -1
  66. package/dist/{workspace-extension-C0qib11C.d.ts → workspace-extension-DAs06Hv_.d.ts} +1 -1
  67. package/package.json +1 -1
  68. package/dist/env-DdaoGjIt.js +0 -74
  69. package/dist/env-DdaoGjIt.js.map +0 -1
  70. package/dist/event-queue-ANzylLK1.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"prisma-DcMrbj7W.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,MAAM,EACJ,aACA,uBAAuB,QAAQ,IAAI,gCAAgC,SACnE,mBACA,2BAA2B,iCAAiC,WAAW,GACvE,0BACA,2BAA2B,MAC3B,GAAG,iBACD;CAOJ,MAAM,2BAA+C;EACnD,GAAG;EACH,iBAAiB,aAAa,mBAAmB,OAAO;CAC1D;CAIA,6BAA6B,WAAW;CAGxC,MAAM,UAAU,mBAAmB,yBAAyB,wBAAwB;CAGpF,MAAM,aAAa,QAAQ,UAAU;CAWrC,IAAI;CAGJ,IAAI,sBAAsB;EAGxB,MAAM,cAAqC;GACzC,SAAS;GACT;GACA,cALmB,qBAAqB,qBAAqB;EAM/D;EAEA,iBAAiB,kBAAkB,YAAY,WAAW;EAE1D,OAAO,KAAK,sCAAsC,EAAE,YAAY,CAAC;CACnE,OAAO;EACL,iBAAiB;EACjB,OAAO,KAAK,qCAAqC;CACnD;CAGA,IAAI,0BAA0B;EAC5B,iBAAiB,sBAAsB,gBAAgB,wBAAwB;EAE/E,OAAO,KAAK,0CAA0C,EAAE,YAAY,CAAC;CACvE,OACE,OAAO,KAAK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gB,OAAO,aAC/D,OAAO;CAET,IAAI,OAAO,UAAU,QAAQ,QAAQ,WAAW,OAAO,QACrD,OAAO;CAET,IAAI,OAAO,aAAa,QAAQ,QAAQ,cAAc,OAAO,WAC3D,OAAO;CAET,IAAI,OAAO,SAAS,QAAQ,QAAQ,UAAU,OAAO,OACnD,OAAO;CAGT,IAAI,OAAO,aAAa,QAAQ,CAAC,kBAAkB,QAAQ,WAAW,OAAO,SAAS,GACpF,OAAO;CAET,IAAI,OAAO,kBAAkB,QAAQ,QAAQ,mBAAmB,OAAO,gBACrE,OAAO;CAGT,OAAO;AACT;;;;;;;AAQA,SAAgB,qBAAqB,YAOhB;CACnB,OAAO;EACL,aAAa,WAAW,eAAe;EACvC,QAAQ,WAAW,UAAU;EAC7B,WAAW,WAAW,aAAa;EACnC,OAAO,WAAW,SAAS;EAC3B,WAAW,WAAW,aAAa;EACnC,gBAAgB,WAAW,kBAAkB;CAC/C;AACF"}
1
+ {"version":3,"file":"prisma-BlB0aalN.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 './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AET,IAAI,OAAO,UAAU,QAAQ,QAAQ,WAAW,OAAO,QACrD,OAAO;CAET,IAAI,OAAO,aAAa,QAAQ,QAAQ,cAAc,OAAO,WAC3D,OAAO;CAET,IAAI,OAAO,SAAS,QAAQ,QAAQ,UAAU,OAAO,OACnD,OAAO;CAGT,IAAI,OAAO,aAAa,QAAQ,CAAC,kBAAkB,QAAQ,WAAW,OAAO,SAAS,GACpF,OAAO;CAET,IAAI,OAAO,kBAAkB,QAAQ,QAAQ,mBAAmB,OAAO,gBACrE,OAAO;CAGT,OAAO;AACT;;;;;;;AAQA,SAAgB,qBAAqB,YAOhB;CACnB,OAAO;EACL,aAAa,WAAW,eAAe;EACvC,QAAQ,WAAW,UAAU;EAC7B,WAAW,WAAW,aAAa;EACnC,OAAO,WAAW,SAAS;EAC3B,WAAW,WAAW,aAAa;EACnC,gBAAgB,WAAW,kBAAkB;CAC/C;AACF"}
@@ -1,2 +1,2 @@
1
- import { _ as createRBACDirective, a as Permission, b as resolveOperation, c as RoleDefaultPermission, d as MAX_ROOT_FRAGMENT_DEPTH, f as OperationResolution, g as collectRootFields, h as RootFieldResolution, i as PBACPermissionLevel, l as createRBACClientFromEnv, m as RBACDirectiveConfig, n as EffectivePermissionEntry, o as RBACModule, p as RBACClient, r as PBACActorType, s as Role, t as CheckPermissionOptions, u as LayerAwareRBACConfig, v as createRBACDirectiveForLayer, y as createRBACDirectiveFromEnv } from "../index-j1B6eYHc.js";
1
+ import { _ as createRBACDirective, a as Permission, b as resolveOperation, c as RoleDefaultPermission, d as MAX_ROOT_FRAGMENT_DEPTH, f as OperationResolution, g as collectRootFields, h as RootFieldResolution, i as PBACPermissionLevel, l as createRBACClientFromEnv, m as RBACDirectiveConfig, n as EffectivePermissionEntry, o as RBACModule, p as RBACClient, r as PBACActorType, s as Role, t as CheckPermissionOptions, u as LayerAwareRBACConfig, v as createRBACDirectiveForLayer, y as createRBACDirectiveFromEnv } from "../index-Ds_V1Crj.js";
2
2
  export { CheckPermissionOptions, EffectivePermissionEntry, type LayerAwareRBACConfig, MAX_ROOT_FRAGMENT_DEPTH, type OperationResolution, PBACActorType, PBACPermissionLevel, Permission, RBACClient, type RBACDirectiveConfig, RBACModule, Role, RoleDefaultPermission, type RootFieldResolution, collectRootFields, createRBACClientFromEnv, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv, resolveOperation };
@@ -1,4 +1,4 @@
1
- import { t as BurdenoffGraphQLClient } from "../graphql-DcZAKC6p.js";
1
+ import { t as BurdenoffGraphQLClient } from "../graphql-DPkc5IMZ.js";
2
2
  import { GraphQLError } from "graphql";
3
3
  export type ResourceName = 'workspace' | 'workspaceMember' | 'sandbox' | 'vibe' | 'agent' | 'conversation' | 'message' | 'tag' | 'file' | 'group' | 'calendar' | 'scheduledTask' | 'form' | 'apiKey' | 'webhook';
4
4
  export type PlanTier = 'free' | 'paid';
@@ -1,5 +1,5 @@
1
- import { t as BurdenoffGraphQLClient } from "../graphql-DcZAKC6p.js";
2
- import { m as SDKContext } from "../index-CQ3vxT5P.js";
1
+ import { t as BurdenoffGraphQLClient } from "../graphql-DPkc5IMZ.js";
2
+ import { m as SDKContext } from "../index-CDdrBQom.js";
3
3
  export interface SearchOptions {
4
4
  query: string;
5
5
  resourceTypes?: string[];
@@ -1,7 +1,7 @@
1
- import { A as DependencyWatchdogConfig, B as resolveDependencyWatchdogConfig, C as VerifiedDelegationContext, D as DEFAULT_DEPENDENCY_WATCHDOG_CONFIG, E as YogaPlugin, F as ServerWatchdogConfig, H as WorkspaceGuardConfig, I as WatchdogDependencyName, L as WatchdogSources, M as FailingDependency, N as LivenessReport, O as DependencyProbe, P as MIN_UNHEALTHY_THRESHOLD_MS, R as buildWatchdogProbes, S as ServerInstance, T as WspaceGraphQLContext, U as WorkspaceMembershipValidation, V as watchdogLivenessResponse, W as createWorkspaceGuardPlugin, _ as RESTEndpoint, a as IActor, b as ServerI18nConfig, c as IOrganization, d as ITenant, f as ITracking, g as PrismaClientConstructor, h as ModuleGraphConfig, i as GraphQLContext, j as DependencyWatchdogOptions, k as DependencyWatchdog, l as IProduct, m as JWTPayload, n as ConsentContext, o as IContextFilterInput, p as IWorkspace, r as ElysiaApp, s as IOperationContext, t as ActorProvenance, u as IProject, v as ServerConfig, w as WorkspaceSecret, x as ServerInfo, y as ServerDefinition, z as createServerWatchdog } from "../types-C36JkwDg.js";
1
+ import { A as DependencyWatchdogConfig, B as resolveDependencyWatchdogConfig, C as VerifiedDelegationContext, D as DEFAULT_DEPENDENCY_WATCHDOG_CONFIG, E as YogaPlugin, F as ServerWatchdogConfig, H as WorkspaceGuardConfig, I as WatchdogDependencyName, L as WatchdogSources, M as FailingDependency, N as LivenessReport, O as DependencyProbe, P as MIN_UNHEALTHY_THRESHOLD_MS, R as buildWatchdogProbes, S as ServerInstance, T as WspaceGraphQLContext, U as WorkspaceMembershipValidation, V as watchdogLivenessResponse, W as createWorkspaceGuardPlugin, _ as RESTEndpoint, a as IActor, b as ServerI18nConfig, c as IOrganization, d as ITenant, f as ITracking, g as PrismaClientConstructor, h as ModuleGraphConfig, i as GraphQLContext, j as DependencyWatchdogOptions, k as DependencyWatchdog, l as IProduct, m as JWTPayload, n as ConsentContext, o as IContextFilterInput, p as IWorkspace, r as ElysiaApp, s as IOperationContext, t as ActorProvenance, u as IProject, v as ServerConfig, w as WorkspaceSecret, x as ServerInfo, y as ServerDefinition, z as createServerWatchdog } from "../types-BxZmaW3v.js";
2
2
  import { n as PrismaClientBase } from "../client-NknQrWsP.js";
3
3
  import { a as ActorOrigin, c as readAssistantSessionAttribution, i as ASSISTANT_SESSION_ID_HEADER, l as toAssistantSessionAttribution, n as AI_ASSISTANT_ACTOR_ORIGIN, o as AssistantSessionAttribution, r as ASSISTANT_CORRELATION_ID_HEADER, s as parseAssistantSessionHeaders, t as ACTOR_ORIGIN_HEADER } from "../assistant-session-DA5ZKJOr.js";
4
4
  import { r as I18nContext, s as LocaleCode } from "../types-DgaQqvxo.js";
5
- import { $ as configureServerAuth, A as assertDsarOrchestrator, B as getContextOptions, C as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, D as DsarOrchestratorRejectionReason, E as DsarOrchestratorOptions, F as getDelegatedPrincipal, G as PayloadTooLargeError, H as DEFAULT_RAW_BODY_MAX_BYTES, I as resolveOnBehalfOf, J as createRawBodyRouter, K as RawBodyResolution, L as ContextBuilderOptions, M as isDsarOrchestratorActor, N as resolveDsarCallerIdentity, O as ResolvedDsarCaller, P as DelegatedPrincipal, Q as resolveMaxRequestBodySize, R as buildContext, S as DSAR_ALLOWED_ORCHESTRATORS_ENV, T as DsarOrchestratorForbiddenError, U as MAX_IDLE_TIMEOUT_SECONDS, V as DEFAULT_MAX_REQUEST_BODY_SIZE, W as OrdinaryRoute, X as readBoundedRawBody, Y as extendRequestIdleTimeout, Z as resolveBodyLimitBytes, _ as MutationAuditPluginOptions, a as UserFacingErrorOptions, at as configureDefaultAuth, b as sanitizeAuditValue, c as createHumanReadableErrorPlugin, ct as generateSymmetricSecret, d as normalizeExecutionResultErrors, dt as tenantCheck, et as createServer, f as normalizeGraphQLResponse, ft as verifyJWT, g as MUTATION_AUDIT_RESOURCE_TYPE, h as MUTATION_AUDIT_ACTIVITY_TYPE, i as NormalizedErrorState, it as configureAuth, j as getAllowedDsarOrchestrators, k as VERIFIED_SERVICE_IDENTITY_HEADER, l as formatHttpError, lt as orgCheck, m as toUserFacingGraphQLError, n as HttpErrorPayload, nt as FetchWorkspaceSecretFn, o as UserFacingGraphQLError, ot as decodeJWT, p as normalizeGraphQLResponsePayload, pt as workspaceCheck, q as RawBodyRouter, r as HttpErrorResult, rt as authCheck, s as createHttpErrorResponse, st as fetchWorkspaceSecret, t as ErrorNormalizationOptions, tt as AuthConfig, u as normalizeError, ut as requireWorkspace, v as createMutationAuditPlugin, w as DsarOrchestratorContext, x as DEFAULT_DSAR_ORCHESTRATOR_ID, y as getMutationFieldNames, z as configureContext } from "../index-C4hRRihw.js";
5
+ import { $ as configureServerAuth, A as assertDsarOrchestrator, B as getContextOptions, C as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, D as DsarOrchestratorRejectionReason, E as DsarOrchestratorOptions, F as getDelegatedPrincipal, G as PayloadTooLargeError, H as DEFAULT_RAW_BODY_MAX_BYTES, I as resolveOnBehalfOf, J as createRawBodyRouter, K as RawBodyResolution, L as ContextBuilderOptions, M as isDsarOrchestratorActor, N as resolveDsarCallerIdentity, O as ResolvedDsarCaller, P as DelegatedPrincipal, Q as resolveMaxRequestBodySize, R as buildContext, S as DSAR_ALLOWED_ORCHESTRATORS_ENV, T as DsarOrchestratorForbiddenError, U as MAX_IDLE_TIMEOUT_SECONDS, V as DEFAULT_MAX_REQUEST_BODY_SIZE, W as OrdinaryRoute, X as readBoundedRawBody, Y as extendRequestIdleTimeout, Z as resolveBodyLimitBytes, _ as MutationAuditPluginOptions, a as UserFacingErrorOptions, at as configureDefaultAuth, b as sanitizeAuditValue, c as createHumanReadableErrorPlugin, ct as generateSymmetricSecret, d as normalizeExecutionResultErrors, dt as tenantCheck, et as createServer, f as normalizeGraphQLResponse, ft as verifyJWT, g as MUTATION_AUDIT_RESOURCE_TYPE, h as MUTATION_AUDIT_ACTIVITY_TYPE, i as NormalizedErrorState, it as configureAuth, j as getAllowedDsarOrchestrators, k as VERIFIED_SERVICE_IDENTITY_HEADER, l as formatHttpError, lt as orgCheck, m as toUserFacingGraphQLError, n as HttpErrorPayload, nt as FetchWorkspaceSecretFn, o as UserFacingGraphQLError, ot as decodeJWT, p as normalizeGraphQLResponsePayload, pt as workspaceCheck, q as RawBodyRouter, r as HttpErrorResult, rt as authCheck, s as createHttpErrorResponse, st as fetchWorkspaceSecret, t as ErrorNormalizationOptions, tt as AuthConfig, u as normalizeError, ut as requireWorkspace, v as createMutationAuditPlugin, w as DsarOrchestratorContext, x as DEFAULT_DSAR_ORCHESTRATOR_ID, y as getMutationFieldNames, z as configureContext } from "../index-Dl32yXnZ.js";
6
6
  import { t as suppressMutationAudit } from "../explicit-activity-scope-D8VeGGpt.js";
7
7
  export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, type ActorOrigin, type ActorProvenance, type AssistantSessionAttribution, type AuthConfig, type ConsentContext, type ContextBuilderOptions, DEFAULT_DEPENDENCY_WATCHDOG_CONFIG, DEFAULT_DSAR_ORCHESTRATOR_ID, DEFAULT_MAX_REQUEST_BODY_SIZE, DEFAULT_RAW_BODY_MAX_BYTES, DSAR_ALLOWED_ORCHESTRATORS_ENV, DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, type DelegatedPrincipal, type DependencyProbe, DependencyWatchdog, type DependencyWatchdogConfig, type DependencyWatchdogOptions, type DsarOrchestratorContext, DsarOrchestratorForbiddenError, type DsarOrchestratorOptions, type DsarOrchestratorRejectionReason, type ElysiaApp, type ErrorNormalizationOptions, type FailingDependency, type FetchWorkspaceSecretFn, type GraphQLContext, type HttpErrorPayload, type HttpErrorResult, type I18nContext, type IActor, type IContextFilterInput, type IOperationContext, type IOrganization, type IProduct, type IProject, type ITenant, type ITracking, type IWorkspace, type JWTPayload, type LivenessReport, type LocaleCode, MAX_IDLE_TIMEOUT_SECONDS, MIN_UNHEALTHY_THRESHOLD_MS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, type ModuleGraphConfig, type MutationAuditPluginOptions, type NormalizedErrorState, type OrdinaryRoute, PayloadTooLargeError, type PrismaClientBase, type PrismaClientConstructor, type RESTEndpoint, type RawBodyResolution, type RawBodyRouter, type ResolvedDsarCaller, type ServerConfig, type ServerDefinition, type ServerI18nConfig, type ServerInfo, type ServerInstance, type ServerWatchdogConfig, type UserFacingErrorOptions, UserFacingGraphQLError, VERIFIED_SERVICE_IDENTITY_HEADER, type VerifiedDelegationContext, type WatchdogDependencyName, type WatchdogSources, type WorkspaceGuardConfig, type WorkspaceMembershipValidation, type WorkspaceSecret, type WspaceGraphQLContext, type YogaPlugin, assertDsarOrchestrator, authCheck, buildContext, buildWatchdogProbes, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createServerWatchdog, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getAllowedDsarOrchestrators, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, isDsarOrchestratorActor, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, readBoundedRawBody, requireWorkspace, resolveBodyLimitBytes, resolveDependencyWatchdogConfig, resolveDsarCallerIdentity, resolveMaxRequestBodySize, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, watchdogLivenessResponse, workspaceCheck };
@@ -1,5 +1,5 @@
1
- import { r as Logger } from "../index-CZWopQsh.js";
2
- import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-BmL-JjQK.js";
1
+ import { r as Logger } from "../index-PvHsCusi.js";
2
+ import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-DMq2xPV7.js";
3
3
  interface TelemetryIdGenerator {
4
4
  generateTraceId(): string;
5
5
  generateSpanId(): string;
@@ -1,5 +1,5 @@
1
1
  import { a as ActorOrigin, n as AI_ASSISTANT_ACTOR_ORIGIN, o as AssistantSessionAttribution } from "../assistant-session-DA5ZKJOr.js";
2
2
  import { t as suppressMutationAudit } from "../explicit-activity-scope-D8VeGGpt.js";
3
- import { p as UsageMetricType } from "../index-UQSbAERe.js";
4
- import { S as trackerStub, _ as UsageTrackingOptions, a as AGENT_ACTIVITY_RESOURCE_TYPE, b as resolveAssistantSession, c as trackAgentActivity, d as RbacCheckOptions, f as TrackedActorType, g as UnifiedTrackingOptions, h as UnifiedTrackerStub, i as AGENT_ACTIVITY_ACTIONS, l as ActivityTrackingOptions, m as UNIFIED_TRACKER_CONSTANTS, n as TrackResult, o as AgentActivityAction, p as TrackingEvent, r as TrackerModule, s as AgentActivityOptions, t as TrackOptions, u as ProductTracker, v as createProductTracker, x as trackOperation, y as isTrackedActorType } from "../index-Cs426iRP.js";
3
+ import { p as UsageMetricType } from "../index--w3AsbqC.js";
4
+ import { S as trackerStub, _ as UsageTrackingOptions, a as AGENT_ACTIVITY_RESOURCE_TYPE, b as resolveAssistantSession, c as trackAgentActivity, d as RbacCheckOptions, f as TrackedActorType, g as UnifiedTrackingOptions, h as UnifiedTrackerStub, i as AGENT_ACTIVITY_ACTIONS, l as ActivityTrackingOptions, m as UNIFIED_TRACKER_CONSTANTS, n as TrackResult, o as AgentActivityAction, p as TrackingEvent, r as TrackerModule, s as AgentActivityOptions, t as TrackOptions, u as ProductTracker, v as createProductTracker, x as trackOperation, y as isTrackedActorType } from "../index-DMKCyeBm.js";
5
5
  export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, AI_ASSISTANT_ACTOR_ORIGIN, type ActivityTrackingOptions, type ActorOrigin, type AgentActivityAction, type AgentActivityOptions, type AssistantSessionAttribution, type ProductTracker, type RbacCheckOptions, TrackOptions, TrackResult, type TrackedActorType, TrackerModule, type TrackingEvent, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, type UnifiedTrackingOptions, UsageMetricType, type UsageTrackingOptions, createProductTracker, isTrackedActorType, resolveAssistantSession, suppressMutationAudit, trackAgentActivity, trackOperation, trackerStub };
@@ -1,5 +1,5 @@
1
- import { t as BurdenoffGraphQLClient } from "../graphql-DcZAKC6p.js";
2
- import { m as SDKContext } from "../index-CQ3vxT5P.js";
1
+ import { t as BurdenoffGraphQLClient } from "../graphql-DPkc5IMZ.js";
2
+ import { m as SDKContext } from "../index-CDdrBQom.js";
3
3
  export type SupportedLanguage = 'en' | 'es' | 'fr' | 'de' | 'it' | 'pt' | 'ru' | 'zh' | 'ja' | 'ko' | 'ar' | 'hi' | 'bn' | 'ta' | 'te' | 'ml';
4
4
  export interface TranslationOptions {
5
5
  text: string;
@@ -1,3 +1,3 @@
1
1
  import { a as DEFAULT_LAYER_RESOURCES, c as GatewayRetryConfig, d as LayerFullConfig, f as LayerGatewayConfig, i as DEFAULT_GATEWAY_ROUTING, l as GatewayRoutingConfig, m as ServiceLayer, n as DEFAULT_CIRCUIT_BREAKER_CONFIG, o as DEFAULT_LAYER_STREAMS, p as LayerResourceUrls, r as DEFAULT_GATEWAY_RETRY_CONFIG, s as GatewayRequestHeaders, t as CircuitBreakerConfig, u as LayerConfig } from "../layer-C0zxAUgR.js";
2
- import { _ as SDKShutdownOptions, a as EventQueueHealthStatus, b as ValidationError, c as LoggerTransport, d as QuotaExceededError, f as RetryConfig, g as SDKHealthStatus, h as SDKError, i as CfAccessCredentials, l as NetworkError, m as SDKContext, n as ActorType, o as EventQueueSDKConfig, p as SDKConfig, r as AuthenticationError, s as LoggerConfig, t as APIError, u as PermissionDeniedError, v as TemporalHealthStatus, y as TimeoutError } from "../index-CQ3vxT5P.js";
2
+ import { _ as SDKShutdownOptions, a as EventQueueHealthStatus, b as ValidationError, c as LoggerTransport, d as QuotaExceededError, f as RetryConfig, g as SDKHealthStatus, h as SDKError, i as CfAccessCredentials, l as NetworkError, m as SDKContext, n as ActorType, o as EventQueueSDKConfig, p as SDKConfig, r as AuthenticationError, s as LoggerConfig, t as APIError, u as PermissionDeniedError, v as TemporalHealthStatus, y as TimeoutError } from "../index-CDdrBQom.js";
3
3
  export { APIError, ActorType, AuthenticationError, CfAccessCredentials, type CircuitBreakerConfig, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG, DEFAULT_GATEWAY_ROUTING, DEFAULT_LAYER_RESOURCES, DEFAULT_LAYER_STREAMS, EventQueueHealthStatus, EventQueueSDKConfig, type GatewayRequestHeaders, type GatewayRetryConfig, type GatewayRoutingConfig, type LayerConfig, type LayerFullConfig, type LayerGatewayConfig, type LayerResourceUrls, LoggerConfig, LoggerTransport, NetworkError, PermissionDeniedError, QuotaExceededError, RetryConfig, SDKConfig, SDKContext, SDKError, SDKHealthStatus, SDKShutdownOptions, type ServiceLayer, TemporalHealthStatus, TimeoutError, ValidationError };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["/**\n * Core type definitions for Burdenoff Backend SDK\n */\n\nimport type { ServiceLayer } from './layer.js';\n\n/**\n * SDK Configuration\n */\nexport interface SDKConfig {\n /** Workspaces API GraphQL endpoint (should point to wspace-int-gateway for M2M calls) */\n workspacesApiUrl: string;\n /**\n * Tenant API GraphQL endpoint for cross-layer (wspace → global) M2M calls.\n * Cross-layer traffic must go through the **public** global gateway\n * (`GLOBAL_PUBLIC_GATEWAY_URL`). In alpha and production this is the private\n * Route53 address of that gateway; the internal gateway is for same-layer calls.\n */\n tenantApiUrl?: string;\n /**\n * Calling service's layer (`wspace` | `global`). Used to construct the\n * cross-layer GatewayClient. Defaults to the `SERVICE_LAYER` env var, then\n * `wspace`.\n */\n serviceLayer?: ServiceLayer;\n /**\n * Calling service name. Used as the cross-layer GatewayClient service identity\n * and the `sub` of the minted service JWT. Defaults to the `SERVICE_NAME` env\n * var, then `burdenoff-be-sdk`.\n */\n serviceName?: string;\n /** Default timeout for API requests in milliseconds */\n timeout?: number;\n /** Retry configuration */\n retry?: RetryConfig;\n /** Logger configuration */\n logger?: LoggerConfig;\n /** Event queue configuration (Redis Streams). Reads `REDIS_URL` when present. */\n eventQueue?: EventQueueSDKConfig;\n /** Temporal module type (workspace or tenant) */\n temporalModuleType?: 'workspace' | 'tenant';\n /** Temporal server address */\n temporalAddress?: string;\n /** Temporal namespace */\n temporalNamespace?: string;\n /** Temporal task queue */\n temporalTaskQueue?: string;\n /** Auto-connect to Temporal (default: true) */\n temporalAutoConnect?: boolean;\n}\n\n/**\n * Retry configuration for API requests\n */\nexport interface RetryConfig {\n /** Maximum number of retry attempts */\n maxAttempts: number;\n /** Initial retry delay in milliseconds */\n initialDelay: number;\n /** Maximum retry delay in milliseconds */\n maxDelay: number;\n /** Backoff multiplier */\n backoffMultiplier: number;\n}\n\n/**\n * Logger configuration\n */\nexport interface LoggerConfig {\n /** Log level */\n level: 'debug' | 'info' | 'warn' | 'error';\n /** Enable console output */\n console: boolean;\n /** Custom logger transport */\n transport?: LoggerTransport;\n}\n\n/**\n * Custom logger transport interface\n */\nexport interface LoggerTransport {\n log(level: string, message: string, meta?: Record<string, unknown>): void;\n}\n\n/**\n * Actor type for RBAC authorization\n * - user: Direct user request (via frontend)\n * - app: OAuth app acting on behalf of user\n * - service: M2M service-to-service communication\n * - super_admin: Platform administration (bypasses all checks)\n */\nexport type ActorType = 'user' | 'app' | 'service' | 'super_admin';\n\n/**\n * Cloudflare Access credentials that one inbound request presented.\n *\n * Request-scoped: carried only inside the request's bound async scope (see\n * `WorkspaceContext.cfAccess` and `ContextManager.getCfAccessHeaders`), never\n * in module state, so one request's credentials cannot reach another request\n * or background work.\n */\nexport interface CfAccessCredentials {\n /** Service-token client id, from the inbound `cf-access-client-id` header. */\n clientId?: string;\n /** Service-token client secret, from `cf-access-client-secret`. Sensitive, never log it. */\n clientSecret?: string;\n /** The `CF_Authorization` cookie value, forwarded as `x-cf-authorization`. Sensitive, never log it. */\n authorization?: string;\n}\n\n/**\n * Request context passed with every SDK operation\n */\nexport interface SDKContext {\n /** Actor ID - identifies the entity making the request */\n actorId?: string;\n /** Actor type - determines authorization behavior */\n actorType?: ActorType;\n /** Workspace ID */\n workspaceId?: string;\n /** Organization routing context for gateway calls. */\n organizationId?: string;\n /** Tenant ID */\n tenantId?: string;\n /** Project ID */\n projectId?: string;\n /** App ID */\n appId?: string;\n /** JWT token for authentication */\n token?: string;\n /** Product ID */\n productId?: string;\n /**\n * Cloudflare Access service-token client id, captured from the inbound\n * `cf-access-client-id` header. Re-presented on cross-layer outbound calls so\n * the peer layer's CF-Access-gated public gateway admits the request.\n */\n cfAccessClientId?: string;\n /**\n * Cloudflare Access service-token client secret, from `cf-access-client-secret`.\n * Sensitive — redacted by the SDK logger's secret pattern; never log directly.\n */\n cfAccessClientSecret?: string;\n /**\n * Cloudflare Access USER-SSO credential — the `CF_Authorization` cookie value,\n * forwarded by the public gateway as `x-cf-authorization`. On alpha a real user\n * request carries this (not the service-token pair); re-presented as the\n * `CF_Authorization` cookie on cross-layer outbound calls so the peer layer's\n * CF-Access-gated public gateway (same CF-Access app / shared AUD) admits it.\n * Sensitive — never log directly. See BOFF-2929.\n */\n cfAuthorization?: string;\n /** Additional custom context */\n [key: string]: unknown;\n}\n\n/**\n * SDK Error base class\n */\nexport class SDKError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'SDKError';\n Object.setPrototypeOf(this, SDKError.prototype);\n }\n}\n\n/**\n * Permission denied error\n */\nexport class PermissionDeniedError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'PERMISSION_DENIED', details);\n this.name = 'PermissionDeniedError';\n Object.setPrototypeOf(this, PermissionDeniedError.prototype);\n }\n}\n\n/**\n * Authentication error\n */\nexport class AuthenticationError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'AUTHENTICATION_ERROR', details);\n this.name = 'AuthenticationError';\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\n/**\n * API error from backend\n */\nexport class APIError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'API_ERROR', details);\n this.name = 'APIError';\n Object.setPrototypeOf(this, APIError.prototype);\n }\n}\n\n/**\n * Validation error\n */\nexport class ValidationError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'VALIDATION_ERROR', details);\n this.name = 'ValidationError';\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\n/**\n * Quota exceeded error\n */\nexport class QuotaExceededError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'QUOTA_EXCEEDED', details);\n this.name = 'QuotaExceededError';\n Object.setPrototypeOf(this, QuotaExceededError.prototype);\n }\n}\n\n/**\n * Network error\n */\nexport class NetworkError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'NETWORK_ERROR', details);\n this.name = 'NetworkError';\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\n/**\n * Timeout error\n */\nexport class TimeoutError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'TIMEOUT_ERROR', details);\n this.name = 'TimeoutError';\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Event queue SDK configuration (Redis Streams backend).\n *\n * The publisher is created via `createPublisher()` from\n * `@burdenoff/be-sdk/event-queue` and reads `REDIS_URL` from the env.\n * The fields here are for client-name + reconnect tuning only.\n */\nexport interface EventQueueSDKConfig {\n /** Redis Streams server URL. Overrides `REDIS_URL` env if set. */\n url?: string;\n /** Optional password for TLS/auth */\n password?: string;\n /** Maximum reconnect attempts (default: -1 = infinite) */\n maxReconnectAttempts?: number;\n /** Reconnect time wait in milliseconds (default: 2000) */\n reconnectTimeWait?: number;\n /** Client name for logging (default: service name) */\n name?: string;\n /** Auto-connect on SDK initialization (default: true) */\n autoConnect?: boolean;\n}\n\n/**\n * Event queue health status\n */\nexport interface EventQueueHealthStatus {\n status: 'healthy' | 'unhealthy' | 'not_configured';\n connected: boolean;\n url?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Temporal health status\n */\nexport interface TemporalHealthStatus {\n status: 'healthy' | 'unhealthy' | 'not_configured';\n connected: boolean;\n address?: string;\n namespace?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Overall SDK health status\n */\nexport interface SDKHealthStatus {\n eventQueue: EventQueueHealthStatus;\n temporal: TemporalHealthStatus;\n}\n\n/**\n * SDK shutdown options\n */\nexport interface SDKShutdownOptions {\n /** Shutdown timeout in milliseconds (default: 5000) */\n timeout?: number;\n /** Force shutdown even if timeout is exceeded (default: true) */\n force?: boolean;\n}\n\n// ============================================================================\n// Layer Types Export\n// ============================================================================\n\n/**\n * Re-export all layer-related types for convenience\n */\nexport type {\n ServiceLayer,\n LayerConfig,\n LayerGatewayConfig,\n LayerResourceUrls,\n LayerFullConfig,\n GatewayRoutingConfig,\n CircuitBreakerConfig,\n GatewayRetryConfig,\n GatewayRequestHeaders,\n} from './layer.js';\n\nexport {\n DEFAULT_GATEWAY_ROUTING,\n DEFAULT_LAYER_RESOURCES,\n DEFAULT_LAYER_STREAMS,\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n} from './layer.js';\n"],"mappings":";;;;;;AA+JA,IAAa,WAAb,MAAa,iBAAiB,MAAM;CAGzB;CACA;CAHT,YACE,SACA,AAAO,MACP,AAAO,SACP;EACA,MAAM,OAAO;EAHN;EACA;EAGP,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,SAAS,SAAS;CAChD;AACF;;;;AAKA,IAAa,wBAAb,MAAa,8BAA8B,SAAS;CAClD,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,qBAAqB,OAAO;EAC3C,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,sBAAsB,SAAS;CAC7D;AACF;;;;AAKA,IAAa,sBAAb,MAAa,4BAA4B,SAAS;CAChD,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,wBAAwB,OAAO;EAC9C,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,oBAAoB,SAAS;CAC3D;AACF;;;;AAKA,IAAa,WAAb,MAAa,iBAAiB,SAAS;CACrC,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,aAAa,OAAO;EACnC,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,SAAS,SAAS;CAChD;AACF;;;;AAKA,IAAa,kBAAb,MAAa,wBAAwB,SAAS;CAC5C,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,oBAAoB,OAAO;EAC1C,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,gBAAgB,SAAS;CACvD;AACF;;;;AAKA,IAAa,qBAAb,MAAa,2BAA2B,SAAS;CAC/C,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,kBAAkB,OAAO;EACxC,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,mBAAmB,SAAS;CAC1D;AACF;;;;AAKA,IAAa,eAAb,MAAa,qBAAqB,SAAS;CACzC,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,iBAAiB,OAAO;EACvC,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,aAAa,SAAS;CACpD;AACF;;;;AAKA,IAAa,eAAb,MAAa,qBAAqB,SAAS;CACzC,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,iBAAiB,OAAO;EACvC,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,aAAa,SAAS;CACpD;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["/**\n * Core type definitions for Burdenoff Backend SDK\n */\n\nimport type { ServiceLayer } from './layer.js';\n\n/**\n * SDK Configuration\n */\nexport interface SDKConfig {\n /** Workspaces API GraphQL endpoint (should point to wspace-int-gateway for M2M calls) */\n workspacesApiUrl: string;\n /**\n * Tenant API GraphQL endpoint for cross-layer (wspace → global) M2M calls.\n * Cross-layer traffic must go through the **public** global gateway\n * (`GLOBAL_PUBLIC_GATEWAY_URL`). In alpha and production this is the private\n * Route53 address of that gateway; the internal gateway is for same-layer calls.\n */\n tenantApiUrl?: string;\n /**\n * Calling service's layer (`wspace` | `global`). Used to construct the\n * cross-layer GatewayClient. Defaults to the `SERVICE_LAYER` env var, then\n * `wspace`.\n */\n serviceLayer?: ServiceLayer;\n /**\n * Calling service name. Used as the cross-layer GatewayClient service identity\n * and the `sub` of the minted service JWT. Defaults to the `SERVICE_NAME` env\n * var, then `burdenoff-be-sdk`.\n */\n serviceName?: string;\n /** Default timeout for API requests in milliseconds */\n timeout?: number;\n /** Retry configuration */\n retry?: RetryConfig;\n /** Logger configuration */\n logger?: LoggerConfig;\n /** Event queue configuration (Redis Streams). Reads `REDIS_URL` when present. */\n eventQueue?: EventQueueSDKConfig;\n /** Temporal module type (workspace or tenant) */\n temporalModuleType?: 'workspace' | 'tenant';\n /** Temporal server address */\n temporalAddress?: string;\n /** Temporal namespace */\n temporalNamespace?: string;\n /** Temporal task queue */\n temporalTaskQueue?: string;\n /** Auto-connect to Temporal (default: true) */\n temporalAutoConnect?: boolean;\n}\n\n/**\n * Retry configuration for API requests\n */\nexport interface RetryConfig {\n /** Maximum number of retry attempts */\n maxAttempts: number;\n /** Initial retry delay in milliseconds */\n initialDelay: number;\n /** Maximum retry delay in milliseconds */\n maxDelay: number;\n /** Backoff multiplier */\n backoffMultiplier: number;\n}\n\n/**\n * Logger configuration\n */\nexport interface LoggerConfig {\n /** Log level */\n level: 'debug' | 'info' | 'warn' | 'error';\n /** Enable console output */\n console: boolean;\n /** Custom logger transport */\n transport?: LoggerTransport;\n}\n\n/**\n * Custom logger transport interface\n */\nexport interface LoggerTransport {\n log(level: string, message: string, meta?: Record<string, unknown>): void;\n}\n\n/**\n * Actor type for RBAC authorization\n * - user: Direct user request (via frontend)\n * - app: OAuth app acting on behalf of user\n * - service: M2M service-to-service communication\n * - super_admin: Platform administration (bypasses all checks)\n */\nexport type ActorType = 'user' | 'app' | 'service' | 'super_admin';\n\n/**\n * Cloudflare Access credentials that one inbound request presented.\n *\n * Request-scoped: carried only inside the request's bound async scope (see\n * `WorkspaceContext.cfAccess` and `ContextManager.getCfAccessHeaders`), never\n * in module state, so one request's credentials cannot reach another request\n * or background work.\n */\nexport interface CfAccessCredentials {\n /** Service-token client id, from the inbound `cf-access-client-id` header. */\n clientId?: string;\n /** Service-token client secret, from `cf-access-client-secret`. Sensitive, never log it. */\n clientSecret?: string;\n /** The `CF_Authorization` cookie value, forwarded as `x-cf-authorization`. Sensitive, never log it. */\n authorization?: string;\n}\n\n/**\n * Request context passed with every SDK operation\n */\nexport interface SDKContext {\n /** Actor ID - identifies the entity making the request */\n actorId?: string;\n /** Actor type - determines authorization behavior */\n actorType?: ActorType;\n /** Workspace ID */\n workspaceId?: string;\n /** Organization routing context for gateway calls. */\n organizationId?: string;\n /** Tenant ID */\n tenantId?: string;\n /** Project ID */\n projectId?: string;\n /** App ID */\n appId?: string;\n /** JWT token for authentication */\n token?: string;\n /** Product ID */\n productId?: string;\n /**\n * Cloudflare Access service-token client id, captured from the inbound\n * `cf-access-client-id` header. Re-presented on cross-layer outbound calls so\n * the peer layer's CF-Access-gated public gateway admits the request.\n */\n cfAccessClientId?: string;\n /**\n * Cloudflare Access service-token client secret, from `cf-access-client-secret`.\n * Sensitive — redacted by the SDK logger's secret pattern; never log directly.\n */\n cfAccessClientSecret?: string;\n /**\n * Cloudflare Access USER-SSO credential — the `CF_Authorization` cookie value,\n * forwarded by the public gateway as `x-cf-authorization`. On alpha a real user\n * request carries this (not the service-token pair); re-presented as the\n * `CF_Authorization` cookie on cross-layer outbound calls so the peer layer's\n * CF-Access-gated public gateway (same CF-Access app / shared AUD) admits it.\n * Sensitive — never log directly. See BOFF-2929.\n */\n cfAuthorization?: string;\n /** Additional custom context */\n [key: string]: unknown;\n}\n\n/**\n * SDK Error base class\n */\nexport class SDKError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'SDKError';\n Object.setPrototypeOf(this, SDKError.prototype);\n }\n}\n\n/**\n * Permission denied error\n */\nexport class PermissionDeniedError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'PERMISSION_DENIED', details);\n this.name = 'PermissionDeniedError';\n Object.setPrototypeOf(this, PermissionDeniedError.prototype);\n }\n}\n\n/**\n * Authentication error\n */\nexport class AuthenticationError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'AUTHENTICATION_ERROR', details);\n this.name = 'AuthenticationError';\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\n/**\n * API error from backend\n */\nexport class APIError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'API_ERROR', details);\n this.name = 'APIError';\n Object.setPrototypeOf(this, APIError.prototype);\n }\n}\n\n/**\n * Validation error\n */\nexport class ValidationError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'VALIDATION_ERROR', details);\n this.name = 'ValidationError';\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\n/**\n * Quota exceeded error\n */\nexport class QuotaExceededError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'QUOTA_EXCEEDED', details);\n this.name = 'QuotaExceededError';\n Object.setPrototypeOf(this, QuotaExceededError.prototype);\n }\n}\n\n/**\n * Network error\n */\nexport class NetworkError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'NETWORK_ERROR', details);\n this.name = 'NetworkError';\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\n/**\n * Timeout error\n */\nexport class TimeoutError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'TIMEOUT_ERROR', details);\n this.name = 'TimeoutError';\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Event queue SDK configuration (Redis Streams backend).\n *\n * The publisher is created via `createPublisher()` from\n * `@burdenoff/be-sdk/event-queue` and reads `REDIS_URL` from the env.\n * The fields here are for client-name + reconnect tuning only.\n */\nexport interface EventQueueSDKConfig {\n /** Redis Streams server URL. Overrides `REDIS_STREAMS_URL` / `REDIS_URL` env if set. */\n url?: string;\n /** Optional password for TLS/auth */\n password?: string;\n /** Optional connection-local key scope (`''` selects the unscoped shared bus). */\n keyScope?: string;\n /** Maximum reconnect attempts (default: -1 = infinite) */\n maxReconnectAttempts?: number;\n /** Reconnect time wait in milliseconds (default: 2000) */\n reconnectTimeWait?: number;\n /** Client name for logging (default: service name) */\n name?: string;\n /** Auto-connect on SDK initialization (default: true) */\n autoConnect?: boolean;\n}\n\n/**\n * Event queue health status\n */\nexport interface EventQueueHealthStatus {\n status: 'healthy' | 'unhealthy' | 'not_configured';\n connected: boolean;\n url?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Temporal health status\n */\nexport interface TemporalHealthStatus {\n status: 'healthy' | 'unhealthy' | 'not_configured';\n connected: boolean;\n address?: string;\n namespace?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Overall SDK health status\n */\nexport interface SDKHealthStatus {\n eventQueue: EventQueueHealthStatus;\n temporal: TemporalHealthStatus;\n}\n\n/**\n * SDK shutdown options\n */\nexport interface SDKShutdownOptions {\n /** Shutdown timeout in milliseconds (default: 5000) */\n timeout?: number;\n /** Force shutdown even if timeout is exceeded (default: true) */\n force?: boolean;\n}\n\n// ============================================================================\n// Layer Types Export\n// ============================================================================\n\n/**\n * Re-export all layer-related types for convenience\n */\nexport type {\n ServiceLayer,\n LayerConfig,\n LayerGatewayConfig,\n LayerResourceUrls,\n LayerFullConfig,\n GatewayRoutingConfig,\n CircuitBreakerConfig,\n GatewayRetryConfig,\n GatewayRequestHeaders,\n} from './layer.js';\n\nexport {\n DEFAULT_GATEWAY_ROUTING,\n DEFAULT_LAYER_RESOURCES,\n DEFAULT_LAYER_STREAMS,\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n} from './layer.js';\n"],"mappings":";;;;;;AA+JA,IAAa,WAAb,MAAa,iBAAiB,MAAM;CAGzB;CACA;CAHT,YACE,SACA,AAAO,MACP,AAAO,SACP;EACA,MAAM,OAAO;EAHN;EACA;EAGP,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,SAAS,SAAS;CAChD;AACF;;;;AAKA,IAAa,wBAAb,MA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./client-NknQrWsP.js";
2
- import { c as WorkspaceExtensionConfig } from "./workspace-extension-C0qib11C.js";
2
+ import { c as WorkspaceExtensionConfig } from "./workspace-extension-DAs06Hv_.js";
3
3
  import { r as I18nContext, s as LocaleCode } from "./types-DgaQqvxo.js";
4
4
  import { o as AssistantSessionAttribution } from "./assistant-session-DA5ZKJOr.js";
5
5
  import { GraphQLSchema } from "graphql";
@@ -1,2 +1,2 @@
1
- import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, _ as UsageSummary, a as Quota, b as BillingUsageClient, c as SetQuotaOptions, d as TrackWorkspaceUsageOptions, f as UsageEntityType, g as UsageRecord, h as UsageOperationUnsupportedError, i as GetUsageOptions, l as TRACK_USAGE_MUTATION, m as UsageModule, n as CheckQuotaOptions, o as QuotaCheckResult, p as UsageMetricType, r as CheckWorkspaceQuotaOptions, s as QuotaPeriod, t as CHECK_WORKSPACE_QUOTA_QUERY, u as TrackUsageOptions, v as WorkspaceQuotaCheckResult, w as QuotaLimit, x as BillingUsageClientConfig, y as buildTrackUsageInput } from "../index-UQSbAERe.js";
1
+ import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, _ as UsageSummary, a as Quota, b as BillingUsageClient, c as SetQuotaOptions, d as TrackWorkspaceUsageOptions, f as UsageEntityType, g as UsageRecord, h as UsageOperationUnsupportedError, i as GetUsageOptions, l as TRACK_USAGE_MUTATION, m as UsageModule, n as CheckQuotaOptions, o as QuotaCheckResult, p as UsageMetricType, r as CheckWorkspaceQuotaOptions, s as QuotaPeriod, t as CHECK_WORKSPACE_QUOTA_QUERY, u as TrackUsageOptions, v as WorkspaceQuotaCheckResult, w as QuotaLimit, x as BillingUsageClientConfig, y as buildTrackUsageInput } from "../index--w3AsbqC.js";
2
2
  export { BillingUsageClient, type BillingUsageClientConfig, type BillingUsageOperationInput, CHECK_WORKSPACE_QUOTA_QUERY, CheckQuotaOptions, CheckWorkspaceQuotaOptions, GetUsageOptions, type OrgBillingUsageOperationInput, Quota, QuotaCheckResult, type QuotaLimit, QuotaPeriod, SetQuotaOptions, TRACK_USAGE_MUTATION, TrackUsageOptions, TrackWorkspaceUsageOptions, UsageEntityType, UsageMetricType, UsageModule, UsageOperationUnsupportedError, UsageRecord, UsageSummary, type WorkspaceBillingUsageOperationInput, WorkspaceQuotaCheckResult, buildTrackUsageInput };
@@ -1,5 +1,5 @@
1
1
  import { o as AssistantSessionAttribution } from "./assistant-session-DA5ZKJOr.js";
2
- import { i as CfAccessCredentials } from "./index-CQ3vxT5P.js";
2
+ import { i as CfAccessCredentials } from "./index-CDdrBQom.js";
3
3
  interface WorkspaceContext {
4
4
  workspaceId?: string;
5
5
  tenantId?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/be-sdk",
3
- "version": "2026.1202.4",
3
+ "version": "2026.1202.6",
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,74 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
-
3
- // src/event-queue/env.ts
4
- var env_exports = /* @__PURE__ */ __exportAll({ resolveEventStreamsUrl: () => resolveEventStreamsUrl });
5
- /**
6
- * Event-bus connection resolution.
7
- *
8
- * Redis Streams is the fleet event bus. Which URL a service uses for it:
9
- *
10
- * 1. `REDIS_STREAMS_URL` - explicit event-bus URL. Optional; no bundle sets
11
- * it today. Use it when a service's cache `REDIS_URL` carries a DB index
12
- * (`.../14`) that must not leak into the event keyspace.
13
- * 2. `REDIS_URL` - the historical default, read by every service today.
14
- *
15
- * Graph events resolve `GRAPH_REDIS_URL` first (graph-svc's own channel), then
16
- * fall back to the same chain.
17
- *
18
- * The DB index in the chosen URL is not a database selection: the connection
19
- * always lands on DB 0 and the index becomes a key prefix (`db14:boff:events:...`,
20
- * see `keyspace.ts`). A producer and its consumers therefore only see each
21
- * other when their URLs resolve to the same host AND the same index.
22
- */
23
- /** Environment variables consulted for the stream bus, in priority order. */
24
- const EVENT_STREAMS_URL_ENV_KEYS = ["REDIS_STREAMS_URL", "REDIS_URL"];
25
- /** Environment variables consulted for graph events, in priority order. */
26
- const GRAPH_EVENTS_URL_ENV_KEYS = ["GRAPH_REDIS_URL", ...EVENT_STREAMS_URL_ENV_KEYS];
27
- function firstNonEmpty(keys, env) {
28
- for (const key of keys) {
29
- const value = env[key]?.trim();
30
- if (value) return {
31
- key,
32
- url: value
33
- };
34
- }
35
- }
36
- /**
37
- * The event-bus URL (`REDIS_STREAMS_URL`, else `REDIS_URL`), or `undefined`
38
- * when neither is set (callers fall back to the in-memory bus).
39
- */
40
- function resolveEventStreamsUrl(env = process.env) {
41
- return firstNonEmpty(EVENT_STREAMS_URL_ENV_KEYS, env)?.url;
42
- }
43
- /** Name of the env var that supplied the event-bus URL, for diagnostics. */
44
- function resolveEventStreamsUrlSource(env = process.env) {
45
- return firstNonEmpty(EVENT_STREAMS_URL_ENV_KEYS, env)?.key;
46
- }
47
- /** The graph-event URL (`GRAPH_REDIS_URL`, else the event-bus chain). */
48
- function resolveGraphEventsUrl(env = process.env) {
49
- return firstNonEmpty(GRAPH_EVENTS_URL_ENV_KEYS, env)?.url;
50
- }
51
- /** Name of the env var that supplied the graph-event URL, for diagnostics. */
52
- function resolveGraphEventsUrlSource(env = process.env) {
53
- return firstNonEmpty(GRAPH_EVENTS_URL_ENV_KEYS, env)?.key;
54
- }
55
- /**
56
- * Key scope the URL will produce (`db14:` for `.../14`, `''` for DB 0 or no
57
- * index). Lets a service log, at startup, which keyspace it publishes to or
58
- * consumes from - the usual cause of a consumer that "subscribes fine and
59
- * never fires" is a producer on a different index.
60
- */
61
- function eventKeyScopeForUrl(url) {
62
- if (!url) return "";
63
- try {
64
- const pathDb = new URL(url.replace(/^valkeys?:\/\//, "redis://")).pathname.replace(/^\//, "");
65
- if (/^\d+$/.test(pathDb)) {
66
- const index = parseInt(pathDb, 10);
67
- return index > 0 ? `db${String(index)}:` : "";
68
- }
69
- } catch {}
70
- return "";
71
- }
72
-
73
- export { resolveEventStreamsUrl as a, resolveGraphEventsUrlSource as c, eventKeyScopeForUrl as i, GRAPH_EVENTS_URL_ENV_KEYS as n, resolveEventStreamsUrlSource as o, env_exports as r, resolveGraphEventsUrl as s, EVENT_STREAMS_URL_ENV_KEYS as t };
74
- //# sourceMappingURL=env-DdaoGjIt.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"env-DdaoGjIt.js","names":[],"sources":["../src/event-queue/env.ts"],"sourcesContent":["/**\n * Event-bus connection resolution.\n *\n * Redis Streams is the fleet event bus. Which URL a service uses for it:\n *\n * 1. `REDIS_STREAMS_URL` - explicit event-bus URL. Optional; no bundle sets\n * it today. Use it when a service's cache `REDIS_URL` carries a DB index\n * (`.../14`) that must not leak into the event keyspace.\n * 2. `REDIS_URL` - the historical default, read by every service today.\n *\n * Graph events resolve `GRAPH_REDIS_URL` first (graph-svc's own channel), then\n * fall back to the same chain.\n *\n * The DB index in the chosen URL is not a database selection: the connection\n * always lands on DB 0 and the index becomes a key prefix (`db14:boff:events:...`,\n * see `keyspace.ts`). A producer and its consumers therefore only see each\n * other when their URLs resolve to the same host AND the same index.\n */\n\n/** Environment variables consulted for the stream bus, in priority order. */\nexport const EVENT_STREAMS_URL_ENV_KEYS = ['REDIS_STREAMS_URL', 'REDIS_URL'] as const;\n\n/** Environment variables consulted for graph events, in priority order. */\nexport const GRAPH_EVENTS_URL_ENV_KEYS = ['GRAPH_REDIS_URL', ...EVENT_STREAMS_URL_ENV_KEYS] as const;\n\ntype EnvSource = Readonly<Record<string, string | undefined>>;\n\nfunction firstNonEmpty(keys: readonly string[], env: EnvSource): { key: string; url: string } | undefined {\n for (const key of keys) {\n const value = env[key]?.trim();\n if (value) return { key, url: value };\n }\n return undefined;\n}\n\n/**\n * The event-bus URL (`REDIS_STREAMS_URL`, else `REDIS_URL`), or `undefined`\n * when neither is set (callers fall back to the in-memory bus).\n */\nexport function resolveEventStreamsUrl(env: EnvSource = process.env): string | undefined {\n return firstNonEmpty(EVENT_STREAMS_URL_ENV_KEYS, env)?.url;\n}\n\n/** Name of the env var that supplied the event-bus URL, for diagnostics. */\nexport function resolveEventStreamsUrlSource(env: EnvSource = process.env): string | undefined {\n return firstNonEmpty(EVENT_STREAMS_URL_ENV_KEYS, env)?.key;\n}\n\n/** The graph-event URL (`GRAPH_REDIS_URL`, else the event-bus chain). */\nexport function resolveGraphEventsUrl(env: EnvSource = process.env): string | undefined {\n return firstNonEmpty(GRAPH_EVENTS_URL_ENV_KEYS, env)?.url;\n}\n\n/** Name of the env var that supplied the graph-event URL, for diagnostics. */\nexport function resolveGraphEventsUrlSource(env: EnvSource = process.env): string | undefined {\n return firstNonEmpty(GRAPH_EVENTS_URL_ENV_KEYS, env)?.key;\n}\n\n/**\n * Key scope the URL will produce (`db14:` for `.../14`, `''` for DB 0 or no\n * index). Lets a service log, at startup, which keyspace it publishes to or\n * consumes from - the usual cause of a consumer that \"subscribes fine and\n * never fires\" is a producer on a different index.\n */\nexport function eventKeyScopeForUrl(url: string | undefined): string {\n if (!url) return '';\n try {\n const parsed = new URL(url.replace(/^valkeys?:\\/\\//, 'redis://'));\n const pathDb = parsed.pathname.replace(/^\\//, '');\n if (/^\\d+$/.test(pathDb)) {\n const index = parseInt(pathDb, 10);\n return index > 0 ? `db${String(index)}:` : '';\n }\n } catch {\n // Unparseable URLs are rejected by the connection itself; no scope here.\n }\n return '';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,6BAA6B,CAAC,qBAAqB,WAAW;;AAG3E,MAAa,4BAA4B,CAAC,mBAAmB,GAAG,0BAA0B;AAI1F,SAAS,cAAc,MAAyB,KAA0D;CACxG,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,QAAQ,IAAI,IAAI,EAAE,KAAK;EAC7B,IAAI,OAAO,OAAO;GAAE;GAAK,KAAK;EAAM;CACtC;AAEF;;;;;AAMA,SAAgB,uBAAuB,MAAiB,QAAQ,KAAyB;CACvF,OAAO,cAAc,4BAA4B,GAAG,CAAC,EAAE;AACzD;;AAGA,SAAgB,6BAA6B,MAAiB,QAAQ,KAAyB;CAC7F,OAAO,cAAc,4BAA4B,GAAG,CAAC,EAAE;AACzD;;AAGA,SAAgB,sBAAsB,MAAiB,QAAQ,KAAyB;CACtF,OAAO,cAAc,2BAA2B,GAAG,CAAC,EAAE;AACxD;;AAGA,SAAgB,4BAA4B,MAAiB,QAAQ,KAAyB;CAC5F,OAAO,cAAc,2BAA2B,GAAG,CAAC,EAAE;AACxD;;;;;;;AAQA,SAAgB,oBAAoB,KAAiC;CACnE,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI;EAEF,MAAM,SAAS,IADI,IAAI,IAAI,QAAQ,kBAAkB,UAAU,CAC3C,CAAC,CAAC,SAAS,QAAQ,OAAO,EAAE;EAChD,IAAI,QAAQ,KAAK,MAAM,GAAG;GACxB,MAAM,QAAQ,SAAS,QAAQ,EAAE;GACjC,OAAO,QAAQ,IAAI,KAAK,OAAO,KAAK,EAAE,KAAK;EAC7C;CACF,QAAQ,CAER;CACA,OAAO;AACT"}