@burdenoff/be-sdk 2026.1027.2 → 2026.1028.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/ai-credits/index.d.ts +3 -3
  2. package/dist/ai-credits/index.js +1 -1
  3. package/dist/assistant-session-CJZhF4D6.d.ts +15 -0
  4. package/dist/auth/index.d.ts +6 -5
  5. package/dist/auth/index.js +1 -1
  6. package/dist/cache/index.d.ts +2 -2
  7. package/dist/cache/index.js +2 -2
  8. package/dist/{chunk-YFOHAHZE.js → chunk-5CAFHK2Z.js} +2 -2
  9. package/dist/{chunk-YFOHAHZE.js.map → chunk-5CAFHK2Z.js.map} +1 -1
  10. package/dist/{chunk-QUF27D73.js → chunk-5RBIDJBZ.js} +3 -3
  11. package/dist/{chunk-QUF27D73.js.map → chunk-5RBIDJBZ.js.map} +1 -1
  12. package/dist/{chunk-JTG6GZTF.js → chunk-E36LPO3K.js} +4 -4
  13. package/dist/{chunk-JTG6GZTF.js.map → chunk-E36LPO3K.js.map} +1 -1
  14. package/dist/{chunk-3Z2VRCT6.js → chunk-E4QNLVY4.js} +7 -3
  15. package/dist/chunk-E4QNLVY4.js.map +1 -0
  16. package/dist/{chunk-6HO5AJ3U.js → chunk-FYFA7WAS.js} +3 -3
  17. package/dist/{chunk-6HO5AJ3U.js.map → chunk-FYFA7WAS.js.map} +1 -1
  18. package/dist/{chunk-HZTDMERF.js → chunk-GKOAAC6D.js} +3 -3
  19. package/dist/{chunk-HZTDMERF.js.map → chunk-GKOAAC6D.js.map} +1 -1
  20. package/dist/{chunk-GP766LND.js → chunk-NBN52AEM.js} +2 -2
  21. package/dist/{chunk-GP766LND.js.map → chunk-NBN52AEM.js.map} +1 -1
  22. package/dist/{chunk-OXGIVASV.js → chunk-PAQK3YF2.js} +3 -3
  23. package/dist/{chunk-OXGIVASV.js.map → chunk-PAQK3YF2.js.map} +1 -1
  24. package/dist/{chunk-X3MNBBOL.js → chunk-PNWFTWBQ.js} +3 -3
  25. package/dist/{chunk-X3MNBBOL.js.map → chunk-PNWFTWBQ.js.map} +1 -1
  26. package/dist/{chunk-5JNHVKHG.js → chunk-PQGMZH6K.js} +3 -3
  27. package/dist/{chunk-5JNHVKHG.js.map → chunk-PQGMZH6K.js.map} +1 -1
  28. package/dist/{chunk-VSP2QCEW.js → chunk-QCOC2SF3.js} +4 -3
  29. package/dist/chunk-QCOC2SF3.js.map +1 -0
  30. package/dist/{chunk-UCNTCCV6.js → chunk-QGADOWSG.js} +4 -4
  31. package/dist/{chunk-UCNTCCV6.js.map → chunk-QGADOWSG.js.map} +1 -1
  32. package/dist/chunk-RM6AIMZT.js +51 -0
  33. package/dist/chunk-RM6AIMZT.js.map +1 -0
  34. package/dist/{chunk-5NT2OEDQ.js → chunk-STWFX5E2.js} +3 -3
  35. package/dist/{chunk-5NT2OEDQ.js.map → chunk-STWFX5E2.js.map} +1 -1
  36. package/dist/{chunk-YNDJQRI3.js → chunk-VXVLKRU6.js} +3 -3
  37. package/dist/{chunk-YNDJQRI3.js.map → chunk-VXVLKRU6.js.map} +1 -1
  38. package/dist/{chunk-Q3SWU4VF.js → chunk-W5Q6JJWA.js} +57 -7
  39. package/dist/chunk-W5Q6JJWA.js.map +1 -0
  40. package/dist/{chunk-OPUC6PYJ.js → chunk-ZJVFK33K.js} +4 -4
  41. package/dist/{chunk-OPUC6PYJ.js.map → chunk-ZJVFK33K.js.map} +1 -1
  42. package/dist/{client-WSFUJHLI.js → client-7DW6EYSA.js} +5 -5
  43. package/dist/{client-WSFUJHLI.js.map → client-7DW6EYSA.js.map} +1 -1
  44. package/dist/database/index.js +1 -1
  45. package/dist/event-queue/index.d.ts +4 -4
  46. package/dist/export/index.d.ts +2 -2
  47. package/dist/export/index.js +6 -6
  48. package/dist/feature-flags/index.d.ts +4 -3
  49. package/dist/files/index.d.ts +3 -3
  50. package/dist/files/index.js +1 -1
  51. package/dist/gateway/index.d.ts +3 -3
  52. package/dist/gateway/index.js +5 -5
  53. package/dist/gateway/security/index.js +1 -1
  54. package/dist/graph/index.d.ts +4 -4
  55. package/dist/graph/index.js +1 -1
  56. package/dist/{graphql-AaLJfGzz.d.ts → graphql-BUbw43Zx.d.ts} +1 -1
  57. package/dist/{index-DG5lCWNk.d.ts → index-3ZE1m-ZJ.d.ts} +2 -2
  58. package/dist/{index-B0ebYV9W.d.ts → index-5x0XMKXN.d.ts} +1 -1
  59. package/dist/{index-Rc5EphmY.d.ts → index-B2YkcG0J.d.ts} +1 -1
  60. package/dist/{index-DMlr5R6K.d.ts → index-BKOBmdq7.d.ts} +2 -2
  61. package/dist/{index-CL7koBpQ.d.ts → index-BTMt4OjA.d.ts} +3 -2
  62. package/dist/{index-Cx5I3ydM.d.ts → index-BvkVcW8I.d.ts} +1 -1
  63. package/dist/{index-CfRZtB99.d.ts → index-CV3r9Taj.d.ts} +1 -1
  64. package/dist/{index-B4ciT3OZ.d.ts → index-CWmH_-RZ.d.ts} +1 -1
  65. package/dist/{index-CN4RA1PN.d.ts → index-CbgWNcus.d.ts} +1 -1
  66. package/dist/{index-Dvv6irk0.d.ts → index-Coua7_P7.d.ts} +1 -1
  67. package/dist/{index-CVX5nRuw.d.ts → index-DJCb-l2J.d.ts} +7 -4
  68. package/dist/{index-BWhuZl8f.d.ts → index-Dcq8OduH.d.ts} +14 -4
  69. package/dist/{index-HxigeZFh.d.ts → index-DieBtd0X.d.ts} +1 -1
  70. package/dist/{index-BKafOO7G.d.ts → index-Dtj9Eer3.d.ts} +1 -1
  71. package/dist/{index-CqNXOs72.d.ts → index-JTx7ZQHe.d.ts} +3 -3
  72. package/dist/{index-C_t30VyQ.d.ts → index-aHtYvc3i.d.ts} +1 -1
  73. package/dist/{index-BCUkR8sC.d.ts → index-ffmipXSA.d.ts} +1 -1
  74. package/dist/index.d.ts +28 -27
  75. package/dist/index.js +20 -20
  76. package/dist/init/index.d.ts +2 -2
  77. package/dist/init/index.js +6 -6
  78. package/dist/instrumentation/index.d.ts +4 -4
  79. package/dist/layer/index.d.ts +2 -2
  80. package/dist/layer/index.js +2 -2
  81. package/dist/{layer-GNAVXBMf.d.ts → layer-Cv9vSwBx.d.ts} +1 -0
  82. package/dist/logger/index.d.ts +3 -3
  83. package/dist/notifications/index.d.ts +4 -4
  84. package/dist/notifications/index.js +1 -1
  85. package/dist/prisma/index.d.ts +3 -2
  86. package/dist/prisma/index.js +2 -2
  87. package/dist/rbac/index.d.ts +3 -3
  88. package/dist/rbac/index.js +2 -2
  89. package/dist/resource-caps/index.d.ts +3 -3
  90. package/dist/server/index.d.ts +21 -4
  91. package/dist/server/index.js +45 -25
  92. package/dist/server/index.js.map +1 -1
  93. package/dist/tags/index.d.ts +3 -3
  94. package/dist/tags/index.js +1 -1
  95. package/dist/telemetry/index.d.ts +5 -5
  96. package/dist/temporal/index.d.ts +1 -1
  97. package/dist/temporal/index.js +2 -2
  98. package/dist/tracker/index.d.ts +6 -5
  99. package/dist/tracker/index.js +5 -5
  100. package/dist/{types-C-6m9NoG.d.ts → types-DLFCJD3D.d.ts} +3 -1
  101. package/dist/{types-B376RbyK.d.ts → types-DgJ4lDYA.d.ts} +1 -1
  102. package/dist/{workspace-extension-DiNiTLa3.d.ts → workspace-extension-BGwTOV_r.d.ts} +5 -1
  103. package/package.json +1 -1
  104. package/dist/chunk-3Z2VRCT6.js.map +0 -1
  105. package/dist/chunk-KGJ7LPE7.js +0 -22
  106. package/dist/chunk-KGJ7LPE7.js.map +0 -1
  107. package/dist/chunk-Q3SWU4VF.js.map +0 -1
  108. package/dist/chunk-VSP2QCEW.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { withWorkspaceContextSync, withWorkspaceContext, setWorkspaceContext, runOperationWithRlsGuc, runOperationInCallerTransaction, resetCallerTransactionStateForTests, maybeTagConnection, maybeSetRlsGuc, injectWhereWorkspaceId, injectCreateFields, getWorkspaceContext, getCallerTransaction, defaultWorkspaceExtensionConfig, buildTransactionContextStatement, addWorkspaceExtension } from './chunk-3Z2VRCT6.js';
1
+ import { withWorkspaceContextSync, withWorkspaceContext, setWorkspaceContext, runOperationWithRlsGuc, runOperationInCallerTransaction, resetCallerTransactionStateForTests, maybeTagConnection, maybeSetRlsGuc, injectWhereWorkspaceId, injectCreateFields, getWorkspaceContext, getScopedWorkspaceContext, getCallerTransaction, defaultWorkspaceExtensionConfig, buildTransactionContextStatement, addWorkspaceExtension } from './chunk-E4QNLVY4.js';
2
2
  import { productSlugVariants, isSameProductSlug } from './chunk-OBBCR6WY.js';
3
3
  import { isTransientAcquireError, installAcquireRetry, ensureServiceApplicationName, createPrismaClient, createPrismaAdapter, createConnectionPool, configurePrismaLogging, PrismaClientWrapper, addGraphExtension } from './chunk-K52ICDCP.js';
