-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
501 lines (421 loc) · 14.3 KB
/
index.js
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
const path = require('path')
const fs = require('fs')
const recast = require('recast')
/**
* Re-using few private methods of react-docgen to avoid code duplication
*/
const isRequiredPropType = require('react-docgen/dist/utils/isRequiredPropType').default
const setPropDescription = require('react-docgen/dist/utils/setPropDescription').default
let babylon
try {
const buildParser = require('react-docgen/dist/babelParser').default
babylon = buildParser()
} catch (e) {
babylon = require('react-docgen/dist/babylon').default
}
const utils = require('react-docgen').utils
const types = recast.types.namedTypes
const HOP = Object.prototype.hasOwnProperty
const createObject = Object.create
function isPropTypesExpression(path) {
const moduleName = utils.resolveToModule(path)
if (moduleName) {
return utils.isReactModuleName(moduleName) || moduleName === 'ReactPropTypes'
}
return false
}
/**
* Amends the documentation object with propTypes information.
* @method amendPropTypes
* @param {Object} documentation documentation object
* @param {Object} path node path reference of propTypes property
*/
function amendPropTypes(documentation, path) {
if (!types.ObjectExpression.check(path.node)) {
return
}
path.get('properties').each(propertyPath => {
let propDescriptor, valuePath, type, resolvedValuePath
const nodeType = propertyPath.node.type
if (nodeType === types.Property.name) {
propDescriptor = documentation.getPropDescriptor(utils.getPropertyName(propertyPath))
valuePath = propertyPath.get('value')
type = isPropTypesExpression(valuePath)
? utils.getPropType(valuePath)
: {
name: 'custom',
raw: utils.printValue(valuePath)
}
if (type) {
propDescriptor.type = type
propDescriptor.required = type.name !== 'custom' && isRequiredPropType(valuePath)
}
} else if (nodeType === types.SpreadProperty.name) {
resolvedValuePath = utils.resolveToValue(propertyPath.get('argument'))
// normal object literal
if (resolvedValuePath.node.type === types.ObjectExpression.name) {
amendPropTypes(documentation, resolvedValuePath)
}
}
if (types.Property.check(propertyPath.node)) {
setPropDescription(documentation, propertyPath)
}
})
}
/**
* Accepts absolute path of a source file and returns the file source as string.
* @method getSrc
* @param {String} filePath File path of the component
* @return {String} Source code of the given file if file exist else returns empty
*/
function getSrc(filePath) {
let src
if (fs.existsSync(filePath)) {
src = fs.readFileSync(filePath, 'utf-8')
}
return src
}
function getAST(src) {
return recast.parse(src, {
source: 'module',
esprima: babylon
})
}
/**
* Resolves propTypes source file path relative to current component,
* which resolves only file extension of type .js or .jsx
*
* @method resolveFilePath
* @param {String} componentPath Relative file path of the component
* @param {String} importedFilePath Relative file path of a dependent component
* @return {String} Resolved file path if file exist else null
*/
function resolveFilePath(componentPath, importedFilePath) {
const regEx = /\.(js|jsx)$/
let srcPath = path.resolve(path.dirname(componentPath), importedFilePath)
if (regEx.exec(srcPath)) {
return srcPath
} else {
srcPath += fs.existsSync(`${srcPath}.js`) ? '.js' : '.jsx'
return srcPath
}
}
/**
* Method which returns actual values from the AST node of type specifiers.
*
* @method getSpecifiersOfNode
*/
function getSpecifiersOfNode(specifiers) {
const specifier = []
specifiers.forEach(node => {
specifier.push(node.local.name)
})
return specifier
}
/**
* Filters the list of identifier node values or node paths from a given AST.
*
* @method getIdentifiers
* @param {Object} ast Root AST node of a component
* @return {Object} Which holds identifier relative file path as `key` and identifier name as `value`
*/
function getIdentifiers(ast) {
const identifiers = createObject(null)
recast.visit(ast, {
visitVariableDeclarator(path) {
const node = path.node
const nodeType = node.init.type
if (nodeType === types.Identifier.name) {
if (identifiers[node.init.name]) {
identifiers[node.init.name].push(node.init.name)
} else {
identifiers[node.init.name] = [node.init.name]
}
} else if (nodeType === types.Literal.name) {
if (identifiers[node.id.name]) {
identifiers[node.id.name].push(node.init.value)
} else {
identifiers[node.id.name] = [node.init.value]
}
} else if (nodeType === types.ArrayExpression.name) {
if (identifiers[node.id.name]) {
identifiers[node.id.name].push(node.init.elements)
} else {
identifiers[node.id.name] = node.init.elements
}
} else if (nodeType === types.ObjectExpression.name) {
if (identifiers[node.id.name]) {
identifiers[node.id.name].push({
path,
value: node.init.properties
})
} else {
identifiers[node.id.name] = {
path,
value: node.init.properties
}
}
}
this.traverse(path)
}
})
return identifiers
}
/**
* Traverse through given AST and filters named and default export declarations.
*
* @method getExports
* @param {Object} ast Root AST node of a component
* @return {Array} which holds list of named identifiers
*/
function getExports(ast) {
const exports = []
recast.visit(ast, {
visitExportNamedDeclaration(path) {
const node = path.node
const specifiers = getSpecifiersOfNode(node.specifiers)
const declarations = Object.keys(getIdentifiers(ast))
exports.push(...new Set(specifiers.concat(declarations)))
this.traverse(path)
},
visitExportDefaultDeclaration(path) {
const node = path.node
if (node.declaration.type === types.Identifier.name) {
exports.push(node.declaration.name)
}
/* Commenting it for now, this might needed for further enhancements.
else if (nodeType === types.Literal.name) {
varDeclarators.push(node.init.value);
} else if (nodeType === types.ArrayExpression.name) {
computedPropNodes[node.id.name] = node.init.elements;
}*/
this.traverse(path)
}
})
return exports
}
/**
* Method to list all specifiers of es6 `import` of a given file(AST)
*
* @method getImports
* @param {Object} ast Root AST node of a component
* @return {Object/Boolean} if Object: Holds import module name or file path as `key`
* and identifier as `value`, else return false
*/
function getImports(ast) {
const specifiers = createObject(null)
recast.visit(ast, {
visitImportDeclaration: path => {
const name = path.node.source.value
const specifier = getSpecifiersOfNode(path.node.specifiers)
if (!specifiers[name]) {
specifiers[name] = specifier
} else {
specifiers[name].push(...specifier)
}
return false
}
})
return specifiers
}
/**
* Method to resolve all dependent values(computed values, which are from external files).
*
* @method resolveImportedDependencies
* @param {Object} ast Root AST node of the component
* @param {Object} srcFilePath Absolute path of a dependent file
* @return {Object} Holds export identifier as `key` and respective AST node path as value
*/
function resolveImportedDependencies(ast, srcFilePath) {
const filteredItems = createObject(null)
const importSpecifiers = getImports(ast)
let identifiers, resolvedNodes
if (importSpecifiers && Object.keys(importSpecifiers).length) {
resolvedNodes = resolveDependencies(importSpecifiers, srcFilePath)
}
const exportSpecifiers = getExports(ast)
if (exportSpecifiers && exportSpecifiers.length) {
identifiers = getIdentifiers(ast)
}
if (resolvedNodes) {
Object.assign(identifiers, ...resolvedNodes)
}
for (const identifier in identifiers) {
if (HOP.call(identifiers, identifier) && exportSpecifiers.indexOf(identifier) > -1) {
filteredItems[identifier] = identifiers[identifier]
}
}
return filteredItems
}
/**
* Method to resolve all the external dependencies of the component propTypes
*
* @method resolveDependencies
* @param {Array} filePaths List of files to resolve
* @param {String} componentPath Absolute path of the component in case `propTypes` are declared in a component file or
* absolute path to the file where `propTypes` is declared.
*/
function resolveDependencies(filePaths, componentPath) {
const importedNodes = []
for (const importedFilePath in filePaths) {
if (HOP.call(filePaths, importedFilePath)) {
const srcPath = resolveFilePath(componentPath, importedFilePath)
if (!srcPath) {
return
}
const src = getSrc(srcPath)
if (src) {
const ast = getAST(src)
importedNodes.push(resolveImportedDependencies(ast, srcPath))
}
}
}
return importedNodes
}
/**
* Method to filter computed props(which are declared out side of the component and used in propTypes object).
*
* @method filterSpecifiers
* @param {Object} specifiers List which holds all the values of external dependencies
* @return {Object} computedPropNames List which holds all the computed values from `propTypes` property
*/
function filterSpecifiers(specifiers, computedPropNames) {
const filteredSpecifiers = createObject(null)
for (const cp in computedPropNames) {
if (HOP.call(computedPropNames, cp)) {
for (const sp in specifiers) {
if (HOP.call(specifiers, sp) && specifiers[sp].indexOf(cp) > -1) {
filteredSpecifiers[sp] ? filteredSpecifiers[sp].push(cp) : (filteredSpecifiers[sp] = [cp])
}
}
}
}
return filteredSpecifiers
}
/**
* Method to parse and get computed nodes from a document object
*
* @method getComputedPropValuesFromDoc
* @param {Object} doc react-docgen document object
* @return {Object/Boolean} Object with computed property identifer as `key` and AST node path as `value`,
* If document object have any computed properties else return false.
*/
function getComputedPropValuesFromDoc(doc) {
let flag
const computedProps = createObject(null)
const props = doc.toObject().props
flag = false
if (props) {
for (const prop in props) {
if (HOP.call(props, prop)) {
const o = props[prop]
if (o.type && o.type.name === 'enum' && o.type.computed) {
flag = true
computedProps[o.type.value] = o
}
}
}
return flag ? computedProps : false
} else {
return false
}
}
/**
* Method to update the document object computed values with actual values to generate doc for external dependent values.
*
* @method amendDocs
* @param {Object} doc react-docgen document object
* @param {Object} path AST node path of component `propTypes`
* @param {Object} props list of actual values of computed properties
*/
function amendDocs(doc, path, props) {
const propsToPatch = path.get('properties')
function getComputedPropVal(name) {
for (let i = 0; i < props.length; i++) {
if (props[i][name]) {
return props[i][name]
}
}
}
function updateWithDefaultValue(descriptor) {
if(descriptor.defaultValue && descriptor.defaultValue.computed) {
const ast = getAST(descriptor.defaultValue.value);
const { expression:node } = ast.program.body[0];
if(types.MemberExpression.name === "MemberExpression") {
const computedObj = props.filter((prop)=>!!prop[node.object.name])[0] || '';
if(!!computedObj) {
const computedValueObj = computedObj[node.object.name];
const defaultValue = computedValueObj[node.property.value].value;
if(defaultValue) {
descriptor.defaultValue.value = defaultValue;
descriptor.defaultValue.computed = false;
}
}
}
}
}
propsToPatch.each(propertyPath => {
const propDescriptor = doc.getPropDescriptor(utils.getPropertyName(propertyPath))
updateWithDefaultValue(propDescriptor)
if (propDescriptor.type.name === 'enum' && propDescriptor.type.computed) {
const oldVal = propDescriptor.type.value
const newVal = getComputedPropVal(propDescriptor.type.value) || oldVal
propDescriptor.type.value = newVal
propDescriptor.type.computed = false
}
})
}
/**
* Initializer of react-docgen custom handler.
*
* @method createImportHandler
* @param {String} componentPath Absolute path of the react component
*/
function createImportHandler(componentPath) {
return (doc, path) => {
const root = path.scope.getGlobalScope().node
let propTypesPath, propTypesFilePath, propTypesAST
propTypesPath = utils.getMemberValuePath(path, 'propTypes')
propTypesAST = root
propTypesFilePath = componentPath
if (!propTypesPath) {
return
}
const propsNameIdentifier = propTypesPath.node.name
propTypesPath = utils.resolveToValue(propTypesPath)
if (!propTypesPath) {
return
}
if (!types.ObjectExpression.check(propTypesPath.node)) {
//First resolve dependencies against component path
propTypesFilePath = resolveFilePath(componentPath, propTypesPath.node.source.value)
const propTypesSrc = getSrc(propTypesFilePath)
propTypesAST = getAST(propTypesSrc)
const importedPropTypes = getIdentifiers(propTypesAST)[propsNameIdentifier]
if (!importedPropTypes) {
return
}
propTypesPath = utils.resolveToValue(importedPropTypes.path)
//updating doc object with external props
amendPropTypes(doc, propTypesPath)
}
const computedPropNames = getComputedPropValuesFromDoc(doc)
if (!computedPropNames) {
return
}
const importSpecifiers = getImports(propTypesAST)
if (!importSpecifiers) {
return
}
const filteredProps = filterSpecifiers(importSpecifiers, computedPropNames)
if (!Object.keys(filteredProps).length) {
return
}
const resolvedImports = resolveDependencies(filteredProps, propTypesFilePath)
if (!resolvedImports.length) {
return
}
amendDocs(doc, propTypesPath, resolvedImports)
}
}
module.exports = createImportHandler