-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathno-uninstalled-addons.ts
274 lines (237 loc) · 9.33 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/**
* @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 dedent from 'ts-dedent'
import { resolve, relative, sep } 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 { TSESTree } from '@typescript-eslint/utils'
import { getMetaObjectExpression } from '../utils'
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
export = createStorybookRule({
name: 'no-uninstalled-addons',
defaultOptions: [
{
packageJsonLocation: '' as string,
ignore: [] as string[],
},
],
meta: {
type: 'problem',
severity: 'error',
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],
},
messages: {
addonIsNotInstalled: `The {{ addonName }} is not installed in {{packageJsonPath}}. Did you forget to install it or is your package.json in a different location?`,
},
schema: [
{
type: 'object',
properties: {
packageJsonLocation: {
type: 'string',
},
ignore: {
type: 'array',
items: {
type: 'string',
},
},
},
},
],
},
create(context) {
// variables should be defined here
const { packageJsonLocation, ignore } = context.options.reduce<{
packageJsonLocation: string
ignore: string[]
}>(
(acc, val) => {
return {
packageJsonLocation: val['packageJsonLocation'] || acc.packageJsonLocation,
ignore: val['ignore'] || acc.ignore,
}
},
{ packageJsonLocation: '', ignore: [] }
)
//----------------------------------------------------------------------
// 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: PackageJsonDependencies) => 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 + file extension from registered addon
const addonName = addon
.replace(/\.[mc]?js$/, '')
.replace(/\/register$/, '')
.replace(/\/preset$/, '')
return installedAddons.includes(addonName)
}
const filterLocalAddons = (addon: string) => {
const isLocalAddon = (addon: string) =>
addon.startsWith('.') ||
addon.startsWith('/') ||
// for local Windows files e.g. (C: F: D:)
/\w:.*/.test(addon) ||
addon.startsWith('\\')
return !isLocalAddon(addon)
}
type AreThereAddonsNotInstalled = (
addons: string[],
installedSbAddons: string[]
) => false | { name: string }[]
const areThereAddonsNotInstalled: AreThereAddonsNotInstalled = (addons, installedSbAddons) => {
const result = addons
// remove local addons (e.g. ./my-addon/register.js)
.filter(filterLocalAddons)
.filter((addon) => !isAddonInstalled(addon, installedSbAddons) && !ignore.includes(addon))
.map((addon) => ({ name: addon }))
return result.length ? result : false
}
type PackageJsonDependencies = {
devDependencies: Record<string, string>
dependencies: Record<string, string>
}
type GetPackageJson = (path: string) => PackageJsonDependencies
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 || {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
throw new Error(
dedent`The provided path in your eslintrc.json - ${path} is not a valid path to a package.json file or your package.json file is not in the same folder as ESLint is running from.
Read more at: https://github.com/storybookjs/eslint-plugin-storybook/blob/main/docs/rules/no-uninstalled-addons.md
`
)
}
return packageJson
}
const extractAllAddonsFromTheStorybookConfig = (
addonsExpression: TSESTree.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: TSESTree.Property = elem.properties.find(
(prop) => isProperty(prop) && isIdentifier(prop.key) && prop.key.name === 'name'
) as TSESTree.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: TSESTree.ArrayExpression) {
const packageJsonPath = resolve(packageJsonLocation || `./package.json`)
let packageJsonObject: PackageJsonDependencies
try {
packageJsonObject = getPackageJson(packageJsonPath)
} catch (e) {
// if we cannot find the package.json, we cannot check if the addons are installed
throw new Error(e as string)
}
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)
)
const rootDir = process.cwd().split(sep).pop()
const packageJsonPath = `${rootDir}${sep}${relative(process.cwd(), packageJsonLocation)}`
elemsWithErrors.forEach((elem) => {
context.report({
node: elem.node,
messageId: 'addonIsNotInstalled',
data: {
addonName: elem.value,
packageJsonPath,
},
})
})
}
}
function findAddonsPropAndReport(node: TSESTree.ObjectExpression) {
const addonsProp = node.properties.find(
(prop): prop is TSESTree.Property =>
isProperty(prop) && isIdentifier(prop.key) && prop.key.name === 'addons'
)
if (addonsProp?.value && isArrayExpression(addonsProp.value)) {
reportUninstalledAddons(addonsProp.value)
}
}
//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
return {
AssignmentExpression: function (node) {
if (isObjectExpression(node.right)) {
findAddonsPropAndReport(node.right)
}
},
ExportDefaultDeclaration: function (node) {
const meta = getMetaObjectExpression(node, context)
if (!meta) return null
findAddonsPropAndReport(meta)
},
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)
}
},
}
},
})