4
4
  import { getGraphEventEmitter } from './chunk-TX2GDIWP.js';
@@ -34,6 +34,7 @@ __export(prisma_exports, {
34
34
  getDatabaseVersion: () => getDatabaseVersion,
35
35
  getDb: () => getDb,
36
36
  getModelFields: () => getModelFields,
37
+ getScopedWorkspaceContext: () => getScopedWorkspaceContext,
37
38
  getWorkspaceContext: () => getWorkspaceContext,
38
39
  hasModel: () => hasModel,
39
40
  initializeDatabase: () => initializeDatabase,
@@ -685,5 +686,5 @@ function createContextFromSDK(sdkContext) {
685
686
  __name(createContextFromSDK, "createContextFromSDK");
686
687
 
687
688
  export { buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, contextMatches, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, prisma_exports, resetDatabaseManager, resolvePoolTuningFromEnv, testConnection, toContextJson };
688
- //# sourceMappingURL=chunk-VSP2QCEW.js.map
689
- //# sourceMappingURL=chunk-VSP2QCEW.js.map
689
+ //# sourceMappingURL=chunk-QCOC2SF3.js.map
690
+ //# sourceMappingURL=chunk-QCOC2SF3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/prisma/index.ts","../src/prisma/factory.ts","../src/prisma/manager.ts","../src/prisma/health.ts","../src/prisma/fields.ts","../src/prisma/context.ts"],"names":["resolveWorkspaceExtensionDefault","productName","explicit","process","env","layer","toLowerCase","name","startsWith","createDatabaseClient","PrismaClientConstructor","config","enableGraphExtension","graphEventEmitter","enableWorkspaceExtension","workspaceExtensionConfig","registerShutdownHandlers","prismaConfig","prismaConfigWithDefaults","applicationName","ensureServiceApplicationName","wrapper","createPrismaClient","baseClient","getClient","extendedClient","eventEmitter","getGraphEventEmitter","graphConfig","enabled","addGraphExtension","logger","info","addWorkspaceExtension","db","debug","connect","retries","delay","disconnect","parsePositiveIntEnv","raw","trim","undefined","parsed","Number","parseInt","isFinite","resolvePoolTuningFromEnv","tuning","queryTimeout","queryTimeoutMillis","statementTimeout","statementTimeoutMillis","idleInTransactionTimeout","idleInTransactionTimeoutMillis","lockTimeout","lockTimeoutMillis","createDatabaseClientFromEnv","overrides","databaseUrl","Error","isDevelopment","maxConnections","idleTimeoutMillis","connectionTimeoutMillis","enableQueryLogging","slowQueryThreshold","acquireRetriesRaw","acquireRetries","acquireRetryDelay","acquireRetryDelayMillis","state","initialized","client","initializeDatabase","initializeDatabaseWithConfig","getDb","getDatabaseManager","isDatabaseInitialized","getDatabaseProductName","resetDatabaseManager","error","warn","checkDatabaseHealth","start","Date","now","$queryRaw","latency","healthy","errorMessage","message","String","testConnection","getDatabaseVersion","result","version","getDatabaseStats","health","Promise","all","timestamp","requireFn","createRequire","url","loadGeneratedFields","generatedFieldsPath","generated","default","path","extractFieldsFromModel","modelName","modelFieldsMap","options","modelFields","Object","keys","join","excludeFields","includeRelations","customFilter","fields","relations","excluded","length","filter","field","includes","push","fieldName","isRelation","shouldInclude","type","metadata","totalFields","excludedCount","excludedFields","relationFields","getModelFields","hasModel","getAllModelNames","buildContextWhereClause","contextFilter","conditions","workspaceId","equals","userId","projectId","appId","productId","organizationId","buildContextWhereConditions","context","slugs","productSlugVariants","OR","map","slug","toContextJson","contextInput","custom","filterNullValues","obj","filtered","key","value","entries","mergeContextField","merged","fieldValue","mergeContext","existingContext","newContext","Array","isArray","parseContext","contextJson","ctx","contextMatches","isSameProductSlug","createContextFromSDK","sdkContext"],"mappings":";;;;;;;;;AAAA,IAAA,cAAA,GAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC8GA,SAASA,iCAAiCC,WAAAA,EAAmB;AAC3D,EAAA,MAAMC,QAAAA,GAAWC,OAAAA,CAAQC,GAAAA,CAAI,6BAAA,CAAA;AAC7B,EAAA,IAAIF,QAAAA,KAAa,QAAQ,OAAO,IAAA;AAChC,EAAA,IAAIA,QAAAA,KAAa,SAAS,OAAO,KAAA;AAEjC,EAAA,MAAMG,KAAAA,GAAQF,OAAAA,CAAQC,GAAAA,CAAI,iBAAA,GAAoBE,WAAAA,EAAAA;AAC9C,EAAA,IAAID,KAAAA,KAAU,UAAU,OAAO,KAAA;AAC/B,EAAA,IAAIA,KAAAA,KAAU,UAAU,OAAO,IAAA;AAE/B,EAAA,MAAME,IAAAA,GAAON,YAAYK,WAAAA,EAAW;AACpC,EAAA,IAAIC,IAAAA,CAAKC,WAAW,SAAA,CAAA,IAAcD,KAAKC,UAAAA,CAAW,SAAA,GAAY,OAAO,KAAA;AACrE,EAAA,OAAO,IAAA;AACT;AAZSR,MAAAA,CAAAA,gCAAAA,EAAAA,kCAAAA,CAAAA;AAsDF,SAASS,oBAAAA,CACdC,yBACAC,MAAAA,EAA4B;AAE5B,EAAA,MAAM,EACJV,WAAAA,EACAW,oBAAAA,GAAuBT,QAAQC,GAAAA,CAAI,0BAAA,MAAgC,OAAA,EACnES,iBAAAA,EACAC,wBAAAA,GAA2Bd,gCAAAA,CAAiCC,WAAAA,CAAAA,EAC5Dc,wBAAAA,EACAC,2BAA2B,IAAA,EAC3B,GAAGC,cAAA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OAAAA,CAAQH,SAAAA,EAAWxB,MAAAA,CAAOwB,SAAS,CAAA,EAAG;AACvF,IAAA,OAAO,KAAA;AACT,EAAA;AACA,EAAA,IAAIxB,OAAOyB,cAAAA,IAAkB,IAAA,IAAQE,OAAAA,CAAQF,cAAAA,KAAmBzB,OAAOyB,cAAAA,EAAgB;AACrF,IAAA,OAAO,KAAA;AACT,EAAA;AAEA,EAAA,OAAO,IAAA;AACT;AA1BgB4B,MAAAA,CAAAA,cAAAA,EAAAA,gBAAAA,CAAAA;AAkCT,SAASE,qBAAqBC,UAAAA,EAOpC;AACC,EAAA,OAAO;AACLrC,IAAAA,WAAAA,EAAaqC,WAAWrC,WAAAA,IAAe,IAAA;AACvCE,IAAAA,MAAAA,EAAQmC,WAAWnC,MAAAA,IAAU,IAAA;AAC7BC,IAAAA,SAAAA,EAAWkC,WAAWlC,SAAAA,IAAa,IAAA;AACnCC,IAAAA,KAAAA,EAAOiC,WAAWjC,KAAAA,IAAS,IAAA;AAC3BC,IAAAA,SAAAA,EAAWgC,WAAWhC,SAAAA,IAAa,IAAA;AACnCC,IAAAA,cAAAA,EAAgB+B,WAAW/B,cAAAA,IAAkB;AAC/C,GAAA;AACF;AAhBgB8B,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"chunk-QCOC2SF3.js","sourcesContent":["/**\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","/**\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"]}
@@ -1,9 +1,9 @@
1
- import { LayerManager } from './chunk-5NT2OEDQ.js';
1
+ import { LayerManager } from './chunk-STWFX5E2.js';
2
2
  import { signServiceJwt } from './chunk-VFCMR5GX.js';
3
3
  import { ContextManager } from './chunk-RZOFS2BQ.js';
4
4
  import { CircuitState, GatewayError, GatewayErrorType } from './chunk-4KK6YJ46.js';
5
5
  import { currentEnvironment, isDeployedEnvironment } from './chunk-A5F6Z5UE.js';
6
- import { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG } from './chunk-YFOHAHZE.js';
6
+ import { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG } from './chunk-5CAFHK2Z.js';
7
7
  import { logger } from './chunk-RU266375.js';
8
8
  import { __name } from './chunk-XE4OXN2W.js';
9
9
 
@@ -509,5 +509,5 @@ function createGatewayClientFromEnv() {
509
509
  __name(createGatewayClientFromEnv, "createGatewayClientFromEnv");
510
510
 
511
511
  export { GatewayClient, createGatewayClient, createGatewayClientFromEnv, resolveBypassPermissionValue };
512
- //# sourceMappingURL=chunk-UCNTCCV6.js.map
513
- //# sourceMappingURL=chunk-UCNTCCV6.js.map
512
+ //# sourceMappingURL=chunk-QGADOWSG.js.map
513
+ //# sourceMappingURL=chunk-QGADOWSG.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/gateway/service-jwt-guard.ts","../src/gateway/client.ts"],"names":["SERVICE_JWT_SECRET_ENV","serviceJwtMisconfigurationMessage","context","environment","currentEnvironment","layer","operation","operationName","identity","serviceIdentity","gatewayUrl","assertServiceJwtConfigured","isDeployedEnvironment","Error","uuidv4","crypto","randomUUID","hasAuthorizationHeader","headers","key","Object","keys","toLowerCase","isGraphQLError","value","message","extensions","Array","isArray","resolveBypassPermissionValue","token","process","env","normalizedToken","trim","CircuitBreaker","state","CircuitState","CLOSED","failures","successes","consecutiveFailures","lastFailureTime","lastSuccessTime","openedAt","failureTimestamps","config","getState","checkStateTransition","recordSuccess","Date","now","HALF_OPEN","logger","info","recordFailure","push","windowStart","failureWindow","filter","t","length","failureThreshold","OPEN","warn","threshold","allowRequest","forceOpen","forceClose","getStats","elapsed","resetTimeout","GatewayClient","layerManager","internalCircuitBreaker","crossLayerCircuitBreaker","retryConfig","defaultHeaders","timeout","enableLogging","LayerManager","serviceName","internalGatewayUrl","crossLayerGatewayUrl","cbConfig","DEFAULT_CIRCUIT_BREAKER_CONFIG","circuitBreaker","DEFAULT_GATEWAY_RETRY_CONFIG","retry","getServiceIdentity","debug","internalUrl","getInternalUrl","crossLayerUrl","getCrossLayerUrl","getInternalGatewayUrl","getCrossLayerGatewayUrl","internalQuery","options","createRequestContext","executeWithRetry","bypassPermission","crossLayerQuery","query","getInternalCircuitBreaker","getCrossLayerCircuitBreaker","getHealthStatus","internal","url","circuitState","stats","crossLayer","updateDefaultHeaders","callType","requestId","actorId","workspaceId","startTime","shouldRetryError","error","GatewayError","type","GatewayErrorType","GRAPHQL_ERROR","CIRCUIT_OPEN","calculateRetryDelay","attempt","Math","min","initialDelay","pow","backoffMultiplier","maxDelay","logRetryAttempt","maxAttempts","delay","settings","skipCircuitBreaker","skipRetry","lastError","result","executeRequest","String","sleep","UNKNOWN_ERROR","buildRequestHeaders","cfHeaders","ContextManager","getCfAccessHeaders","assign","entries","undefined","toString","cfCookie","existing","split","some","c","handleGraphQLErrors","duration","errors","errorMessages","map","e","join","graphqlErrors","handleFetchError","name","TIMEOUT_ERROR","cause","NETWORK_ERROR","serviceActorId","serviceJwt","signServiceJwt","getLayer","body","JSON","stringify","variables","controller","AbortController","timeoutId","setTimeout","abort","response","fetch","method","signal","clearTimeout","ok","json","every","status","statusText","statusCode","hasData","data","ms","Promise","resol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AA;AACA4E,IAAAA,WAAAA;AACAxE,IAAAA;GACF,CAAA;AACF;AAnBgBgM,MAAAA,CAAAA,0BAAAA,EAAAA,4BAAAA,CAAAA","file":"chunk-UCNTCCV6.js","sourcesContent":["/**\n * Cross-layer service-JWT configuration guard.\n *\n * A cross-layer call transits the peer layer's PUBLIC gateway, which propagates\n * `x-actor-*` context to subgraphs only when the request carries a valid JWT.\n * Without one the gateway strips those headers as potential client spoofing and\n * the subgraph rejects the call. So on a cross-layer request with no\n * Authorization header and no mintable service JWT, the outcome is already\n * decided before the request leaves the process: it will fail, downstream, with\n * an authentication error that names the callee rather than the missing secret.\n *\n * That is a bad trade in a deployed environment. It converts a one-line config\n * problem into an opaque failure attributed to the wrong service, and — because\n * several cross-layer callers treat these calls as best-effort and swallow the\n * error — into no visible failure at all. Alpha ran exactly that way: 414 calls\n * in 24h on `AddWorkspaceMemberFromWspace` and `WorkspaceOrganization`, every\n * one rejected, workspace-member mirroring silently not happening, and nothing\n * in the caller's logs above debug level.\n *\n * So in alpha, staging and production this throws before the request is sent,\n * naming the secret and the bundle to fix. Locally it stays a log: a laptop\n * calling across layers without a service JWT is a normal state while a\n * developer is mid-setup, and failing their `bun run dev` would be hostile.\n *\n * Verified inert before shipping, the same way the cache guard was: of the\n * alpha and prod service bundles in Secrets Manager, every be-sdk service that\n * makes cross-layer calls already carries `SERVICE_JWT_SECRET` (166 bundles).\n * The bundles without it are Temporal, OPA, the OTel collectors, NATS, Gatus,\n * the vibetunnels pair, the ai-assistant trio, the dormant `*-community`\n * deployments and the retired `state-archive-*` configs — none of which\n * constructs a GatewayClient or makes a cross-layer call. Nothing changes\n * today; this only catches the next caller rolled out without the secret.\n */\nimport { isDeployedEnvironment, currentEnvironment } from '../runtime/deployed-environment.js';\n\n/** Env var that must hold the signing key for service-actor JWTs. */\nexport const SERVICE_JWT_SECRET_ENV = 'SERVICE_JWT_SECRET';\n\nexport interface ServiceJwtGuardContext {\n /** Absolute URL of the peer gateway the call was about to be sent to. */\n gatewayUrl: string;\n /** GraphQL operation name, when the caller supplied one. */\n operationName?: string;\n /** Layer boundary of the CALLER, used to name the bundle to fix. */\n layer?: string;\n /** Service identity the JWT would have been minted for. */\n serviceIdentity?: string;\n}\n\n/**\n * Build the operator-facing explanation. Exported so the message itself is\n * covered by tests — a guard whose text does not say what to change just moves\n * the debugging, it does not remove it.\n */\nexport function serviceJwtMisconfigurationMessage(context: ServiceJwtGuardContext): string {\n const environment = currentEnvironment() || 'unset';\n const layer = context.layer ?? '{layer}';\n const operation = context.operationName ? ` (operation ${context.operationName})` : '';\n const identity = context.serviceIdentity ? ` as '${context.serviceIdentity}'` : '';\n return (\n `[GatewayClient] Cross-layer call to ${context.gatewayUrl}${operation} cannot be authenticated${identity}: ` +\n `${SERVICE_JWT_SECRET_ENV} is not set, so no service JWT can be minted. The peer layer's public ` +\n `gateway will strip actor headers and the subgraph will reject the request, so this call cannot ` +\n `succeed. Refusing to send it with DEPLOY_ENV=${environment}. Set ${SERVICE_JWT_SECRET_ENV} in ` +\n `boff/${environment}/${layer}/{module} — it must match the value the peer layer's gateway ` +\n `verifies with, which is per-environment and must never be copied across environments.`\n );\n}\n\n/**\n * Throw in a deployed environment when a cross-layer call is about to be sent\n * with no way to authenticate it. Returns normally everywhere else, and\n * whenever a JWT was available — so this costs nothing on the happy path.\n */\nexport function assertServiceJwtConfigured(context: ServiceJwtGuardContext): void {\n if (!isDeployedEnvironment()) return;\n throw new Error(serviceJwtMisconfigurationMessage(context));\n}\n","/**\n * Unified Gateway Client\n *\n * Provides a layer-aware GraphQL client with circuit breaker,\n * retry logic, and automatic header management for M2M communication.\n *\n * @module gateway/client\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient } from '@burdenoff/be-sdk/gateway';\n *\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer)\n * const result = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call\n * const authResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { logger } from '../logger/index.js';\nimport { signServiceJwt } from './service-jwt.js';\nimport { assertServiceJwtConfigured } from './service-jwt-guard.js';\nimport {\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n type CircuitBreakerConfig,\n type GatewayRequestHeaders,\n type GatewayRetryConfig,\n type ServiceLayer,\n} from '../types/layer.js';\nimport {\n CircuitState,\n GatewayError,\n GatewayErrorType,\n type CircuitBreakerStats,\n type GatewayClientConfig,\n type GatewayClientHealth,\n type GraphQLError,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type ICircuitBreaker,\n type IGatewayClient,\n type RequestContext,\n} from './types.js';\n\nconst uuidv4 = (): string => crypto.randomUUID();\n\n/**\n * Case-insensitive presence check for the `Authorization` header. HTTP header\n * names are case-insensitive (RFC 7230), and while the outbound `fetch` will\n * preserve whatever casing the caller supplies, callers may legitimately set\n * `authorization` / `Authorization` / even `AUTHORIZATION` via defaultHeaders\n * or options.headers. We must not overwrite an already-supplied token.\n */\nfunction hasAuthorizationHeader(headers: Record<string, string>): boolean {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === 'authorization') return true;\n }\n return false;\n}\n\nfunction isGraphQLError(value: unknown): value is GraphQLError {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'message' in value &&\n typeof value.message === 'string' &&\n (!('extensions' in value) ||\n (value.extensions !== null && typeof value.extensions === 'object' && !Array.isArray(value.extensions)))\n );\n}\n\nexport function resolveBypassPermissionValue(\n token: string | undefined = process.env['INTERNAL_SERVICE_TOKEN']\n): string {\n const normalizedToken = token?.trim();\n\n if (!normalizedToken) {\n throw new Error('INTERNAL_SERVICE_TOKEN must be configured for bypass-enabled gateway calls');\n }\n\n return normalizedToken;\n}\n\n/**\n * Circuit Breaker Implementation\n */\nclass CircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = CircuitState.CLOSED;\n private failures = 0;\n private successes = 0;\n private consecutiveFailures = 0;\n private lastFailureTime: number | null = null;\n private lastSuccessTime: number | null = null;\n private openedAt: number | null = null;\n private failureTimestamps: number[] = [];\n private config: CircuitBreakerConfig;\n\n constructor(config: CircuitBreakerConfig) {\n this.config = config;\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n recordSuccess(): void {\n this.successes++;\n this.consecutiveFailures = 0;\n this.lastSuccessTime = Date.now();\n\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit closed after successful test');\n }\n }\n\n recordFailure(): void {\n this.failures++;\n this.consecutiveFailures++;\n this.lastFailureTime = Date.now();\n this.failureTimestamps.push(Date.now());\n\n // Clean up old timestamps\n const windowStart = Date.now() - this.config.failureWindow;\n this.failureTimestamps = this.failureTimestamps.filter((t) => t > windowStart);\n\n // Check if we should open the circuit\n if (this.state === CircuitState.CLOSED && this.failureTimestamps.length >= this.config.failureThreshold) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit opened due to failures', {\n failures: this.failureTimestamps.length,\n threshold: this.config.failureThreshold,\n });\n }\n\n // If we're half-open and fail, go back to open\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit re-opened after failed test');\n }\n }\n\n allowRequest(): boolean {\n this.checkStateTransition();\n\n switch (this.state) {\n case CircuitState.CLOSED:\n return true;\n case CircuitState.OPEN:\n return false;\n case CircuitState.HALF_OPEN:\n // Allow one test request\n return true;\n default:\n return true;\n }\n }\n\n forceOpen(): void {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.info('[CircuitBreaker] Circuit force-opened');\n }\n\n forceClose(): void {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.consecutiveFailures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit force-closed');\n }\n\n getStats(): CircuitBreakerStats {\n return {\n state: this.state,\n failures: this.failures,\n successes: this.successes,\n consecutiveFailures: this.consecutiveFailures,\n lastFailureTime: this.lastFailureTime,\n lastSuccessTime: this.lastSuccessTime,\n openedAt: this.openedAt,\n };\n }\n\n private checkStateTransition(): void {\n if (this.state === CircuitState.OPEN && this.openedAt) {\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.config.resetTimeout) {\n this.state = CircuitState.HALF_OPEN;\n logger.info('[CircuitBreaker] Circuit transitioning to half-open');\n }\n }\n }\n}\n\n/**\n * Unified Gateway Client\n */\nexport class GatewayClient implements IGatewayClient {\n private config: GatewayClientConfig;\n private layerManager: LayerManager;\n private internalCircuitBreaker: CircuitBreaker;\n private crossLayerCircuitBreaker: CircuitBreaker;\n private retryConfig: GatewayRetryConfig;\n private defaultHeaders: GatewayRequestHeaders;\n\n constructor(config: GatewayClientConfig) {\n this.config = {\n timeout: 30000,\n enableLogging: true,\n ...config,\n };\n\n // Initialize layer manager\n this.layerManager = new LayerManager({\n layer: config.layer,\n serviceName: config.serviceName,\n serviceIdentity: config.serviceIdentity,\n });\n\n // Override URLs if provided\n if (config.internalGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n if (config.crossLayerGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n\n // Initialize circuit breakers\n const cbConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...config.circuitBreaker,\n };\n this.internalCircuitBreaker = new CircuitBreaker(cbConfig);\n this.crossLayerCircuitBreaker = new CircuitBreaker(cbConfig);\n\n // Initialize retry config\n this.retryConfig = {\n ...DEFAULT_GATEWAY_RETRY_CONFIG,\n ...config.retry,\n };\n\n // Initialize default headers\n this.defaultHeaders = {\n 'x-service-identity': this.layerManager.getServiceIdentity(),\n 'x-actor-type': 'service',\n ...config.defaultHeaders,\n };\n\n logger.debug('[GatewayClient] Initialized', {\n layer: config.layer,\n serviceName: config.serviceName,\n internalUrl: this.getInternalUrl(),\n crossLayerUrl: this.getCrossLayerUrl(),\n });\n }\n\n private getInternalUrl(): string {\n return this.config.internalGatewayUrl || this.layerManager.getInternalGatewayUrl();\n }\n\n private getCrossLayerUrl(): string {\n return this.config.crossLayerGatewayUrl || this.layerManager.getCrossLayerGatewayUrl();\n }\n\n /**\n * Execute internal (same layer) GraphQL query/mutation\n */\n async internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('internal', options);\n\n return this.executeWithRetry(this.getInternalUrl(), options, this.internalCircuitBreaker, context, {\n bypassPermission: true,\n });\n }\n\n /**\n * Execute cross-layer GraphQL query/mutation\n */\n async crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('cross-layer', options);\n\n return this.executeWithRetry(\n this.getCrossLayerUrl(),\n options,\n this.crossLayerCircuitBreaker,\n context,\n { bypassPermission: false } // Cross-layer calls go through public gateway\n );\n }\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n */\n async query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('direct', options);\n\n // Use internal circuit breaker for direct calls\n return this.executeWithRetry(gatewayUrl, options, this.internalCircuitBreaker, context, {\n bypassPermission: false,\n });\n }\n\n getInternalCircuitBreaker(): ICircuitBreaker {\n return this.internalCircuitBreaker;\n }\n\n getCrossLayerCircuitBreaker(): ICircuitBreaker {\n return this.crossLayerCircuitBreaker;\n }\n\n getHealthStatus(): GatewayClientHealth {\n return {\n internal: {\n url: this.getInternalUrl(),\n circuitState: this.internalCircuitBreaker.getState(),\n stats: this.internalCircuitBreaker.getStats(),\n },\n crossLayer: {\n url: this.getCrossLayerUrl(),\n circuitState: this.crossLayerCircuitBreaker.getState(),\n stats: this.crossLayerCircuitBreaker.getStats(),\n },\n };\n }\n\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void {\n this.defaultHeaders = { ...this.defaultHeaders, ...headers };\n }\n\n private createRequestContext(\n callType: 'internal' | 'cross-layer' | 'direct',\n options: GraphQLRequestOptions\n ): RequestContext {\n return {\n requestId: uuidv4(),\n actorId: options.headers?.['x-actor-id'] || this.defaultHeaders['x-actor-id'],\n workspaceId: options.headers?.['x-workspace-id'] || this.defaultHeaders['x-workspace-id'],\n startTime: Date.now(),\n callType,\n };\n }\n\n /**\n * Check if an error should be retried\n */\n private shouldRetryError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) {\n return true;\n }\n // Don't retry GraphQL errors or circuit open errors\n return error.type !== GatewayErrorType.GRAPHQL_ERROR && error.type !== GatewayErrorType.CIRCUIT_OPEN;\n }\n\n /**\n * Calculate retry delay with exponential backoff\n */\n private calculateRetryDelay(attempt: number): number {\n return Math.min(\n this.retryConfig.initialDelay * Math.pow(this.retryConfig.backoffMultiplier, attempt - 1),\n this.retryConfig.maxDelay\n );\n }\n\n /**\n * Log retry attempt if logging is enabled\n */\n private logRetryAttempt(\n context: RequestContext,\n attempt: number,\n maxAttempts: number,\n delay: number,\n error: Error\n ): void {\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] Request failed, retrying', {\n requestId: context.requestId,\n attempt,\n maxAttempts,\n delay,\n error: error.message,\n });\n }\n }\n\n private async executeWithRetry<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n circuitBreaker: CircuitBreaker,\n context: RequestContext,\n settings: { bypassPermission: boolean }\n ): Promise<GraphQLResponse<T>> {\n // Check circuit breaker\n if (!options.skipCircuitBreaker && !circuitBreaker.allowRequest()) {\n throw new GatewayError(`Circuit breaker is open for ${gatewayUrl}`, GatewayErrorType.CIRCUIT_OPEN, gatewayUrl);\n }\n\n const maxAttempts = options.skipRetry ? 1 : this.retryConfig.maxAttempts;\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.executeRequest<T>(gatewayUrl, options, context, settings.bypassPermission);\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordSuccess();\n }\n return result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordFailure();\n }\n\n if (!this.shouldRetryError(error)) {\n throw error;\n }\n\n if (attempt < maxAttempts) {\n const delay = this.calculateRetryDelay(attempt);\n this.logRetryAttempt(context, attempt, maxAttempts, delay, lastError);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError || new GatewayError('Request failed after retries', GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n /**\n * Build headers for a request\n */\n private buildRequestHeaders(\n context: RequestContext,\n options: GraphQLRequestOptions,\n bypassPermission: boolean\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-request-id': context.requestId,\n 'x-call-type': context.callType,\n };\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which on alpha\n // sits behind Cloudflare Access. Re-present the inbound request's CF creds\n // (service token and/or the CF_Authorization cookie) so the call passes the\n // CF edge. Added before default/request headers so a caller may still\n // override the non-cookie CF headers explicitly; the CF cookie is reconciled\n // after the merges below so it is never silently clobbered. No-op when the\n // inbound request carried no CF creds (local dev, production) — returns {}.\n const cfHeaders = context.callType === 'cross-layer' ? ContextManager.getCfAccessHeaders() : {};\n Object.assign(headers, cfHeaders);\n\n // Add default headers\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n\n // Add request-specific headers\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n }\n\n // Add bypass headers for internal calls\n if (bypassPermission) {\n headers['x-bypass-permission'] = resolveBypassPermissionValue();\n headers['x-bypass-source'] = this.layerManager.getServiceIdentity();\n headers['x-bypass-timestamp'] = Date.now().toString();\n }\n\n // Reconcile the CF_Authorization cookie: the default/request-header merges\n // above may set their own `cookie`, which would otherwise clobber the CF\n // cookie applied earlier (or vice versa). Merge so both survive, without\n // duplicating if it's already present.\n const cfCookie = cfHeaders['cookie'];\n if (cfCookie) {\n const existing = headers['cookie'];\n if (!existing) {\n headers['cookie'] = cfCookie;\n } else if (!existing.split(';').some((c) => c.trim() === cfCookie)) {\n headers['cookie'] = `${existing}; ${cfCookie}`;\n }\n }\n\n return headers;\n }\n\n /**\n * Handle GraphQL errors in response\n */\n private handleGraphQLErrors<T>(\n result: GraphQLResponse<T>,\n context: RequestContext,\n gatewayUrl: string,\n duration: number\n ): void {\n if (!result.errors || result.errors.length === 0) {\n return;\n }\n\n const errorMessages = result.errors.map((e: GraphQLError) => e.message).join(', ');\n\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] GraphQL errors', {\n requestId: context.requestId,\n errors: result.errors,\n duration,\n });\n }\n\n throw new GatewayError(`GraphQL error: ${errorMessages}`, GatewayErrorType.GRAPHQL_ERROR, gatewayUrl, {\n graphqlErrors: result.errors,\n });\n }\n\n /**\n * Handle fetch errors\n */\n private handleFetchError(\n error: unknown,\n context: RequestContext,\n gatewayUrl: string,\n timeout: number,\n duration: number\n ): never {\n if (error instanceof GatewayError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new GatewayError(`Request timed out after ${timeout}ms`, GatewayErrorType.TIMEOUT_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n if (this.config.enableLogging) {\n logger.error('[GatewayClient] Request failed', {\n requestId: context.requestId,\n error: error.message,\n duration,\n });\n }\n\n throw new GatewayError(error.message, GatewayErrorType.NETWORK_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n throw new GatewayError(String(error), GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n private async executeRequest<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n context: RequestContext,\n bypassPermission: boolean\n ): Promise<GraphQLResponse<T>> {\n const timeout = options.timeout || this.config.timeout || 30000;\n const headers = this.buildRequestHeaders(context, options, bypassPermission);\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which\n // requires JWT auth to propagate actor context. Mint a short-lived\n // service-actor JWT so the gateway admits the call and preserves\n // `x-actor-type: service` downstream. Skipped when the caller has\n // already supplied an Authorization header (e.g., user-originated\n // cross-layer flows) or when SERVICE_JWT_SECRET is unset.\n if (context.callType === 'cross-layer' && !hasAuthorizationHeader(headers)) {\n const serviceActorId = this.layerManager.getServiceIdentity();\n const serviceJwt = await signServiceJwt(serviceActorId);\n if (serviceJwt) {\n headers['Authorization'] = `Bearer ${serviceJwt}`;\n } else {\n // Without the JWT this call is already decided: the peer layer's public\n // gateway strips actor headers and the subgraph rejects it. Continuing\n // only converts a missing secret into an authentication error that names\n // the callee — and several cross-layer callers swallow that as\n // best-effort, so it surfaces as nothing at all. In a deployed\n // environment, refuse instead. See ./service-jwt-guard.ts.\n assertServiceJwtConfigured({\n gatewayUrl,\n operationName: options.operationName,\n layer: this.layerManager.getLayer(),\n serviceIdentity: serviceActorId,\n });\n if (this.config.enableLogging) {\n logger.debug(\n '[GatewayClient] SERVICE_JWT_SECRET not configured — cross-layer call will proceed without service JWT',\n { requestId: context.requestId, gatewayUrl }\n );\n }\n }\n }\n\n const body = JSON.stringify({\n query: options.query,\n variables: options.variables || {},\n operationName: options.operationName,\n });\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Executing request', {\n requestId: context.requestId,\n gatewayUrl,\n operationName: options.operationName,\n callType: context.callType,\n bypassPermission,\n });\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n const duration = Date.now() - context.startTime;\n\n if (!response.ok) {\n let graphqlErrors: GraphQLError[] | undefined;\n try {\n const body: unknown = await response.json();\n if (\n body !== null &&\n typeof body === 'object' &&\n 'errors' in body &&\n Array.isArray(body.errors) &&\n body.errors.length > 0 &&\n body.errors.every(isGraphQLError)\n )\n graphqlErrors = body.errors;\n } catch {\n // Edge/proxy errors need not contain JSON; retain the original HTTP failure.\n }\n throw new GatewayError(\n `HTTP ${response.status}: ${response.statusText}`,\n graphqlErrors && response.status < 500 ? GatewayErrorType.GRAPHQL_ERROR : GatewayErrorType.NETWORK_ERROR,\n gatewayUrl,\n { statusCode: response.status, graphqlErrors }\n );\n }\n\n const result = (await response.json()) as GraphQLResponse<T>;\n this.handleGraphQLErrors(result, context, gatewayUrl, duration);\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Request completed', {\n requestId: context.requestId,\n duration,\n hasData: !!result.data,\n });\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - context.startTime;\n this.handleFetchError(error, context, gatewayUrl, timeout, duration);\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Create a gateway client for a specific layer\n */\nexport function createGatewayClient(config: GatewayClientConfig): GatewayClient {\n return new GatewayClient(config);\n}\n\n/**\n * Create a gateway client from environment variables\n *\n * Required environment variables:\n * - SERVICE_LAYER: 'wspace' | 'global'\n * - SERVICE_NAME: Service name\n *\n * Optional:\n * - SERVICE_IDENTITY: Service identity (defaults to SERVICE_NAME)\n * - {LAYER}_INT_GATEWAY_URL: Internal gateway URL\n * - {OPPOSITE_LAYER}_PUBLIC_GATEWAY_URL: Cross-layer gateway URL\n */\nexport function createGatewayClientFromEnv(): GatewayClient {\n const layer = process.env['SERVICE_LAYER'] as ServiceLayer;\n\n if (!layer || (layer !== 'wspace' && layer !== 'global')) {\n throw new Error(`[GatewayClient] Invalid or missing SERVICE_LAYER. Expected 'wspace' or 'global', got '${layer}'`);\n }\n\n const serviceName = process.env['SERVICE_NAME'];\n if (!serviceName) {\n throw new Error('[GatewayClient] SERVICE_NAME environment variable is required');\n }\n\n const serviceIdentity = process.env['SERVICE_IDENTITY'] || serviceName;\n\n return new GatewayClient({\n layer,\n serviceName,\n serviceIdentity,\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/gateway/service-jwt-guard.ts","../src/gateway/client.ts"],"names":["SERVICE_JWT_SECRET_ENV","serviceJwtMisconfigurationMessage","context","environment","currentEnvironment","layer","operation","operationName","identity","serviceIdentity","gatewayUrl","assertServiceJwtConfigured","isDeployedEnvironment","Error","uuidv4","crypto","randomUUID","hasAuthorizationHeader","headers","key","Object","keys","toLowerCase","isGraphQLError","value","message","extensions","Array","isArray","resolveBypassPermissionValue","token","process","env","normalizedToken","trim","CircuitBreaker","state","CircuitState","CLOSED","failures","successes","consecutiveFailures","lastFailureTime","lastSuccessTime","openedAt","failureTimestamps","config","getState","checkStateTransition","recordSuccess","Date","now","HALF_OPEN","logger","info","recordFailure","push","windowStart","failureWindow","filter","t","length","failureThreshold","OPEN","warn","threshold","allowRequest","forceOpen","forceClose","getStats","elapsed","resetTimeout","GatewayClient","layerManager","internalCircuitBreaker","crossLayerCircuitBreaker","retryConfig","defaultHeaders","timeout","enableLogging","LayerManager","serviceName","internalGatewayUrl","crossLayerGatewayUrl","cbConfig","DEFAULT_CIRCUIT_BREAKER_CONFIG","circuitBreaker","DEFAULT_GATEWAY_RETRY_CONFIG","retry","getServiceIdentity","debug","internalUrl","getInternalUrl","crossLayerUrl","getCrossLayerUrl","getInternalGatewayUrl","getCrossLayerGatewayUrl","internalQuery","options","createRequestContext","executeWithRetry","bypassPermission","crossLayerQuery","query","getInternalCircuitBreaker","getCrossLayerCircuitBreaker","getHealthStatus","internal","url","circuitState","stats","crossLayer","updateDefaultHeaders","callType","requestId","actorId","workspaceId","startTime","shouldRetryError","error","GatewayError","type","GatewayErrorType","GRAPHQL_ERROR","CIRCUIT_OPEN","calculateRetryDelay","attempt","Math","min","initialDelay","pow","backoffMultiplier","maxDelay","logRetryAttempt","maxAttempts","delay","settings","skipCircuitBreaker","skipRetry","lastError","result","executeRequest","String","sleep","UNKNOWN_ERROR","buildRequestHeaders","cfHeaders","ContextManager","getCfAccessHeaders","assign","entries","undefined","toString","cfCookie","existing","split","some","c","handleGraphQLErrors","duration","errors","errorMessages","map","e","join","graphqlErrors","handleFetchError","name","TIMEOUT_ERROR","cause","NETWORK_ERROR","serviceActorId","serviceJwt","signServiceJwt","getLayer","body","JSON","stringify","variables","controller","AbortController","timeoutId","setTimeout","abort","response","fetch","method","signal","clearTimeout","ok","json","every","status","statusText","statusCode","hasData","data","ms","Promise","resolve","createGatewayClient","createGatewayClientFromEnv"],"mappings":";;;;;;;;;;AAoCO,IAAMA,sBAAAA,GAAyB,oBAAA;AAkB/B,SAASC,kCAAkCC,OAAAA,EAA+B;AAC/E,EAAA,MAAMC,WAAAA,GAAcC,oBAAAA,IAAwB,OAAA;AAC5C,EAAA,MAAMC,KAAAA,GAAQH,QAAQG,KAAAA,IAAS,SAAA;AAC/B,EAAA,MAAMC,YAAYJ,OAAAA,CAAQK,aAAAA,GAAgB,CAAA,YAAA,EAAeL,OAAAA,CAAQK,aAAa,CAAA,CAAA,CAAA,GAAM,EAAA;AACpF,EAAA,MAAMC,WAAWN,OAAAA,CAAQO,eAAAA,GAAkB,CAAA,KAAA,EAAQP,OAAAA,CAAQO,eAAe,CAAA,CAAA,CAAA,GAAM,EAAA;AAChF,EAAA,OACE,uCAAuCP,OAAAA,CAAQQ,UAAU,CAAA,EAAGJ,SAAAA,2BAAoCE,QAAAA,CAAAA,EAAAA,EAC7FR,sBAAAA,CAAAA,kNAAAA,EAE6CG,WAAAA,CAAAA,MAAAA,EAAoBH,sBAAAA,CAAAA,SAAAA,EAC5DG,WAAAA,IAAeE,KAAAA,CAAAA,uJAAAA,CAAAA;AAG3B;AAbgBJ,MAAAA,CAAAA,iCAAAA,EAAAA,mCAAAA,CAAAA;AAoBT,SAASU,2BAA2BT,OAAAA,EA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M,CAAA,sFAAA,EAAyFR,KAAAA,CAAAA,CAAAA,CAAQ,CAAA;AACnH,EAAA;AAEA,EAAA,MAAM4E,WAAAA,GAAclD,OAAAA,CAAQC,GAAAA,CAAI,cAAA,CAAA;AAChC,EAAA,IAAI,CAACiD,WAAAA,EAAa;AAChB,IAAA,MAAM,IAAIpE,MAAM,+DAAA,CAAA;AAClB,EAAA;AAEA,EAAA,MAAMJ,eAAAA,GAAkBsB,OAAAA,CAAQC,GAAAA,CAAI,kBAAA,CAAA,IAAuBiD,WAAAA;AAE3D,EAAA,OAAO,IAAIT,aAAAA,CAAc;AACvBnE,IAAAA,KAAAA;AACA4E,IAAAA,WAAAA;AACAxE,IAAAA;GACF,CAAA;AACF;AAnBgBgM,MAAAA,CAAAA,0BAAAA,EAAAA,4BAAAA,CAAAA","file":"chunk-QGADOWSG.js","sourcesContent":["/**\n * Cross-layer service-JWT configuration guard.\n *\n * A cross-layer call transits the peer layer's PUBLIC gateway, which propagates\n * `x-actor-*` context to subgraphs only when the request carries a valid JWT.\n * Without one the gateway strips those headers as potential client spoofing and\n * the subgraph rejects the call. So on a cross-layer request with no\n * Authorization header and no mintable service JWT, the outcome is already\n * decided before the request leaves the process: it will fail, downstream, with\n * an authentication error that names the callee rather than the missing secret.\n *\n * That is a bad trade in a deployed environment. It converts a one-line config\n * problem into an opaque failure attributed to the wrong service, and — because\n * several cross-layer callers treat these calls as best-effort and swallow the\n * error — into no visible failure at all. Alpha ran exactly that way: 414 calls\n * in 24h on `AddWorkspaceMemberFromWspace` and `WorkspaceOrganization`, every\n * one rejected, workspace-member mirroring silently not happening, and nothing\n * in the caller's logs above debug level.\n *\n * So in alpha, staging and production this throws before the request is sent,\n * naming the secret and the bundle to fix. Locally it stays a log: a laptop\n * calling across layers without a service JWT is a normal state while a\n * developer is mid-setup, and failing their `bun run dev` would be hostile.\n *\n * Verified inert before shipping, the same way the cache guard was: of the\n * alpha and prod service bundles in Secrets Manager, every be-sdk service that\n * makes cross-layer calls already carries `SERVICE_JWT_SECRET` (166 bundles).\n * The bundles without it are Temporal, OPA, the OTel collectors, NATS, Gatus,\n * the vibetunnels pair, the ai-assistant trio, the dormant `*-community`\n * deployments and the retired `state-archive-*` configs — none of which\n * constructs a GatewayClient or makes a cross-layer call. Nothing changes\n * today; this only catches the next caller rolled out without the secret.\n */\nimport { isDeployedEnvironment, currentEnvironment } from '../runtime/deployed-environment.js';\n\n/** Env var that must hold the signing key for service-actor JWTs. */\nexport const SERVICE_JWT_SECRET_ENV = 'SERVICE_JWT_SECRET';\n\nexport interface ServiceJwtGuardContext {\n /** Absolute URL of the peer gateway the call was about to be sent to. */\n gatewayUrl: string;\n /** GraphQL operation name, when the caller supplied one. */\n operationName?: string;\n /** Layer boundary of the CALLER, used to name the bundle to fix. */\n layer?: string;\n /** Service identity the JWT would have been minted for. */\n serviceIdentity?: string;\n}\n\n/**\n * Build the operator-facing explanation. Exported so the message itself is\n * covered by tests — a guard whose text does not say what to change just moves\n * the debugging, it does not remove it.\n */\nexport function serviceJwtMisconfigurationMessage(context: ServiceJwtGuardContext): string {\n const environment = currentEnvironment() || 'unset';\n const layer = context.layer ?? '{layer}';\n const operation = context.operationName ? ` (operation ${context.operationName})` : '';\n const identity = context.serviceIdentity ? ` as '${context.serviceIdentity}'` : '';\n return (\n `[GatewayClient] Cross-layer call to ${context.gatewayUrl}${operation} cannot be authenticated${identity}: ` +\n `${SERVICE_JWT_SECRET_ENV} is not set, so no service JWT can be minted. The peer layer's public ` +\n `gateway will strip actor headers and the subgraph will reject the request, so this call cannot ` +\n `succeed. Refusing to send it with DEPLOY_ENV=${environment}. Set ${SERVICE_JWT_SECRET_ENV} in ` +\n `boff/${environment}/${layer}/{module} — it must match the value the peer layer's gateway ` +\n `verifies with, which is per-environment and must never be copied across environments.`\n );\n}\n\n/**\n * Throw in a deployed environment when a cross-layer call is about to be sent\n * with no way to authenticate it. Returns normally everywhere else, and\n * whenever a JWT was available — so this costs nothing on the happy path.\n */\nexport function assertServiceJwtConfigured(context: ServiceJwtGuardContext): void {\n if (!isDeployedEnvironment()) return;\n throw new Error(serviceJwtMisconfigurationMessage(context));\n}\n","/**\n * Unified Gateway Client\n *\n * Provides a layer-aware GraphQL client with circuit breaker,\n * retry logic, and automatic header management for M2M communication.\n *\n * @module gateway/client\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient } from '@burdenoff/be-sdk/gateway';\n *\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer)\n * const result = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call\n * const authResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { logger } from '../logger/index.js';\nimport { signServiceJwt } from './service-jwt.js';\nimport { assertServiceJwtConfigured } from './service-jwt-guard.js';\nimport {\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n type CircuitBreakerConfig,\n type GatewayRequestHeaders,\n type GatewayRetryConfig,\n type ServiceLayer,\n} from '../types/layer.js';\nimport {\n CircuitState,\n GatewayError,\n GatewayErrorType,\n type CircuitBreakerStats,\n type GatewayClientConfig,\n type GatewayClientHealth,\n type GraphQLError,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type ICircuitBreaker,\n type IGatewayClient,\n type RequestContext,\n} from './types.js';\n\nconst uuidv4 = (): string => crypto.randomUUID();\n\n/**\n * Case-insensitive presence check for the `Authorization` header. HTTP header\n * names are case-insensitive (RFC 7230), and while the outbound `fetch` will\n * preserve whatever casing the caller supplies, callers may legitimately set\n * `authorization` / `Authorization` / even `AUTHORIZATION` via defaultHeaders\n * or options.headers. We must not overwrite an already-supplied token.\n */\nfunction hasAuthorizationHeader(headers: Record<string, string>): boolean {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === 'authorization') return true;\n }\n return false;\n}\n\nfunction isGraphQLError(value: unknown): value is GraphQLError {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'message' in value &&\n typeof value.message === 'string' &&\n (!('extensions' in value) ||\n (value.extensions !== null && typeof value.extensions === 'object' && !Array.isArray(value.extensions)))\n );\n}\n\nexport function resolveBypassPermissionValue(\n token: string | undefined = process.env['INTERNAL_SERVICE_TOKEN']\n): string {\n const normalizedToken = token?.trim();\n\n if (!normalizedToken) {\n throw new Error('INTERNAL_SERVICE_TOKEN must be configured for bypass-enabled gateway calls');\n }\n\n return normalizedToken;\n}\n\n/**\n * Circuit Breaker Implementation\n */\nclass CircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = CircuitState.CLOSED;\n private failures = 0;\n private successes = 0;\n private consecutiveFailures = 0;\n private lastFailureTime: number | null = null;\n private lastSuccessTime: number | null = null;\n private openedAt: number | null = null;\n private failureTimestamps: number[] = [];\n private config: CircuitBreakerConfig;\n\n constructor(config: CircuitBreakerConfig) {\n this.config = config;\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n recordSuccess(): void {\n this.successes++;\n this.consecutiveFailures = 0;\n this.lastSuccessTime = Date.now();\n\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit closed after successful test');\n }\n }\n\n recordFailure(): void {\n this.failures++;\n this.consecutiveFailures++;\n this.lastFailureTime = Date.now();\n this.failureTimestamps.push(Date.now());\n\n // Clean up old timestamps\n const windowStart = Date.now() - this.config.failureWindow;\n this.failureTimestamps = this.failureTimestamps.filter((t) => t > windowStart);\n\n // Check if we should open the circuit\n if (this.state === CircuitState.CLOSED && this.failureTimestamps.length >= this.config.failureThreshold) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit opened due to failures', {\n failures: this.failureTimestamps.length,\n threshold: this.config.failureThreshold,\n });\n }\n\n // If we're half-open and fail, go back to open\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit re-opened after failed test');\n }\n }\n\n allowRequest(): boolean {\n this.checkStateTransition();\n\n switch (this.state) {\n case CircuitState.CLOSED:\n return true;\n case CircuitState.OPEN:\n return false;\n case CircuitState.HALF_OPEN:\n // Allow one test request\n return true;\n default:\n return true;\n }\n }\n\n forceOpen(): void {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.info('[CircuitBreaker] Circuit force-opened');\n }\n\n forceClose(): void {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.consecutiveFailures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit force-closed');\n }\n\n getStats(): CircuitBreakerStats {\n return {\n state: this.state,\n failures: this.failures,\n successes: this.successes,\n consecutiveFailures: this.consecutiveFailures,\n lastFailureTime: this.lastFailureTime,\n lastSuccessTime: this.lastSuccessTime,\n openedAt: this.openedAt,\n };\n }\n\n private checkStateTransition(): void {\n if (this.state === CircuitState.OPEN && this.openedAt) {\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.config.resetTimeout) {\n this.state = CircuitState.HALF_OPEN;\n logger.info('[CircuitBreaker] Circuit transitioning to half-open');\n }\n }\n }\n}\n\n/**\n * Unified Gateway Client\n */\nexport class GatewayClient implements IGatewayClient {\n private config: GatewayClientConfig;\n private layerManager: LayerManager;\n private internalCircuitBreaker: CircuitBreaker;\n private crossLayerCircuitBreaker: CircuitBreaker;\n private retryConfig: GatewayRetryConfig;\n private defaultHeaders: GatewayRequestHeaders;\n\n constructor(config: GatewayClientConfig) {\n this.config = {\n timeout: 30000,\n enableLogging: true,\n ...config,\n };\n\n // Initialize layer manager\n this.layerManager = new LayerManager({\n layer: config.layer,\n serviceName: config.serviceName,\n serviceIdentity: config.serviceIdentity,\n });\n\n // Override URLs if provided\n if (config.internalGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n if (config.crossLayerGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n\n // Initialize circuit breakers\n const cbConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...config.circuitBreaker,\n };\n this.internalCircuitBreaker = new CircuitBreaker(cbConfig);\n this.crossLayerCircuitBreaker = new CircuitBreaker(cbConfig);\n\n // Initialize retry config\n this.retryConfig = {\n ...DEFAULT_GATEWAY_RETRY_CONFIG,\n ...config.retry,\n };\n\n // Initialize default headers\n this.defaultHeaders = {\n 'x-service-identity': this.layerManager.getServiceIdentity(),\n 'x-actor-type': 'service',\n ...config.defaultHeaders,\n };\n\n logger.debug('[GatewayClient] Initialized', {\n layer: config.layer,\n serviceName: config.serviceName,\n internalUrl: this.getInternalUrl(),\n crossLayerUrl: this.getCrossLayerUrl(),\n });\n }\n\n private getInternalUrl(): string {\n return this.config.internalGatewayUrl || this.layerManager.getInternalGatewayUrl();\n }\n\n private getCrossLayerUrl(): string {\n return this.config.crossLayerGatewayUrl || this.layerManager.getCrossLayerGatewayUrl();\n }\n\n /**\n * Execute internal (same layer) GraphQL query/mutation\n */\n async internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('internal', options);\n\n return this.executeWithRetry(this.getInternalUrl(), options, this.internalCircuitBreaker, context, {\n bypassPermission: true,\n });\n }\n\n /**\n * Execute cross-layer GraphQL query/mutation\n */\n async crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('cross-layer', options);\n\n return this.executeWithRetry(\n this.getCrossLayerUrl(),\n options,\n this.crossLayerCircuitBreaker,\n context,\n { bypassPermission: false } // Cross-layer calls go through public gateway\n );\n }\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n */\n async query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('direct', options);\n\n // Use internal circuit breaker for direct calls\n return this.executeWithRetry(gatewayUrl, options, this.internalCircuitBreaker, context, {\n bypassPermission: false,\n });\n }\n\n getInternalCircuitBreaker(): ICircuitBreaker {\n return this.internalCircuitBreaker;\n }\n\n getCrossLayerCircuitBreaker(): ICircuitBreaker {\n return this.crossLayerCircuitBreaker;\n }\n\n getHealthStatus(): GatewayClientHealth {\n return {\n internal: {\n url: this.getInternalUrl(),\n circuitState: this.internalCircuitBreaker.getState(),\n stats: this.internalCircuitBreaker.getStats(),\n },\n crossLayer: {\n url: this.getCrossLayerUrl(),\n circuitState: this.crossLayerCircuitBreaker.getState(),\n stats: this.crossLayerCircuitBreaker.getStats(),\n },\n };\n }\n\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void {\n this.defaultHeaders = { ...this.defaultHeaders, ...headers };\n }\n\n private createRequestContext(\n callType: 'internal' | 'cross-layer' | 'direct',\n options: GraphQLRequestOptions\n ): RequestContext {\n return {\n requestId: uuidv4(),\n actorId: options.headers?.['x-actor-id'] || this.defaultHeaders['x-actor-id'],\n workspaceId: options.headers?.['x-workspace-id'] || this.defaultHeaders['x-workspace-id'],\n startTime: Date.now(),\n callType,\n };\n }\n\n /**\n * Check if an error should be retried\n */\n private shouldRetryError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) {\n return true;\n }\n // Don't retry GraphQL errors or circuit open errors\n return error.type !== GatewayErrorType.GRAPHQL_ERROR && error.type !== GatewayErrorType.CIRCUIT_OPEN;\n }\n\n /**\n * Calculate retry delay with exponential backoff\n */\n private calculateRetryDelay(attempt: number): number {\n return Math.min(\n this.retryConfig.initialDelay * Math.pow(this.retryConfig.backoffMultiplier, attempt - 1),\n this.retryConfig.maxDelay\n );\n }\n\n /**\n * Log retry attempt if logging is enabled\n */\n private logRetryAttempt(\n context: RequestContext,\n attempt: number,\n maxAttempts: number,\n delay: number,\n error: Error\n ): void {\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] Request failed, retrying', {\n requestId: context.requestId,\n attempt,\n maxAttempts,\n delay,\n error: error.message,\n });\n }\n }\n\n private async executeWithRetry<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n circuitBreaker: CircuitBreaker,\n context: RequestContext,\n settings: { bypassPermission: boolean }\n ): Promise<GraphQLResponse<T>> {\n // Check circuit breaker\n if (!options.skipCircuitBreaker && !circuitBreaker.allowRequest()) {\n throw new GatewayError(`Circuit breaker is open for ${gatewayUrl}`, GatewayErrorType.CIRCUIT_OPEN, gatewayUrl);\n }\n\n const maxAttempts = options.skipRetry ? 1 : this.retryConfig.maxAttempts;\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.executeRequest<T>(gatewayUrl, options, context, settings.bypassPermission);\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordSuccess();\n }\n return result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordFailure();\n }\n\n if (!this.shouldRetryError(error)) {\n throw error;\n }\n\n if (attempt < maxAttempts) {\n const delay = this.calculateRetryDelay(attempt);\n this.logRetryAttempt(context, attempt, maxAttempts, delay, lastError);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError || new GatewayError('Request failed after retries', GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n /**\n * Build headers for a request\n */\n private buildRequestHeaders(\n context: RequestContext,\n options: GraphQLRequestOptions,\n bypassPermission: boolean\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-request-id': context.requestId,\n 'x-call-type': context.callType,\n };\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which on alpha\n // sits behind Cloudflare Access. Re-present the inbound request's CF creds\n // (service token and/or the CF_Authorization cookie) so the call passes the\n // CF edge. Added before default/request headers so a caller may still\n // override the non-cookie CF headers explicitly; the CF cookie is reconciled\n // after the merges below so it is never silently clobbered. No-op when the\n // inbound request carried no CF creds (local dev, production) — returns {}.\n const cfHeaders = context.callType === 'cross-layer' ? ContextManager.getCfAccessHeaders() : {};\n Object.assign(headers, cfHeaders);\n\n // Add default headers\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n\n // Add request-specific headers\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n }\n\n // Add bypass headers for internal calls\n if (bypassPermission) {\n headers['x-bypass-permission'] = resolveBypassPermissionValue();\n headers['x-bypass-source'] = this.layerManager.getServiceIdentity();\n headers['x-bypass-timestamp'] = Date.now().toString();\n }\n\n // Reconcile the CF_Authorization cookie: the default/request-header merges\n // above may set their own `cookie`, which would otherwise clobber the CF\n // cookie applied earlier (or vice versa). Merge so both survive, without\n // duplicating if it's already present.\n const cfCookie = cfHeaders['cookie'];\n if (cfCookie) {\n const existing = headers['cookie'];\n if (!existing) {\n headers['cookie'] = cfCookie;\n } else if (!existing.split(';').some((c) => c.trim() === cfCookie)) {\n headers['cookie'] = `${existing}; ${cfCookie}`;\n }\n }\n\n return headers;\n }\n\n /**\n * Handle GraphQL errors in response\n */\n private handleGraphQLErrors<T>(\n result: GraphQLResponse<T>,\n context: RequestContext,\n gatewayUrl: string,\n duration: number\n ): void {\n if (!result.errors || result.errors.length === 0) {\n return;\n }\n\n const errorMessages = result.errors.map((e: GraphQLError) => e.message).join(', ');\n\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] GraphQL errors', {\n requestId: context.requestId,\n errors: result.errors,\n duration,\n });\n }\n\n throw new GatewayError(`GraphQL error: ${errorMessages}`, GatewayErrorType.GRAPHQL_ERROR, gatewayUrl, {\n graphqlErrors: result.errors,\n });\n }\n\n /**\n * Handle fetch errors\n */\n private handleFetchError(\n error: unknown,\n context: RequestContext,\n gatewayUrl: string,\n timeout: number,\n duration: number\n ): never {\n if (error instanceof GatewayError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new GatewayError(`Request timed out after ${timeout}ms`, GatewayErrorType.TIMEOUT_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n if (this.config.enableLogging) {\n logger.error('[GatewayClient] Request failed', {\n requestId: context.requestId,\n error: error.message,\n duration,\n });\n }\n\n throw new GatewayError(error.message, GatewayErrorType.NETWORK_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n throw new GatewayError(String(error), GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n private async executeRequest<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n context: RequestContext,\n bypassPermission: boolean\n ): Promise<GraphQLResponse<T>> {\n const timeout = options.timeout || this.config.timeout || 30000;\n const headers = this.buildRequestHeaders(context, options, bypassPermission);\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which\n // requires JWT auth to propagate actor context. Mint a short-lived\n // service-actor JWT so the gateway admits the call and preserves\n // `x-actor-type: service` downstream. Skipped when the caller has\n // already supplied an Authorization header (e.g., user-originated\n // cross-layer flows) or when SERVICE_JWT_SECRET is unset.\n if (context.callType === 'cross-layer' && !hasAuthorizationHeader(headers)) {\n const serviceActorId = this.layerManager.getServiceIdentity();\n const serviceJwt = await signServiceJwt(serviceActorId);\n if (serviceJwt) {\n headers['Authorization'] = `Bearer ${serviceJwt}`;\n } else {\n // Without the JWT this call is already decided: the peer layer's public\n // gateway strips actor headers and the subgraph rejects it. Continuing\n // only converts a missing secret into an authentication error that names\n // the callee — and several cross-layer callers swallow that as\n // best-effort, so it surfaces as nothing at all. In a deployed\n // environment, refuse instead. See ./service-jwt-guard.ts.\n assertServiceJwtConfigured({\n gatewayUrl,\n operationName: options.operationName,\n layer: this.layerManager.getLayer(),\n serviceIdentity: serviceActorId,\n });\n if (this.config.enableLogging) {\n logger.debug(\n '[GatewayClient] SERVICE_JWT_SECRET not configured — cross-layer call will proceed without service JWT',\n { requestId: context.requestId, gatewayUrl }\n );\n }\n }\n }\n\n const body = JSON.stringify({\n query: options.query,\n variables: options.variables || {},\n operationName: options.operationName,\n });\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Executing request', {\n requestId: context.requestId,\n gatewayUrl,\n operationName: options.operationName,\n callType: context.callType,\n bypassPermission,\n });\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n const duration = Date.now() - context.startTime;\n\n if (!response.ok) {\n let graphqlErrors: GraphQLError[] | undefined;\n try {\n const body: unknown = await response.json();\n if (\n body !== null &&\n typeof body === 'object' &&\n 'errors' in body &&\n Array.isArray(body.errors) &&\n body.errors.length > 0 &&\n body.errors.every(isGraphQLError)\n )\n graphqlErrors = body.errors;\n } catch {\n // Edge/proxy errors need not contain JSON; retain the original HTTP failure.\n }\n throw new GatewayError(\n `HTTP ${response.status}: ${response.statusText}`,\n graphqlErrors && response.status < 500 ? GatewayErrorType.GRAPHQL_ERROR : GatewayErrorType.NETWORK_ERROR,\n gatewayUrl,\n { statusCode: response.status, graphqlErrors }\n );\n }\n\n const result = (await response.json()) as GraphQLResponse<T>;\n this.handleGraphQLErrors(result, context, gatewayUrl, duration);\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Request completed', {\n requestId: context.requestId,\n duration,\n hasData: !!result.data,\n });\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - context.startTime;\n this.handleFetchError(error, context, gatewayUrl, timeout, duration);\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Create a gateway client for a specific layer\n */\nexport function createGatewayClient(config: GatewayClientConfig): GatewayClient {\n return new GatewayClient(config);\n}\n\n/**\n * Create a gateway client from environment variables\n *\n * Required environment variables:\n * - SERVICE_LAYER: 'wspace' | 'global'\n * - SERVICE_NAME: Service name\n *\n * Optional:\n * - SERVICE_IDENTITY: Service identity (defaults to SERVICE_NAME)\n * - {LAYER}_INT_GATEWAY_URL: Internal gateway URL\n * - {OPPOSITE_LAYER}_PUBLIC_GATEWAY_URL: Cross-layer gateway URL\n */\nexport function createGatewayClientFromEnv(): GatewayClient {\n const layer = process.env['SERVICE_LAYER'] as ServiceLayer;\n\n if (!layer || (layer !== 'wspace' && layer !== 'global')) {\n throw new Error(`[GatewayClient] Invalid or missing SERVICE_LAYER. Expected 'wspace' or 'global', got '${layer}'`);\n }\n\n const serviceName = process.env['SERVICE_NAME'];\n if (!serviceName) {\n throw new Error('[GatewayClient] SERVICE_NAME environment variable is required');\n }\n\n const serviceIdentity = process.env['SERVICE_IDENTITY'] || serviceName;\n\n return new GatewayClient({\n layer,\n serviceName,\n serviceIdentity,\n });\n}\n"]}
@@ -0,0 +1,51 @@
1
+ import { security_exports } from './chunk-NBN52AEM.js';
2
+ import { createGatewayClientFromEnv, createGatewayClient, GatewayClient } from './chunk-QGADOWSG.js';
3
+ import { signServiceJwt } from './chunk-VFCMR5GX.js';
4
+ import { GatewayErrorType, GatewayError, CircuitState } from './chunk-4KK6YJ46.js';
5
+ import { __export, __name } from './chunk-XE4OXN2W.js';
6
+
7
+ // src/gateway/index.ts
8
+ var gateway_exports = {};
9
+ __export(gateway_exports, {
10
+ CircuitState: () => CircuitState,
11
+ DELEGATED_AUTHORIZATION_HEADER: () => DELEGATED_AUTHORIZATION_HEADER,
12
+ GatewayClient: () => GatewayClient,
13
+ GatewayError: () => GatewayError,
14
+ GatewayErrorType: () => GatewayErrorType,
15
+ Security: () => security_exports,
16
+ buildDelegatedGatewayHeaders: () => buildDelegatedGatewayHeaders,
17
+ createGatewayClient: () => createGatewayClient,
18
+ createGatewayClientFromEnv: () => createGatewayClientFromEnv,
19
+ signServiceJwt: () => signServiceJwt
20
+ });
21
+
22
+ // src/gateway/delegated-transport.ts
23
+ var DELEGATED_AUTHORIZATION_HEADER = "x-delegated-authorization";
24
+ var JWT_SEGMENT = /^[A-Za-z0-9_-]+$/;
25
+ function isCompactJwt(token) {
26
+ const segments = token.split(".");
27
+ return segments.length === 3 && segments.every((segment) => JWT_SEGMENT.test(segment));
28
+ }
29
+ __name(isCompactJwt, "isCompactJwt");
30
+ function buildDelegatedGatewayHeaders(input) {
31
+ const token = input.appAsUserToken;
32
+ if (typeof token !== "string" || token.length === 0 || token.length > 8192 || !isCompactJwt(token)) {
33
+ throw new Error("Delegated gateway transport requires a compact app_as_user token");
34
+ }
35
+ const headers = {
36
+ [DELEGATED_AUTHORIZATION_HEADER]: `Bearer ${token}`
37
+ };
38
+ if (input.workspaceId !== void 0) {
39
+ const workspaceId = input.workspaceId.trim();
40
+ if (workspaceId.length === 0 || workspaceId !== input.workspaceId) {
41
+ throw new Error("Delegated gateway transport requires a non-blank workspace id");
42
+ }
43
+ headers["x-workspace-id"] = workspaceId;
44
+ }
45
+ return headers;
46
+ }
47
+ __name(buildDelegatedGatewayHeaders, "buildDelegatedGatewayHeaders");
48
+
49
+ export { DELEGATED_AUTHORIZATION_HEADER, buildDelegatedGatewayHeaders, gateway_exports };
50
+ //# sourceMappingURL=chunk-RM6AIMZT.js.map
51
+ //# sourceMappingURL=chunk-RM6AIMZT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gateway/index.ts","../src/gateway/delegated-transport.ts"],"names":["DELEGATED_AUTHORIZATION_HEADER","JWT_SEGMENT","isCompactJwt","token","segments","split","length","every","segment","test","buildDelegatedGatewayHeaders","input","appAsUserToken","Error","headers","workspaceId","undefined","trim"],"mappings":";;;;;;;AAAA,IAAA,eAAA,GAAA;;;;;;;;;;;;;;;ACiBO,IAAMA,8BAAAA,GAAiC;AAS9C,IAAMC,WAAAA,GAAc,kBAAA;AAEpB,SAASC,aAAaC,KAAAA,EAAa;AACjC,EAAA,MAAMC,QAAAA,GAAWD,KAAAA,CAAME,KAAAA,CAAM,GAAA,CAAA;AAC7B,EAAA,OAAOD,QAAAA,CAASE,MAAAA,KAAW,CAAA,IAAKF,QAAAA,CAASG,KAAAA,CAAM,CAACC,OAAAA,KAAYP,WAAAA,CAAYQ,IAAAA,CAAKD,OAAAA,CAAAA,CAAAA;AAC/E;AAHSN,MAAAA,CAAAA,YAAAA,EAAAA,cAAAA,CAAAA;AAYF,SAASQ,6BAA6BC,KAAAA,EAAqC;AAChF,EAAA,MAAMR,QAAQQ,KAAAA,CAAMC,cAAAA;AACpB,EAAA,IAAI,OAAOT,KAAAA,KAAU,QAAA,IAAYA,KAAAA,CAAMG,MAAAA,KAAW,CAAA,IAAKH,KAAAA,CAAMG,MAAAA,GAAS,IAAA,IAAQ,CAACJ,YAAAA,CAAaC,KAAAA,CAAAA,EAAQ;AAClG,IAAA,MAAM,IAAIU,MAAM,kEAAA,CAAA;AAClB,EAAA;AACA,EAAA,MAAMC,OAAAA,GAAiC;IACrC,CAACd,8BAAAA,GAAiC,CAAA,OAAA,EAAUG,KAAAA,CAAAA;AAC9C,GAAA;AACA,EAAA,IAAIQ,KAAAA,CAAMI,gBAAgBC,MAAAA,EAAW;AACnC,IAAA,MAAMD,WAAAA,GAAcJ,KAAAA,CAAMI,WAAAA,CAAYE,IAAAA,EAAI;AAC1C,IAAA,IAAIF,WAAAA,CAAYT,MAAAA,KAAW,CAAA,IAAKS,WAAAA,KAAgBJ,MAAMI,WAAAA,EAAa;AACjE,MAAA,MAAM,IAAIF,MAAM,+DAAA,CAAA;AAClB,IAAA;AACAC,IAAAA,OAAAA,CAAQ,gBAAA,CAAA,GAAoBC,WAAAA;AAC9B,EAAA;AACA,EAAA,OAAOD,OAAAA;AACT;AAhBgBJ,MAAAA,CAAAA,4BAAAA,EAAAA,8BAAAA,CAAAA","file":"chunk-RM6AIMZT.js","sourcesContent":["/**\n * Gateway Module\n *\n * Provides unified gateway client for layer-aware M2M communication\n * with circuit breaker and retry logic.\n *\n * @module gateway\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient, createGatewayClientFromEnv } from '@burdenoff/be-sdk/gateway';\n *\n * // Create from environment variables\n * const client = createGatewayClientFromEnv();\n *\n * // Or create manually\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer, uses int-gateway with bypass)\n * const internalResult = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call (via public gateway)\n * const crossLayerResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\n// Client exports\nexport { GatewayClient, createGatewayClient, createGatewayClientFromEnv } from './client.js';\n\n// Service-JWT minting for cross-layer M2M auth. Exposed so non-GatewayClient\n// callers (e.g. bespoke graphql-request clients) can authenticate identically.\nexport { signServiceJwt } from './service-jwt.js';\n\n// Delegated internal-gateway transport (BOFF-9962): call as an agent acting\n// for a user by presenting a verified app_as_user token, never raw headers.\nexport {\n buildDelegatedGatewayHeaders,\n DELEGATED_AUTHORIZATION_HEADER,\n type DelegatedGatewayTransportInput,\n} from './delegated-transport.js';\n\n// Type exports\nexport {\n CircuitState,\n GatewayErrorType,\n GatewayError,\n type GatewayClientConfig,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type GraphQLError,\n type IGatewayClient,\n type ICircuitBreaker,\n type CircuitBreakerStats,\n type GatewayClientHealth,\n type RequestContext,\n} from './types.js';\n\n// Gateway-side security plugin stack (for public gateways).\n// Imported by consumers as `@burdenoff/be-sdk/gateway/security` — this\n// re-export lets `@burdenoff/be-sdk/gateway` also resolve the namespace.\nexport * as Security from './security/index.js';\n","/**\n * Delegated gateway transport (BOFF-9962).\n *\n * A service that must call the platform as \"agent X acting for user Y\" does\n * not set actor or consent headers itself: internal gateways strip those.\n * Instead it obtains a short-lived `app_as_user` token from global-auth\n * (`issueAppAsUserTokenInternal`) and presents it on the internal gateway's\n * `x-delegated-authorization` header. The gateway verifies the signature,\n * checks revocation and the grant's workspace bounds, and only then forwards\n * the represented user as the actor together with `x-verified-delegation`.\n *\n * @module gateway/delegated-transport\n */\n\nimport type { GatewayRequestHeaders } from '../types/layer.js';\n\n/** Header an internal gateway reads a delegated `app_as_user` bearer from. */\nexport const DELEGATED_AUTHORIZATION_HEADER = 'x-delegated-authorization';\n\nexport interface DelegatedGatewayTransportInput {\n /** Signed `app_as_user` access token issued by global-auth. */\n appAsUserToken: string;\n /** Workspace the call targets; must be inside the grant's workspace bounds. */\n workspaceId?: string;\n}\n\nconst JWT_SEGMENT = /^[A-Za-z0-9_-]+$/;\n\nfunction isCompactJwt(token: string): boolean {\n const segments = token.split('.');\n return segments.length === 3 && segments.every((segment) => JWT_SEGMENT.test(segment));\n}\n\n/**\n * Builds the request headers for a delegated internal-gateway call, for use as\n * `GatewayClient.internalQuery({ query, headers })`.\n *\n * @throws Error when the token is not a compact JWS (so a malformed value can\n * never be smuggled into a header) or the workspace id is blank.\n */\nexport function buildDelegatedGatewayHeaders(input: DelegatedGatewayTransportInput): GatewayRequestHeaders {\n const token = input.appAsUserToken;\n if (typeof token !== 'string' || token.length === 0 || token.length > 8192 || !isCompactJwt(token)) {\n throw new Error('Delegated gateway transport requires a compact app_as_user token');\n }\n const headers: GatewayRequestHeaders = {\n [DELEGATED_AUTHORIZATION_HEADER]: `Bearer ${token}`,\n };\n if (input.workspaceId !== undefined) {\n const workspaceId = input.workspaceId.trim();\n if (workspaceId.length === 0 || workspaceId !== input.workspaceId) {\n throw new Error('Delegated gateway transport requires a non-blank workspace id');\n }\n headers['x-workspace-id'] = workspaceId;\n }\n return headers;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { DEFAULT_LAYER_STREAMS, DEFAULT_LAYER_RESOURCES, DEFAULT_GATEWAY_ROUTING } from './chunk-YFOHAHZE.js';
1
+ import { DEFAULT_LAYER_STREAMS, DEFAULT_LAYER_RESOURCES, DEFAULT_GATEWAY_ROUTING } from './chunk-5CAFHK2Z.js';
2
2
  import { logger } from './chunk-RU266375.js';
3
3
  import { __export, __name } from './chunk-XE4OXN2W.js';
4
4
 
@@ -229,5 +229,5 @@ function validateLayerConfig(config) {
229
229
  __name(validateLayerConfig, "validateLayerConfig");
230
230
 
231
231
  export { LayerManager, createLayerManagerFromEnv, detectLayerFromServiceName, getGatewayUrlForLayer, layer_exports, validateLayerConfig };
232
- //# sourceMappingURL=chunk-5NT2OEDQ.js.map
233
- //# sourceMappingURL=chunk-5NT2OEDQ.js.map
232
+ //# sourceMappingURL=chunk-STWFX5E2.js.map
233
+ //# sourceMappingURL=chunk-STWFX5E2.js.map