1 import { AST_NODE_TYPES, TSESLint, TSESTree } from "@typescript-eslint/utils"
2 import { createRule } from "../../create-rule"
3 import { FRAMEWORK_UTILS_SOURCE, MODULES_BY_VALUE } from "../../constants"
4 import {
5 findProperty,
6 resolveObjectExpression,
7 unwrapTsExpression,
8 } from "../../util/ast"
9
10 type MessageIds = "preferWorkflowEvent" | "internalModuleEvent"
11
12 const MODULE_EVENT_MAP = buildModuleEventMap()
13
14 export const rule = createRule<[], MessageIds>({
15 name: "prefer-workflow-event-over-module-event",
16 meta: {
17 type: "suggestion",
18 docs: {
19 description:
20 "In a subscriber's `config.event`, prefer workflow event enums (`*WorkflowEvents`) over the equivalent internal module-level events.",
21 },
22 fixable: "code",
23 messages: {
24 preferWorkflowEvent:
25 "`{{source}}` is an internal module event. Subscribe to the workflow event `{{target}}` instead.",
26 internalModuleEvent:
27 "`{{source}}` is an internal module event with no public workflow-event equivalent. Confirm you mean to subscribe to an internal event, as these are implementation details and may change.",
28 },
29 schema: [],
30 },
31 defaultOptions: [],
32 create(context) {
33 if (MODULE_EVENT_MAP.size === 0) {
34 return {}
35 }
36
37 const sourceCode = context.sourceCode
38
39 // local binding -> imported name
40 // e.g. `PE -> ProductEvents` for `import { ProductEvents as PE }`.
41 const importedLocals = new Map<string, string>()
42 // Imported names already present, so the fix skips a duplicate import.
43 const importedUtilsNames = new Set<string>()
44 // `import * as utils` -> `utils`.
45 const namespaceLocals = new Set<string>()
46
47 // Workflow enums whose import this fix pass already queued.
48 const addedWorkflowImports = new Set<string>()
49
50 // A named framework/utils import the fix can append workflow enums to.
51 let utilsImportDecl: TSESTree.ImportDeclaration | null = null
52 // The resolved subscriber `config` object, checked on `Program:exit`.
53 let configObject: TSESTree.ObjectExpression | null = null
54
55 /**
56 * Ensure the workflow `enumName` is imported from framework/utils, appending
57 * to an existing named import when there is one, otherwise inserting a fresh
58 * import at the top of the file. Returns `null` when it is already imported
59 * (or another fix in this pass already queued it).
60 */
61 function ensureWorkflowImport(
62 fixer: TSESLint.RuleFixer,
63 enumName: string
64 ): TSESLint.RuleFix | null {
65 if (
66 importedUtilsNames.has(enumName) ||
67 addedWorkflowImports.has(enumName)
68 ) {
69 return null
70 }
71 addedWorkflowImports.add(enumName)
72
73 const specifiers = utilsImportDecl?.specifiers.filter(
74 (s): s is TSESTree.ImportSpecifier =>
75 s.type === AST_NODE_TYPES.ImportSpecifier
76 )
77 const last = specifiers?.[specifiers.length - 1]
78 if (last) {
79 return fixer.insertTextAfter(last, `, ${enumName}`)
80 }
81 return fixer.insertTextBeforeRange(
82 [0, 0],
83 `import { ${enumName} } from "${FRAMEWORK_UTILS_SOURCE}"\n`
84 )
85 }
86
87 /** Check one entry of the subscriber `config.event` value. */
88 function checkEventExpression(node: TSESTree.Expression): void {
89 const expr = unwrapTsExpression(node)
90 const resolved = normalizeEnum(expr, importedLocals, namespaceLocals)
91 if (!resolved) {
92 return
93 }
94 const replacement = MODULE_EVENT_MAP.get(resolved.key)
95 // undefined -> not an internal module event, ignore
96 if (replacement === undefined) {
97 return
98 }
99
100 const source = sourceCode.getText(expr)
101 if (replacement === null) {
102 context.report({
103 node: expr,
104 messageId: "internalModuleEvent",
105 data: { source },
106 })
107 return
108 }
109
110 context.report({
111 node: expr,
112 messageId: "preferWorkflowEvent",
113 data: { source, target: replacement },
114 fix(fixer) {
115 // Namespace form keeps its prefix and reaches the enum through the
116 // existing `utils` binding, so it needs no import.
117 if (resolved.namespace) {
118 return fixer.replaceText(
119 expr,
120 `${resolved.namespace}.${replacement}`
121 )
122 }
123 const fixes: TSESLint.RuleFix[] = [
124 fixer.replaceText(expr, replacement),
125 ]
126 const enumName = replacement.slice(0, replacement.indexOf("."))
127 const importFix = ensureWorkflowImport(fixer, enumName)
128 if (importFix) {
129 fixes.push(importFix)
130 }
131 return fixes
132 },
133 })
134 }
135
136 return {
137 ImportDeclaration(node) {
138 if (node.source.value !== FRAMEWORK_UTILS_SOURCE) {
139 return
140 }
141 for (const specifier of node.specifiers) {
142 if (
143 specifier.type === AST_NODE_TYPES.ImportSpecifier &&
144 specifier.imported.type === AST_NODE_TYPES.Identifier
145 ) {
146 // `{ ProductEvents as PE }`: `PE -> ProductEvents`.
147 // `{ ProductEvents }`: `ProductEvents -> ProductEvents`.
148 importedUtilsNames.add(specifier.imported.name)
149 importedLocals.set(specifier.local.name, specifier.imported.name)
150 // Has named specifiers, so the fix can append into it.
151 utilsImportDecl ??= node
152 } else if (
153 specifier.type === AST_NODE_TYPES.ImportNamespaceSpecifier
154 ) {
155 namespaceLocals.add(specifier.local.name)
156 }
157 }
158 },
159
160 // Capture the subscriber `config` object, from either
161 // `export const config = { ... }` or `export { config }`.
162 ExportNamedDeclaration(node) {
163 if (
164 node.declaration &&
165 node.declaration.type === AST_NODE_TYPES.VariableDeclaration
166 ) {
167 for (const decl of node.declaration.declarations) {
168 if (
169 decl.id.type === AST_NODE_TYPES.Identifier &&
170 decl.id.name === "config"
171 ) {
172 const resolved = resolveObjectExpression(
173 decl.init,
174 sourceCode.getScope(node)
175 )
176 if (resolved) {
177 configObject = resolved
178 }
179 }
180 }
181 }
182
183 for (const spec of node.specifiers) {
184 if (
185 spec.exported.type !== AST_NODE_TYPES.Identifier ||
186 spec.exported.name !== "config" ||
187 node.source
188 ) {
189 continue
190 }
191 const resolved = resolveObjectExpression(
192 spec.local,
193 sourceCode.getScope(node)
194 )
195 if (resolved) {
196 configObject = resolved
197 }
198 }
199 },
200
201 // Deferred to the end so imports and the `config` object are both known.
202 "Program:exit"() {
203 if (!configObject) {
204 return
205 }
206 const eventProp = findProperty(configObject, "event")
207 if (!eventProp) {
208 return
209 }
210 const value = eventProp.value
211 if (value.type === AST_NODE_TYPES.ArrayExpression) {
212 for (const entry of value.elements) {
213 if (entry && entry.type !== AST_NODE_TYPES.SpreadElement) {
214 checkEventExpression(entry)
215 }
216 }
217 return
218 }
219 // Ignore non-expression shapes (`AssignmentPattern`, empty-body method)
220 // that can't be an event name.
221 if (
222 value.type !== AST_NODE_TYPES.AssignmentPattern &&
223 value.type !== AST_NODE_TYPES.TSEmptyBodyFunctionExpression
224 ) {
225 checkEventExpression(value)
226 }
227 },
228 }
229 },
230 })
231
232 export default rule
233
234 function tryOrDefault<T>(fn: () => T, defaultValue: T): T {
235 try {
236 return fn()
237 } catch {
238 return defaultValue
239 }
240 }
241
242 /**
243 * Build a map of internal module events to their workflow-event equivalent, if any.
244 * Only enums whose value is in the internal `{module}.{data-model}.{action}`
245 * form are included.
246 */
247 function buildModuleEventMap(): Map<string, string | null> {
248 const map = new Map<string, string | null>()
249 const exports = tryOrDefault(() => require(FRAMEWORK_UTILS_SOURCE), null)
250 if (!exports) {
251 return map
252 }
253
254 const isEnumObject = (value: unknown): value is Record<string, unknown> =>
255 !!value && typeof value === "object"
256
257 const moduleValues = new Set(Object.keys(MODULES_BY_VALUE))
258
259 // workflow event value -> `WorkflowEnum.MEMBER`, e.g.
260 // `product-category.deleted` -> `ProductCategoryWorkflowEvents.DELETED`.
261 const workflowByValue = new Map<string, string>(
262 Object.entries(exports)
263 .filter(
264 ([enumName, enumObj]) =>
265 enumName.endsWith("WorkflowEvents") && isEnumObject(enumObj)
266 )
267 .flatMap(([enumName, enumObj]) =>
268 Object.entries(enumObj as Record<string, string>).map(
269 ([member, value]) => [value, `${enumName}.${member}`]
270 )
271 )
272 )
273
274 for (const [enumName, enumObj] of Object.entries(exports)) {
275 if (!enumName.endsWith("Events") || enumName.endsWith("WorkflowEvents")) {
276 continue
277 }
278 if (!isEnumObject(enumObj)) {
279 continue
280 }
281 for (const [member, value] of Object.entries(enumObj)) {
282 if (typeof value !== "string") {
283 continue
284 }
285 // Internal service events are `{module}.{data-model}.{action}`
286 const parts = value.split(".")
287 if (parts.length < 3 || !moduleValues.has(parts[0])) {
288 continue
289 }
290 const replacement = workflowByValue.get(parts.slice(1).join(".")) ?? null
291 map.set(`${enumName}.${member}`, replacement)
292 map.set(value, replacement)
293 }
294 }
295
296 return map
297 }
298
299 /**
300 * - `"order.placed"` -> literal value key, no namespace
301 * - `ProductEvents.PROD...` -> `ProductEvents.PRODUCT_CATEGORY_DELETED`, no namespace
302 * - `utils.ProductEvents.PROD...` -> same key, namespace `utils`
303 *
304 * Returns `null` otherwise
305 */
306 function normalizeEnum(
307 node: TSESTree.Expression,
308 importedLocals: Map<string, string>,
309 namespaceLocals: Set<string>
310 ): { key: string; namespace: string | null } | null {
311 if (node.type === AST_NODE_TYPES.Literal && typeof node.value === "string") {
312 return { key: node.value, namespace: null }
313 }
314 if (node.type !== AST_NODE_TYPES.MemberExpression) {
315 return null
316 }
317 const member = memberName(node)
318 if (!member) {
319 return null
320 }
321 const object = node.object
322 // `PE.MEMBER` -> resolve `PE` to its imported enum name.
323 if (object.type === AST_NODE_TYPES.Identifier) {
324 const canonical = importedLocals.get(object.name)
325 return canonical ? { key: `${canonical}.${member}`, namespace: null } : null
326 }
327 // `utils.ProductEvents.MEMBER` -> the middle property is the enum name.
328 if (
329 object.type === AST_NODE_TYPES.MemberExpression &&
330 !object.computed &&
331 object.object.type === AST_NODE_TYPES.Identifier &&
332 namespaceLocals.has(object.object.name) &&
333 object.property.type === AST_NODE_TYPES.Identifier
334 ) {
335 return {
336 key: `${object.property.name}.${member}`,
337 namespace: object.object.name,
338 }
339 }
340 return null
341 }
342
343 /** The accessed member, from `Enum.MEMBER` or `Enum["MEMBER"]`. */
344 function memberName(node: TSESTree.MemberExpression): string | null {
345 if (!node.computed && node.property.type === AST_NODE_TYPES.Identifier) {
346 return node.property.name
347 }
348 if (
349 node.computed &&
350 node.property.type === AST_NODE_TYPES.Literal &&
351 typeof node.property.value === "string"
352 ) {
353 return node.property.value
354 }
355 return null
356 }