@open-mercato/core 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8572.1.85986dc508

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 (164) 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/catalog/lib/productScopeReindex.js +1 -1
  17. package/dist/modules/catalog/lib/productScopeReindex.js.map +2 -2
  18. package/dist/modules/configs/cli.js +26 -29
  19. package/dist/modules/configs/cli.js.map +2 -2
  20. package/dist/modules/configs/di.js +3 -1
  21. package/dist/modules/configs/di.js.map +2 -2
  22. package/dist/modules/configs/lib/instance-config-initializer.js +44 -0
  23. package/dist/modules/configs/lib/instance-config-initializer.js.map +7 -0
  24. package/dist/modules/configs/lib/instance-defaults.js +204 -0
  25. package/dist/modules/configs/lib/instance-defaults.js.map +7 -0
  26. package/dist/modules/configs/lib/module-config-service.js +115 -1
  27. package/dist/modules/configs/lib/module-config-service.js.map +2 -2
  28. package/dist/modules/entities/api/definitions.batch.js +55 -25
  29. package/dist/modules/entities/api/definitions.batch.js.map +2 -2
  30. package/dist/modules/entities/api/definitions.js +35 -8
  31. package/dist/modules/entities/api/definitions.js.map +2 -2
  32. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +14 -8
  33. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  34. package/dist/modules/notifications/lib/deliveryConfig.js +19 -12
  35. package/dist/modules/notifications/lib/deliveryConfig.js.map +2 -2
  36. package/dist/modules/notifications/setup.js +10 -0
  37. package/dist/modules/notifications/setup.js.map +2 -2
  38. package/dist/modules/payment_gateways/lib/gateway-service.js +1 -1
  39. package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
  40. package/dist/modules/query_index/api/purge.js +1 -1
  41. package/dist/modules/query_index/api/purge.js.map +2 -2
  42. package/dist/modules/query_index/api/reindex.js +1 -1
  43. package/dist/modules/query_index/api/reindex.js.map +2 -2
  44. package/dist/modules/query_index/cli.js +2 -2
  45. package/dist/modules/query_index/cli.js.map +2 -2
  46. package/dist/modules/query_index/lib/engine.js +5 -1
  47. package/dist/modules/query_index/lib/engine.js.map +2 -2
  48. package/dist/modules/query_index/subscribers/purge.js +3 -3
  49. package/dist/modules/query_index/subscribers/purge.js.map +2 -2
  50. package/dist/modules/query_index/subscribers/reindex.js +11 -13
  51. package/dist/modules/query_index/subscribers/reindex.js.map +2 -2
  52. package/dist/modules/translations/components/TranslationManager.js +47 -10
  53. package/dist/modules/translations/components/TranslationManager.js.map +2 -2
  54. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js +8 -1
  55. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js.map +2 -2
  56. package/dist/modules/workflows/ai-tools/authoring-pack.js +1 -1
  57. package/dist/modules/workflows/ai-tools/authoring-pack.js.map +2 -2
  58. package/dist/modules/workflows/api/instances/[id]/advance/route.js +1 -0
  59. package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
  60. package/dist/modules/workflows/api/instances/route.js +1 -1
  61. package/dist/modules/workflows/api/instances/route.js.map +2 -2
  62. package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
  63. package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
  64. package/dist/modules/workflows/components/fields/ActivityConfigFields.js +2 -0
  65. package/dist/modules/workflows/components/fields/ActivityConfigFields.js.map +2 -2
  66. package/dist/modules/workflows/di.js +3 -1
  67. package/dist/modules/workflows/di.js.map +2 -2
  68. package/dist/modules/workflows/events.js +13 -0
  69. package/dist/modules/workflows/events.js.map +2 -2
  70. package/dist/modules/workflows/lib/activity-executor.js +48 -15
  71. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  72. package/dist/modules/workflows/lib/condition-handler.js +1 -1
  73. package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
  74. package/dist/modules/workflows/lib/error-handler.js +1 -1
  75. package/dist/modules/workflows/lib/error-handler.js.map +2 -2
  76. package/dist/modules/workflows/lib/event-trigger-service.js +1 -1
  77. package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
  78. package/dist/modules/workflows/lib/example-definition-authoring.js +90 -0
  79. package/dist/modules/workflows/lib/example-definition-authoring.js.map +7 -0
  80. package/dist/modules/workflows/lib/named-rules.js +42 -0
  81. package/dist/modules/workflows/lib/named-rules.js.map +7 -0
  82. package/dist/modules/workflows/lib/owned-definition.js +2 -0
  83. package/dist/modules/workflows/lib/owned-definition.js.map +2 -2
  84. package/dist/modules/workflows/lib/parallel-handler.js +1 -1
  85. package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
  86. package/dist/modules/workflows/lib/signal-handler.js +1 -0
  87. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  88. package/dist/modules/workflows/lib/start-validator.js +87 -85
  89. package/dist/modules/workflows/lib/start-validator.js.map +2 -2
  90. package/dist/modules/workflows/lib/step-handler.js +1 -1
  91. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  92. package/dist/modules/workflows/lib/task-handler.js +1 -0
  93. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  94. package/dist/modules/workflows/lib/timer-handler.js +1 -0
  95. package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
  96. package/dist/modules/workflows/lib/transition-handler.js +48 -166
  97. package/dist/modules/workflows/lib/transition-handler.js.map +3 -3
  98. package/dist/modules/workflows/lib/workflow-executor.js +3 -2
  99. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  100. package/package.json +8 -8
  101. package/src/modules/api_keys/di.ts +7 -2
  102. package/src/modules/api_keys/services/oneTimeIssuerService.ts +61 -0
  103. package/src/modules/audit_logs/di.ts +1 -0
  104. package/src/modules/audit_logs/services/actionLogService.ts +132 -1
  105. package/src/modules/auth/cli.ts +1 -0
  106. package/src/modules/auth/commands/users.ts +10 -2
  107. package/src/modules/auth/i18n/de.json +2 -0
  108. package/src/modules/auth/i18n/en.json +2 -0
  109. package/src/modules/auth/i18n/es.json +2 -0
  110. package/src/modules/auth/i18n/ko.json +2 -0
  111. package/src/modules/auth/i18n/pl.json +2 -0
  112. package/src/modules/auth/lib/setup-app.ts +30 -7
  113. package/src/modules/catalog/lib/productScopeReindex.ts +1 -1
  114. package/src/modules/configs/cli.ts +39 -37
  115. package/src/modules/configs/di.ts +2 -0
  116. package/src/modules/configs/lib/instance-config-initializer.ts +56 -0
  117. package/src/modules/configs/lib/instance-defaults.ts +262 -0
  118. package/src/modules/configs/lib/module-config-service.ts +156 -0
  119. package/src/modules/entities/api/definitions.batch.ts +65 -27
  120. package/src/modules/entities/api/definitions.ts +40 -11
  121. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +14 -7
  122. package/src/modules/notifications/lib/deliveryConfig.ts +20 -11
  123. package/src/modules/notifications/setup.ts +11 -0
  124. package/src/modules/payment_gateways/lib/gateway-service.ts +2 -2
  125. package/src/modules/query_index/api/purge.ts +1 -1
  126. package/src/modules/query_index/api/reindex.ts +1 -1
  127. package/src/modules/query_index/cli.ts +2 -2
  128. package/src/modules/query_index/lib/engine.ts +5 -1
  129. package/src/modules/query_index/subscribers/purge.ts +5 -4
  130. package/src/modules/query_index/subscribers/reindex.ts +14 -15
  131. package/src/modules/translations/components/TranslationManager.tsx +49 -10
  132. package/src/modules/translations/i18n/de.json +1 -0
  133. package/src/modules/translations/i18n/en.json +1 -0
  134. package/src/modules/translations/i18n/es.json +1 -0
  135. package/src/modules/translations/i18n/ko.json +1 -0
  136. package/src/modules/translations/i18n/pl.json +1 -0
  137. package/src/modules/wms/components/backend/CompletePutawayTaskDialog.tsx +8 -1
  138. package/src/modules/wms/i18n/de.json +1 -0
  139. package/src/modules/wms/i18n/en.json +1 -0
  140. package/src/modules/wms/i18n/es.json +1 -0
  141. package/src/modules/wms/i18n/ko.json +1 -0
  142. package/src/modules/wms/i18n/pl.json +1 -0
  143. package/src/modules/workflows/ai-tools/authoring-pack.ts +3 -1
  144. package/src/modules/workflows/api/instances/[id]/advance/route.ts +1 -0
  145. package/src/modules/workflows/api/instances/route.ts +1 -1
  146. package/src/modules/workflows/api/instances/validate-start/route.ts +3 -1
  147. package/src/modules/workflows/components/fields/ActivityConfigFields.tsx +2 -0
  148. package/src/modules/workflows/di.ts +2 -0
  149. package/src/modules/workflows/events.ts +14 -0
  150. package/src/modules/workflows/lib/activity-executor.ts +64 -40
  151. package/src/modules/workflows/lib/condition-handler.ts +1 -1
  152. package/src/modules/workflows/lib/error-handler.ts +1 -1
  153. package/src/modules/workflows/lib/event-trigger-service.ts +1 -1
  154. package/src/modules/workflows/lib/example-definition-authoring.ts +114 -0
  155. package/src/modules/workflows/lib/named-rules.ts +54 -0
  156. package/src/modules/workflows/lib/owned-definition.ts +4 -1
  157. package/src/modules/workflows/lib/parallel-handler.ts +1 -1
  158. package/src/modules/workflows/lib/signal-handler.ts +1 -0
  159. package/src/modules/workflows/lib/start-validator.ts +96 -94
  160. package/src/modules/workflows/lib/step-handler.ts +1 -1
  161. package/src/modules/workflows/lib/task-handler.ts +1 -0
  162. package/src/modules/workflows/lib/timer-handler.ts +1 -0
  163. package/src/modules/workflows/lib/transition-handler.ts +74 -238
  164. package/src/modules/workflows/lib/workflow-executor.ts +7 -4
