/
no-uninstalled-addons.ts
214 lines (185 loc) · 7.88 KB
/
no-uninstalled-addons.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/**
* @fileoverview This rule identifies storybook addons that are invalid because they are either not installed or contain a typo in their name.
* @author Andre "andrelas1" Santos
*/
import { readFileSync } from 'fs'
import { resolve } from 'path'
import { createStorybookRule } from '../utils/create-storybook-rule'
import { CategoryId } from '../utils/constants'
import {
isObjectExpression,
isProperty,
isIdentifier,
isArrayExpression,
isLiteral,
isVariableDeclarator,
isVariableDeclaration,
} from '../utils/ast'
import { Property, ArrayExpression } from '@typescript-eslint/types/dist/ast-spec'
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
export = createStorybookRule({
name: 'no-uninstalled-addons',
defaultOptions: [],
meta: {
type: 'problem',
docs: {
description:
'This rule identifies storybook addons that are invalid because they are either not installed or contain a typo in their name.',
categories: [CategoryId.RECOMMENDED],
recommended: 'error', // or 'error'
},
messages: {
addonIsNotInstalled: `The {{ addonName }} is not installed. Did you forget to install it?`,
},
schema: [], // Add a schema if the rule has options. Otherwise remove this
},
create(context) {
// variables should be defined here
//----------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------
// this will not only exclude the nullables but it will also exclude the type undefined from them, so that TS does not complain
function excludeNullable<T>(item: T | undefined): item is T {
return !!item
}
type MergeDepsWithDevDeps = (packageJson: Record<string, string>) => string[]
const mergeDepsWithDevDeps: MergeDepsWithDevDeps = (packageJson) => {
const deps = Object.keys(packageJson.dependencies || {})
const devDeps = Object.keys(packageJson.devDependencies || {})
return [...deps, ...devDeps]
}
type IsAddonInstalled = (addon: string, installedAddons: string[]) => boolean
const isAddonInstalled: IsAddonInstalled = (addon, installedAddons) => {
// cleanup /register or /preset from registered addon
const addonName = addon.replace(/\/register$/, '').replace(/\/preset$/, '')
return installedAddons.includes(addonName)
}
type AreThereAddonsNotInstalled = (
addons: string[],
installedSbAddons: string[]
) => false | { name: string }[]
const areThereAddonsNotInstalled: AreThereAddonsNotInstalled = (addons, installedSbAddons) => {
const result = addons
.filter((addon) => !isAddonInstalled(addon, installedSbAddons))
.map((addon) => ({ name: addon }))
return result.length ? result : false
}
type GetPackageJson = (path: string) => Record<string, any>
const getPackageJson: GetPackageJson = (path) => {
const packageJson = {
devDependencies: {},
dependencies: {},
}
try {
const file = readFileSync(path, 'utf8')
const parsedFile = JSON.parse(file)
packageJson.dependencies = parsedFile.dependencies || {}
packageJson.devDependencies = parsedFile.devDependencies || {}
} catch (e) {
throw new Error(
'Could not fetch package.json - it is probably not in the same directory as the .storybook folder'
)
}
return packageJson
}
const extractAllAddonsFromTheStorybookConfig = (
addonsExpression: ArrayExpression | undefined
) => {
if (addonsExpression?.elements) {
// extract all nodes taht are a string inside the addons array
const nodesWithAddons = addonsExpression.elements
.map((elem) => (isLiteral(elem) ? { value: elem.value, node: elem } : undefined))
.filter(excludeNullable)
const listOfAddonsInString = nodesWithAddons.map((elem) => elem.value) as string[]
// extract all nodes that are an object inside the addons array
const nodesWithAddonsInObj = addonsExpression.elements
.map((elem) => (isObjectExpression(elem) ? elem : { properties: [] }))
.map((elem) => {
const property: Property = elem.properties.find(
(prop) => isProperty(prop) && isIdentifier(prop.key) && prop.key.name === 'name'
) as Property
return isLiteral(property?.value)
? { value: property.value.value, node: property.value }
: undefined
})
.filter(excludeNullable)
const listOfAddonsInObj = nodesWithAddonsInObj.map((elem) => elem.value) as string[]
const listOfAddons = [...listOfAddonsInString, ...listOfAddonsInObj]
const listOfAddonElements = [...nodesWithAddons, ...nodesWithAddonsInObj]
return { listOfAddons, listOfAddonElements }
}
return { listOfAddons: [], listOfAddonElements: [] }
}
function reportUninstalledAddons(addonsProp: ArrayExpression) {
// when this is running for .storybook/main.js, we get the path to the folder which contains the package.json of the
// project. This will be handy for monorepos that may be running ESLint in a node process in another folder.
const projectRoot = context.getPhysicalFilename
? resolve(context.getPhysicalFilename(), '../../')
: './'
let packageJsonObject: Record<string, any>
try {
packageJsonObject = getPackageJson(`${projectRoot}/package.json`)
} catch (e) {
// if we cannot find the package.json, we cannot check if the addons are installed
console.error(e)
return
}
const depsAndDevDeps = mergeDepsWithDevDeps(packageJsonObject)
const { listOfAddons, listOfAddonElements } =
extractAllAddonsFromTheStorybookConfig(addonsProp)
const result = areThereAddonsNotInstalled(listOfAddons, depsAndDevDeps)
if (result) {
const elemsWithErrors = listOfAddonElements.filter(
(elem) => !!result.find((addon) => addon.name === elem.value)
)
elemsWithErrors.forEach((elem) => {
context.report({
node: elem.node,
messageId: 'addonIsNotInstalled',
data: { addonName: elem.value },
})
})
}
}
//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
return {
AssignmentExpression: function (node) {
if (isObjectExpression(node.right)) {
const addonsProp = node.right.properties.find(
(prop): prop is Property =>
isProperty(prop) && isIdentifier(prop.key) && prop.key.name === 'addons'
)
if (addonsProp && addonsProp.value && isArrayExpression(addonsProp.value)) {
reportUninstalledAddons(addonsProp.value)
}
}
},
ExportDefaultDeclaration: function (node) {
if (isObjectExpression(node.declaration)) {
const addonsProp = node.declaration.properties.find(
(prop): prop is Property =>
isProperty(prop) && isIdentifier(prop.key) && prop.key.name === 'addons'
)
if (addonsProp && addonsProp.value && isArrayExpression(addonsProp.value)) {
reportUninstalledAddons(addonsProp.value)
}
}
},
ExportNamedDeclaration: function (node) {
const addonsProp =
isVariableDeclaration(node.declaration) &&
node.declaration.declarations.find(
(decl) =>
isVariableDeclarator(decl) && isIdentifier(decl.id) && decl.id.name === 'addons'
)
if (addonsProp && isArrayExpression(addonsProp.init)) {
reportUninstalledAddons(addonsProp.init)
}
},
}
},
})