@open-mercato/core 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8567.1.a167594505

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 (134) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/api_keys/di.js +6 -2
  3. package/dist/modules/api_keys/di.js.map +2 -2
  4. package/dist/modules/api_keys/services/oneTimeIssuerService.js +47 -0
  5. package/dist/modules/api_keys/services/oneTimeIssuerService.js.map +7 -0
  6. package/dist/modules/audit_logs/di.js +2 -1
  7. package/dist/modules/audit_logs/di.js.map +2 -2
  8. package/dist/modules/audit_logs/services/actionLogService.js +65 -1
  9. package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
  10. package/dist/modules/auth/cli.js +1 -0
  11. package/dist/modules/auth/cli.js.map +2 -2
  12. package/dist/modules/auth/commands/users.js +10 -2
  13. package/dist/modules/auth/commands/users.js.map +2 -2
  14. package/dist/modules/auth/lib/setup-app.js +19 -5
  15. package/dist/modules/auth/lib/setup-app.js.map +2 -2
  16. package/dist/modules/configs/cli.js +26 -29
  17. package/dist/modules/configs/cli.js.map +2 -2
  18. package/dist/modules/configs/di.js +3 -1
  19. package/dist/modules/configs/di.js.map +2 -2
  20. package/dist/modules/configs/lib/instance-config-initializer.js +44 -0
  21. package/dist/modules/configs/lib/instance-config-initializer.js.map +7 -0
  22. package/dist/modules/configs/lib/instance-defaults.js +204 -0
  23. package/dist/modules/configs/lib/instance-defaults.js.map +7 -0
  24. package/dist/modules/configs/lib/module-config-service.js +115 -1
  25. package/dist/modules/configs/lib/module-config-service.js.map +2 -2
  26. package/dist/modules/entities/api/definitions.batch.js +55 -25
  27. package/dist/modules/entities/api/definitions.batch.js.map +2 -2
  28. package/dist/modules/entities/api/definitions.js +35 -8
  29. package/dist/modules/entities/api/definitions.js.map +2 -2
  30. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +14 -8
  31. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  32. package/dist/modules/notifications/lib/deliveryConfig.js +19 -12
  33. package/dist/modules/notifications/lib/deliveryConfig.js.map +2 -2
  34. package/dist/modules/notifications/setup.js +10 -0
  35. package/dist/modules/notifications/setup.js.map +2 -2
  36. package/dist/modules/translations/components/TranslationManager.js +47 -10
  37. package/dist/modules/translations/components/TranslationManager.js.map +2 -2
  38. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js +8 -1
  39. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js.map +2 -2
  40. package/dist/modules/workflows/ai-tools/authoring-pack.js +1 -1
  41. package/dist/modules/workflows/ai-tools/authoring-pack.js.map +2 -2
  42. package/dist/modules/workflows/api/instances/[id]/advance/route.js +1 -0
  43. package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
  44. package/dist/modules/workflows/api/instances/route.js +1 -1
  45. package/dist/modules/workflows/api/instances/route.js.map +2 -2
  46. package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
  47. package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
  48. package/dist/modules/workflows/di.js +3 -1
  49. package/dist/modules/workflows/di.js.map +2 -2
  50. package/dist/modules/workflows/lib/activity-executor.js +35 -7
  51. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  52. package/dist/modules/workflows/lib/condition-handler.js +1 -1
  53. package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
  54. package/dist/modules/workflows/lib/error-handler.js +1 -1
  55. package/dist/modules/workflows/lib/error-handler.js.map +2 -2
  56. package/dist/modules/workflows/lib/event-trigger-service.js +1 -1
  57. package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
  58. package/dist/modules/workflows/lib/example-definition-authoring.js +90 -0
  59. package/dist/modules/workflows/lib/example-definition-authoring.js.map +7 -0
  60. package/dist/modules/workflows/lib/named-rules.js +42 -0
  61. package/dist/modules/workflows/lib/named-rules.js.map +7 -0
  62. package/dist/modules/workflows/lib/owned-definition.js +2 -0
  63. package/dist/modules/workflows/lib/owned-definition.js.map +2 -2
  64. package/dist/modules/workflows/lib/parallel-handler.js +1 -1
  65. package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
  66. package/dist/modules/workflows/lib/signal-handler.js +1 -0
  67. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  68. package/dist/modules/workflows/lib/start-validator.js +87 -85
  69. package/dist/modules/workflows/lib/start-validator.js.map +2 -2
  70. package/dist/modules/workflows/lib/step-handler.js +1 -1
  71. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  72. package/dist/modules/workflows/lib/task-handler.js +1 -0
  73. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  74. package/dist/modules/workflows/lib/timer-handler.js +1 -0
  75. package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
  76. package/dist/modules/workflows/lib/transition-handler.js +48 -166
  77. package/dist/modules/workflows/lib/transition-handler.js.map +3 -3
  78. package/dist/modules/workflows/lib/workflow-executor.js +3 -2
  79. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  80. package/package.json +8 -8
  81. package/src/modules/api_keys/di.ts +7 -2
  82. package/src/modules/api_keys/services/oneTimeIssuerService.ts +61 -0
  83. package/src/modules/audit_logs/di.ts +1 -0
  84. package/src/modules/audit_logs/services/actionLogService.ts +132 -1
  85. package/src/modules/auth/cli.ts +1 -0
  86. package/src/modules/auth/commands/users.ts +10 -2
  87. package/src/modules/auth/i18n/de.json +2 -0
  88. package/src/modules/auth/i18n/en.json +2 -0
  89. package/src/modules/auth/i18n/es.json +2 -0
  90. package/src/modules/auth/i18n/ko.json +2 -0
  91. package/src/modules/auth/i18n/pl.json +2 -0
  92. package/src/modules/auth/lib/setup-app.ts +30 -7
  93. package/src/modules/configs/cli.ts +39 -37
  94. package/src/modules/configs/di.ts +2 -0
  95. package/src/modules/configs/lib/instance-config-initializer.ts +56 -0
  96. package/src/modules/configs/lib/instance-defaults.ts +262 -0
  97. package/src/modules/configs/lib/module-config-service.ts +156 -0
  98. package/src/modules/entities/api/definitions.batch.ts +65 -27
  99. package/src/modules/entities/api/definitions.ts +40 -11
  100. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +14 -7
  101. package/src/modules/notifications/lib/deliveryConfig.ts +20 -11
  102. package/src/modules/notifications/setup.ts +11 -0
  103. package/src/modules/translations/components/TranslationManager.tsx +49 -10
  104. package/src/modules/translations/i18n/de.json +1 -0
  105. package/src/modules/translations/i18n/en.json +1 -0
  106. package/src/modules/translations/i18n/es.json +1 -0
  107. package/src/modules/translations/i18n/ko.json +1 -0
  108. package/src/modules/translations/i18n/pl.json +1 -0
  109. package/src/modules/wms/components/backend/CompletePutawayTaskDialog.tsx +8 -1
  110. package/src/modules/wms/i18n/de.json +1 -0
  111. package/src/modules/wms/i18n/en.json +1 -0
  112. package/src/modules/wms/i18n/es.json +1 -0
  113. package/src/modules/wms/i18n/ko.json +1 -0
  114. package/src/modules/wms/i18n/pl.json +1 -0
  115. package/src/modules/workflows/ai-tools/authoring-pack.ts +3 -1
  116. package/src/modules/workflows/api/instances/[id]/advance/route.ts +1 -0
  117. package/src/modules/workflows/api/instances/route.ts +1 -1
  118. package/src/modules/workflows/api/instances/validate-start/route.ts +3 -1
  119. package/src/modules/workflows/di.ts +2 -0
  120. package/src/modules/workflows/lib/activity-executor.ts +48 -30
  121. package/src/modules/workflows/lib/condition-handler.ts +1 -1
  122. package/src/modules/workflows/lib/error-handler.ts +1 -1
  123. package/src/modules/workflows/lib/event-trigger-service.ts +1 -1
  124. package/src/modules/workflows/lib/example-definition-authoring.ts +114 -0
  125. package/src/modules/workflows/lib/named-rules.ts +54 -0
  126. package/src/modules/workflows/lib/owned-definition.ts +4 -1
  127. package/src/modules/workflows/lib/parallel-handler.ts +1 -1
  128. package/src/modules/workflows/lib/signal-handler.ts +1 -0
  129. package/src/modules/workflows/lib/start-validator.ts +96 -94
  130. package/src/modules/workflows/lib/step-handler.ts +1 -1
  131. package/src/modules/workflows/lib/task-handler.ts +1 -0
  132. package/src/modules/workflows/lib/timer-handler.ts +1 -0
  133. package/src/modules/workflows/lib/transition-handler.ts +74 -238
  134. package/src/modules/workflows/lib/workflow-executor.ts +7 -4