@@ -41,6 +41,7 @@ import {
41
41
  } from '../data/validators'
42
42
  import { workflowDraftGenerationSchema } from '../lib/ai-authoring'
43
43
  import { isComponentKind } from '../lib/component-guard'
44
+ import type { WorkflowRuleContainer } from '../lib/named-rules'
44
45
  import {
45
46
  computeDefinitionContextLedger,
46
47
  narrowLedgerToStep,
@@ -624,6 +625,7 @@ const startTestRunTool: WorkflowsAiToolDefinition<z.infer<typeof startTestRunInp
624
625
  startWorkflow: (
625
626
  em: EntityManager,
626
627
  options: Record<string, unknown>,
628
+ container?: WorkflowRuleContainer,
627
629
  ) => Promise<WorkflowInstance>
628
630
  executeWorkflow: (
629
631
  em: EntityManager,
@@ -644,7 +646,7 @@ const startTestRunTool: WorkflowsAiToolDefinition<z.infer<typeof startTestRunInp
644
646
  isDryRun: true,
645
647
  tenantId: scope.tenantId,
646
648
  organizationId: scope.organizationId,
647
- })
649
+ }, ctx.container)
648
650
 
649
651
  let executionError: string | null = null
650
652
  try {
@@ -156,6 +156,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
156
156
 
157
157
  // Build evaluation context
158
158
  const evalContext: transitionHandler.TransitionEvaluationContext = {
159
+ container,
159
160
  workflowContext: instance.context,
160
161
  userId: auth.sub,
161
162
  triggerData: input.triggerData,
@@ -338,7 +338,7 @@ export async function POST(request: NextRequest) {
338
338
  isDryRun: input.dryRun === true,
339
339
  tenantId,
340
340
  organizationId,
341
- })
341
+ }, container)
342
342
 
