@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
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # `@codemation/host`
2
+
3
+ The **framework host**: application composition (`CodemationApplication`), HTTP/WebSocket gateway (Hono), persistence (Prisma/Postgres), plugin and workflow discovery, shared React UI shell pieces, and server/client **subpath bundles** so Next.js and Node servers only import what they need.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @codemation/host@^0.0.0
9
+ # or
10
+ npm install @codemation/host@^0.0.0
11
+ ```
12
+
13
+ ## When to use
14
+
15
+ Depend on this package when you embed Codemation in a custom server, extend the host, or build tooling that must open the same application graph as production. Browser bundles should use `@codemation/host/client` (and related entry points), not the full server graph.
16
+
17
+ ## Usage
18
+
19
+ Root re-exports types and `CodemationApplication` for programmatic hosting:
20
+
21
+ ```ts
22
+ import { CodemationApplication, type CodemationApplicationConfig } from "@codemation/host";
23
+ ```
24
+
25
+ Common subpaths (see `package.json` `exports`):
26
+
27
+ | Import | Role |
28
+ | ------------------------------------- | -------------------------- |
29
+ | `@codemation/host/server` | Hono/server wiring |
30
+ | `@codemation/host/next/server` | Next.js server integration |
31
+ | `@codemation/host/client` | Browser/client bundle |
32
+ | `@codemation/host/consumer` | Consumer-app helpers |
33
+ | `@codemation/host/credentials` | Credential-related surface |
34
+ | `@codemation/host/persistence` | Persistence layer entry |
35
+ | `@codemation/host/dev-server-sidecar` | Dev-time sidecar/guards |
36
+
37
+ The `development` condition in `exports` can resolve TypeScript sources during local work; published builds use `dist`.
38
+
39
+ ## Persistence: TCP PostgreSQL vs PGlite
40
+
41
+ Codemation uses a **single** Prisma schema (`provider = "postgresql"`). You can run it against either:
42
+
43
+ - **TCP PostgreSQL** — a normal `postgresql://` or `postgres://` URL (Docker, managed cloud, CI services). Use this for production, shared databases, and any deployment where **multiple processes** need the same database (API + workers, horizontal scale).
44
+ - **PGlite** — embedded Postgres via [`@electric-sql/pglite`](https://github.com/electric-sql/pglite), with the Prisma adapter. Data lives under a directory on disk (default relative path `.codemation/pglite` in the consumer app). **Single-process**; ideal for local dev, quick scaffolding, and tests that do not need a shared server.
45
+
46
+ ### Configuration
47
+
48
+ In `codemation.config.ts`, `runtime.database` accepts:
49
+
50
+ | Field | Meaning |
51
+ | --------------- | --------------------------------------------------------------------------------------------------------------------- |
52
+ | `kind` | `"postgresql"` or `"pglite"` (if omitted, inferred from `url` or defaults to PGlite when no postgres URL is present). |
53
+ | `url` | Required when using TCP Postgres (`postgresql://…`). |
54
+ | `pgliteDataDir` | Relative to the **consumer root** or absolute; used when `kind` is `"pglite"` (default: `.codemation/pglite`). |
55
+
56
+ Environment overrides (optional; persistence is primarily defined in **`codemation.config.ts`** — use `process.env` **inside** that file if you want `.env` to supply values):
57
+
58
+ - **`CODEMATION_DATABASE_KIND`** — `postgresql` or `pglite` to force kind.
59
+ - **`CODEMATION_PGLITE_DATA_DIR`** — Path to the PGlite data directory (relative to consumer root or absolute).
60
+
61
+ ### Migrations
62
+
63
+ `codemation db migrate` and startup migrations both run **`prisma migrate deploy`**: TCP Postgres uses your `runtime.database.url`; PGlite temporarily exposes the data directory on a local Postgres protocol socket ([`@electric-sql/pglite-socket`](https://github.com/electric-sql/pglite-socket)) so the Prisma CLI applies the same migration history as server Postgres.
64
+
65
+ ### Scheduler and PGlite
66
+
67
+ **BullMQ** (non-local scheduler) requires a **shared** PostgreSQL database. The host **fails fast** at bootstrap if the scheduler is BullMQ and persistence is PGlite. Set `runtime.database` to TCP Postgres when `REDIS_URL` / BullMQ is enabled. The **local** in-process scheduler is compatible with PGlite.
68
+
69
+ ### Integration tests
70
+
71
+ Point the suite at PGlite or TCP Postgres by setting **`DATABASE_URL`** for the harness factory (`pglite:///…` vs `postgresql://…`) and merging the resulting database into **`CodemationConfig.runtime.database`** (see `mergeIntegrationDatabaseRuntime` in host tests). CI can use a matrix: PGlite vs a Postgres service.
72
+
73
+ ### Gitignore
74
+
75
+ Ignore the embedded data directory (e.g. `.codemation/pglite`) in consumer repos so PGlite files are not committed.
@@ -0,0 +1,168 @@
1
+ import { n as CodemationLogConfig, o as LoggerFactory, t as CodemationWhitelabelConfig } from "./CodemationWhitelabelConfig-DgbjgtrR.js";
2
+ import { a as EngineExecutionLimitsPolicyConfig, j as WorkflowDefinition, n as Container, r as TypeToken, s as AnyCredentialType } from "./index-Bs4F1IsC.js";
3
+
4
+ //#region src/presentation/config/CodemationAuthConfig.d.ts
5
+ /**
6
+ * Consumer-declared authentication profile for the hosted UI + HTTP API.
7
+ * NextAuth / Auth.js wires concrete providers from this configuration plus environment secrets.
8
+ */
9
+ type CodemationAuthKind = "local" | "oauth" | "oidc";
10
+ interface CodemationAuthOAuthProviderConfig {
11
+ readonly provider: "google" | "github" | "microsoft-entra-id";
12
+ readonly clientIdEnv: string;
13
+ readonly clientSecretEnv: string;
14
+ /** Microsoft Entra ID tenant; environment variable name whose value is the tenant ID. */
15
+ readonly tenantIdEnv?: string;
16
+ }
17
+ interface CodemationAuthOidcProviderConfig {
18
+ readonly id: string;
19
+ readonly issuer: string;
20
+ readonly clientIdEnv: string;
21
+ readonly clientSecretEnv: string;
22
+ }
23
+ interface CodemationAuthConfig {
24
+ readonly kind: CodemationAuthKind;
25
+ /**
26
+ * When true and NODE_ENV is not production, the API accepts requests without a real session
27
+ * (synthetic principal only — never honored in production).
28
+ */
29
+ readonly allowUnauthenticatedInDevelopment?: boolean;
30
+ readonly oauth?: ReadonlyArray<CodemationAuthOAuthProviderConfig>;
31
+ readonly oidc?: ReadonlyArray<CodemationAuthOidcProviderConfig>;
32
+ }
33
+ //#endregion
34
+ //#region src/presentation/config/AppConfig.d.ts
35
+ interface AppConfig {
36
+ readonly consumerRoot: string;
37
+ readonly repoRoot: string;
38
+ readonly env: Readonly<NodeJS.ProcessEnv>;
39
+ readonly workflowSources: ReadonlyArray<string>;
40
+ readonly databaseUrl?: string;
41
+ readonly database?: CodemationDatabaseConfig;
42
+ readonly scheduler: Readonly<{
43
+ kind: CodemationSchedulerKind;
44
+ queuePrefix?: string;
45
+ workerQueues: ReadonlyArray<string>;
46
+ redisUrl?: string;
47
+ }>;
48
+ readonly eventing: Readonly<{
49
+ kind: CodemationEventBusKind;
50
+ queuePrefix?: string;
51
+ redisUrl?: string;
52
+ }>;
53
+ readonly auth?: CodemationAuthConfig;
54
+ readonly whitelabel: CodemationWhitelabelConfig;
55
+ }
56
+ //#endregion
57
+ //#region src/presentation/config/CodemationClassToken.d.ts
58
+ type CodemationClassToken<TValue> = TypeToken<TValue> & (new (...args: never[]) => TValue);
59
+ //#endregion
60
+ //#region src/presentation/config/CodemationAppContext.d.ts
61
+ interface CodemationRegistrationContextBase {
62
+ readonly appConfig?: AppConfig;
63
+ registerCredentialType(type: AnyCredentialType): void;
64
+ registerNode<TValue>(token: TypeToken<TValue>, implementation?: CodemationClassToken<TValue>): void;
65
+ registerValue<TValue>(token: TypeToken<TValue>, value: TValue): void;
66
+ registerClass<TValue>(token: TypeToken<TValue>, implementation: CodemationClassToken<TValue>): void;
67
+ registerFactory<TValue>(token: TypeToken<TValue>, factory: (container: Container) => TValue): void;
68
+ }
69
+ interface CodemationAppContext extends CodemationRegistrationContextBase {
70
+ registerWorkflow(workflow: WorkflowDefinition): void;
71
+ registerWorkflows(workflows: ReadonlyArray<WorkflowDefinition>): void;
72
+ discoverWorkflows(...directories: ReadonlyArray<string>): void;
73
+ }
74
+ //#endregion
75
+ //#region src/presentation/config/CodemationPlugin.d.ts
76
+ interface CodemationPluginContext extends CodemationRegistrationContextBase {
77
+ readonly container: Container;
78
+ readonly appConfig: AppConfig;
79
+ readonly loggerFactory: LoggerFactory;
80
+ }
81
+ interface CodemationPlugin {
82
+ /**
83
+ * Optional npm package name for this plugin (e.g. `"@codemation/core-nodes-gmail"`).
84
+ * When set, the host merges configured and discovered plugin lists by this id so the same package is not
85
+ * registered twice when separate module graphs load duplicate class instances (different `constructor` values).
86
+ */
87
+ readonly pluginPackageId?: string;
88
+ register(context: CodemationPluginContext): void | Promise<void>;
89
+ }
90
+ //#endregion
91
+ //#region src/presentation/config/CodemationWorkflowDiscovery.d.ts
92
+ interface CodemationWorkflowDiscovery {
93
+ readonly directories?: ReadonlyArray<string>;
94
+ }
95
+ //#endregion
96
+ //#region src/presentation/config/CodemationConfig.d.ts
97
+ type CodemationEventBusKind = "memory" | "redis";
98
+ type CodemationSchedulerKind = "local" | "bullmq";
99
+ type CodemationDatabaseKind = "postgresql" | "pglite";
100
+ interface CodemationDatabaseConfig {
101
+ readonly kind?: CodemationDatabaseKind;
102
+ /** TCP PostgreSQL URL when `kind` is `postgresql` (or omitted with a postgres URL). */
103
+ readonly url?: string;
104
+ /** Directory for embedded PGlite data when `kind` is `pglite`. Relative paths resolve from the consumer app root. */
105
+ readonly pgliteDataDir?: string;
106
+ }
107
+ interface CodemationEventBusConfig {
108
+ readonly kind?: CodemationEventBusKind;
109
+ readonly redisUrl?: string;
110
+ readonly queuePrefix?: string;
111
+ }
112
+ interface CodemationSchedulerConfig {
113
+ readonly kind?: CodemationSchedulerKind;
114
+ readonly queuePrefix?: string;
115
+ readonly workerQueues?: ReadonlyArray<string>;
116
+ }
117
+ type CodemationAppSchedulerKind = "inline" | "queue";
118
+ interface CodemationAppSchedulerConfig {
119
+ readonly kind?: CodemationAppSchedulerKind;
120
+ readonly queuePrefix?: string;
121
+ readonly workerQueues?: ReadonlyArray<string>;
122
+ readonly redisUrl?: string;
123
+ }
124
+ /**
125
+ * Optional overrides for engine execution limits (activation budget and subworkflow depth caps).
126
+ * Omitted fields keep framework defaults. Advanced users can bind `CoreTokens.EngineExecutionLimitsPolicy` for full control.
127
+ */
128
+ type CodemationEngineExecutionLimitsConfig = Readonly<Partial<EngineExecutionLimitsPolicyConfig>>;
129
+ interface CodemationAppDefinition {
130
+ readonly frontendPort?: number;
131
+ readonly databaseUrl?: string;
132
+ readonly database?: CodemationDatabaseConfig;
133
+ readonly scheduler?: CodemationAppSchedulerConfig;
134
+ readonly auth?: CodemationAuthConfig;
135
+ readonly whitelabel?: CodemationWhitelabelConfig;
136
+ readonly log?: CodemationLogConfig;
137
+ readonly engineExecutionLimits?: CodemationEngineExecutionLimitsConfig;
138
+ }
139
+ interface CodemationApplicationRuntimeConfig {
140
+ readonly frontendPort?: number;
141
+ readonly database?: CodemationDatabaseConfig;
142
+ readonly eventBus?: CodemationEventBusConfig;
143
+ readonly scheduler?: CodemationSchedulerConfig;
144
+ /** Merged with engine defaults when building the execution limits policy (API + workers). */
145
+ readonly engineExecutionLimits?: CodemationEngineExecutionLimitsConfig;
146
+ }
147
+ interface CodemationConfig {
148
+ readonly app?: CodemationAppDefinition;
149
+ readonly register?: (context: CodemationAppContext) => void;
150
+ readonly runtime?: CodemationApplicationRuntimeConfig;
151
+ readonly workflows?: ReadonlyArray<WorkflowDefinition>;
152
+ readonly workflowDiscovery?: CodemationWorkflowDiscovery;
153
+ readonly plugins?: ReadonlyArray<CodemationPlugin>;
154
+ /** Consumer-defined `CredentialType` entries (see `@codemation/core`), applied when the host loads config. */
155
+ readonly credentialTypes?: ReadonlyArray<AnyCredentialType>;
156
+ /** Optional shell whitelabel (product name, logo path). */
157
+ readonly whitelabel?: CodemationWhitelabelConfig;
158
+ /** Required for production hosts; optional only when using development bypass (never in production). */
159
+ readonly auth?: CodemationAuthConfig;
160
+ /**
161
+ * Namespace-level log filters (first matching rule wins). Unmatched namespaces use `CODEMATION_LOG_LEVEL` / defaults.
162
+ * Omit to keep env-only behavior.
163
+ */
164
+ readonly log?: CodemationLogConfig;
165
+ }
166
+ //#endregion
167
+ export { CodemationAuthOidcProviderConfig as C, CodemationAuthOAuthProviderConfig as S, CodemationRegistrationContextBase as _, CodemationConfig as a, CodemationAuthConfig as b, CodemationEngineExecutionLimitsConfig as c, CodemationSchedulerConfig as d, CodemationSchedulerKind as f, CodemationAppContext as g, CodemationPluginContext as h, CodemationApplicationRuntimeConfig as i, CodemationEventBusConfig as l, CodemationPlugin as m, CodemationAppSchedulerConfig as n, CodemationDatabaseConfig as o, CodemationWorkflowDiscovery as p, CodemationAppSchedulerKind as r, CodemationDatabaseKind as s, CodemationAppDefinition as t, CodemationEventBusKind as u, CodemationClassToken as v, CodemationAuthKind as x, AppConfig as y };
168
+ //# sourceMappingURL=CodemationConfig-XCkSV2dj.d.ts.map
@@ -0,0 +1,61 @@
1
+ import { a as CodemationConfig } from "./CodemationConfig-XCkSV2dj.js";
2
+
3
+ //#region src/presentation/server/CodemationConsumerAppResolver.d.ts
4
+ type CodemationConsumerApp = Readonly<{
5
+ config: CodemationConfig;
6
+ workflowSources: ReadonlyArray<string>;
7
+ }>;
8
+ declare class CodemationConsumerAppResolver {
9
+ private readonly configExportsResolver;
10
+ private readonly configNormalizer;
11
+ private readonly workflowDefinitionExportsResolver;
12
+ private readonly discoveredWorkflowsEmptyMessageFactory;
13
+ resolve(args: Readonly<{
14
+ configModule: Readonly<Record<string, unknown>>;
15
+ workflowModules: ReadonlyArray<Readonly<Record<string, unknown>>>;
16
+ workflowSourcePaths: ReadonlyArray<string>;
17
+ workflowDiscoveryPathSegmentsList?: ReadonlyArray<readonly string[]>;
18
+ }>): CodemationConsumerApp;
19
+ private resolveDiscoveredWorkflows;
20
+ private mergeWorkflows;
21
+ }
22
+ //#endregion
23
+ //#region src/presentation/server/CodemationConsumerConfigLoader.d.ts
24
+ type CodemationConsumerConfigResolution = Readonly<{
25
+ config: CodemationConfig;
26
+ bootstrapSource: string | null;
27
+ workflowSources: ReadonlyArray<string>;
28
+ }>;
29
+ declare class CodemationConsumerConfigLoader {
30
+ private static readonly importerRegistrationsByTsconfig;
31
+ private readonly configExportsResolver;
32
+ private readonly configNormalizer;
33
+ private readonly workflowModulePathFinder;
34
+ private readonly workflowDefinitionExportsResolver;
35
+ private readonly discoveredWorkflowsEmptyMessageFactory;
36
+ private readonly pathSegmentsComputer;
37
+ private readonly performanceDiagnosticsLogger;
38
+ load(args: Readonly<{
39
+ consumerRoot: string;
40
+ configPathOverride?: string;
41
+ }>): Promise<CodemationConsumerConfigResolution>;
42
+ private resolveConfigPath;
43
+ private getConventionCandidates;
44
+ private resolveWorkflowSources;
45
+ private loadDiscoveredWorkflows;
46
+ private mergeWorkflows;
47
+ private importModule;
48
+ private importModuleWithNativeRuntime;
49
+ private resolveTsconfigPath;
50
+ private getOrCreateImporter;
51
+ private resetImporter;
52
+ private toNamespace;
53
+ private findNearestTsconfig;
54
+ private createImportSpecifier;
55
+ private shouldUseNativeRuntimeImport;
56
+ private isStoppedTransformServiceError;
57
+ private exists;
58
+ }
59
+ //#endregion
60
+ export { CodemationConsumerAppResolver as i, CodemationConsumerConfigResolution as n, CodemationConsumerApp as r, CodemationConsumerConfigLoader as t };
61
+ //# sourceMappingURL=CodemationConsumerConfigLoader-Dmm2TzAA.d.ts.map
@@ -0,0 +1,334 @@
1
+ import { c as CodemationConfigNormalizer, s as logLevelPolicyFactory, t as ServerLoggerFactory } from "./ServerLoggerFactory-BRHxIDS7.js";
2
+ import { access, readdir, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { register } from "tsx/esm/api";
6
+
7
+ //#region src/presentation/server/CodemationConsumerConfigExportsResolver.ts
8
+ var CodemationConsumerConfigExportsResolver = class {
9
+ resolveConfig(moduleExports) {
10
+ const defaultExport = moduleExports.default;
11
+ if (this.isConfig(defaultExport)) return defaultExport;
12
+ const namedConfig = moduleExports.codemationHost ?? moduleExports.config;
13
+ if (this.isConfig(namedConfig)) return namedConfig;
14
+ return null;
15
+ }
16
+ isConfig(value) {
17
+ if (!value || typeof value !== "object") return false;
18
+ return "app" in value || "register" in value || "credentials" in value || "runtime" in value || "workflows" in value || "workflowDiscovery" in value || "plugins" in value || "whitelabel" in value || "auth" in value || "log" in value;
19
+ }
20
+ };
21
+
22
+ //#endregion
23
+ //#region src/presentation/server/DiscoveredWorkflowsEmptyMessageFactory.ts
24
+ var DiscoveredWorkflowsEmptyMessageFactory = class {
25
+ create(discoveredPaths) {
26
+ const lines = discoveredPaths.map((p) => ` - ${p}`).join("\n");
27
+ return [
28
+ `Discovered ${discoveredPaths.length} file(s) under workflow discovery, but none export a WorkflowDefinition.`,
29
+ lines,
30
+ "",
31
+ "Move shared helpers outside the discovery directories (for example src/lib), or export at least one object with id, name, nodes, and edges from a workflow module."
32
+ ].join("\n");
33
+ }
34
+ };
35
+
36
+ //#endregion
37
+ //#region src/presentation/server/WorkflowDefinitionExportsResolver.ts
38
+ /**
39
+ * Collects exported values that match the {@link WorkflowDefinition} shape.
40
+ * Other exports (helpers, constants, type-only re-exports) are ignored.
41
+ */
42
+ var WorkflowDefinitionExportsResolver = class {
43
+ resolve(moduleExports) {
44
+ const workflows = [];
45
+ for (const exportedValue of Object.values(moduleExports)) if (this.isWorkflowDefinition(exportedValue)) workflows.push(exportedValue);
46
+ return workflows;
47
+ }
48
+ isWorkflowDefinition(value) {
49
+ if (!value || typeof value !== "object") return false;
50
+ return "id" in value && "name" in value && "nodes" in value && "edges" in value;
51
+ }
52
+ };
53
+
54
+ //#endregion
55
+ //#region src/presentation/server/CodemationConsumerAppResolver.ts
56
+ var CodemationConsumerAppResolver = class {
57
+ configExportsResolver = new CodemationConsumerConfigExportsResolver();
58
+ configNormalizer = new CodemationConfigNormalizer();
59
+ workflowDefinitionExportsResolver = new WorkflowDefinitionExportsResolver();
60
+ discoveredWorkflowsEmptyMessageFactory = new DiscoveredWorkflowsEmptyMessageFactory();
61
+ resolve(args) {
62
+ const rawConfig = this.configExportsResolver.resolveConfig(args.configModule);
63
+ if (!rawConfig) throw new Error("Consumer app module does not export a Codemation config object.");
64
+ const config = this.configNormalizer.normalize(rawConfig);
65
+ const discoveredWorkflows = this.resolveDiscoveredWorkflows(args.workflowModules, args.workflowSourcePaths, args.workflowDiscoveryPathSegmentsList);
66
+ return {
67
+ config: {
68
+ ...config,
69
+ workflows: this.mergeWorkflows(config.workflows ?? [], discoveredWorkflows)
70
+ },
71
+ workflowSources: args.workflowSourcePaths
72
+ };
73
+ }
74
+ resolveDiscoveredWorkflows(workflowModules, workflowSourcePaths, workflowDiscoveryPathSegmentsList) {
75
+ const workflowsById = /* @__PURE__ */ new Map();
76
+ workflowModules.forEach((workflowModule, index) => {
77
+ const pathSegments = workflowDiscoveryPathSegmentsList?.[index];
78
+ this.workflowDefinitionExportsResolver.resolve(workflowModule).forEach((workflow) => {
79
+ const enriched = pathSegments && pathSegments.length > 0 ? {
80
+ ...workflow,
81
+ discoveryPathSegments: pathSegments
82
+ } : workflow;
83
+ workflowsById.set(workflow.id, enriched);
84
+ });
85
+ });
86
+ if (workflowsById.size === 0 && workflowSourcePaths.length > 0) throw new Error(this.discoveredWorkflowsEmptyMessageFactory.create(workflowSourcePaths));
87
+ return [...workflowsById.values()];
88
+ }
89
+ mergeWorkflows(configuredWorkflows, discoveredWorkflows) {
90
+ const workflowsById = /* @__PURE__ */ new Map();
91
+ for (const workflow of discoveredWorkflows) workflowsById.set(workflow.id, workflow);
92
+ for (const workflow of configuredWorkflows) workflowsById.set(workflow.id, workflow);
93
+ return [...workflowsById.values()];
94
+ }
95
+ };
96
+
97
+ //#endregion
98
+ //#region src/presentation/server/WorkflowModulePathFinder.ts
99
+ var WorkflowModulePathFinder = class WorkflowModulePathFinder {
100
+ static defaultWorkflowDirectories = ["src/workflows", "workflows"];
101
+ workflowExtensions = new Set([
102
+ ".ts",
103
+ ".js",
104
+ ".mts",
105
+ ".mjs"
106
+ ]);
107
+ async discoverModulePaths(args) {
108
+ const directories = args.workflowDirectories ?? WorkflowModulePathFinder.defaultWorkflowDirectories;
109
+ const workflowModulePaths = [];
110
+ for (const directory of directories) {
111
+ const absoluteDirectory = path.resolve(args.consumerRoot, directory);
112
+ if (!await args.exists(absoluteDirectory)) continue;
113
+ workflowModulePaths.push(...await this.collectWorkflowModulePaths(absoluteDirectory));
114
+ }
115
+ return workflowModulePaths;
116
+ }
117
+ async collectWorkflowModulePaths(directoryPath) {
118
+ const entries = await readdir(directoryPath, { withFileTypes: true });
119
+ const workflowModulePaths = [];
120
+ for (const entry of entries) {
121
+ const entryPath = path.resolve(directoryPath, entry.name);
122
+ if (entry.isDirectory()) {
123
+ workflowModulePaths.push(...await this.collectWorkflowModulePaths(entryPath));
124
+ continue;
125
+ }
126
+ if (this.isWorkflowModulePath(entryPath)) workflowModulePaths.push(entryPath);
127
+ }
128
+ return workflowModulePaths;
129
+ }
130
+ isWorkflowModulePath(modulePath) {
131
+ const extension = path.extname(modulePath);
132
+ return this.workflowExtensions.has(extension) && !modulePath.endsWith(".d.ts");
133
+ }
134
+ };
135
+
136
+ //#endregion
137
+ //#region src/presentation/server/WorkflowDiscoveryPathSegmentsComputer.ts
138
+ var WorkflowDiscoveryPathSegmentsComputer = class {
139
+ compute(args) {
140
+ const normalizedConsumer = path.resolve(args.consumerRoot);
141
+ const normalizedWorkflowPath = path.resolve(args.absoluteWorkflowModulePath);
142
+ const directories = args.workflowDiscoveryDirectories.length > 0 ? args.workflowDiscoveryDirectories : [...WorkflowModulePathFinder.defaultWorkflowDirectories];
143
+ let bestRoot = null;
144
+ for (const directory of directories) {
145
+ const absoluteDirectory = path.resolve(normalizedConsumer, directory);
146
+ if (!(normalizedWorkflowPath === absoluteDirectory || normalizedWorkflowPath.startsWith(`${absoluteDirectory}${path.sep}`))) continue;
147
+ if (!bestRoot || absoluteDirectory.length > bestRoot.length) bestRoot = absoluteDirectory;
148
+ }
149
+ if (!bestRoot) return;
150
+ const relative = path.relative(bestRoot, normalizedWorkflowPath);
151
+ if (relative.startsWith("..") || path.isAbsolute(relative)) return;
152
+ if (relative.length === 0) return;
153
+ const parts = relative.split(path.sep).filter((segment) => segment.length > 0);
154
+ if (parts.length === 0) return;
155
+ const lastIndex = parts.length - 1;
156
+ const last = parts[lastIndex] ?? "";
157
+ const ext = path.extname(last);
158
+ parts[lastIndex] = ext ? last.slice(0, -ext.length) : last;
159
+ return parts;
160
+ }
161
+ };
162
+
163
+ //#endregion
164
+ //#region src/presentation/server/CodemationConsumerConfigLoader.ts
165
+ var CodemationConsumerConfigLoader = class CodemationConsumerConfigLoader {
166
+ static importerRegistrationsByTsconfig = /* @__PURE__ */ new Map();
167
+ configExportsResolver = new CodemationConsumerConfigExportsResolver();
168
+ configNormalizer = new CodemationConfigNormalizer();
169
+ workflowModulePathFinder = new WorkflowModulePathFinder();
170
+ workflowDefinitionExportsResolver = new WorkflowDefinitionExportsResolver();
171
+ discoveredWorkflowsEmptyMessageFactory = new DiscoveredWorkflowsEmptyMessageFactory();
172
+ pathSegmentsComputer = new WorkflowDiscoveryPathSegmentsComputer();
173
+ performanceDiagnosticsLogger = new ServerLoggerFactory(logLevelPolicyFactory).createPerformanceDiagnostics("codemation-config-loader.timing");
174
+ async load(args) {
175
+ const loadStarted = performance.now();
176
+ let mark = loadStarted;
177
+ const phaseMs = (label) => {
178
+ const now = performance.now();
179
+ const delta = now - mark;
180
+ mark = now;
181
+ this.performanceDiagnosticsLogger.info(`load.${label} +${delta.toFixed(1)}ms (cumulative ${(now - loadStarted).toFixed(1)}ms)`);
182
+ };
183
+ const bootstrapSource = await this.resolveConfigPath(args.consumerRoot, args.configPathOverride);
184
+ phaseMs("resolveConfigPath");
185
+ if (!bootstrapSource) throw new Error("Codemation config not found. Expected \"codemation.config.ts\" in the consumer project root or \"src/\".");
186
+ const moduleExports = await this.importModule(bootstrapSource);
187
+ phaseMs("importConfigModule");
188
+ const rawConfig = this.configExportsResolver.resolveConfig(moduleExports);
189
+ if (!rawConfig) throw new Error(`Config file does not export a Codemation config object: ${bootstrapSource}`);
190
+ const config = this.configNormalizer.normalize(rawConfig);
191
+ const workflowSources = await this.resolveWorkflowSources(args.consumerRoot, config);
192
+ phaseMs("resolveWorkflowSources");
193
+ const workflows = this.mergeWorkflows(config.workflows ?? [], await this.loadDiscoveredWorkflows(args.consumerRoot, config, workflowSources));
194
+ phaseMs("loadDiscoveredWorkflows");
195
+ const resolvedConfig = {
196
+ ...config,
197
+ workflows
198
+ };
199
+ logLevelPolicyFactory.create().applyCodemationLogConfig(resolvedConfig.log);
200
+ return {
201
+ config: resolvedConfig,
202
+ bootstrapSource,
203
+ workflowSources
204
+ };
205
+ }
206
+ async resolveConfigPath(consumerRoot, configPathOverride) {
207
+ if (configPathOverride) {
208
+ const explicitPath = path.isAbsolute(configPathOverride) ? configPathOverride : path.resolve(consumerRoot, configPathOverride);
209
+ if (!await this.exists(explicitPath)) throw new Error(`Config file not found: ${explicitPath}`);
210
+ return explicitPath;
211
+ }
212
+ for (const candidate of this.getConventionCandidates(consumerRoot)) if (await this.exists(candidate)) return candidate;
213
+ return null;
214
+ }
215
+ getConventionCandidates(consumerRoot) {
216
+ return [
217
+ path.resolve(consumerRoot, "codemation.config.ts"),
218
+ path.resolve(consumerRoot, "codemation.config.js"),
219
+ path.resolve(consumerRoot, "src", "codemation.config.ts"),
220
+ path.resolve(consumerRoot, "src", "codemation.config.js")
221
+ ];
222
+ }
223
+ async resolveWorkflowSources(consumerRoot, config) {
224
+ if ((config.workflowDiscovery?.directories?.length ?? 0) === 0) return [];
225
+ return [...await this.workflowModulePathFinder.discoverModulePaths({
226
+ consumerRoot,
227
+ workflowDirectories: config.workflowDiscovery?.directories,
228
+ exists: (absolutePath) => this.exists(absolutePath)
229
+ })].sort((left, right) => left.localeCompare(right));
230
+ }
231
+ async loadDiscoveredWorkflows(consumerRoot, config, workflowSources) {
232
+ const workflowDiscoveryDirectories = config.workflowDiscovery?.directories ?? [];
233
+ const workflowsById = /* @__PURE__ */ new Map();
234
+ const loadedWorkflowModules = await Promise.all(workflowSources.map(async (workflowSource) => ({
235
+ workflowSource,
236
+ segments: this.pathSegmentsComputer.compute({
237
+ consumerRoot,
238
+ workflowDiscoveryDirectories,
239
+ absoluteWorkflowModulePath: workflowSource
240
+ }),
241
+ moduleExports: await this.importModule(workflowSource)
242
+ })));
243
+ for (const loadedWorkflowModule of loadedWorkflowModules) for (const workflow of this.workflowDefinitionExportsResolver.resolve(loadedWorkflowModule.moduleExports)) {
244
+ const enriched = loadedWorkflowModule.segments && loadedWorkflowModule.segments.length > 0 ? {
245
+ ...workflow,
246
+ discoveryPathSegments: loadedWorkflowModule.segments
247
+ } : workflow;
248
+ workflowsById.set(workflow.id, enriched);
249
+ }
250
+ if (workflowsById.size === 0 && workflowSources.length > 0) throw new Error(this.discoveredWorkflowsEmptyMessageFactory.create(workflowSources));
251
+ return [...workflowsById.values()];
252
+ }
253
+ mergeWorkflows(configuredWorkflows, discoveredWorkflows) {
254
+ const workflowsById = /* @__PURE__ */ new Map();
255
+ for (const workflow of discoveredWorkflows) workflowsById.set(workflow.id, workflow);
256
+ for (const workflow of configuredWorkflows) workflowsById.set(workflow.id, workflow);
257
+ return [...workflowsById.values()];
258
+ }
259
+ async importModule(modulePath) {
260
+ if (this.shouldUseNativeRuntimeImport()) return await this.importModuleWithNativeRuntime(modulePath);
261
+ const tsconfigPath = await this.resolveTsconfigPath(modulePath);
262
+ const importSpecifier = await this.createImportSpecifier(modulePath);
263
+ for (let attempt = 0; attempt < 3; attempt += 1) try {
264
+ return await this.getOrCreateImporter(tsconfigPath).import(importSpecifier, import.meta.url);
265
+ } catch (error) {
266
+ if (!this.isStoppedTransformServiceError(error) || attempt === 2) throw error;
267
+ await this.resetImporter(tsconfigPath);
268
+ }
269
+ throw new Error(`Failed to import consumer module after retries: ${modulePath}`);
270
+ }
271
+ async importModuleWithNativeRuntime(modulePath) {
272
+ return await import(await this.createImportSpecifier(modulePath));
273
+ }
274
+ async resolveTsconfigPath(modulePath) {
275
+ const overridePath = process.env.CODEMATION_TSCONFIG_PATH;
276
+ if (overridePath && await this.exists(overridePath)) return overridePath;
277
+ return await this.findNearestTsconfig(modulePath) ?? false;
278
+ }
279
+ getOrCreateImporter(tsconfigPath) {
280
+ const cacheKey = tsconfigPath || "default";
281
+ const existingImporter = CodemationConsumerConfigLoader.importerRegistrationsByTsconfig.get(cacheKey);
282
+ if (existingImporter) return existingImporter;
283
+ const nextImporter = register({
284
+ namespace: this.toNamespace(cacheKey),
285
+ tsconfig: tsconfigPath
286
+ });
287
+ CodemationConsumerConfigLoader.importerRegistrationsByTsconfig.set(cacheKey, nextImporter);
288
+ return nextImporter;
289
+ }
290
+ async resetImporter(tsconfigPath) {
291
+ const cacheKey = tsconfigPath || "default";
292
+ const existingImporter = CodemationConsumerConfigLoader.importerRegistrationsByTsconfig.get(cacheKey);
293
+ if (!existingImporter) return;
294
+ CodemationConsumerConfigLoader.importerRegistrationsByTsconfig.delete(cacheKey);
295
+ await existingImporter.unregister().catch(() => null);
296
+ }
297
+ toNamespace(cacheKey) {
298
+ return `codemation_consumer_${cacheKey.replace(/[^a-zA-Z0-9_-]+/g, "_")}`;
299
+ }
300
+ async findNearestTsconfig(modulePath) {
301
+ let currentDirectory = path.dirname(modulePath);
302
+ while (true) {
303
+ const candidate = path.resolve(currentDirectory, "tsconfig.json");
304
+ if (await this.exists(candidate)) return candidate;
305
+ const parentDirectory = path.dirname(currentDirectory);
306
+ if (parentDirectory === currentDirectory) return null;
307
+ currentDirectory = parentDirectory;
308
+ }
309
+ }
310
+ async createImportSpecifier(modulePath) {
311
+ const moduleUrl = pathToFileURL(modulePath);
312
+ const moduleStats = await stat(modulePath);
313
+ moduleUrl.searchParams.set("t", String(moduleStats.mtimeMs));
314
+ return moduleUrl.href;
315
+ }
316
+ shouldUseNativeRuntimeImport() {
317
+ return process.env.CODEMATION_TS_RUNTIME === "ts-node";
318
+ }
319
+ isStoppedTransformServiceError(error) {
320
+ return error instanceof Error && error.message.includes("The service is no longer running");
321
+ }
322
+ async exists(filePath) {
323
+ try {
324
+ await access(filePath);
325
+ return true;
326
+ } catch {
327
+ return false;
328
+ }
329
+ }
330
+ };
331
+
332
+ //#endregion
333
+ export { CodemationConsumerAppResolver as i, WorkflowDiscoveryPathSegmentsComputer as n, WorkflowModulePathFinder as r, CodemationConsumerConfigLoader as t };
334
+ //# sourceMappingURL=CodemationConsumerConfigLoader-scS_RQMy.js.map