1 import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/utils"
2 import { createRule } from "../../create-rule"
3 import { objectHasProperty, resolveObjectExpression } from "../../util/ast"
4
5 type MessageIds = "missingConfigExport" | "missingEventProperty"
6
7 export const rule = createRule<[], MessageIds>({
8 name: "subscriber-config-export-required",
9 meta: {
10 type: "problem",
11 docs: {
12 description:
13 "Subscriber files must export a `config` object with at least an `event` property.",
14 },
15 messages: {
16 missingConfigExport:
17 "Subscriber files must have a named export `config` (a `SubscriberConfig`) with at least an `event` property.",
18 missingEventProperty:
19 "The subscriber `config` export must declare an `event` property naming the event(s) to subscribe to.",
20 },
21 schema: [],
22 },
23 defaultOptions: [],
24 create(context) {
25 const sourceCode = context.sourceCode ?? context.getSourceCode()
26
27 let hasConfigExport = false
28 // The resolved config object literal, used for the `event` check. Stays
29 // null when `config` is exported but can't be resolved to an object (e.g.
30 // a re-export or a non-object initializer) — the `event` check is skipped.
31 let configObject: TSESTree.ObjectExpression | null = null
32
33 return {
34 ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration) {
35 // export const config = { ... } | export const config: SubscriberConfig = { ... }
36 if (
37 node.declaration &&
38 node.declaration.type === AST_NODE_TYPES.VariableDeclaration
39 ) {
40 for (const decl of node.declaration.declarations) {
41 if (
42 decl.id.type === AST_NODE_TYPES.Identifier &&
43 decl.id.name === "config"
44 ) {
45 hasConfigExport = true
46 const resolved = resolveObjectExpression(
47 decl.init,
48 sourceCode.getScope(node)
49 )
50 if (resolved) {
51 configObject = resolved
52 }
53 }
54 }
55 }
56
57 // export { config } | export { foo as config } | export { config } from "./x"
58 for (const spec of node.specifiers) {
59 if (
60 spec.exported.type !== AST_NODE_TYPES.Identifier ||
61 spec.exported.name !== "config"
62 ) {
63 continue
64 }
65
66 hasConfigExport = true
67 // A re-export from another module can't be resolved locally — skip
68 // the `event` check (no false positive).
69 if (node.source) {
70 continue
71 }
72
73 const resolved = resolveObjectExpression(
74 spec.local,
75 sourceCode.getScope(node)
76 )
77 if (resolved) {
78 configObject = resolved
79 }
80 }
81 },
82 "Program:exit"(node: TSESTree.Program) {
83 if (!hasConfigExport) {
84 context.report({ node, messageId: "missingConfigExport" })
85 return
86 }
87
88 if (
89 configObject &&
90 objectHasProperty(configObject, "event") === false
91 ) {
92 context.report({
93 node: configObject,
94 messageId: "missingEventProperty",
95 })
96 }
97 },
98 }
99 },
100 })
101
102 export default rule