@codemation/host 0.0.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 (358) hide show
  1. package/README.md +75 -0
  2. package/dist/CodemationConfig-XCkSV2dj.d.ts +168 -0
  3. package/dist/CodemationConsumerConfigLoader-Dmm2TzAA.d.ts +61 -0
  4. package/dist/CodemationConsumerConfigLoader-scS_RQMy.js +334 -0
  5. package/dist/CodemationConsumerConfigLoader-scS_RQMy.js.map +1 -0
  6. package/dist/CodemationFrontendBootstrapRequest-CE6DjOWJ.js +5768 -0
  7. package/dist/CodemationFrontendBootstrapRequest-CE6DjOWJ.js.map +1 -0
  8. package/dist/CodemationPluginListMerger-BNmaoXQL.js +49 -0
  9. package/dist/CodemationPluginListMerger-BNmaoXQL.js.map +1 -0
  10. package/dist/CodemationPluginListMerger-BRYqEk0y.d.ts +793 -0
  11. package/dist/CodemationWhitelabelConfig-DgbjgtrR.d.ts +48 -0
  12. package/dist/ConsoleLogger-ClPU7jtc.js +35 -0
  13. package/dist/ConsoleLogger-ClPU7jtc.js.map +1 -0
  14. package/dist/CredentialServices-BKBGe7l3.js +1030 -0
  15. package/dist/CredentialServices-BKBGe7l3.js.map +1 -0
  16. package/dist/CredentialServices-DpDpm8mL.d.ts +291 -0
  17. package/dist/LogLevelPolicy-4cq9z0TI.d.ts +37 -0
  18. package/dist/PrismaMigrationDeployer-B1E_gYz7.js +8212 -0
  19. package/dist/PrismaMigrationDeployer-B1E_gYz7.js.map +1 -0
  20. package/dist/ServerLoggerFactory-BRHxIDS7.js +340 -0
  21. package/dist/ServerLoggerFactory-BRHxIDS7.js.map +1 -0
  22. package/dist/WorkflowViewContracts-DCLpTn25.d.ts +47 -0
  23. package/dist/chunk-7V6ThxGB.js +39 -0
  24. package/dist/client-Yh7-CQud.d.ts +21995 -0
  25. package/dist/client.d.ts +12 -0
  26. package/dist/client.js +15 -0
  27. package/dist/client.js.map +1 -0
  28. package/dist/consumer.d.ts +5 -0
  29. package/dist/consumer.js +7 -0
  30. package/dist/credentials.d.ts +50 -0
  31. package/dist/credentials.js +11 -0
  32. package/dist/credentials.js.map +1 -0
  33. package/dist/decorate-B-N_5S4p.js +10 -0
  34. package/dist/decorateParam-BTcc3KNk.js +15 -0
  35. package/dist/devServerSidecar.d.ts +52 -0
  36. package/dist/devServerSidecar.js +131 -0
  37. package/dist/devServerSidecar.js.map +1 -0
  38. package/dist/index-Bs4F1IsC.d.ts +1044 -0
  39. package/dist/index.d.ts +19 -0
  40. package/dist/index.js +14 -0
  41. package/dist/nextServer.d.ts +89 -0
  42. package/dist/nextServer.js +127 -0
  43. package/dist/nextServer.js.map +1 -0
  44. package/dist/persistenceServer-K5eqlZm3.d.ts +36 -0
  45. package/dist/persistenceServer-W9uRw0dJ.js +19 -0
  46. package/dist/persistenceServer-W9uRw0dJ.js.map +1 -0
  47. package/dist/persistenceServer.d.ts +6 -0
  48. package/dist/persistenceServer.js +6 -0
  49. package/dist/server-BBdsATju.d.ts +132 -0
  50. package/dist/server-BiHSuA13.js +175 -0
  51. package/dist/server-BiHSuA13.js.map +1 -0
  52. package/dist/server.d.ts +9 -0
  53. package/dist/server.js +13 -0
  54. package/package.json +152 -0
  55. package/playwright.config.ts +74 -0
  56. package/prisma/migrations/20260315063514_init/migration.sql +16 -0
  57. package/prisma/migrations/20260316090000_workflow_debugger_overlay/migration.sql +9 -0
  58. package/prisma/migrations/20260317120000_trigger_state_store/migration.sql +3 -0
  59. package/prisma/migrations/20260317153000_trigger_setup_state/migration.sql +8 -0
  60. package/prisma/migrations/20260318110000_credentials_v2/migration.sql +49 -0
  61. package/prisma/migrations/20260319110000_credential_oauth2_material/migration.sql +28 -0
  62. package/prisma/migrations/20260319200000_codemation_auth_tables/migration.sql +56 -0
  63. package/prisma/migrations/20260320140000_user_invites_account_status/migration.sql +20 -0
  64. package/prisma/migrations/20260325120000_workflow_activation/migration.sql +8 -0
  65. package/prisma/migrations/migration_lock.toml +3 -0
  66. package/prisma/schema.prisma +179 -0
  67. package/prisma.config.ts +12 -0
  68. package/scripts/ensure-prisma-runtime-sourcemaps.mjs +42 -0
  69. package/scripts/integration-database-global-setup.mjs +30 -0
  70. package/src/application/ApplicationRequestError.ts +12 -0
  71. package/src/application/auth/AuthenticatedPrincipal.ts +5 -0
  72. package/src/application/auth/SessionVerifier.ts +5 -0
  73. package/src/application/binary/OverlayPinnedBinaryUploadService.ts +119 -0
  74. package/src/application/binary/RunBinaryAttachmentLookupService.ts +139 -0
  75. package/src/application/binary/RunStateBinaryStorageKeysCollector.ts +57 -0
  76. package/src/application/bus/Command.ts +3 -0
  77. package/src/application/bus/CommandBus.ts +5 -0
  78. package/src/application/bus/CommandHandler.ts +5 -0
  79. package/src/application/bus/DomainEvent.ts +1 -0
  80. package/src/application/bus/DomainEventBus.ts +5 -0
  81. package/src/application/bus/DomainEventHandler.ts +5 -0
  82. package/src/application/bus/Query.ts +3 -0
  83. package/src/application/bus/QueryBus.ts +5 -0
  84. package/src/application/bus/QueryHandler.ts +5 -0
  85. package/src/application/commands/AcceptUserInviteCommand.ts +10 -0
  86. package/src/application/commands/AcceptUserInviteCommandHandler.ts +19 -0
  87. package/src/application/commands/CopyRunToWorkflowDebuggerCommand.ts +14 -0
  88. package/src/application/commands/CopyRunToWorkflowDebuggerCommandHandler.ts +56 -0
  89. package/src/application/commands/CreateCredentialInstanceCommand.ts +9 -0
  90. package/src/application/commands/CreateCredentialInstanceCommandHandler.ts +28 -0
  91. package/src/application/commands/CredentialCommandHandlers.ts +10 -0
  92. package/src/application/commands/DeleteCredentialInstanceCommand.ts +7 -0
  93. package/src/application/commands/DeleteCredentialInstanceCommandHandler.ts +27 -0
  94. package/src/application/commands/HandleWebhookInvocationCommand.ts +12 -0
  95. package/src/application/commands/HandleWebhookInvocationCommandHandler.ts +42 -0
  96. package/src/application/commands/InviteUserCommand.ts +12 -0
  97. package/src/application/commands/InviteUserCommandHandler.ts +22 -0
  98. package/src/application/commands/RegenerateUserInviteCommand.ts +12 -0
  99. package/src/application/commands/RegenerateUserInviteCommandHandler.ts +24 -0
  100. package/src/application/commands/ReplaceMutableRunWorkflowSnapshotCommand.ts +12 -0
  101. package/src/application/commands/ReplaceMutableRunWorkflowSnapshotCommandHandler.ts +47 -0
  102. package/src/application/commands/ReplaceWorkflowDebuggerOverlayCommand.ts +14 -0
  103. package/src/application/commands/ReplaceWorkflowDebuggerOverlayCommandHandler.ts +35 -0
  104. package/src/application/commands/ReplayWorkflowNodeCommand.ts +12 -0
  105. package/src/application/commands/ReplayWorkflowNodeCommandHandler.ts +164 -0
  106. package/src/application/commands/SetPinnedNodeInputCommand.ts +13 -0
  107. package/src/application/commands/SetPinnedNodeInputCommandHandler.ts +50 -0
  108. package/src/application/commands/SetWorkflowActivationCommand.ts +10 -0
  109. package/src/application/commands/SetWorkflowActivationCommandHandler.ts +39 -0
  110. package/src/application/commands/StartWorkflowRunCommand.ts +8 -0
  111. package/src/application/commands/StartWorkflowRunCommandHandler.ts +286 -0
  112. package/src/application/commands/TestCredentialInstanceCommand.ts +9 -0
  113. package/src/application/commands/TestCredentialInstanceCommandHandler.ts +28 -0
  114. package/src/application/commands/UpdateCredentialInstanceCommand.ts +12 -0
  115. package/src/application/commands/UpdateCredentialInstanceCommandHandler.ts +28 -0
  116. package/src/application/commands/UpdateUserAccountStatusCommand.ts +12 -0
  117. package/src/application/commands/UpdateUserAccountStatusCommandHandler.ts +24 -0
  118. package/src/application/commands/UploadOverlayPinnedBinaryCommand.ts +16 -0
  119. package/src/application/commands/UploadOverlayPinnedBinaryCommandHandler.ts +31 -0
  120. package/src/application/commands/UpsertCredentialBindingCommand.ts +11 -0
  121. package/src/application/commands/UpsertCredentialBindingCommandHandler.ts +28 -0
  122. package/src/application/commands/UpsertLocalBootstrapUserCommand.ts +12 -0
  123. package/src/application/commands/UpsertLocalBootstrapUserCommandHandler.ts +24 -0
  124. package/src/application/commands/UserAccountCommandHandlers.ts +10 -0
  125. package/src/application/contracts/CredentialContractsRegistry.ts +88 -0
  126. package/src/application/contracts/RunContracts.ts +41 -0
  127. package/src/application/contracts/WorkflowDebuggerContracts.ts +12 -0
  128. package/src/application/contracts/WorkflowViewContracts.ts +40 -0
  129. package/src/application/contracts/WorkflowWebsocketMessage.ts +8 -0
  130. package/src/application/contracts/userDirectoryContracts.types.ts +60 -0
  131. package/src/application/dev/BootRuntimeSnapshotHolder.ts +19 -0
  132. package/src/application/dev/BootRuntimeSummary.types.ts +11 -0
  133. package/src/application/dev/DevBootstrapSummaryAssembler.ts +84 -0
  134. package/src/application/dev/DevBootstrapSummaryJson.types.ts +9 -0
  135. package/src/application/logging/LogFilter.ts +7 -0
  136. package/src/application/logging/Logger.ts +10 -0
  137. package/src/application/mapping/DataMapper.ts +3 -0
  138. package/src/application/mapping/WorkflowDefinitionMapper.ts +171 -0
  139. package/src/application/mapping/WorkflowPolicyUiPresentationFactory.ts +39 -0
  140. package/src/application/queries/CredentialQueryHandlers.ts +12 -0
  141. package/src/application/queries/GetCredentialFieldEnvStatusQuery.ts +5 -0
  142. package/src/application/queries/GetCredentialFieldEnvStatusQueryHandler.ts +52 -0
  143. package/src/application/queries/GetCredentialInstanceQuery.ts +9 -0
  144. package/src/application/queries/GetCredentialInstanceQueryHandler.ts +27 -0
  145. package/src/application/queries/GetCredentialInstanceWithSecretsQuery.ts +9 -0
  146. package/src/application/queries/GetCredentialInstanceWithSecretsQueryHandler.ts +27 -0
  147. package/src/application/queries/GetRunBinaryAttachmentQuery.ts +11 -0
  148. package/src/application/queries/GetRunBinaryAttachmentQueryHandler.ts +23 -0
  149. package/src/application/queries/GetRunStateQuery.ts +8 -0
  150. package/src/application/queries/GetRunStateQueryHandler.ts +21 -0
  151. package/src/application/queries/GetWorkflowCredentialHealthQuery.ts +9 -0
  152. package/src/application/queries/GetWorkflowCredentialHealthQueryHandler.ts +27 -0
  153. package/src/application/queries/GetWorkflowDebuggerOverlayQuery.ts +8 -0
  154. package/src/application/queries/GetWorkflowDebuggerOverlayQueryHandler.ts +28 -0
  155. package/src/application/queries/GetWorkflowDetailQuery.ts +8 -0
  156. package/src/application/queries/GetWorkflowDetailQueryHandler.ts +24 -0
  157. package/src/application/queries/GetWorkflowOverlayBinaryAttachmentQuery.ts +11 -0
  158. package/src/application/queries/GetWorkflowOverlayBinaryAttachmentQueryHandler.ts +23 -0
  159. package/src/application/queries/GetWorkflowSummariesQuery.ts +4 -0
  160. package/src/application/queries/GetWorkflowSummariesQueryHandler.ts +23 -0
  161. package/src/application/queries/ListCredentialInstancesQuery.ts +5 -0
  162. package/src/application/queries/ListCredentialInstancesQueryHandler.ts +27 -0
  163. package/src/application/queries/ListCredentialTypesQuery.ts +5 -0
  164. package/src/application/queries/ListCredentialTypesQueryHandler.ts +28 -0
  165. package/src/application/queries/ListUserAccountsQuery.ts +5 -0
  166. package/src/application/queries/ListUserAccountsQueryHandler.ts +22 -0
  167. package/src/application/queries/ListWorkflowRunsQuery.ts +8 -0
  168. package/src/application/queries/ListWorkflowRunsQueryHandler.ts +21 -0
  169. package/src/application/queries/UserAccountQueryHandlers.ts +4 -0
  170. package/src/application/queries/VerifyUserInviteQuery.ts +9 -0
  171. package/src/application/queries/VerifyUserInviteQueryHandler.ts +21 -0
  172. package/src/application/runs/WorkflowRunRetentionPruneScheduler.ts +98 -0
  173. package/src/application/websocket/WorkflowRunEventWebsocketRelay.ts +36 -0
  174. package/src/application/websocket/WorkflowWebsocketPublisher.ts +5 -0
  175. package/src/application/workflows/WebhookEndpointPathValidator.ts +35 -0
  176. package/src/application/workflows/WorkflowDebuggerOverlayStateFactory.ts +122 -0
  177. package/src/applicationTokens.ts +72 -0
  178. package/src/bootstrap/CodemationBootstrapRequest.ts +27 -0
  179. package/src/bootstrap/CodemationContainerFactory.ts +310 -0
  180. package/src/bootstrap/CodemationContainerRegistration.ts +23 -0
  181. package/src/bootstrap/CodemationContainerRegistrationRegistrar.ts +42 -0
  182. package/src/bootstrap/CodemationFrontendBootstrapRequest.ts +16 -0
  183. package/src/bootstrap/CodemationWorkerBootstrapRequest.ts +19 -0
  184. package/src/bootstrap/PreparedCodemationRuntime.ts +37 -0
  185. package/src/bootstrap/PreparedCodemationRuntimeFactory.ts +308 -0
  186. package/src/bootstrap/boot/CliRuntimeBootService.ts +27 -0
  187. package/src/bootstrap/boot/FrontendRuntimeBootService.ts +86 -0
  188. package/src/bootstrap/boot/WorkerRuntimeBootService.ts +64 -0
  189. package/src/bootstrap/runtime/AppConfigFactory.ts +57 -0
  190. package/src/bootstrap/runtime/ResolvedImplementationSelectionFactory.ts +118 -0
  191. package/src/client.ts +3 -0
  192. package/src/codemationApplication.ts +311 -0
  193. package/src/consumer.ts +4 -0
  194. package/src/credentials.ts +24 -0
  195. package/src/devServerSidecar.ts +10 -0
  196. package/src/domain/credentials/CredentialBindingService.ts +139 -0
  197. package/src/domain/credentials/CredentialFieldEnvOverlayService.ts +60 -0
  198. package/src/domain/credentials/CredentialInstanceService.ts +391 -0
  199. package/src/domain/credentials/CredentialMaterialResolver.ts +55 -0
  200. package/src/domain/credentials/CredentialRuntimeMaterialService.ts +39 -0
  201. package/src/domain/credentials/CredentialSecretCipher.ts +70 -0
  202. package/src/domain/credentials/CredentialServices.ts +145 -0
  203. package/src/domain/credentials/CredentialSessionServiceImpl.ts +119 -0
  204. package/src/domain/credentials/CredentialTestService.ts +73 -0
  205. package/src/domain/credentials/CredentialTypeRegistryImpl.ts +29 -0
  206. package/src/domain/credentials/OAuth2ConnectServiceFactory.ts +396 -0
  207. package/src/domain/credentials/OAuth2ProviderRegistry.ts +75 -0
  208. package/src/domain/credentials/WorkflowCredentialNodeResolver.ts +246 -0
  209. package/src/domain/runs/WorkflowRunRepository.ts +11 -0
  210. package/src/domain/users/UserAccountServiceRegistry.ts +315 -0
  211. package/src/domain/users/userLoginMethodLabels.types.ts +29 -0
  212. package/src/domain/workflows/WorkflowActivationPreflight.ts +32 -0
  213. package/src/domain/workflows/WorkflowActivationPreflightRules.ts +77 -0
  214. package/src/domain/workflows/WorkflowActivationRepository.ts +9 -0
  215. package/src/domain/workflows/WorkflowDebuggerOverlayRepository.ts +7 -0
  216. package/src/domain/workflows/WorkflowDebuggerOverlayState.ts +8 -0
  217. package/src/domain/workflows/WorkflowDefinitionRepository.ts +11 -0
  218. package/src/index.ts +58 -0
  219. package/src/infrastructure/auth/AuthJsSessionVerifier.ts +26 -0
  220. package/src/infrastructure/auth/DevelopmentSessionBypassVerifier.ts +12 -0
  221. package/src/infrastructure/binary/BinaryBodyNodeReadableFactory.ts +22 -0
  222. package/src/infrastructure/binary/CountingSha256Transform.ts +26 -0
  223. package/src/infrastructure/binary/LocalFilesystemBinaryStorageRegistry.ts +86 -0
  224. package/src/infrastructure/config/CodemationPluginRegistrar.ts +44 -0
  225. package/src/infrastructure/credentials/FrameworkBuiltinCredentialTypesRegistrar.ts +21 -0
  226. package/src/infrastructure/credentials/OpenAiApiKeyCredentialHealthTester.ts +89 -0
  227. package/src/infrastructure/credentials/OpenAiApiKeyCredentialShapes.types.ts +15 -0
  228. package/src/infrastructure/credentials/OpenAiApiKeyCredentialTypeFactory.ts +47 -0
  229. package/src/infrastructure/di/HandlesCommandRegistry.ts +24 -0
  230. package/src/infrastructure/di/HandlesDomainEventRegistry.ts +24 -0
  231. package/src/infrastructure/di/HandlesQueryRegistry.ts +24 -0
  232. package/src/infrastructure/di/InMemoryCommandBus.ts +47 -0
  233. package/src/infrastructure/di/InMemoryDomainEventBus.ts +47 -0
  234. package/src/infrastructure/di/InMemoryQueryBus.ts +45 -0
  235. package/src/infrastructure/ids/CodemationIdFactory.ts +12 -0
  236. package/src/infrastructure/logging/BrowserLogger.ts +1 -0
  237. package/src/infrastructure/logging/BrowserLoggerFactory.ts +14 -0
  238. package/src/infrastructure/logging/ConsoleLogger.ts +41 -0
  239. package/src/infrastructure/logging/FilteringLogger.ts +38 -0
  240. package/src/infrastructure/logging/LogLevelPolicy.ts +148 -0
  241. package/src/infrastructure/logging/LogLevelPolicyFactory.ts +16 -0
  242. package/src/infrastructure/logging/PerformanceLogPolicy.ts +10 -0
  243. package/src/infrastructure/logging/PerformanceLogPolicyFactory.ts +14 -0
  244. package/src/infrastructure/logging/ServerLogger.ts +1 -0
  245. package/src/infrastructure/logging/ServerLoggerFactory.ts +28 -0
  246. package/src/infrastructure/persistence/CodemationPostgresPrismaClientFactory.ts +9 -0
  247. package/src/infrastructure/persistence/CredentialPersistenceStore.ts +139 -0
  248. package/src/infrastructure/persistence/DatabasePersistenceResolver.ts +91 -0
  249. package/src/infrastructure/persistence/InMemoryTriggerSetupStateRepository.ts +23 -0
  250. package/src/infrastructure/persistence/InMemoryWorkflowActivationRepository.ts +18 -0
  251. package/src/infrastructure/persistence/InMemoryWorkflowDebuggerOverlayRepository.ts +16 -0
  252. package/src/infrastructure/persistence/InMemoryWorkflowRunRepository.ts +94 -0
  253. package/src/infrastructure/persistence/PrismaClientFactory.ts +26 -0
  254. package/src/infrastructure/persistence/PrismaCredentialStore.ts +368 -0
  255. package/src/infrastructure/persistence/PrismaMigrationDeployer.ts +184 -0
  256. package/src/infrastructure/persistence/PrismaTriggerSetupStateRepository.ts +68 -0
  257. package/src/infrastructure/persistence/PrismaWorkflowActivationRepository.ts +36 -0
  258. package/src/infrastructure/persistence/PrismaWorkflowDebuggerOverlayRepository.ts +65 -0
  259. package/src/infrastructure/persistence/PrismaWorkflowRunRepository.ts +243 -0
  260. package/src/infrastructure/persistence/RuntimeWorkflowActivationPolicy.ts +27 -0
  261. package/src/infrastructure/persistence/SchedulerPersistenceCompatibilityValidator.ts +20 -0
  262. package/src/infrastructure/persistence/WorkflowDefinitionRepositoryAdapter.ts +31 -0
  263. package/src/infrastructure/persistence/WorkflowRunRepository.ts +46 -0
  264. package/src/infrastructure/persistence/generated/prisma/client.d.ts +1 -0
  265. package/src/infrastructure/persistence/generated/prisma/default.d.ts +1 -0
  266. package/src/infrastructure/persistence/generated/prisma/edge.d.ts +1 -0
  267. package/src/infrastructure/persistence/generated/prisma/index.d.ts +4766 -0
  268. package/src/infrastructure/persistence/generated/prisma/package.json +144 -0
  269. package/src/infrastructure/persistence/generated/prisma/query_compiler_fast_bg.wasm +0 -0
  270. package/src/infrastructure/persistence/generated/prisma/runtime/client.d.ts +3358 -0
  271. package/src/infrastructure/persistence/generated/prisma/runtime/index-browser.d.ts +90 -0
  272. package/src/infrastructure/persistence/generated/prisma/schema.prisma +35 -0
  273. package/src/infrastructure/persistence/generated/prisma/wasm-edge-light-loader.mjs +5 -0
  274. package/src/infrastructure/persistence/generated/prisma/wasm-worker-loader.mjs +5 -0
  275. package/src/infrastructure/persistence/generated/prisma-client/client.d.ts +1 -0
  276. package/src/infrastructure/persistence/generated/prisma-client/client.js +5 -0
  277. package/src/infrastructure/persistence/generated/prisma-client/default.d.ts +1 -0
  278. package/src/infrastructure/persistence/generated/prisma-client/default.js +5 -0
  279. package/src/infrastructure/persistence/generated/prisma-client/edge.d.ts +1 -0
  280. package/src/infrastructure/persistence/generated/prisma-client/edge.js +299 -0
  281. package/src/infrastructure/persistence/generated/prisma-client/index-browser.js +325 -0
  282. package/src/infrastructure/persistence/generated/prisma-client/index.d.ts +21623 -0
  283. package/src/infrastructure/persistence/generated/prisma-client/index.js +299 -0
  284. package/src/infrastructure/persistence/generated/prisma-client/package.json +144 -0
  285. package/src/infrastructure/persistence/generated/prisma-client/query_compiler_fast_bg.js +2 -0
  286. package/src/infrastructure/persistence/generated/prisma-client/query_compiler_fast_bg.wasm +0 -0
  287. package/src/infrastructure/persistence/generated/prisma-client/query_compiler_fast_bg.wasm-base64.js +2 -0
  288. package/src/infrastructure/persistence/generated/prisma-client/runtime/client.d.ts +3358 -0
  289. package/src/infrastructure/persistence/generated/prisma-client/runtime/client.js +86 -0
  290. package/src/infrastructure/persistence/generated/prisma-client/runtime/client.js.map +1 -0
  291. package/src/infrastructure/persistence/generated/prisma-client/runtime/index-browser.d.ts +90 -0
  292. package/src/infrastructure/persistence/generated/prisma-client/runtime/index-browser.js +6 -0
  293. package/src/infrastructure/persistence/generated/prisma-client/runtime/index-browser.js.map +1 -0
  294. package/src/infrastructure/persistence/generated/prisma-client/runtime/wasm-compiler-edge.js +76 -0
  295. package/src/infrastructure/persistence/generated/prisma-client/runtime/wasm-compiler-edge.js.map +1 -0
  296. package/src/infrastructure/persistence/generated/prisma-client/schema.prisma +179 -0
  297. package/src/infrastructure/persistence/generated/prisma-client/wasm-edge-light-loader.mjs +5 -0
  298. package/src/infrastructure/persistence/generated/prisma-client/wasm-worker-loader.mjs +5 -0
  299. package/src/infrastructure/runtime/LiveWorkflowRepository.ts +14 -0
  300. package/src/infrastructure/runtime/WorkerRuntimeScheduler.ts +35 -0
  301. package/src/infrastructure/server/http/ServerHttpRouteParams.ts +1 -0
  302. package/src/infrastructure/webhooks/RequestToWebhookItemMapper.ts +128 -0
  303. package/src/nextServer.ts +31 -0
  304. package/src/persistenceServer.ts +5 -0
  305. package/src/presentation/config/AppConfig.ts +25 -0
  306. package/src/presentation/config/CodemationAppContext.ts +19 -0
  307. package/src/presentation/config/CodemationApplicationFacade.ts +5 -0
  308. package/src/presentation/config/CodemationAuthConfig.ts +31 -0
  309. package/src/presentation/config/CodemationClassToken.ts +3 -0
  310. package/src/presentation/config/CodemationConfig.ts +86 -0
  311. package/src/presentation/config/CodemationConfigNormalizer.ts +179 -0
  312. package/src/presentation/config/CodemationLogConfig.ts +22 -0
  313. package/src/presentation/config/CodemationPackageManifest.ts +9 -0
  314. package/src/presentation/config/CodemationPlugin.ts +20 -0
  315. package/src/presentation/config/CodemationPluginListMerger.ts +46 -0
  316. package/src/presentation/config/CodemationWhitelabelConfig.ts +9 -0
  317. package/src/presentation/config/CodemationWorkflowDiscovery.ts +3 -0
  318. package/src/presentation/http/ApiPaths.ts +165 -0
  319. package/src/presentation/http/CodemationServerGatewayFactory.ts +120 -0
  320. package/src/presentation/http/HttpRequestJsonBodyReader.ts +12 -0
  321. package/src/presentation/http/ServerHttpErrorResponseFactory.ts +33 -0
  322. package/src/presentation/http/ServerHttpRouteParams.ts +1 -0
  323. package/src/presentation/http/hono/CodemationHonoApiAppFactory.ts +64 -0
  324. package/src/presentation/http/hono/HonoApiRouteRegistrar.ts +5 -0
  325. package/src/presentation/http/hono/HonoHttpAnonymousRoutePolicyRegistry.ts +27 -0
  326. package/src/presentation/http/hono/registrars/BinaryHonoApiRouteRegistrar.ts +21 -0
  327. package/src/presentation/http/hono/registrars/CredentialHonoApiRouteRegistrar.ts +34 -0
  328. package/src/presentation/http/hono/registrars/DevHonoApiRouteRegistrar.ts +17 -0
  329. package/src/presentation/http/hono/registrars/OAuth2HonoApiRouteRegistrar.ts +18 -0
  330. package/src/presentation/http/hono/registrars/RunHonoApiRouteRegistrar.ts +31 -0
  331. package/src/presentation/http/hono/registrars/UserHonoApiRouteRegistrar.ts +24 -0
  332. package/src/presentation/http/hono/registrars/WebhookHonoApiRouteRegistrar.ts +23 -0
  333. package/src/presentation/http/hono/registrars/WhitelabelHonoApiRouteRegistrar.ts +18 -0
  334. package/src/presentation/http/hono/registrars/WorkflowHonoApiRouteRegistrar.ts +33 -0
  335. package/src/presentation/http/routeHandlers/BinaryHttpRouteHandlerFactory.ts +101 -0
  336. package/src/presentation/http/routeHandlers/CredentialHttpRouteHandler.ts +129 -0
  337. package/src/presentation/http/routeHandlers/DevBootstrapSummaryHttpRouteHandler.ts +21 -0
  338. package/src/presentation/http/routeHandlers/OAuth2HttpRouteHandlerFactory.ts +129 -0
  339. package/src/presentation/http/routeHandlers/RunHttpRouteHandler.ts +82 -0
  340. package/src/presentation/http/routeHandlers/UserHttpRouteHandlerFactory.ts +109 -0
  341. package/src/presentation/http/routeHandlers/WebhookHttpRouteHandler.ts +42 -0
  342. package/src/presentation/http/routeHandlers/WhitelabelLogoHttpRouteHandler.ts +96 -0
  343. package/src/presentation/http/routeHandlers/WorkflowHttpRouteHandler.ts +104 -0
  344. package/src/presentation/server/CodemationConsumerAppResolver.ts +82 -0
  345. package/src/presentation/server/CodemationConsumerConfigExportsResolver.ts +33 -0
  346. package/src/presentation/server/CodemationConsumerConfigLoader.ts +270 -0
  347. package/src/presentation/server/CodemationPluginDiscovery.ts +151 -0
  348. package/src/presentation/server/CodemationTsyringeParamInfoReader.ts +26 -0
  349. package/src/presentation/server/CodemationTsyringeTypeInfoRegistrar.ts +121 -0
  350. package/src/presentation/server/DevelopmentRuntimeRouteGuard.ts +59 -0
  351. package/src/presentation/server/DiscoveredWorkflowsEmptyMessageFactory.ts +11 -0
  352. package/src/presentation/server/WorkflowDefinitionExportsResolver.ts +24 -0
  353. package/src/presentation/server/WorkflowDiscoveryPathSegmentsComputer.ts +53 -0
  354. package/src/presentation/server/WorkflowModulePathFinder.ts +47 -0
  355. package/src/presentation/websocket/WorkflowWebsocketServer.ts +169 -0
  356. package/src/server.ts +14 -0
  357. package/tsconfig.json +10 -0
  358. package/vitest.shared.ts +45 -0
