1 import type { TSESTree, TSESLint } from "@typescript-eslint/utils"
2 import { AST_NODE_TYPES } from "@typescript-eslint/utils"
3 import { createRule } from "../../create-rule"
4 import { toKebab } from "../../util/strings"
5 import {
6 createWorkflowSdkBindings,
7 isInWorkflowConstructor,
8 trackWorkflowSdkImports,
9 WorkflowSdkBindings,
10 } from "../../util/workflow-scope"
11
12 type MessageIds = "duplicateStepId"
13
14 const SDK_HELPER_NAMES: ReadonlySet<string> = new Set([
15 "transform",
16 "when",
17 "parallelize",
18 "createHook",
19 "createStep",
20 "createWorkflow",
21 ])
22
23 const stepBaseName = (calleeName: string): string => {
24 const kebab = toKebab(calleeName)
25 return kebab.endsWith("-step") ? kebab.slice(0, -"-step".length) : kebab
26 }
27
28 type StepCall = {
29 node: TSESTree.CallExpression
30 calleeName: string
31 effectiveKey: string
32 hasConfig: boolean
33 }
34
35 const findConfigCall = (
36 call: TSESTree.CallExpression
37 ): TSESTree.CallExpression | null => {
38 const parent = call.parent
39 if (!parent || parent.type !== AST_NODE_TYPES.MemberExpression) {
40 return null
41 }
42 if (parent.object !== call) {
43 return null
44 }
45 if (parent.computed) {
46 return null
47 }
48 if (parent.property.type !== AST_NODE_TYPES.Identifier) {
49 return null
50 }
51 if (parent.property.name !== "config") {
52 return null
53 }
54 const grand = parent.parent
55 if (!grand || grand.type !== AST_NODE_TYPES.CallExpression) {
56 return null
57 }
58 if (grand.callee !== parent) {
59 return null
60 }
61 return grand
62 }
63
64 /**
65 * Sentinel returned when a `.config({ name })` is present but its `name` value
66 * isn't a static string literal (e.g. a variable or expression). The developer
67 * explicitly set a name, so the call must not be treated as a bare duplicate —
68 * we just can't compare its value statically.
69 */
70 const DYNAMIC_CONFIG_NAME = Symbol("dynamic-config-name")
71
72 const extractConfigName = (
73 configCall: TSESTree.CallExpression
74 ): string | typeof DYNAMIC_CONFIG_NAME | null => {
75 const arg = configCall.arguments[0]
76 if (!arg || arg.type !== AST_NODE_TYPES.ObjectExpression) {
77 return null
78 }
79 for (const prop of arg.properties) {
80 if (prop.type !== AST_NODE_TYPES.Property) {
81 continue
82 }
83 if (prop.computed) {
84 continue
85 }
86 const keyName =
87 prop.key.type === AST_NODE_TYPES.Identifier
88 ? prop.key.name
89 : prop.key.type === AST_NODE_TYPES.Literal &&
90 typeof prop.key.value === "string"
91 ? prop.key.value
92 : null
93 if (keyName !== "name") {
94 continue
95 }
96 if (
97 prop.value.type === AST_NODE_TYPES.Literal &&
98 typeof prop.value.value === "string"
99 ) {
100 return prop.value.value
101 }
102 // A `name` is set, but not to a literal we can compare — treat as dynamic.
103 return DYNAMIC_CONFIG_NAME
104 }
105 return null
106 }
107
108 export const rule = createRule<[], MessageIds>({
109 name: "no-duplicate-step-id-in-workflow",
110 meta: {
111 type: "problem",
112 docs: {
113 description:
114 "Disallow invoking the same step factory more than once in a `createWorkflow` constructor without renaming subsequent calls via `.config({ name })`. Steps registered with the same ID throw at runtime.",
115 },
116 messages: {
117 duplicateStepId:
118 'Step "{{key}}" is invoked more than once in this workflow. Rename this call with `.config({ name: "<unique-id>" })` so each step has a unique ID.',
119 },
120 fixable: "code",
121 schema: [],
122 },
123 defaultOptions: [],
124 create(context) {
125 const bindings: WorkflowSdkBindings = createWorkflowSdkBindings()
126 const callsByWorkflow = new Map<TSESTree.Node, StepCall[]>()
127
128 const isStepInvocation = (node: TSESTree.CallExpression): boolean => {
129 if (node.callee.type !== AST_NODE_TYPES.Identifier) {
130 return false
131 }
132 const name = node.callee.name
133 if (SDK_HELPER_NAMES.has(name)) {
134 return false
135 }
136 if (bindings.transform.has(name)) {
137 return false
138 }
139 if (bindings.when.has(name)) {
140 return false
141 }
142 if (bindings.createStep.has(name)) {
143 return false
144 }
145 if (bindings.createWorkflow.has(name)) {
146 return false
147 }
148 return true
149 }
150
151 return {
152 ImportDeclaration(node) {
153 trackWorkflowSdkImports(node, bindings)
154 },
155 CallExpression(node) {
156 if (bindings.createWorkflow.size === 0) {
157 return
158 }
159 if (!isStepInvocation(node)) {
160 return
161 }
162 if (!isInWorkflowConstructor(node, bindings)) {
163 return
164 }
165
166 // Identify the enclosing workflow constructor to scope the bucket.
167 let fn: TSESTree.Node | undefined = node.parent
168 while (fn) {
169 if (
170 fn.type === AST_NODE_TYPES.ArrowFunctionExpression ||
171 fn.type === AST_NODE_TYPES.FunctionExpression ||
172 fn.type === AST_NODE_TYPES.FunctionDeclaration
173 ) {
174 break
175 }
176 fn = fn.parent
177 }
178 if (!fn) {
179 return
180 }
181
182 if (node.callee.type !== AST_NODE_TYPES.Identifier) {
183 return
184 }
185 const calleeName = node.callee.name
186
187 const configCall = findConfigCall(node)
188 const configuredName = configCall ? extractConfigName(configCall) : null
189
190 // A literal name groups by value; a dynamic name (variable/expression)
191 // gets a per-call unique key so it never collides; no name falls back
192 // to the bare factory identifier.
193 const effectiveKey =
194 configuredName === DYNAMIC_CONFIG_NAME
195 ? `DYNAMIC:${node.range[0]}`
196 : configuredName !== null
197 ? `NAMED:${configuredName}`
198 : `BARE:${calleeName}`
199
200 const bucket = callsByWorkflow.get(fn) ?? []
201 bucket.push({
202 node,
203 calleeName,
204 effectiveKey,
205 hasConfig: configCall !== null,
206 })
207 callsByWorkflow.set(fn, bucket)
208 },
209 "Program:exit"() {
210 for (const calls of callsByWorkflow.values()) {
211 const groups = new Map<string, StepCall[]>()
212 for (const c of calls) {
213 const g = groups.get(c.effectiveKey) ?? []
214 g.push(c)
215 groups.set(c.effectiveKey, g)
216 }
217
218 for (const group of groups.values()) {
219 if (group.length < 2) {
220 continue
221 }
222 const base = stepBaseName(group[0].calleeName)
223 // Leave the first call untouched; flag every subsequent
224 // duplicate and offer a deterministic .config rename.
225 for (let i = 1; i < group.length; i++) {
226 const dup = group[i]
227 const displayKey = dup.effectiveKey.startsWith("NAMED:")
228 ? dup.effectiveKey.slice("NAMED:".length)
229 : stepBaseName(dup.calleeName)
230
231 const suggestedName = `${base || dup.calleeName}-${i + 1}`
232
233 const fix = dup.hasConfig
234 ? undefined
235 : (fixer: TSESLint.RuleFixer) =>
236 fixer.insertTextAfter(
237 dup.node,
238 `.config({ name: "${suggestedName}" })`
239 )
240
241 context.report({
242 node: dup.node,
243 messageId: "duplicateStepId",
244 data: { key: displayKey },
245 ...(fix ? { fix } : {}),
246 })
247 }
248 }
249 }
250 },
251 }
252 },
253 })
254
255 export default rule