Skip to content

Commit

Permalink
feat(docz-utils): add exports parser to add to Playground scope
Browse files Browse the repository at this point in the history
  • Loading branch information
rakannimer committed Dec 14, 2019
1 parent 99ebf82 commit 9c564d0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
43 changes: 43 additions & 0 deletions core/docz-utils/src/exports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import * as parser from '@babel/parser'
import traverse from '@babel/traverse'
import get from 'lodash/get'

const fromDeclarations = (declarations: any = []) =>
Array.isArray(declarations) && declarations.length > 0
? declarations.map(declaration => get(declaration, 'id.name'))
: []

const traverseOnExports = (fn: (path: any) => any[]) => (node: any) => {
try {
const ast = parser.parse(node.value, {
sourceType: 'module',
})
let populated: any[] = []
traverse(ast, {
enter(path: any): void {
if (path.isExportDeclaration()) {
populated = populated.concat(fn(path))
return
}
},
})
return populated
} catch (err) {
return []
}
}

export const getExportsVariables = traverseOnExports(path => {
const type = get(path, 'node.declaration.type')
switch (type) {
case 'VariableDeclaration':
return fromDeclarations(get(path, 'node.declaration.declarations', []))
case 'FunctionDeclaration':
const declaration = get(path, 'node.declaration', false)
return fromDeclarations(declaration ? [declaration] : [])
case 'Identifier':
return get(path, 'node.declaration.name')
default:
console.error(`Unexpected export type ${type} in docz-utils/exports`)
}
})
1 change: 1 addition & 0 deletions core/docz-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './ast'
export * from './fs'
export * from './imports'
export * from './exports'
export * from './jsx'
export * from './mdast'
export { format } from './format'
Expand Down

0 comments on commit 9c564d0

Please sign in to comment.