1 import type { TSESTree } from "@typescript-eslint/utils"
2 import { AST_NODE_TYPES } from "@typescript-eslint/utils"
3 import { createRule } from "../../create-rule"
4 import {
5 createWorkflowSdkBindings,
6 isWorkflowSdkHelperCall,
7 trackWorkflowSdkImports,
8 WorkflowSdkBindings,
9 } from "../../util/workflow-scope"
10
11 type MessageIds = "whenBlockMissingName"
12
13 type FunctionLike =
14 | TSESTree.ArrowFunctionExpression
15 | TSESTree.FunctionExpression
16
17 /**
18 * Returns the `.then(fn)` callback chained directly off a `when(...)` call,
19 * or `null` if `node` isn't immediately followed by `.then(...)`.
20 */
21 const getThenCallback = (
22 node: TSESTree.CallExpression
23 ): FunctionLike | null => {
24 const parent = node.parent
25 if (!parent || parent.type !== AST_NODE_TYPES.MemberExpression) {
26 return null
27 }
28 if (parent.object !== node || parent.computed) {
29 return null
30 }
31 if (
32 parent.property.type !== AST_NODE_TYPES.Identifier ||
33 parent.property.name !== "then"
34 ) {
35 return null
36 }
37 const grandparent = parent.parent
38 if (!grandparent || grandparent.type !== AST_NODE_TYPES.CallExpression) {
39 return null
40 }
41 if (grandparent.callee !== parent) {
42 return null
43 }
44 const callback = grandparent.arguments[0]
45 if (
46 !callback ||
47 (callback.type !== AST_NODE_TYPES.ArrowFunctionExpression &&
48 callback.type !== AST_NODE_TYPES.FunctionExpression)
49 ) {
50 return null
51 }
52 return callback
53 }
54
55 /**
56 * Unwraps a trailing `.config(...)` call — steps are commonly renamed with
57 * `someStep(...).config({ name: ... })`, which doesn't change what the
58 * expression fundamentally returns.
59 */
60 const unwrapConfigCall = (expr: TSESTree.Expression): TSESTree.Expression => {
61 if (expr.type !== AST_NODE_TYPES.CallExpression) {
62 return expr
63 }
64 const callee = expr.callee
65 if (
66 callee.type === AST_NODE_TYPES.MemberExpression &&
67 !callee.computed &&
68 callee.property.type === AST_NODE_TYPES.Identifier &&
69 callee.property.name === "config" &&
70 callee.object.type === AST_NODE_TYPES.CallExpression
71 ) {
72 return callee.object
73 }
74 return expr
75 }
76
77 /**
78 * True when `expr` (after unwrapping `.config(...)`) is a direct step or
79 * `.runAsStep(...)` invocation. `when().then()` returns those values as-is,
80 * without wrapping them in a synthetic step — so no name is required for
81 * this shape at runtime, matching the behavior in
82 * `packages/core/workflows-sdk/src/utils/composer/when.ts`.
83 */
84 const isStepLikeReturn = (
85 expr: TSESTree.Expression,
86 bindings: WorkflowSdkBindings
87 ): boolean => {
88 const unwrapped = unwrapConfigCall(expr)
89 if (unwrapped.type !== AST_NODE_TYPES.CallExpression) {
90 return false
91 }
92 const callee = unwrapped.callee
93 if (callee.type === AST_NODE_TYPES.Identifier) {
94 return !isWorkflowSdkHelperCall(callee.name, bindings)
95 }
96 if (
97 callee.type === AST_NODE_TYPES.MemberExpression &&
98 !callee.computed &&
99 callee.property.type === AST_NODE_TYPES.Identifier
100 ) {
101 return callee.property.name === "runAsStep"
102 }
103 return false
104 }
105
106 /**
107 * Collects the top-level `return` argument expressions of a `.then(fn)`
108 * callback. `if`/`try`/loops are already banned in this scope by other
109 * rules, so callbacks are effectively flat — only the block's direct
110 * statements (not nested functions) are inspected.
111 */
112 const getReturnArguments = (fn: FunctionLike): TSESTree.Expression[] => {
113 if (fn.body.type !== AST_NODE_TYPES.BlockStatement) {
114 return [fn.body]
115 }
116 const args: TSESTree.Expression[] = []
117 for (const statement of fn.body.body) {
118 if (
119 statement.type === AST_NODE_TYPES.ReturnStatement &&
120 statement.argument
121 ) {
122 args.push(statement.argument)
123 }
124 }
125 return args
126 }
127
128 export const rule = createRule<[], MessageIds>({
129 name: "when-block-must-have-name",
130 meta: {
131 type: "suggestion",
132 docs: {
133 description:
134 "Require a `name` on `when(...)` calls whose `.then()` callback returns a value that isn't a step invocation. Medusa core assigns a random name at runtime in this case and logs a warning — pass `when(name, values, condition)` instead.",
135 },
136 messages: {
137 whenBlockMissingName:
138 "This `when` block's `.then()` returns a value that will be wrapped in a synthetic step. Without an explicit name, Medusa assigns a random one and logs a warning in production. Pass a name as the first argument: `when('<unique-name>', values, condition)`.",
139 },
140 schema: [],
141 },
142 defaultOptions: [],
143 create(context) {
144 const bindings = createWorkflowSdkBindings()
145
146 return {
147 ImportDeclaration(node) {
148 trackWorkflowSdkImports(node, bindings)
149 },
150
151 CallExpression(node) {
152 if (bindings.when.size === 0) {
153 return
154 }
155 if (node.callee.type !== AST_NODE_TYPES.Identifier) {
156 return
157 }
158 if (!bindings.when.has(node.callee.name)) {
159 return
160 }
161 // Named form: `when(name, values, condition)`. Any 3-arg call is
162 // treated as named, including a non-literal `name`, since a variable
163 // could still resolve to a non-empty string at runtime — we can't
164 // tell statically, so we don't flag it.
165 if (node.arguments.length !== 2) {
166 return
167 }
168
169 const thenCallback = getThenCallback(node)
170 if (!thenCallback) {
171 return
172 }
173
174 const hasNonStepReturn = getReturnArguments(thenCallback).some(
175 (returnArg) => !isStepLikeReturn(returnArg, bindings)
176 )
177 if (!hasNonStepReturn) {
178 return
179 }
180
181 context.report({
182 node,
183 messageId: "whenBlockMissingName",
184 })
185 },
186 }
187 },
188 })
189
190 export default rule