@@ -0,0 +1,1030 @@
1
+ import { n as __decorateMetadata, t as __decorateParam } from "./decorateParam-BTcc3KNk.js";
2
+ import { t as __decorate } from "./decorate-B-N_5S4p.js";
3
+ import { AgentConfigInspector, ConnectionNodeIdFactory, CoreTokens, CredentialUnboundError, WorkflowExecutableNodeClassifierFactory, inject, injectable } from "@codemation/core";
4
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
5
+
6
+ //#region src/infrastructure/credentials/OpenAiApiKeyCredentialHealthTester.ts
7
+ /**
8
+ * Verifies an OpenAI-compatible API key by calling the provider's models list endpoint
9
+ * (GET `/v1/models` relative to the configured base URL).
10
+ */
11
+ var OpenAiApiKeyCredentialHealthTester = class {
12
+ constructor(fetchImpl) {
13
+ this.fetchImpl = fetchImpl;
14
+ }
15
+ async test(args) {
16
+ const testedAt = (/* @__PURE__ */ new Date()).toISOString();
17
+ const apiKey = String(args.material.apiKey ?? "").trim();
18
+ if (apiKey.length === 0) return {
19
+ status: "failing",
20
+ message: "OpenAI API key is empty.",
21
+ testedAt
22
+ };
23
+ const modelsUrl = this.resolveModelsListUrl(args.publicConfig.baseUrl);
24
+ try {
25
+ const response = await this.fetchImpl(modelsUrl, {
26
+ method: "GET",
27
+ headers: { Authorization: `Bearer ${apiKey}` },
28
+ signal: AbortSignal.timeout(25e3)
29
+ });
30
+ if (response.ok) return {
31
+ status: "healthy",
32
+ message: "API key verified against the models endpoint.",
33
+ testedAt
34
+ };
35
+ return {
36
+ status: "failing",
37
+ message: await this.parseErrorMessage(response),
38
+ testedAt
39
+ };
40
+ } catch (error) {
41
+ return {
42
+ status: "failing",
43
+ message: error instanceof Error ? error.message : String(error),
44
+ testedAt
45
+ };
46
+ }
47
+ }
48
+ resolveModelsListUrl(baseUrlRaw) {
49
+ const defaultBase = "https://api.openai.com/v1";
50
+ const raw = typeof baseUrlRaw === "string" ? baseUrlRaw.trim() : "";
51
+ const base = raw === "" ? defaultBase : raw.replace(/\/+$/, "");
52
+ if (base.endsWith("/models")) return base;
53
+ if (base.endsWith("/v1")) return `${base}/models`;
54
+ return `${base}/v1/models`;
55
+ }
56
+ async parseErrorMessage(response) {
57
+ const prefix = `HTTP ${response.status}`;
58
+ try {
59
+ const text = await response.text();
60
+ if (text.trim() === "") return prefix;
61
+ const fromApi = JSON.parse(text).error?.message;
62
+ if (typeof fromApi === "string" && fromApi.trim() !== "") return `${prefix}: ${fromApi.trim()}`;
63
+ return `${prefix}: ${text.length > 280 ? `${text.slice(0, 280)}…` : text}`;
64
+ } catch {
65
+ return prefix;
66
+ }
67
+ }
68
+ };
69
+
70
+ //#endregion
71
+ //#region src/infrastructure/credentials/OpenAiApiKeyCredentialTypeFactory.ts
72
+ /**
73
+ * Builds the OpenAI-compatible API key credential (`openai.apiKey`) registration.
74
+ * Used by {@link FrameworkBuiltinCredentialTypesRegistrar} and may be listed in {@link CodemationConfig.credentialTypes}
75
+ * so consumer apps always register the type even when bootstrap order differs.
76
+ */
77
+ var OpenAiApiKeyCredentialTypeFactory = class {
78
+ constructor(healthTester) {
79
+ this.healthTester = healthTester;
80
+ }
81
+ createCredentialType() {
82
+ return {
83
+ definition: {
84
+ typeId: "openai.apiKey",
85
+ displayName: "OpenAI API key",
86
+ description: "API key and optional base URL for OpenAI or OpenAI-compatible chat endpoints.",
87
+ publicFields: [{
88
+ key: "baseUrl",
89
+ label: "Base URL",
90
+ type: "string",
91
+ placeholder: "https://api.openai.com/v1",
92
+ helpText: "Leave empty to use the default OpenAI API endpoint."
93
+ }],
94
+ secretFields: [{
95
+ key: "apiKey",
96
+ label: "API key",
97
+ type: "password",
98
+ required: true
99
+ }],
100
+ supportedSourceKinds: [
101
+ "db",
102
+ "env",
103
+ "code"
104
+ ]
105
+ },
106
+ createSession: async (args) => {
107
+ const baseUrlRaw = args.publicConfig.baseUrl;
108
+ const baseUrl = typeof baseUrlRaw === "string" && baseUrlRaw.trim() !== "" ? baseUrlRaw.trim() : void 0;
109
+ return {
110
+ apiKey: String(args.material.apiKey ?? ""),
111
+ baseUrl
112
+ };
113
+ },
114
+ test: async (args) => this.healthTester.test(args)
115
+ };
116
+ }
117
+ };
118
+
119
+ //#endregion
120
+ //#region src/domain/credentials/CredentialTypeRegistryImpl.ts
121
+ let CredentialTypeRegistryImpl = class CredentialTypeRegistryImpl$1 {
122
+ credentialTypesById = /* @__PURE__ */ new Map();
123
+ register(type) {
124
+ if (this.credentialTypesById.has(type.definition.typeId)) throw new Error(`Credential type already registered: ${type.definition.typeId}`);
125
+ this.credentialTypesById.set(type.definition.typeId, type);
126
+ }
127
+ listTypes() {
128
+ return [...this.credentialTypesById.values()].map((entry) => entry.definition);
129
+ }
130
+ getType(typeId) {
131
+ return this.credentialTypesById.get(typeId)?.definition;
132
+ }
133
+ getCredentialType(typeId) {
134
+ return this.credentialTypesById.get(typeId);
135
+ }
136
+ };
137
+ CredentialTypeRegistryImpl = __decorate([injectable()], CredentialTypeRegistryImpl);
138
+
139
+ //#endregion
140
+ //#region src/application/ApplicationRequestError.ts
141
+ var ApplicationRequestError = class extends Error {
142
+ status;
143
+ payload;
144
+ constructor(status, message, errors) {
145
+ super(message);
146
+ this.name = "ApplicationRequestError";
147
+ this.status = status;
148
+ this.payload = errors && errors.length > 0 ? {
149
+ error: message,
150
+ errors
151
+ } : { error: message };
152
+ }
153
+ };
154
+
155
+ //#endregion
156
+ //#region src/applicationTokens.ts
157
+ const ApplicationTokens = {
158
+ CodemationAuthConfig: Symbol.for("codemation.application.CodemationAuthConfig"),
159
+ CodemationWhitelabelConfig: Symbol.for("codemation.application.CodemationWhitelabelConfig"),
160
+ AppConfig: Symbol.for("codemation.application.AppConfig"),
161
+ WebSocketPort: Symbol.for("codemation.application.WebSocketPort"),
162
+ WebSocketBindHost: Symbol.for("codemation.application.WebSocketBindHost"),
163
+ QueryBus: Symbol.for("codemation.application.QueryBus"),
164
+ CommandBus: Symbol.for("codemation.application.CommandBus"),
165
+ DomainEventBus: Symbol.for("codemation.application.DomainEventBus"),
166
+ QueryHandler: Symbol.for("codemation.application.QueryHandler"),
167
+ CommandHandler: Symbol.for("codemation.application.CommandHandler"),
168
+ DomainEventHandler: Symbol.for("codemation.application.DomainEventHandler"),
169
+ HonoApiRouteRegistrar: Symbol.for("codemation.application.HonoApiRouteRegistrar"),
170
+ WorkflowWebsocketPublisher: Symbol.for("codemation.application.WorkflowWebsocketPublisher"),
171
+ WorkerRuntimeScheduler: Symbol.for("codemation.application.WorkerRuntimeScheduler"),
172
+ WorkflowDefinitionRepository: Symbol.for("codemation.application.WorkflowDefinitionRepository"),
173
+ WorkflowActivationRepository: Symbol.for("codemation.application.WorkflowActivationRepository"),
174
+ WorkflowDebuggerOverlayRepository: Symbol.for("codemation.application.WorkflowDebuggerOverlayRepository"),
175
+ WorkflowRunRepository: Symbol.for("codemation.application.WorkflowRunRepository"),
176
+ LoggerFactory: Symbol.for("codemation.application.LoggerFactory"),
177
+ PerformanceDiagnosticsLogger: Symbol.for("codemation.application.PerformanceDiagnosticsLogger"),
178
+ CredentialStore: Symbol.for("codemation.application.CredentialStore"),
179
+ PrismaClient: Symbol.for("codemation.application.PrismaClient"),
180
+ SessionVerifier: Symbol.for("codemation.application.SessionVerifier"),
181
+ Clock: Symbol.for("codemation.application.Clock")
182
+ };
183
+
184
+ //#endregion
185
+ //#region src/domain/credentials/WorkflowCredentialNodeResolver.ts
186
+ let WorkflowCredentialNodeResolver = class WorkflowCredentialNodeResolver$1 {
187
+ /**
188
+ * Human-readable label for credential errors (workflow node name or agent › attachment).
189
+ */
190
+ describeCredentialNodeDisplay(workflow, nodeId) {
191
+ const direct = workflow.nodes.find((n) => n.id === nodeId);
192
+ if (direct) return direct.name ?? direct.config.name ?? direct.id;
193
+ if (ConnectionNodeIdFactory.isLanguageModelConnectionNodeId(nodeId)) {
194
+ const parentId = this.parseParentForLanguageModelConnectionNodeId(nodeId);
195
+ return `${(parentId ? workflow.nodes.find((n) => n.id === parentId) : void 0)?.name ?? parentId ?? "Agent"} › Language model`;
196
+ }
197
+ if (ConnectionNodeIdFactory.isToolConnectionNodeId(nodeId)) {
198
+ const parsed = this.parseToolConnectionNodeId(nodeId);
199
+ if (!parsed) return nodeId;
200
+ const parent = workflow.nodes.find((n) => n.id === parsed.parentNodeId);
201
+ const agentLabel = parent?.name ?? parsed.parentNodeId;
202
+ const toolConfig = parent && AgentConfigInspector.isAgentNodeConfig(parent.config) ? parent.config.tools?.find((tool) => ConnectionNodeIdFactory.normalizeToolName(tool.name) === parsed.normalizedToolName) : void 0;
203
+ return `${agentLabel} › ${toolConfig?.presentation?.label ?? toolConfig?.name ?? parsed.normalizedToolName}`;
204
+ }
205
+ return nodeId;
206
+ }
207
+ isCredentialNodeIdInWorkflow(workflow, nodeId) {
208
+ if (workflow.nodes.some((n) => n.id === nodeId)) return true;
209
+ if (ConnectionNodeIdFactory.isLanguageModelConnectionNodeId(nodeId)) {
210
+ const parent = this.parseParentForLanguageModelConnectionNodeId(nodeId);
211
+ if (parent && workflow.nodes.some((n) => n.id === parent)) return true;
212
+ }
213
+ if (ConnectionNodeIdFactory.isToolConnectionNodeId(nodeId)) {
214
+ const parsed = this.parseToolConnectionNodeId(nodeId);
215
+ if (parsed && workflow.nodes.some((n) => n.id === parsed.parentNodeId)) return true;
216
+ }
217
+ return false;
218
+ }
219
+ findRequirement(workflow, nodeId, slotKey) {
220
+ const direct = this.findDirectRequirement(workflow, nodeId, slotKey);
221
+ if (direct) return direct;
222
+ if (ConnectionNodeIdFactory.isLanguageModelConnectionNodeId(nodeId)) {
223
+ const parent = this.parseParentForLanguageModelConnectionNodeId(nodeId);
224
+ if (parent) {
225
+ const fromConn = this.findLanguageModelRequirement(workflow, parent, slotKey);
226
+ if (fromConn) return fromConn;
227
+ }
228
+ }
229
+ if (ConnectionNodeIdFactory.isToolConnectionNodeId(nodeId)) {
230
+ const parsed = this.parseToolConnectionNodeId(nodeId);
231
+ if (parsed) {
232
+ const fromConn = this.findToolRequirement(workflow, parsed.parentNodeId, parsed.normalizedToolName, slotKey);
233
+ if (fromConn) return fromConn;
234
+ }
235
+ }
236
+ }
237
+ listSlots(workflow) {
238
+ const slots = [];
239
+ const classifier = WorkflowExecutableNodeClassifierFactory.create(workflow);
240
+ const hasConnectionMetadata = (workflow.connections?.length ?? 0) > 0;
241
+ for (const node of workflow.nodes) {
242
+ if (classifier.isConnectionOwnedNodeId(node.id)) {
243
+ for (const requirement of node.config.getCredentialRequirements?.() ?? []) slots.push({
244
+ workflowId: workflow.id,
245
+ nodeId: node.id,
246
+ nodeName: node.name ?? node.config.name ?? node.id,
247
+ requirement
248
+ });
249
+ continue;
250
+ }
251
+ if (AgentConfigInspector.isAgentNodeConfig(node.config)) {
252
+ if (!hasConnectionMetadata) {
253
+ const lmNodeId = ConnectionNodeIdFactory.languageModelConnectionNodeId(node.id);
254
+ const lmLabel = node.config.chatModel.presentation?.label ?? node.config.chatModel.name;
255
+ for (const requirement of node.config.chatModel.getCredentialRequirements?.() ?? []) slots.push({
256
+ workflowId: workflow.id,
257
+ nodeId: lmNodeId,
258
+ nodeName: lmLabel,
259
+ requirement
260
+ });
261
+ for (const toolConfig of node.config.tools ?? []) {
262
+ const toolNodeId = ConnectionNodeIdFactory.toolConnectionNodeId(node.id, toolConfig.name);
263
+ const toolLabel = toolConfig.presentation?.label ?? toolConfig.name;
264
+ for (const requirement of toolConfig.getCredentialRequirements?.() ?? []) slots.push({
265
+ workflowId: workflow.id,
266
+ nodeId: toolNodeId,
267
+ nodeName: toolLabel,
268
+ requirement
269
+ });
270
+ }
271
+ }
272
+ continue;
273
+ }
274
+ for (const requirement of node.config.getCredentialRequirements?.() ?? []) slots.push({
275
+ workflowId: workflow.id,
276
+ nodeId: node.id,
277
+ nodeName: node.name ?? node.config.name ?? node.id,
278
+ requirement
279
+ });
280
+ }
281
+ return slots;
282
+ }
283
+ findDirectRequirement(workflow, nodeId, slotKey) {
284
+ const node = workflow.nodes.find((entry) => entry.id === nodeId);
285
+ if (!node || AgentConfigInspector.isAgentNodeConfig(node.config)) return;
286
+ const requirement = node.config.getCredentialRequirements?.()?.find((entry) => entry.slotKey === slotKey);
287
+ if (!requirement) return;
288
+ return {
289
+ nodeName: node.name ?? node.config.name ?? node.id,
290
+ requirement
291
+ };
292
+ }
293
+ findLanguageModelRequirement(workflow, parentNodeId, slotKey) {
294
+ const parent = workflow.nodes.find((entry) => entry.id === parentNodeId);
295
+ if (!parent || !AgentConfigInspector.isAgentNodeConfig(parent.config)) return;
296
+ const requirement = parent.config.chatModel.getCredentialRequirements?.()?.find((entry) => entry.slotKey === slotKey);
297
+ if (!requirement) return;
298
+ return {
299
+ nodeName: parent.config.chatModel.presentation?.label ?? parent.config.chatModel.name ?? parent.name ?? parent.id,
300
+ requirement
301
+ };
302
+ }
303
+ findToolRequirement(workflow, parentNodeId, normalizedToolName, slotKey) {
304
+ const parent = workflow.nodes.find((entry) => entry.id === parentNodeId);
305
+ if (!parent || !AgentConfigInspector.isAgentNodeConfig(parent.config)) return;
306
+ const toolConfig = parent.config.tools?.find((tool) => ConnectionNodeIdFactory.normalizeToolName(tool.name) === normalizedToolName);
307
+ if (!toolConfig) return;
308
+ const requirement = toolConfig.getCredentialRequirements?.()?.find((entry) => entry.slotKey === slotKey);
309
+ if (!requirement) return;
310
+ return {
311
+ nodeName: toolConfig.presentation?.label ?? toolConfig.name ?? parent.name ?? parent.id,
312
+ requirement
313
+ };
314
+ }
315
+ parseParentForLanguageModelConnectionNodeId(nodeId) {
316
+ if (!ConnectionNodeIdFactory.isLanguageModelConnectionNodeId(nodeId)) return;
317
+ const suffix = `${ConnectionNodeIdFactory.connectionSegment}llm`;
318
+ return nodeId.slice(0, -suffix.length);
319
+ }
320
+ parseToolConnectionNodeId(nodeId) {
321
+ if (!ConnectionNodeIdFactory.isToolConnectionNodeId(nodeId)) return;
322
+ const marker = `${ConnectionNodeIdFactory.connectionSegment}tool${ConnectionNodeIdFactory.connectionSegment}`;
323
+ const idx = nodeId.indexOf(marker);
324
+ if (idx < 0) return;
325
+ const parentNodeId = nodeId.slice(0, idx);
326
+ const normalizedToolName = nodeId.slice(idx + marker.length);
327
+ if (!parentNodeId || !normalizedToolName) return;
328
+ return {
329
+ parentNodeId,
330
+ normalizedToolName
331
+ };
332
+ }
333
+ };
334
+ WorkflowCredentialNodeResolver = __decorate([injectable()], WorkflowCredentialNodeResolver);
335
+
336
+ //#endregion
337
+ //#region src/domain/credentials/CredentialFieldEnvOverlayService.ts
338
+ let CredentialFieldEnvOverlayService = class CredentialFieldEnvOverlayService$1 {
339
+ constructor(appConfig) {
340
+ this.appConfig = appConfig;
341
+ }
342
+ /** True when the field declares an env var and process.env has a non-empty string for it. */
343
+ isFieldResolvedFromEnv(field) {
344
+ const name = field.envVarName?.trim();
345
+ if (!name) return false;
346
+ const v = this.appConfig.env[name];
347
+ return typeof v === "string" && v.length > 0;
348
+ }
349
+ apply(args) {
350
+ const pub = { ...args.publicConfig };
351
+ const mat = { ...args.material };
352
+ for (const field of args.definition.publicFields ?? []) {
353
+ const name = field.envVarName?.trim();
354
+ if (!name) continue;
355
+ const v = this.appConfig.env[name];
356
+ if (typeof v === "string" && v.length > 0) pub[field.key] = v;
357
+ }
358
+ for (const field of args.definition.secretFields ?? []) {
359
+ const name = field.envVarName?.trim();
360
+ if (!name) continue;
361
+ const v = this.appConfig.env[name];
362
+ if (typeof v === "string" && v.length > 0) mat[field.key] = v;
363
+ }
364
+ return Object.freeze({
365
+ resolvedPublicConfig: Object.freeze(pub),
366
+ resolvedMaterial: Object.freeze(mat)
367
+ });
368
+ }
369
+ };
370
+ CredentialFieldEnvOverlayService = __decorate([
371
+ injectable(),
372
+ __decorateParam(0, inject(ApplicationTokens.AppConfig)),
373
+ __decorateMetadata("design:paramtypes", [Object])
374
+ ], CredentialFieldEnvOverlayService);
375
+
376
+ //#endregion
377
+ //#region src/domain/credentials/CredentialSecretCipher.ts
378
+ var _CredentialSecretCipher;
379
+ let CredentialSecretCipher = class CredentialSecretCipher$1 {
380
+ static {
381
+ _CredentialSecretCipher = this;
382
+ }
383
+ static algorithm = "aes-256-gcm";
384
+ static schemaVersion = 1;
385
+ static ivLength = 12;
386
+ constructor(appConfig) {
387
+ this.appConfig = appConfig;
388
+ }
389
+ encrypt(value) {
390
+ const iv = randomBytes(_CredentialSecretCipher.ivLength);
391
+ const cipher = createCipheriv(_CredentialSecretCipher.algorithm, this.resolveKeyMaterial(), iv);
392
+ const plaintext = Buffer.from(JSON.stringify(value), "utf8");
393
+ const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
394
+ const authTag = cipher.getAuthTag();
395
+ return {
396
+ encryptedJson: Buffer.concat([
397
+ iv,
398
+ authTag,
399
+ encrypted
400
+ ]).toString("base64"),
401
+ encryptionKeyId: this.resolveKeyId(),
402
+ schemaVersion: _CredentialSecretCipher.schemaVersion
403
+ };
404
+ }
405
+ decrypt(record) {
406
+ const packed = Buffer.from(record.encryptedJson, "base64");
407
+ const iv = packed.subarray(0, _CredentialSecretCipher.ivLength);
408
+ const authTag = packed.subarray(_CredentialSecretCipher.ivLength, _CredentialSecretCipher.ivLength + 16);
409
+ const encrypted = packed.subarray(_CredentialSecretCipher.ivLength + 16);
410
+ const decipher = createDecipheriv(_CredentialSecretCipher.algorithm, this.resolveKeyMaterial(), iv);
411
+ decipher.setAuthTag(authTag);
412
+ const plaintext = Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");
413
+ return JSON.parse(plaintext);
414
+ }
415
+ resolveKeyMaterial() {
416
+ const rawValue = this.appConfig.env.CODEMATION_CREDENTIALS_MASTER_KEY;
417
+ if (!rawValue || rawValue.trim().length === 0) throw new Error("CODEMATION_CREDENTIALS_MASTER_KEY is required to encrypt database-managed credentials.");
418
+ return createHash("sha256").update(rawValue).digest();
419
+ }
420
+ resolveKeyId() {
421
+ const rawValue = this.appConfig.env.CODEMATION_CREDENTIALS_MASTER_KEY;
422
+ return createHash("sha256").update(rawValue ?? "").digest("hex").slice(0, 12);
423
+ }
424
+ };
425
+ CredentialSecretCipher = _CredentialSecretCipher = __decorate([
426
+ injectable(),
427
+ __decorateParam(0, inject(ApplicationTokens.AppConfig)),
428
+ __decorateMetadata("design:paramtypes", [Object])
429
+ ], CredentialSecretCipher);
430
+
431
+ //#endregion
432
+ //#region src/domain/credentials/CredentialMaterialResolver.ts
433
+ var _ref$5;
434
+ let CredentialMaterialResolver = class CredentialMaterialResolver$1 {
435
+ constructor(credentialStore, credentialSecretCipher, appConfig) {
436
+ this.credentialStore = credentialStore;
437
+ this.credentialSecretCipher = credentialSecretCipher;
438
+ this.appConfig = appConfig;
439
+ }
440
+ async resolveMaterial(instance) {
441
+ if (instance.secretRef.kind === "db") {
442
+ const secretMaterial = await this.credentialStore.getSecretMaterial(instance.instanceId);
443
+ if (!secretMaterial) throw new Error(`Credential ${instance.instanceId} is missing encrypted secret material.`);
444
+ return this.credentialSecretCipher.decrypt(secretMaterial);
445
+ }
446
+ if (instance.secretRef.kind === "env") return this.resolveEnvMaterial(instance);
447
+ return instance.secretRef.value;
448
+ }
449
+ resolveEnvMaterial(instance) {
450
+ if (instance.secretRef.kind !== "env") throw new Error(`Credential ${instance.instanceId} is not environment-backed.`);
451
+ const resolved = {};
452
+ const missingEnvironmentVariables = [];
453
+ for (const [fieldKey, envVarName] of Object.entries(instance.secretRef.envByField)) {
454
+ const value = this.appConfig.env[envVarName];
455
+ if (value === void 0 || value.length === 0) {
456
+ missingEnvironmentVariables.push(envVarName);
457
+ continue;
458
+ }
459
+ resolved[fieldKey] = value;
460
+ }
461
+ if (missingEnvironmentVariables.length > 0) throw new Error(`Credential ${instance.instanceId} requires environment variables that are not set: ${missingEnvironmentVariables.join(", ")}.`);
462
+ return resolved;
463
+ }
464
+ };
465
+ CredentialMaterialResolver = __decorate([
466
+ injectable(),
467
+ __decorateParam(0, inject(ApplicationTokens.CredentialStore)),
468
+ __decorateParam(1, inject(CredentialSecretCipher)),
469
+ __decorateParam(2, inject(ApplicationTokens.AppConfig)),
470
+ __decorateMetadata("design:paramtypes", [
471
+ Object,
472
+ typeof (_ref$5 = typeof CredentialSecretCipher !== "undefined" && CredentialSecretCipher) === "function" ? _ref$5 : Object,
473
+ Object
474
+ ])
475
+ ], CredentialMaterialResolver);
476
+
477
+ //#endregion
478
+ //#region src/domain/credentials/CredentialInstanceService.ts
479
+ var _ref$4, _ref2$4, _ref3$3, _ref4$2;
480
+ let CredentialInstanceService = class CredentialInstanceService$1 {
481
+ constructor(credentialStore, credentialTypeRegistry, credentialSecretCipher, credentialFieldEnvOverlayService, credentialMaterialResolver, credentialSessionService) {
482
+ this.credentialStore = credentialStore;
483
+ this.credentialTypeRegistry = credentialTypeRegistry;
484
+ this.credentialSecretCipher = credentialSecretCipher;
485
+ this.credentialFieldEnvOverlayService = credentialFieldEnvOverlayService;
486
+ this.credentialMaterialResolver = credentialMaterialResolver;
487
+ this.credentialSessionService = credentialSessionService;
488
+ }
489
+ async listInstances() {
490
+ const instances = await this.credentialStore.listInstances();
491
+ const latestTestResults = await this.credentialStore.getLatestTestResults(instances.map((instance) => instance.instanceId));
492
+ return await Promise.all(instances.map(async (instance) => await this.toDto(instance, latestTestResults.get(instance.instanceId))));
493
+ }
494
+ async getInstance(instanceId) {
495
+ const instance = await this.credentialStore.getInstance(instanceId);
496
+ if (!instance) return;
497
+ const latestTestResult = await this.credentialStore.getLatestTestResult(instanceId);
498
+ return await this.toDto(instance, latestTestResult);
499
+ }
500
+ async getInstanceWithSecrets(instanceId) {
501
+ const instance = await this.credentialStore.getInstance(instanceId);
502
+ if (!instance) return;
503
+ const latestTestResult = await this.credentialStore.getLatestTestResult(instanceId);
504
+ const base = await this.toDto(instance, latestTestResult);
505
+ try {
506
+ const material = await this.credentialMaterialResolver.resolveMaterial(instance);
507
+ const secretConfig = Object.fromEntries(Object.entries(material).map(([k, v]) => [k, String(v ?? "")]));
508
+ const envSecretRefs = instance.secretRef.kind === "env" ? instance.secretRef.envByField : void 0;
509
+ return {
510
+ ...base,
511
+ secretConfig,
512
+ envSecretRefs
513
+ };
514
+ } catch {
515
+ return base;
516
+ }
517
+ }
518
+ async create(request) {
519
+ const credentialType = this.requireCredentialType(request.typeId);
520
+ const publicFields = credentialType.definition.publicFields ?? [];
521
+ const secretFields = credentialType.definition.secretFields ?? [];
522
+ this.validateRequestFields({
523
+ displayName: request.displayName,
524
+ publicFields,
525
+ publicConfig: request.publicConfig ?? {},
526
+ secretFields,
527
+ sourceKind: request.sourceKind,
528
+ secretConfig: request.secretConfig ?? {},
529
+ envSecretRefs: request.envSecretRefs ?? {}
530
+ });
531
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
532
+ const strippedPublic = this.stripEnvManagedFieldValues(publicFields, request.publicConfig ?? {});
533
+ const strippedSecretForRef = this.stripEnvManagedFieldValues(secretFields, request.secretConfig ?? {});
534
+ const instance = {
535
+ instanceId: randomUUID(),
536
+ typeId: request.typeId,
537
+ displayName: request.displayName.trim(),
538
+ sourceKind: request.sourceKind,
539
+ publicConfig: Object.freeze({ ...strippedPublic }),
540
+ secretRef: this.createSecretRef(request.sourceKind, strippedSecretForRef, request.envSecretRefs ?? {}),
541
+ tags: Object.freeze([...request.tags ?? []]),
542
+ setupStatus: credentialType.definition.auth?.kind === "oauth2" ? "draft" : "ready",
543
+ createdAt: timestamp,
544
+ updatedAt: timestamp
545
+ };
546
+ await this.credentialStore.saveInstance({
547
+ instance,
548
+ secretMaterial: this.createSecretMaterial(instance, strippedSecretForRef, timestamp)
549
+ });
550
+ this.credentialSessionService.evictInstance(instance.instanceId);
551
+ return this.toDto(instance, void 0);
552
+ }
553
+ async update(instanceId, request) {
554
+ const existing = await this.requireInstance(instanceId);
555
+ const credentialType = this.requireCredentialType(existing.typeId);
556
+ const mergedPublicRaw = { ...request.publicConfig ?? existing.publicConfig };
557
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
558
+ const nextSecretConfig = request.secretConfig;
559
+ const nextEnvSecretRefs = request.envSecretRefs;
560
+ const secretFields = credentialType.definition.secretFields ?? [];
561
+ this.validateRequestFields({
562
+ displayName: request.displayName ?? existing.displayName,
563
+ publicFields: credentialType.definition.publicFields ?? [],
564
+ publicConfig: mergedPublicRaw,
565
+ secretFields,
566
+ sourceKind: existing.sourceKind,
567
+ secretConfig: nextSecretConfig ?? {},
568
+ envSecretRefs: nextEnvSecretRefs ?? {},
569
+ allowSecretOmission: true
570
+ });
571
+ const publicConfig = Object.freeze({ ...this.stripEnvManagedFieldValues(credentialType.definition.publicFields ?? [], mergedPublicRaw) });
572
+ const mergedSecretForRef = nextSecretConfig !== void 0 ? this.stripEnvManagedFieldValues(secretFields, nextSecretConfig) : void 0;
573
+ const instance = {
574
+ ...existing,
575
+ displayName: request.displayName?.trim() || existing.displayName,
576
+ publicConfig,
577
+ tags: Object.freeze([...request.tags ?? existing.tags]),
578
+ setupStatus: request.setupStatus ?? existing.setupStatus,
579
+ secretRef: nextSecretConfig || nextEnvSecretRefs ? this.createSecretRef(existing.sourceKind, mergedSecretForRef ?? {}, nextEnvSecretRefs ?? {}) : existing.secretRef,
580
+ updatedAt
581
+ };
582
+ await this.credentialStore.saveInstance({
583
+ instance,
584
+ secretMaterial: nextSecretConfig !== void 0 && mergedSecretForRef !== void 0 ? this.createSecretMaterial(instance, mergedSecretForRef, updatedAt) : void 0
585
+ });
586
+ this.credentialSessionService.evictInstance(instance.instanceId);
587
+ return this.toDto(instance, await this.credentialStore.getLatestTestResult(instance.instanceId));
588
+ }
589
+ async delete(instanceId) {
590
+ await this.credentialStore.deleteInstance(instanceId);
591
+ this.credentialSessionService.evictInstance(instanceId);
592
+ }
593
+ async disconnectOAuth2(instanceId) {
594
+ const instance = await this.requireInstance(instanceId);
595
+ if (this.requireCredentialType(instance.typeId).definition.auth?.kind !== "oauth2") throw new ApplicationRequestError(400, `Credential instance ${instanceId} does not use OAuth2.`);
596
+ const updatedInstance = {
597
+ ...instance,
598
+ setupStatus: "draft",
599
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
600
+ };
601
+ await this.credentialStore.saveInstance({ instance: updatedInstance });
602
+ await this.credentialStore.deleteOAuth2Material(instanceId);
603
+ this.credentialSessionService.evictInstance(instanceId);
604
+ return await this.toDto(updatedInstance, await this.credentialStore.getLatestTestResult(instanceId));
605
+ }
606
+ async requireInstance(instanceId) {
607
+ const instance = await this.credentialStore.getInstance(instanceId);
608
+ if (!instance) throw new ApplicationRequestError(404, `Unknown credential instance: ${instanceId}`);
609
+ return instance;
610
+ }
611
+ createSecretRef(sourceKind, secretConfig, envSecretRefs) {
612
+ if (sourceKind === "db") return { kind: "db" };
613
+ if (sourceKind === "env") return {
614
+ kind: "env",
615
+ envByField: Object.freeze({ ...envSecretRefs })
616
+ };
617
+ return {
618
+ kind: "code",
619
+ value: Object.freeze({ ...secretConfig })
620
+ };
621
+ }
622
+ createSecretMaterial(instance, secretConfig, updatedAt) {
623
+ if (instance.sourceKind !== "db") return;
624
+ const encrypted = this.credentialSecretCipher.encrypt(secretConfig);
625
+ return {
626
+ instanceId: instance.instanceId,
627
+ encryptedJson: encrypted.encryptedJson,
628
+ encryptionKeyId: encrypted.encryptionKeyId,
629
+ schemaVersion: encrypted.schemaVersion,
630
+ updatedAt
631
+ };
632
+ }
633
+ validateRequestFields(args) {
634
+ if (!args.displayName || args.displayName.trim().length === 0) throw new ApplicationRequestError(400, "Credential displayName is required.");
635
+ this.assertRequiredFields("publicConfig", args.publicFields, args.publicConfig);
636
+ if (args.sourceKind === "db") {
637
+ if (!args.allowSecretOmission || Object.keys(args.secretConfig).length > 0) this.assertRequiredFields("secretConfig", args.secretFields, args.secretConfig);
638
+ return;
639
+ }
640
+ if (args.sourceKind === "env") {
641
+ if (!args.allowSecretOmission || Object.keys(args.envSecretRefs).length > 0) this.assertRequiredEnvFields(args.secretFields, args.envSecretRefs);
642
+ return;
643
+ }
644
+ if (!args.allowSecretOmission || Object.keys(args.secretConfig).length > 0) this.assertRequiredFields("secretConfig", args.secretFields, args.secretConfig);
645
+ }
646
+ stripEnvManagedFieldValues(fields, value) {
647
+ const out = { ...value };
648
+ for (const field of fields) if (this.credentialFieldEnvOverlayService.isFieldResolvedFromEnv(field)) delete out[field.key];
649
+ return Object.freeze(out);
650
+ }
651
+ assertRequiredFields(fieldName, schema, value) {
652
+ const missing = schema.filter((field) => field.required === true).filter((field) => !this.credentialFieldEnvOverlayService.isFieldResolvedFromEnv(field)).filter((field) => value[field.key] === void 0 || value[field.key] === null || value[field.key] === "").map((field) => field.key);
653
+ if (missing.length > 0) throw new ApplicationRequestError(400, `Missing required ${fieldName} field(s): ${missing.join(", ")}`);
654
+ }
655
+ assertRequiredEnvFields(schema, envSecretRefs) {
656
+ const missing = schema.filter((field) => field.required === true).filter((field) => !this.credentialFieldEnvOverlayService.isFieldResolvedFromEnv(field)).filter((field) => !envSecretRefs[field.key] || envSecretRefs[field.key].trim().length === 0).map((field) => field.key);
657
+ if (missing.length > 0) throw new ApplicationRequestError(400, `Missing required envSecretRefs field(s): ${missing.join(", ")}`);
658
+ }
659
+ requireCredentialType(typeId) {
660
+ const credentialType = this.credentialTypeRegistry.getCredentialType(typeId);
661
+ if (!credentialType) throw new ApplicationRequestError(400, `Unknown credential type: ${typeId}`);
662
+ return credentialType;
663
+ }
664
+ async markOAuth2Connected(instanceId, connectedAt) {
665
+ const instance = await this.requireInstance(instanceId);
666
+ await this.credentialStore.saveInstance({ instance: {
667
+ ...instance,
668
+ setupStatus: "ready",
669
+ updatedAt: connectedAt
670
+ } });
671
+ this.credentialSessionService.evictInstance(instanceId);
672
+ }
673
+ async toDto(instance, latestTestResult) {
674
+ const oauth2Connection = await this.toOAuth2ConnectionDto(instance);
675
+ return {
676
+ instanceId: instance.instanceId,
677
+ typeId: instance.typeId,
678
+ displayName: instance.displayName,
679
+ sourceKind: instance.sourceKind,
680
+ publicConfig: instance.publicConfig,
681
+ tags: instance.tags,
682
+ setupStatus: instance.setupStatus,
683
+ createdAt: instance.createdAt,
684
+ updatedAt: instance.updatedAt,
685
+ latestHealth: latestTestResult?.health,
686
+ oauth2Connection
687
+ };
688
+ }
689
+ async toOAuth2ConnectionDto(instance) {
690
+ const credentialType = this.credentialTypeRegistry.getCredentialType(instance.typeId);
691
+ if (credentialType?.definition.auth?.kind !== "oauth2") return;
692
+ const providerId = "providerId" in credentialType.definition.auth ? credentialType.definition.auth.providerId : "custom";
693
+ const material = await this.credentialStore.getOAuth2Material(instance.instanceId);
694
+ if (!material) return {
695
+ status: "disconnected",
696
+ providerId,
697
+ scopes: [...credentialType.definition.auth.scopes]
698
+ };
699
+ return {
700
+ status: "connected",
701
+ providerId: material.providerId,
702
+ connectedEmail: material.connectedEmail,
703
+ connectedAt: material.connectedAt,
704
+ scopes: material.scopes,
705
+ updatedAt: material.updatedAt
706
+ };
707
+ }
708
+ };
709
+ CredentialInstanceService = __decorate([
710
+ injectable(),
711
+ __decorateParam(0, inject(ApplicationTokens.CredentialStore)),
712
+ __decorateParam(1, inject(CredentialTypeRegistryImpl)),
713
+ __decorateParam(2, inject(CredentialSecretCipher)),
714
+ __decorateParam(3, inject(CredentialFieldEnvOverlayService)),
715
+ __decorateParam(4, inject(CredentialMaterialResolver)),
716
+ __decorateParam(5, inject(CoreTokens.CredentialSessionService)),
717
+ __decorateMetadata("design:paramtypes", [
718
+ Object,
719
+ typeof (_ref$4 = typeof CredentialTypeRegistryImpl !== "undefined" && CredentialTypeRegistryImpl) === "function" ? _ref$4 : Object,
720
+ typeof (_ref2$4 = typeof CredentialSecretCipher !== "undefined" && CredentialSecretCipher) === "function" ? _ref2$4 : Object,
721
+ typeof (_ref3$3 = typeof CredentialFieldEnvOverlayService !== "undefined" && CredentialFieldEnvOverlayService) === "function" ? _ref3$3 : Object,
722
+ typeof (_ref4$2 = typeof CredentialMaterialResolver !== "undefined" && CredentialMaterialResolver) === "function" ? _ref4$2 : Object,
723
+ Object
724
+ ])
725
+ ], CredentialInstanceService);
726
+
727
+ //#endregion
728
+ //#region src/domain/credentials/CredentialBindingService.ts
729
+ var _ref$3, _ref2$3;
730
+ let CredentialBindingService = class CredentialBindingService$1 {
731
+ constructor(credentialStore, credentialInstanceService, workflowRepository, credentialSessionService, workflowCredentialNodeResolver) {
732
+ this.credentialStore = credentialStore;
733
+ this.credentialInstanceService = credentialInstanceService;
734
+ this.workflowRepository = workflowRepository;
735
+ this.credentialSessionService = credentialSessionService;
736
+ this.workflowCredentialNodeResolver = workflowCredentialNodeResolver;
737
+ }
738
+ async upsertBinding(args) {
739
+ const workflow = this.requireWorkflow(args.workflowId);
740
+ const requirement = this.requireRequirement(workflow, args.nodeId, args.slotKey);
741
+ const instance = await this.credentialInstanceService.requireInstance(args.instanceId);
742
+ if (!requirement.acceptedTypes.includes(instance.typeId)) throw new ApplicationRequestError(400, `Credential instance ${instance.instanceId} (${instance.typeId}) is not compatible with slot ${args.slotKey}. Accepted types: ${requirement.acceptedTypes.join(", ")}`);
743
+ const binding = {
744
+ key: {
745
+ workflowId: args.workflowId,
746
+ nodeId: args.nodeId,
747
+ slotKey: args.slotKey
748
+ },
749
+ instanceId: args.instanceId,
750
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
751
+ };
752
+ await this.credentialStore.upsertBinding(binding);
753
+ this.credentialSessionService.evictBinding(binding.key);
754
+ return binding;
755
+ }
756
+ async listWorkflowHealth(workflowId) {
757
+ const workflow = this.requireWorkflow(workflowId);
758
+ const bindings = await this.credentialStore.listBindingsByWorkflowId(workflowId);
759
+ const bindingsByKey = new Map(bindings.map((binding) => [this.toBindingKeyString(binding.key), binding]));
760
+ const slots = [];
761
+ for (const slotRef of this.workflowCredentialNodeResolver.listSlots(workflow)) {
762
+ const requirement = slotRef.requirement;
763
+ const bindingKey = {
764
+ workflowId,
765
+ nodeId: slotRef.nodeId,
766
+ slotKey: requirement.slotKey
767
+ };
768
+ const binding = bindingsByKey.get(this.toBindingKeyString(bindingKey));
769
+ if (!binding) {
770
+ slots.push({
771
+ workflowId,
772
+ nodeId: slotRef.nodeId,
773
+ nodeName: slotRef.nodeName,
774
+ requirement,
775
+ health: { status: requirement.optional ? "optional-unbound" : "unbound" }
776
+ });
777
+ continue;
778
+ }
779
+ const instance = await this.credentialInstanceService.requireInstance(binding.instanceId);
780
+ const latestTestResult = await this.credentialStore.getLatestTestResult(instance.instanceId);
781
+ slots.push({
782
+ workflowId,
783
+ nodeId: slotRef.nodeId,
784
+ nodeName: slotRef.nodeName,
785
+ requirement,
786
+ instance: {
787
+ instanceId: instance.instanceId,
788
+ typeId: instance.typeId,
789
+ displayName: instance.displayName,
790
+ setupStatus: instance.setupStatus
791
+ },
792
+ health: {
793
+ status: latestTestResult?.health.status ?? "unknown",
794
+ message: latestTestResult?.health.message,
795
+ testedAt: latestTestResult?.health.testedAt
796
+ }
797
+ });
798
+ }
799
+ return {
800
+ workflowId,
801
+ slots
802
+ };
803
+ }
804
+ requireWorkflow(workflowId) {
805
+ const workflow = this.workflowRepository.get(decodeURIComponent(workflowId));
806
+ if (!workflow) throw new ApplicationRequestError(404, `Unknown workflowId: ${workflowId}`);
807
+ return workflow;
808
+ }
809
+ requireRequirement(workflow, nodeId, slotKey) {
810
+ const resolved = this.workflowCredentialNodeResolver.findRequirement(workflow, nodeId, slotKey);
811
+ if (!resolved) {
812
+ if (!this.workflowCredentialNodeResolver.isCredentialNodeIdInWorkflow(workflow, nodeId)) throw new ApplicationRequestError(404, `Unknown workflow node: ${nodeId}`);
813
+ throw new ApplicationRequestError(400, `Node ${nodeId} does not declare credential slot ${slotKey}.`);
814
+ }
815
+ return resolved.requirement;
816
+ }
817
+ toBindingKeyString(bindingKey) {
818
+ return `${bindingKey.workflowId}:${bindingKey.nodeId}:${bindingKey.slotKey}`;
819
+ }
820
+ };
821
+ CredentialBindingService = __decorate([
822
+ injectable(),
823
+ __decorateParam(0, inject(ApplicationTokens.CredentialStore)),
824
+ __decorateParam(1, inject(CredentialInstanceService)),
825
+ __decorateParam(2, inject(CoreTokens.WorkflowRepository)),
826
+ __decorateParam(3, inject(CoreTokens.CredentialSessionService)),
827
+ __decorateParam(4, inject(WorkflowCredentialNodeResolver)),
828
+ __decorateMetadata("design:paramtypes", [
829
+ Object,
830
+ typeof (_ref$3 = typeof CredentialInstanceService !== "undefined" && CredentialInstanceService) === "function" ? _ref$3 : Object,
831
+ Object,
832
+ Object,
833
+ typeof (_ref2$3 = typeof WorkflowCredentialNodeResolver !== "undefined" && WorkflowCredentialNodeResolver) === "function" ? _ref2$3 : Object
834
+ ])
835
+ ], CredentialBindingService);
836
+
837
+ //#endregion
838
+ //#region src/domain/credentials/CredentialRuntimeMaterialService.ts
839
+ var _ref$2, _ref2$2, _ref3$2;
840
+ let CredentialRuntimeMaterialService = class CredentialRuntimeMaterialService$1 {
841
+ constructor(credentialStore, credentialMaterialResolver, credentialSecretCipher, credentialTypeRegistry) {
842
+ this.credentialStore = credentialStore;
843
+ this.credentialMaterialResolver = credentialMaterialResolver;
844
+ this.credentialSecretCipher = credentialSecretCipher;
845
+ this.credentialTypeRegistry = credentialTypeRegistry;
846
+ }
847
+ async compose(instance) {
848
+ const baseMaterial = await this.credentialMaterialResolver.resolveMaterial(instance);
849
+ if ((this.credentialTypeRegistry.getCredentialType(instance.typeId)?.definition.auth)?.kind !== "oauth2") return baseMaterial;
850
+ const oauth2Material = await this.credentialStore.getOAuth2Material(instance.instanceId);
851
+ if (!oauth2Material) return baseMaterial;
852
+ const decryptedOauth2Material = this.credentialSecretCipher.decrypt(oauth2Material);
853
+ return Object.freeze({
854
+ ...baseMaterial,
855
+ ...decryptedOauth2Material
856
+ });
857
+ }
858
+ };
859
+ CredentialRuntimeMaterialService = __decorate([
860
+ injectable(),
861
+ __decorateParam(0, inject(ApplicationTokens.CredentialStore)),
862
+ __decorateParam(1, inject(CredentialMaterialResolver)),
863
+ __decorateParam(2, inject(CredentialSecretCipher)),
864
+ __decorateParam(3, inject(CredentialTypeRegistryImpl)),
865
+ __decorateMetadata("design:paramtypes", [
866
+ Object,
867
+ typeof (_ref$2 = typeof CredentialMaterialResolver !== "undefined" && CredentialMaterialResolver) === "function" ? _ref$2 : Object,
868
+ typeof (_ref2$2 = typeof CredentialSecretCipher !== "undefined" && CredentialSecretCipher) === "function" ? _ref2$2 : Object,
869
+ typeof (_ref3$2 = typeof CredentialTypeRegistryImpl !== "undefined" && CredentialTypeRegistryImpl) === "function" ? _ref3$2 : Object
870
+ ])
871
+ ], CredentialRuntimeMaterialService);
872
+
873
+ //#endregion
874
+ //#region src/domain/credentials/CredentialSessionServiceImpl.ts
875
+ var _ref$1, _ref2$1, _ref3$1, _ref4$1;
876
+ let CredentialSessionServiceImpl = class CredentialSessionServiceImpl$1 {
877
+ cachedSessionsByInstanceId = /* @__PURE__ */ new Map();
878
+ cachedInstanceIdsByBindingKey = /* @__PURE__ */ new Map();
879
+ constructor(credentialStore, credentialRuntimeMaterialService, credentialFieldEnvOverlayService, credentialTypeRegistry, workflowRepository, workflowCredentialNodeResolver) {
880
+ this.credentialStore = credentialStore;
881
+ this.credentialRuntimeMaterialService = credentialRuntimeMaterialService;
882
+ this.credentialFieldEnvOverlayService = credentialFieldEnvOverlayService;
883
+ this.credentialTypeRegistry = credentialTypeRegistry;
884
+ this.workflowRepository = workflowRepository;
885
+ this.workflowCredentialNodeResolver = workflowCredentialNodeResolver;
886
+ }
887
+ async getSession(args) {
888
+ const workflow = this.workflowRepository.get(decodeURIComponent(args.workflowId));
889
+ const displayLabel = workflow ? this.workflowCredentialNodeResolver.describeCredentialNodeDisplay(workflow, args.nodeId) : void 0;
890
+ const requirement = workflow ? this.workflowCredentialNodeResolver.findRequirement(workflow, args.nodeId, args.slotKey)?.requirement : void 0;
891
+ const bindingKey = {
892
+ workflowId: args.workflowId,
893
+ nodeId: args.nodeId,
894
+ slotKey: args.slotKey
895
+ };
896
+ const binding = await this.credentialStore.getBinding(bindingKey);
897
+ if (!binding) {
898
+ const unbound = new CredentialUnboundError(bindingKey, requirement?.acceptedTypes ?? []);
899
+ if (displayLabel) throw new Error(`${displayLabel}: ${unbound.message}`, { cause: unbound });
900
+ throw unbound;
901
+ }
902
+ const bindingCacheKey = this.toBindingKeyString(bindingKey);
903
+ this.cachedInstanceIdsByBindingKey.set(bindingCacheKey, binding.instanceId);
904
+ const cachedSession = this.cachedSessionsByInstanceId.get(binding.instanceId);
905
+ if (cachedSession) return await cachedSession;
906
+ const nextSessionPromise = this.createSession(binding.instanceId, displayLabel).catch((error) => {
907
+ this.cachedSessionsByInstanceId.delete(binding.instanceId);
908
+ throw error;
909
+ });
910
+ this.cachedSessionsByInstanceId.set(binding.instanceId, nextSessionPromise);
911
+ return await nextSessionPromise;
912
+ }
913
+ evictInstance(instanceId) {
914
+ this.cachedSessionsByInstanceId.delete(instanceId);
915
+ }
916
+ evictBinding(bindingKey) {
917
+ const cacheKey = this.toBindingKeyString(bindingKey);
918
+ const instanceId = this.cachedInstanceIdsByBindingKey.get(cacheKey);
919
+ if (instanceId) this.cachedSessionsByInstanceId.delete(instanceId);
920
+ this.cachedInstanceIdsByBindingKey.delete(cacheKey);
921
+ }
922
+ async createSession(instanceId, displayLabel) {
923
+ const instance = await this.credentialStore.getInstance(instanceId);
924
+ if (!instance) throw new ApplicationRequestError(404, `Unknown credential instance: ${instanceId}`);
925
+ const credentialType = this.credentialTypeRegistry.getCredentialType(instance.typeId);
926
+ if (!credentialType) throw new ApplicationRequestError(400, `${displayLabel ? `${displayLabel}: ` : ""}Credential type "${instance.typeId}" is not registered in this runtime (binding points at an unknown type).`);
927
+ const material = await this.credentialRuntimeMaterialService.compose(instance);
928
+ const { resolvedPublicConfig, resolvedMaterial } = this.credentialFieldEnvOverlayService.apply({
929
+ definition: credentialType.definition,
930
+ publicConfig: instance.publicConfig,
931
+ material
932
+ });
933
+ return await credentialType.createSession({
934
+ instance,
935
+ material: resolvedMaterial,
936
+ publicConfig: resolvedPublicConfig
937
+ });
938
+ }
939
+ toBindingKeyString(bindingKey) {
940
+ return `${bindingKey.workflowId}:${bindingKey.nodeId}:${bindingKey.slotKey}`;
941
+ }
942
+ };
943
+ CredentialSessionServiceImpl = __decorate([
944
+ injectable(),
945
+ __decorateParam(0, inject(ApplicationTokens.CredentialStore)),
946
+ __decorateParam(1, inject(CredentialRuntimeMaterialService)),
947
+ __decorateParam(2, inject(CredentialFieldEnvOverlayService)),
948
+ __decorateParam(3, inject(CredentialTypeRegistryImpl)),
949
+ __decorateParam(4, inject(CoreTokens.WorkflowRepository)),
950
+ __decorateParam(5, inject(WorkflowCredentialNodeResolver)),
951
+ __decorateMetadata("design:paramtypes", [
952
+ Object,
953
+ typeof (_ref$1 = typeof CredentialRuntimeMaterialService !== "undefined" && CredentialRuntimeMaterialService) === "function" ? _ref$1 : Object,
954
+ typeof (_ref2$1 = typeof CredentialFieldEnvOverlayService !== "undefined" && CredentialFieldEnvOverlayService) === "function" ? _ref2$1 : Object,
955
+ typeof (_ref3$1 = typeof CredentialTypeRegistryImpl !== "undefined" && CredentialTypeRegistryImpl) === "function" ? _ref3$1 : Object,
956
+ Object,
957
+ typeof (_ref4$1 = typeof WorkflowCredentialNodeResolver !== "undefined" && WorkflowCredentialNodeResolver) === "function" ? _ref4$1 : Object
958
+ ])
959
+ ], CredentialSessionServiceImpl);
960
+
961
+ //#endregion
962
+ //#region src/domain/credentials/CredentialTestService.ts
963
+ var _ref, _ref2, _ref3, _ref4;
964
+ let CredentialTestService = class CredentialTestService$1 {
965
+ constructor(credentialInstanceService, credentialRuntimeMaterialService, credentialFieldEnvOverlayService, credentialTypeRegistry, credentialStore, credentialSessionService) {
966
+ this.credentialInstanceService = credentialInstanceService;
967
+ this.credentialRuntimeMaterialService = credentialRuntimeMaterialService;
968
+ this.credentialFieldEnvOverlayService = credentialFieldEnvOverlayService;
969
+ this.credentialTypeRegistry = credentialTypeRegistry;
970
+ this.credentialStore = credentialStore;
971
+ this.credentialSessionService = credentialSessionService;
972
+ }
973
+ async test(instanceId) {
974
+ const instance = await this.credentialInstanceService.requireInstance(instanceId);
975
+ const credentialType = this.requireCredentialType(instance.typeId);
976
+ const material = await this.credentialRuntimeMaterialService.compose(instance);
977
+ const { resolvedPublicConfig, resolvedMaterial } = this.credentialFieldEnvOverlayService.apply({
978
+ definition: credentialType.definition,
979
+ publicConfig: instance.publicConfig,
980
+ material
981
+ });
982
+ const health = await credentialType.test({
983
+ instance,
984
+ material: resolvedMaterial,
985
+ publicConfig: resolvedPublicConfig
986
+ });
987
+ const testedAt = health.testedAt ?? (/* @__PURE__ */ new Date()).toISOString();
988
+ await this.credentialStore.saveTestResult({
989
+ testId: randomUUID(),
990
+ instanceId,
991
+ health: {
992
+ ...health,
993
+ testedAt
994
+ },
995
+ testedAt,
996
+ expiresAt: health.expiresAt
997
+ });
998
+ this.credentialSessionService.evictInstance(instanceId);
999
+ return {
1000
+ ...health,
1001
+ testedAt
1002
+ };
1003
+ }
1004
+ requireCredentialType(typeId) {
1005
+ const credentialType = this.credentialTypeRegistry.getCredentialType(typeId);
1006
+ if (!credentialType) throw new ApplicationRequestError(400, `Unknown credential type: ${typeId}`);
1007
+ return credentialType;
1008
+ }
1009
+ };
1010
+ CredentialTestService = __decorate([
1011
+ injectable(),
1012
+ __decorateParam(0, inject(CredentialInstanceService)),
1013
+ __decorateParam(1, inject(CredentialRuntimeMaterialService)),
1014
+ __decorateParam(2, inject(CredentialFieldEnvOverlayService)),
1015
+ __decorateParam(3, inject(CredentialTypeRegistryImpl)),
1016
+ __decorateParam(4, inject(ApplicationTokens.CredentialStore)),
1017
+ __decorateParam(5, inject(CoreTokens.CredentialSessionService)),
1018
+ __decorateMetadata("design:paramtypes", [
1019
+ typeof (_ref = typeof CredentialInstanceService !== "undefined" && CredentialInstanceService) === "function" ? _ref : Object,
1020
+ typeof (_ref2 = typeof CredentialRuntimeMaterialService !== "undefined" && CredentialRuntimeMaterialService) === "function" ? _ref2 : Object,
1021
+ typeof (_ref3 = typeof CredentialFieldEnvOverlayService !== "undefined" && CredentialFieldEnvOverlayService) === "function" ? _ref3 : Object,
1022
+ typeof (_ref4 = typeof CredentialTypeRegistryImpl !== "undefined" && CredentialTypeRegistryImpl) === "function" ? _ref4 : Object,
1023
+ Object,
1024
+ Object
1025
+ ])
1026
+ ], CredentialTestService);
1027
+
1028
+ //#endregion
1029
+ export { CredentialInstanceService as a, CredentialFieldEnvOverlayService as c, ApplicationRequestError as d, CredentialTypeRegistryImpl as f, CredentialBindingService as i, WorkflowCredentialNodeResolver as l, OpenAiApiKeyCredentialHealthTester as m, CredentialSessionServiceImpl as n, CredentialMaterialResolver as o, OpenAiApiKeyCredentialTypeFactory as p, CredentialRuntimeMaterialService as r, CredentialSecretCipher as s, CredentialTestService as t, ApplicationTokens as u };
1030
+ //# sourceMappingURL=CredentialServices-BKBGe7l3.js.map