343
343
  // Advance the workflow asynchronously after responding (non-blocking, so the
344
344
  // frontend can poll step-by-step progress). This is a fire-and-forget task in
@@ -24,6 +24,7 @@ import {
24
24
  } from '../../openapi'
25
25
  import { createLogger } from '@open-mercato/shared/lib/logger'
26
26
  import { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
27
+ import { reportError } from '@open-mercato/telemetry'
27
28
 
28
29
  const logger = createLogger('workflows')
29
30
 
@@ -87,7 +88,7 @@ export async function POST(request: NextRequest) {
87
88
  locale,
88
89
  tenantId,
89
90
  organizationId,
90
- })
91
+ }, { container })
91
92
 
92
93
  // Always return 200 with the validation result
93
94
  // The client can check canStart to determine if workflow can proceed
@@ -100,6 +101,7 @@ export async function POST(request: NextRequest) {
100
101
  } catch (error) {
101
102
  if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status })
102
103
  logger.error('Error validating workflow start', { err: error })
104
+ reportError(error, { module: 'workflows', code: 'workflows.start_validation_failed' })
103
105
  return NextResponse.json(
104
106
  { error: 'Failed to validate workflow start' },
105
107
  { status: 500 }
@@ -525,6 +525,8 @@ export function ActivityConfigFields({ activityType, idPrefix, config, onChange,
525
525
  case 'eventName':
526
526
  return (
527
527
  <EventPatternInput
528
+ workflowEmittableOnly
529
+ placeholder={t('ui.inputs.eventSelect.placeholder', 'Select an event...')}
528
530
  value={stringValue(rawValue)}
529
531
  onChange={(nextValue) => setField(spec, nextValue)}
530
532
  disabled={disabled}
@@ -21,6 +21,7 @@ import * as conditionHandler from './lib/condition-handler'
21
21
  import * as taskHandler from './lib/task-handler'
22
22
  import * as workInboxService from './lib/work-inbox/service'
23
23
  import { createWorkflowDefinitionAuthoring } from './lib/owned-definition'
24
+ import { createWorkflowExampleAuthoring } from './lib/example-definition-authoring'
24
25
  import { registerWorkInboxSources } from './lib/work-inbox/provider'
25
26
  import { userTaskWorkInboxSource, WORKFLOWS_MODULE_ID } from './lib/work-inbox/user-task-source'
26
27
 
@@ -66,6 +67,7 @@ export function register(container: AwilixContainer): void {
66
67
  // Lets another module own a real workflow definition instead of building a
67
68
  // second executor for its simple case — see lib/owned-definition.ts.
68
69
  workflowDefinitionAuthoring: asScopedService((scope) => createWorkflowDefinitionAuthoring(scope)),
70
+ workflowExampleAuthoring: asScopedService((scope) => createWorkflowExampleAuthoring(scope)),
69
71
  })
70
72
  }
71
73
 
@@ -6,6 +6,20 @@ import { createModuleEvents } from '@open-mercato/shared/modules/events'
6
6
  * Declares all events that can be emitted by the workflows module.
7
7
  */
8
8
  const events = [
9
+ { id: 'approval.completed', label: 'Approval Completed', category: 'lifecycle', workflowEmittable: true },
10
+ { id: 'approval.requested', label: 'Approval Requested', category: 'lifecycle', workflowEmittable: true },
11
+ { id: 'checkout.started', label: 'Checkout Started', category: 'lifecycle', workflowEmittable: true },
12
+ { id: 'fulfillment.ready', label: 'Fulfillment Ready', category: 'lifecycle', workflowEmittable: true },
13
+ { id: 'order.approved', label: 'Order Approved', category: 'lifecycle', workflowEmittable: true },
14
+ { id: 'order.created', label: 'Order Created', category: 'lifecycle', workflowEmittable: true },
15
+ { id: 'oze.install.failed', label: 'Oze Install Failed', category: 'lifecycle', workflowEmittable: true },
16
+ { id: 'oze.quote.sent', label: 'Oze Quote Sent', category: 'lifecycle', workflowEmittable: true },
17
+ { id: 'sales.order.approval.approved', label: 'Sales Order Approval Approved', category: 'lifecycle', workflowEmittable: true },
18
+ { id: 'sales.order.approval.rejected', label: 'Sales Order Approval Rejected', category: 'lifecycle', workflowEmittable: true },
19
+ { id: 'sales.order.approval.requested', label: 'Sales Order Approval Requested', category: 'lifecycle', workflowEmittable: true },
20
+ { id: 'sales.pipeline.completed', label: 'Sales Pipeline Completed', category: 'lifecycle', workflowEmittable: true },
21
+ { id: 'workflows.task.escalated', label: 'Workflows Task Escalated', category: 'lifecycle', workflowEmittable: true },
22
+
9
23
  // Workflow Definitions
10
24
  { id: 'workflows.definition.created', label: 'Workflow Definition Created', entity: 'definition', category: 'crud' },
11
25
  { id: 'workflows.definition.updated', label: 'Workflow Definition Updated', entity: 'definition', category: 'crud' },
@@ -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 {
@@ -24,7 +24,7 @@ import {
24
24
  type HostLookup,
25
25
  } from '@open-mercato/shared/lib/url-safety'
26
26
  import { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'
27
- import { isPrivateCrossProcessBroadcastEvent } from '@open-mercato/shared/modules/events'
27
+ import { getDeclaredEvents, isPrivateCrossProcessBroadcastEvent } from '@open-mercato/shared/modules/events'
28
28
  import { hasAllFeatures } from '@open-mercato/shared/security/features'
29
29
  import {
30
30
  definitionDeclaresGrant,
@@ -963,9 +963,9 @@ export async function executeEmitEvent(
963
963
  container: AwilixContainer,
964
964
  signal?: AbortSignal
965
965
  ): Promise<any> {
966
- const { eventName, payload } = config
966
+ const { eventName, payload }: { eventName?: unknown; payload?: Record<string, unknown> } = config
967
967
 
968
- if (!eventName) {
968
+ if (typeof eventName !== 'string' || !eventName) {
969
969
  throw new Error('EMIT_EVENT requires "eventName" field')
970
970
  }
971
971
 
@@ -977,6 +977,11 @@ export async function executeEmitEvent(
977
977
  throw new Error(`EMIT_EVENT cannot emit private cross-process event "${eventName}"`)
978
978
  }
979
979
 
980
+ const declaration = getDeclaredEvents().find((event) => event.id === eventName)
981
+ if (declaration?.workflowEmittable !== true || declaration.portalBroadcast || declaration.crossProcessBroadcast) {
982
+ throw new Error(`EMIT_EVENT cannot emit event "${eventName}" from a workflow`)
983
+ }
984
+
980
985
  // Emissions are fire-and-forget and no subscriber validates the payload shape,
981
986
  // so an unresolved `{{context.x}}` here is even quieter than on the command
982
987
  // path — it ships the literal template to every consumer. Fail loudly instead.
@@ -998,22 +1003,23 @@ export async function executeEmitEvent(
998
1003
  }
999
1004
 
1000
1005
  // Publish event with workflow metadata
1001
- const enrichedPayload = {
1006
+ const { tenantId, organizationId } = context.workflowInstance
1007
+ const enrichedPayload: Record<string, unknown> = {
1002
1008
  ...payload,
1009
+ tenantId,
1010
+ organizationId,
1003
1011
  _workflow: {
1004
1012
  workflowInstanceId: context.workflowInstance.id,
1005
1013
  workflowId: context.workflowInstance.workflowId,
1006
- tenantId: context.workflowInstance.tenantId,
1007
- organizationId: context.workflowInstance.organizationId,
1014
+ tenantId,
1015
+ organizationId,
1008
1016
  },
1009
1017
  }
1018
+ delete enrichedPayload.organizationIds
1010
1019
 
1011
1020
  await raceAbortable(
1012
1021
  Promise.resolve(
1013
- eventBus.emitEvent(eventName, enrichedPayload, {
1014
- tenantId: context.workflowInstance.tenantId,
1015
- organizationId: context.workflowInstance.organizationId,
1016
- })
1022
+ eventBus.emitEvent(eventName, enrichedPayload, { tenantId, organizationId })
1017
1023
  ),
1018
1024
  signal
1019
1025
  )
@@ -1750,11 +1756,46 @@ export async function executeInvokeAgent(
1750
1756
  }
1751
1757
  }
1752
1758
 
1759
+ function isMissingApiKeyOneTimeIssuerError(error: unknown): boolean {
1760
+ if (!error || typeof error !== 'object') return false
1761
+ const candidate = error as { name?: unknown; message?: unknown }
1762
+ if (candidate.name !== 'AwilixResolutionError') return false
1763
+ const message = typeof candidate.message === 'string' ? candidate.message : ''
1764
+ return /Could not resolve ['"]apiKeyOneTimeIssuer['"]/.test(message)
1765
+ }
1766
+
1767
+ function resolveApiKeyOneTimeIssuer(container: AwilixContainer): ApiKeyOneTimeIssuer | null {
1768
+ if (
1769
+ typeof container.hasRegistration === 'function' &&
1770
+ !container.hasRegistration('apiKeyOneTimeIssuer')
1771
+ ) {
1772
+ return null
1773
+ }
1774
+ let candidate: unknown
1775
+ try {
1776
+ candidate = container.resolve<ApiKeyOneTimeIssuer | null | undefined>('apiKeyOneTimeIssuer')
1777
+ } catch (error) {
1778
+ if (isMissingApiKeyOneTimeIssuerError(error)) {
1779
+ return null
1780
+ }
1781
+ throw error
1782
+ }
1783
+ if (candidate === null || candidate === undefined) {
1784
+ return null
1785
+ }
1786
+ if (typeof (candidate as ApiKeyOneTimeIssuer).withOneTimeApiKey !== 'function') {
1787
+ throw new Error(
1788
+ '[CALL_API] Registered apiKeyOneTimeIssuer service is invalid: missing withOneTimeApiKey().',
1789
+ )
1790
+ }
1791
+ return candidate as ApiKeyOneTimeIssuer
1792
+ }
1793
+
1753
1794
  /**
1754
1795
  * CALL_API activity handler
1755
1796
  *
1756
1797
  * Makes authenticated HTTP request to internal Open Mercato APIs
1757
- * - Automatically creates one-time API key for authentication
1798
+ * - Soft-resolves `apiKeyOneTimeIssuer` from DI to mint a short-lived one-time API key
1758
1799
  * - Injects tenant/organization context headers
1759
1800
  * - Validates URL security (SSRF prevention)
1760
1801
  * - Classifies errors (retriable vs non-retriable)
@@ -1788,36 +1829,20 @@ export async function executeCallApi(
1788
1829
  // 2. Build full URL (prepend APP_URL for relative paths)
1789
1830
  const requestUrl = await resolveCallApiUrl(endpoint)
1790
1831
 
1791
- if (!isApiKeysModuleEnabled()) {
1832
+ // 3. Soft-resolve the API Keys-owned one-time credential issuer from the active container.
1833
+ // A missing registration takes the translated API Keys-unavailable refusal; a present
1834
+ // dependency that fails propagates into normal activity failure and retry classification.
1835
+ const apiKeyOneTimeIssuer = resolveApiKeyOneTimeIssuer(container)
1836
+ if (!apiKeyOneTimeIssuer) {
1792
1837
  throw await createCallApiError(
1793
1838
  'workflows.errors.callApi.apiKeysModuleDisabled',
1794
1839
  'CALL_API needs the api_keys module to authenticate internal calls',
1795
1840
  )
1796
1841
  }
1797
1842
 
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
1843
+ // 4. Resolve active user roles on a context-free EntityManager fork outside the surrounding
1844
+ // workflow transaction (matching the isolated-EM convention).
1845
+ const roleResolutionEm = container
1821
1846
  .resolve<PostgreSqlEntityManager>('em')
1822
1847
  .fork({ clear: true, freshEventManager: true, useContext: false }) as PostgreSqlEntityManager
1823
1848
 
@@ -1841,7 +1866,7 @@ export async function executeCallApi(
1841
1866
  // when the instance was started by an event trigger with no user.
1842
1867
  // 3. If no traceable principal exists, the activity refuses to run —
1843
1868
  // there is no "system" fallback that bypasses RBAC.
1844
- const resolvedRoleIds = await resolveCallApiRoleIds(apiKeyEm, context.workflowInstance)
1869
+ const resolvedRoleIds = await resolveCallApiRoleIds(roleResolutionEm, context.workflowInstance)
1845
1870
 
1846
1871
  if (resolvedRoleIds.length === 0) {
1847
1872
  throw new Error(
@@ -1851,9 +1876,8 @@ export async function executeCallApi(
1851
1876
  )
1852
1877
  }
1853
1878
 
1854
- // 6. Execute request with one-time API key scoped to the resolved user's roles
1855
- return await withOnetimeApiKey(
1856
- apiKeyEm,
1879
+ // 6. Execute request with a one-time API key issued by the API Keys provider
1880
+ return await apiKeyOneTimeIssuer.withOneTimeApiKey(
1857
1881
  {
1858
1882
  name: `__workflow_${context.workflowInstance.id}__`,
1859
1883
  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
  }