@@ -15,7 +15,7 @@ import { EntityManager } from '@mikro-orm/core'
15
15
  import type { EntityManager as PostgreSqlEntityManager } from '@mikro-orm/postgresql'
16
16
  import type { AwilixContainer } from 'awilix'
17
17
  import { WorkflowInstance } from '../data/entities'
18
- import { isApiKeysModuleEnabled } from './optional-modules'
18
+ import type { ApiKeyOneTimeIssuer } from '@open-mercato/shared/lib/auth/principal-service'
19
19
  import { createModuleQueue, Queue } from '@open-mercato/queue'
20
20
  import { getRedisUrl } from '@open-mercato/shared/lib/redis/connection'
21
21
  import {
@@ -1750,11 +1750,46 @@ export async function executeInvokeAgent(
1750
1750
  }
1751
1751
  }
1752
1752
 
1753
+ function isMissingApiKeyOneTimeIssuerError(error: unknown): boolean {
1754
+ if (!error || typeof error !== 'object') return false
1755
+ const candidate = error as { name?: unknown; message?: unknown }
1756
+ if (candidate.name !== 'AwilixResolutionError') return false
1757
+ const message = typeof candidate.message === 'string' ? candidate.message : ''
1758
+ return /Could not resolve ['"]apiKeyOneTimeIssuer['"]/.test(message)
1759
+ }
1760
+
1761
+ function resolveApiKeyOneTimeIssuer(container: AwilixContainer): ApiKeyOneTimeIssuer | null {
1762
+ if (
1763
+ typeof container.hasRegistration === 'function' &&
1764
+ !container.hasRegistration('apiKeyOneTimeIssuer')
1765
+ ) {
1766
+ return null
1767
+ }
1768
+ let candidate: unknown
1769
+ try {
1770
+ candidate = container.resolve<ApiKeyOneTimeIssuer | null | undefined>('apiKeyOneTimeIssuer')
1771
+ } catch (error) {
1772
+ if (isMissingApiKeyOneTimeIssuerError(error)) {
1773
+ return null
1774
+ }
1775
+ throw error
1776
+ }
1777
+ if (candidate === null || candidate === undefined) {
1778
+ return null
1779
+ }
1780
+ if (typeof (candidate as ApiKeyOneTimeIssuer).withOneTimeApiKey !== 'function') {
1781
+ throw new Error(
1782
+ '[CALL_API] Registered apiKeyOneTimeIssuer service is invalid: missing withOneTimeApiKey().',
1783
+ )
1784
+ }
1785
+ return candidate as ApiKeyOneTimeIssuer
1786
+ }
1787
+
1753
1788
  /**
1754
1789
  * CALL_API activity handler
1755
1790
  *
1756
1791
  * Makes authenticated HTTP request to internal Open Mercato APIs
1757
- * - Automatically creates one-time API key for authentication
1792
+ * - Soft-resolves `apiKeyOneTimeIssuer` from DI to mint a short-lived one-time API key
1758
1793
  * - Injects tenant/organization context headers
1759
1794
  * - Validates URL security (SSRF prevention)
1760
1795
  * - Classifies errors (retriable vs non-retriable)
@@ -1788,36 +1823,20 @@ export async function executeCallApi(
1788
1823
  // 2. Build full URL (prepend APP_URL for relative paths)
1789
1824
  const requestUrl = await resolveCallApiUrl(endpoint)
1790
1825
 
1791
- if (!isApiKeysModuleEnabled()) {
1826
+ // 3. Soft-resolve the API Keys-owned one-time credential issuer from the active container.
1827
+ // A missing registration takes the translated API Keys-unavailable refusal; a present
1828
+ // dependency that fails propagates into normal activity failure and retry classification.
1829
+ const apiKeyOneTimeIssuer = resolveApiKeyOneTimeIssuer(container)
1830
+ if (!apiKeyOneTimeIssuer) {
1792
1831
  throw await createCallApiError(
1793
1832
  'workflows.errors.callApi.apiKeysModuleDisabled',
1794
1833
  'CALL_API needs the api_keys module to authenticate internal calls',
1795
1834
  )
1796
1835
  }
1797
1836
 
1798
- // 3. Import the one-time API key helper
1799
- const { withOnetimeApiKey } = await import('../../api_keys/services/apiKeyService')
1800
-
1801
- // 4. Create the one-time API key on an EntityManager that is fully detached
1802
- // from the surrounding request/transaction context.
1803
- //
1804
- // CALL_API runs inside `workflowExecutor.executeWorkflow()`, which wraps
1805
- // the whole execution in `em.transactional(...)`. The request EM is forked
1806
- // with `useContext: true`, so while that transaction is open, EVERY
1807
- // operation on the container's `em` — including this API key's
1808
- // persist/flush — is transparently redirected to the uncommitted
1809
- // transaction fork (MikroORM `getContext()` → `TransactionContext`). The
1810
- // key would therefore stay invisible until the transaction commits, but
1811
- // the commit cannot happen until this activity returns. The outbound
1812
- // self-authenticated `fetch` below opens a SEPARATE DB connection that
1813
- // cannot see the uncommitted row, so the internal API responds `401` and
1814
- // the activity fails (issue #4202).
1815
- //
1816
- // Forking with `useContext: false` (matching the query_index/webhooks
1817
- // isolated-EM convention) gives the key its own pooled connection with
1818
- // autocommit, so it is committed and visible to the internal request
1819
- // immediately.
1820
- const apiKeyEm = container
1837
+ // 4. Resolve active user roles on a context-free EntityManager fork outside the surrounding
1838
+ // workflow transaction (matching the isolated-EM convention).
1839
+ const roleResolutionEm = container
1821
1840
  .resolve<PostgreSqlEntityManager>('em')
1822
1841
  .fork({ clear: true, freshEventManager: true, useContext: false }) as PostgreSqlEntityManager
1823
1842
 
@@ -1841,7 +1860,7 @@ export async function executeCallApi(
1841
1860
  // when the instance was started by an event trigger with no user.
1842
1861
  // 3. If no traceable principal exists, the activity refuses to run —
1843
1862
  // there is no "system" fallback that bypasses RBAC.
1844
- const resolvedRoleIds = await resolveCallApiRoleIds(apiKeyEm, context.workflowInstance)
1863
+ const resolvedRoleIds = await resolveCallApiRoleIds(roleResolutionEm, context.workflowInstance)
1845
1864
 
1846
1865
  if (resolvedRoleIds.length === 0) {
1847
1866
  throw new Error(
@@ -1851,9 +1870,8 @@ export async function executeCallApi(
1851
1870
  )
1852
1871
  }
1853
1872
 
1854
- // 6. Execute request with one-time API key scoped to the resolved user's roles
1855
- return await withOnetimeApiKey(
1856
- apiKeyEm,
1873
+ // 6. Execute request with a one-time API key issued by the API Keys provider
1874
+ return await apiKeyOneTimeIssuer.withOneTimeApiKey(
1857
1875
  {
1858
1876
  name: `__workflow_${context.workflowInstance.id}__`,
1859
1877
  description: `One-time key for workflow ${context.workflowInstance.workflowId} instance ${context.workflowInstance.id}`,
@@ -339,7 +339,7 @@ async function completeConditionWait(
339
339
  return
340
340
  }
341
341
 
342
- const transitionContext = { workflowContext: instance.context, userId }
342
+ const transitionContext = { container, workflowContext: instance.context, userId }
343
343
 
344
344
  const validTransitions = await transitionHandler.findValidTransitions(
345
345
  em,
@@ -171,7 +171,7 @@ export async function runWorkflowErrorHandler(
171
171
  },
172
172
  tenantId: payload.tenantId,
173
173
  organizationId: payload.organizationId,
174
- })
174
+ }, container)
175
175
 
176
176
  await logWorkflowEvent(em, {
177
177
  workflowInstanceId: payload.workflowInstanceId,
@@ -823,7 +823,7 @@ export async function processEventTriggers(
823
823
  },
824
824
  tenantId: context.tenantId,
825
825
  organizationId: context.organizationId,
826
- })
826
+ }, container)
827
827
 
828
828
  startedWorkflow = true
829
829
  result.triggered++
@@ -0,0 +1,114 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type { EntityManager } from '@mikro-orm/postgresql'
3
+ import { asValue, type AwilixContainer } from 'awilix'
4
+ import { z } from 'zod'
5
+ import type { OrganizationHierarchyService } from '@open-mercato/shared/lib/auth/principal-service'
6
+ import { readPgSqlState } from '@open-mercato/shared/lib/db/pg-errors'
7
+ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
8
+ import { WorkflowDefinition, type WorkflowDefinitionData } from '../data/entities'
9
+ import { createWorkflowDefinitionSchema, workflowDefinitionDataSchema } from '../data/validators'
10
+
11
+ const exampleScopeSchema = createWorkflowDefinitionSchema.pick({
12
+ tenantId: true,
13
+ organizationId: true,
14
+ })
15
+ const exampleFixtureSchema = createWorkflowDefinitionSchema.pick({
16
+ workflowId: true,
17
+ workflowName: true,
18
+ description: true,
19
+ metadata: true,
20
+ enabled: true,
21
+ }).extend({
22
+ version: z.literal(1).default(1),
23
+ definition: z.custom<WorkflowDefinitionData>((value) => workflowDefinitionDataSchema.safeParse(value).success),
24
+ })
25
+
26
+ const exampleInputSchema = exampleScopeSchema.extend({ fixture: exampleFixtureSchema })
27
+
28
+ type ExampleScope = z.infer<typeof exampleScopeSchema>
29
+ type ExampleFixture = z.infer<typeof exampleFixtureSchema>
30
+
31
+ export type CreateExampleWorkflowDefinitionInput = ExampleScope & { fixture: unknown }
32
+ export type CreateExampleWorkflowDefinitionResult = 'created' | 'already_exists'
33
+
34
+ export interface WorkflowExampleAuthoring {
35
+ createExampleDefinitionIfAbsent(
36
+ em: EntityManager,
37
+ input: CreateExampleWorkflowDefinitionInput,
38
+ ): Promise<CreateExampleWorkflowDefinitionResult>
39
+ }
40
+
41
+ const WORKFLOW_VERSION_CONSTRAINT = 'workflow_definitions_workflow_id_version_tenant_id_unique'
42
+
43
+ function isWorkflowVersionConflict(error: unknown): boolean {
44
+ return readPgSqlState(error) === '23505'
45
+ && error instanceof Error
46
+ && (('constraint' in error && error.constraint === WORKFLOW_VERSION_CONSTRAINT)
47
+ || error.message.includes(`duplicate key value violates unique constraint "${WORKFLOW_VERSION_CONSTRAINT}"`))
48
+ }
49
+
50
+ async function validateSetupOrganization(container: AwilixContainer, em: EntityManager, scope: ExampleScope): Promise<void> {
51
+ const setupScope = container.createScope()
52
+ setupScope.register('em', asValue(em))
53
+ try {
54
+ const directory = setupScope.resolve<OrganizationHierarchyService>('organizationHierarchyService')
55
+ if (await directory.resolveAncestorIds(scope) == null) {
56
+ throw new Error('[internal] Invalid organization scope for workflow example.')
57
+ }
58
+ } finally {
59
+ await setupScope.dispose()
60
+ }
61
+ }
62
+
63
+ async function persistIfAbsent(
64
+ em: EntityManager,
65
+ scope: ExampleScope,
66
+ fixture: ExampleFixture,
67
+ ): Promise<CreateExampleWorkflowDefinitionResult | 'scope_conflict'> {
68
+ const where = { ...scope, workflowId: fixture.workflowId }
69
+ const findExisting = () => findOneWithDecryption(
70
+ em, WorkflowDefinition, where, { fields: ['id'], refresh: true }, scope,
71
+ )
72
+ if (await findExisting()) return 'already_exists'
73
+
74
+ try {
75
+ await em.transactional(async (transaction) => {
76
+ transaction.persist(transaction.create(WorkflowDefinition, {
77
+ ...fixture,
78
+ ...scope,
79
+ id: randomUUID(),
80
+ }))
81
+ }, { clear: true })
82
+ return 'created'
83
+ } catch (error) {
84
+ if (!isWorkflowVersionConflict(error)) throw error
85
+ return await findExisting() ? 'already_exists' : 'scope_conflict'
86
+ }
87
+ }
88
+
89
+ export function createWorkflowExampleAuthoring(container: AwilixContainer): WorkflowExampleAuthoring {
90
+ return {
91
+ async createExampleDefinitionIfAbsent(em, input) {
92
+ const parsed = exampleInputSchema.safeParse(input)
93
+ if (!parsed.success || parsed.data.fixture.workflowName.trim().length === 0) {
94
+ throw new Error('[internal] Invalid workflow example input.')
95
+ }
96
+ const { fixture, ...scope } = parsed.data
97
+
98
+ await validateSetupOrganization(container, em, scope)
99
+
100
+ let result: Awaited<ReturnType<typeof persistIfAbsent>>
101
+ try {
102
+ result = await persistIfAbsent(em, scope, fixture)
103
+ } catch (error) {
104
+ throw Object.assign(new Error('[internal] Workflow example could not be saved.'), {
105
+ code: readPgSqlState(error),
106
+ })
107
+ }
108
+ if (result === 'scope_conflict') {
109
+ throw new Error('[internal] Workflow example version conflicts with an existing definition.')
110
+ }
111
+ return result
112
+ },
113
+ }
114
+ }
@@ -0,0 +1,54 @@
1
+ import type { executeRuleByRuleId } from '@open-mercato/core/modules/business_rules'
2
+ import type { AppContainer } from '@open-mercato/shared/lib/di/container'
3
+ import { reportError } from '@open-mercato/telemetry'
4
+ import { getRequestScopeContainer, runInRequestScope } from '@open-mercato/shared/lib/di/request-scope'
5
+ import { isBusinessRulesModuleEnabled } from './optional-modules'
6
+
7
+ export type WorkflowRuleContainer = {
8
+ resolve: <T>(name: string, options?: { allowUnregistered?: boolean }) => T
9
+ }
10
+
11
+ type NamedWorkflowRuleRunner = { executeRuleByRuleId: typeof executeRuleByRuleId }
12
+
13
+ function resolveNamedRuleRunner(container: WorkflowRuleContainer | null): NamedWorkflowRuleRunner | undefined {
14
+ const runner = container?.resolve<NamedWorkflowRuleRunner | undefined>('ruleEngine', { allowUnregistered: true })
15
+ return typeof runner?.executeRuleByRuleId === 'function' ? runner : undefined
16
+ }
17
+
18
+ export function createNamedWorkflowRuleScope(container: WorkflowRuleContainer | null | undefined) {
19
+ let ownedContainer: AppContainer | undefined
20
+ let resolved: Promise<NamedWorkflowRuleRunner | undefined> | undefined
21
+
22
+ async function resolve() {
23
+ const activeContainer = container === undefined ? getRequestScopeContainer() : container
24
+ if (activeContainer || container !== undefined) return resolveNamedRuleRunner(activeContainer)
25
+ if (!isBusinessRulesModuleEnabled()) return undefined
26
+
27
+ const { createRequestContainer } = await import('@open-mercato/shared/lib/di/container')
28
+ ownedContainer = await runInRequestScope(createRequestContainer)
29
+ return resolveNamedRuleRunner(ownedContainer)
30
+ }
31
+
32
+ return {
33
+ resolve: () => resolved ??= resolve(),
34
+ async dispose() {
35
+ try {
36
+ await ownedContainer?.dispose()
37
+ } catch (error) {
38
+ reportError(error, { module: 'workflows', code: 'workflows.named_rule_scope_disposal_failed' })
39
+ }
40
+ },
41
+ }
42
+ }
43
+
44
+ export async function withNamedWorkflowRuleRunner<Result>(
45
+ container: WorkflowRuleContainer | null | undefined,
46
+ useRunner: (runner: NamedWorkflowRuleRunner | undefined) => Promise<Result>,
47
+ ): Promise<Result> {
48
+ const scope = createNamedWorkflowRuleScope(container)
49
+ try {
50
+ return await useRunner(await scope.resolve())
51
+ } finally {
52
+ await scope.dispose()
53
+ }
54
+ }
@@ -8,6 +8,7 @@ import {
8
8
  } from '../data/entities'
9
9
  import { normalizeGrantedFeatures, syncWorkflowDefinitionPrincipal } from './definition-grant'
10
10
  import { invalidateTriggerCache } from './event-trigger-service'
11
+ import { createWorkflowExampleAuthoring, type WorkflowExampleAuthoring } from './example-definition-authoring'
11
12
 
12
13
  /**
13
14
  * Create-or-update of a workflow definition that ANOTHER module authors and owns.
@@ -50,7 +51,7 @@ export type OwnedWorkflowDefinitionResult =
50
51
  | { ok: true; definition: WorkflowDefinition; created: boolean }
51
52
  | { ok: false; reason: 'owned_by_other'; definition: WorkflowDefinition }
52
53
 
53
- export interface WorkflowDefinitionAuthoring {
54
+ export interface WorkflowDefinitionAuthoring extends Partial<WorkflowExampleAuthoring> {
54
55
  upsertOwnedDefinition(
55
56
  em: EntityManager,
56
57
  input: OwnedWorkflowDefinitionInput,
@@ -77,6 +78,8 @@ function ownedBy(definition: WorkflowDefinition, ownerModule: string, ownerId: s
77
78
 
78
79
  export function createWorkflowDefinitionAuthoring(container: AwilixContainer): WorkflowDefinitionAuthoring {
79
80
  return {
81
+ ...createWorkflowExampleAuthoring(container),
82
+
80
83
  async findOwnedDefinition(em, params) {
81
84
  return em.findOne(
82
85
  WorkflowDefinition,
@@ -435,7 +435,7 @@ async function advanceOneBranch(
435
435
  const token = branchToken(instance, branch)
436
436
  // Token read context = instance snapshot overlaid with branch namespace.
437
437
  const readContext = { ...(instance.context || {}), ...(branch.contextNamespace || {}) }
438
- const evalContext = { workflowContext: readContext, userId: context.userId }
438
+ const evalContext = { container, workflowContext: readContext, userId: context.userId }
439
439
 
440
440
  // Select the transition to take. Branches positioned on the fork follow their
441
441
  // own branch_key transition; otherwise pick the highest-priority valid auto one.
@@ -483,6 +483,7 @@ export async function sendSignal(
483
483
 
484
484
  // Find valid transitions
485
485
  const transitionContext = {
486
+ container,
486
487
  workflowContext: instance.context,
487
488
  userId,
488
489
  }
@@ -7,10 +7,8 @@
7
7
  */
8
8
 
9
9
  import { EntityManager } from '@mikro-orm/core'
10
- import { WorkflowDefinition } from '../data/entities'
11
- import * as ruleEngine from '../../business_rules/lib/rule-engine'
12
10
  import { findWorkflowDefinition } from './find-definition'
13
- import { isBusinessRulesModuleEnabled } from './optional-modules'
11
+ import { withNamedWorkflowRuleRunner, type WorkflowRuleContainer } from './named-rules'
14
12
  import type { StartPreCondition } from '../data/validators'
15
13
  import { defaultLocale } from '@open-mercato/shared/lib/i18n/config'
16
14
  import { resolveLocaleFromCandidates } from '@open-mercato/shared/lib/i18n/locale'
@@ -64,7 +62,8 @@ export interface ValidateStartResult {
64
62
  */
65
63
  export async function validateWorkflowStart(
66
64
  em: EntityManager,
67
- options: ValidateStartOptions
65
+ options: ValidateStartOptions,
66
+ runtime?: { container?: WorkflowRuleContainer | null; skipActions?: boolean },
68
67
  ): Promise<ValidateStartResult> {
69
68
  const { workflowId, version, context, locale = 'en', tenantId, organizationId } = options
70
69
 
@@ -136,111 +135,114 @@ export async function validateWorkflowStart(
136
135
  }
137
136
  }
138
137
 
139
- if (!isBusinessRulesModuleEnabled()) {
140
- const required = preConditions.filter((condition) => condition.required)
141
- if (required.length === 0) return { canStart: true, errors: [], validatedRules: [] }
142
- const language = resolveLocaleFromCandidates([locale], getSupportedLocales()) ?? defaultLocale
143
- const t = createTranslator(await loadDictionary(language))
144
- return {
145
- canStart: false,
146
- errors: required.map((condition) => ({
138
+ return withNamedWorkflowRuleRunner(runtime?.container, async (runner) => {
139
+ if (!runner) {
140
+ const required = preConditions.filter((condition) => condition.required)
141
+ if (required.length === 0) return { canStart: true, errors: [], validatedRules: [] }
142
+ const language = resolveLocaleFromCandidates([locale], getSupportedLocales()) ?? defaultLocale
143
+ const t = createTranslator(await loadDictionary(language))
144
+ return {
145
+ canStart: false,
146
+ errors: required.map((condition) => ({
147
+ ruleId: condition.ruleId,
148
+ message: getLocalizedMessage(
149
+ condition,
150
+ null,
151
+ locale,
152
+ t('workflows.errors.businessRulesModuleDisabled', 'Business rules module is disabled: {ruleId}', {
153
+ ruleId: condition.ruleId,
154
+ }),
155
+ ),
156
+ code: 'RULE_ENGINE_UNAVAILABLE',
157
+ })),
158
+ validatedRules: [],
159
+ }
160
+ }
161
+
162
+ // Evaluate each pre-condition using rule engine
163
+ const errors: ValidationError[] = []
164
+ const validatedRules: ValidatedRule[] = []
165
+
166
+ for (const condition of preConditions) {
167
+ // Execute rule directly by string rule_id
168
+ const result = await runner.executeRuleByRuleId(em, {
169
+ ruleId: condition.ruleId, // String identifier like "workflow_checkout_inventory_available"
170
+ data: {
171
+ workflowId,
172
+ workflowContext: context,
173
+ },
174
+ tenantId,
175
+ organizationId,
176
+ entityType: `workflow:${workflowId}:start`,
177
+ entityId: 'pre_start_validation',
178
+ eventType: 'validate_start',
179
+ dryRun: true, // Don't log execution during validation
180
+ ...(runtime?.skipActions ? { skipActions: true } : {}),
181
+ })
182
+
183
+ validatedRules.push({
147
184
  ruleId: condition.ruleId,
148
- message: getLocalizedMessage(
149
- condition,
150
- null,
151
- locale,
152
- t('workflows.errors.businessRulesModuleDisabled', 'Business rules module is disabled: {ruleId}', {
185
+ passed: result.conditionResult,
186
+ executionTime: result.executionTime,
187
+ })
188
+
189
+ // Handle rule not found
190
+ if (result.error === 'Rule not found') {
191
+ if (condition.required) {
192
+ errors.push({
153
193
  ruleId: condition.ruleId,
154
- }),
155
- ),
156
- code: 'RULE_ENGINE_UNAVAILABLE',
157
- })),
158
- validatedRules: [],
159
- }
160
- }
194
+ message: getLocalizedMessage(condition, null, locale, `Business rule not found: ${condition.ruleId}`),
195
+ code: 'RULE_NOT_FOUND',
196
+ })
197
+ }
198
+ continue
199
+ }
200
+
201
+ // Handle disabled rule
202
+ if (result.error === 'Rule is disabled') {
203
+ if (condition.required) {
204
+ errors.push({
205
+ ruleId: condition.ruleId,
206
+ message: getLocalizedMessage(condition, null, locale, `Business rule is disabled: ${result.ruleName}`),
207
+ code: 'RULE_DISABLED',
208
+ })
209
+ }
210
+ continue
211
+ }
161
212
 
162
- // Evaluate each pre-condition using rule engine
163
- const errors: ValidationError[] = []
164
- const validatedRules: ValidatedRule[] = []
165
-
166
- for (const condition of preConditions) {
167
- // Execute rule directly by string rule_id
168
- const result = await ruleEngine.executeRuleByRuleId(em, {
169
- ruleId: condition.ruleId, // String identifier like "workflow_checkout_inventory_available"
170
- data: {
171
- workflowId,
172
- workflowContext: context,
173
- },
174
- tenantId,
175
- organizationId,
176
- entityType: `workflow:${workflowId}:start`,
177
- entityId: 'pre_start_validation',
178
- eventType: 'validate_start',
179
- dryRun: true, // Don't log execution during validation
180
- })
181
-
182
- validatedRules.push({
183
- ruleId: condition.ruleId,
184
- passed: result.conditionResult,
185
- executionTime: result.executionTime,
186
- })
187
-
188
- // Handle rule not found
189
- if (result.error === 'Rule not found') {
190
- if (condition.required) {
213
+ // Handle other errors (not yet effective, expired, etc.)
214
+ if (result.error && condition.required) {
191
215
  errors.push({
192
216
  ruleId: condition.ruleId,
193
- message: getLocalizedMessage(condition, null, locale, `Business rule not found: ${condition.ruleId}`),
194
- code: 'RULE_NOT_FOUND',
217
+ message: getLocalizedMessage(condition, null, locale, `Rule error: ${result.error}`),
218
+ code: 'RULE_ERROR',
195
219
  })
220
+ continue
196
221
  }
197
- continue
198
- }
199
222
 
200
- // Handle disabled rule
201
- if (result.error === 'Rule is disabled') {
202
- if (condition.required) {
223
+ // Handle condition failure
224
+ if (!result.conditionResult && condition.required) {
225
+ // Get localized message from condition or use default with rule name
226
+ const message = getLocalizedMessage(
227
+ condition,
228
+ null,
229
+ locale,
230
+ `Pre-condition '${result.ruleName || condition.ruleId}' failed`
231
+ )
203
232
  errors.push({
204
233
  ruleId: condition.ruleId,
205
- message: getLocalizedMessage(condition, null, locale, `Business rule is disabled: ${result.ruleName}`),
206
- code: 'RULE_DISABLED',
234
+ message,
235
+ code: 'PRE_CONDITION_FAILED',
207
236
  })
208
237
  }
209
- continue
210
- }
211
-
212
- // Handle other errors (not yet effective, expired, etc.)
213
- if (result.error && condition.required) {
214
- errors.push({
215
- ruleId: condition.ruleId,
216
- message: getLocalizedMessage(condition, null, locale, `Rule error: ${result.error}`),
217
- code: 'RULE_ERROR',
218
- })
219
- continue
220
238
  }
221
239
 
222
- // Handle condition failure
223
- if (!result.conditionResult && condition.required) {
224
- // Get localized message from condition or use default with rule name
225
- const message = getLocalizedMessage(
226
- condition,
227
- null,
228
- locale,
229
- `Pre-condition '${result.ruleName || condition.ruleId}' failed`
230
- )
231
- errors.push({
232
- ruleId: condition.ruleId,
233
- message,
234
- code: 'PRE_CONDITION_FAILED',
235
- })
240
+ return {
241
+ canStart: errors.length === 0,
242
+ errors,
243
+ validatedRules,
236
244
  }
237
- }
238
-
239
- return {
240
- canStart: errors.length === 0,
241
- errors,
242
- validatedRules,
243
- }
245
+ })
244
246
  }
245
247
 
246
248
  // ============================================================================
@@ -1204,7 +1204,7 @@ async function handleSubWorkflowStep(
1204
1204
  },
1205
1205
  tenantId: instance.tenantId,
1206
1206
  organizationId: instance.organizationId,
1207
- })
1207
+ }, container)
1208
1208
 
1209
1209
  // Log sub-workflow invocation event
1210
1210
  await logStepEvent(em, {
@@ -334,6 +334,7 @@ export async function completeUserTask(
334
334
  }
335
335
 
336
336
  const transitionContext = {
337
+ container,
337
338
  workflowContext: instance.context,
338
339
  userId,
339
340
  }
@@ -203,6 +203,7 @@ export async function fireTimer(
203
203
  }
204
204
 
205
205
  const transitionContext = {
206
+ container,
206
207
  workflowContext: instance.context,
207
208
  userId,
208
209
  }