wix-storybook-utils
Version:
Utilities for automated component documentation within Storybook
95 lines • 3.14 kB
JavaScript
import prettier from 'prettier/standalone';
import { parse } from '@babel/parser';
import { transformFromAst } from '@babel/standalone';
import { isIdentifier } from '@babel/types';
import traverse from '@babel/traverse';
var babelParse = function (source) {
return parse(source, {
plugins: [
['decorators', { decoratorsBeforeExport: true }],
'jsx',
'typescript',
'classProperties',
'objectRestSpread',
'dynamicImport',
require('@babel/plugin-proposal-class-properties'),
require('@babel/plugin-transform-async-to-generator'),
],
sourceType: 'module',
});
};
var locStart = function (node, opts) {
var ignoreDecorators = (opts || {}).ignoreDecorators;
if (!ignoreDecorators) {
var decorators = (node.declaration && node.declaration.decorators) || node.decorators;
if (decorators && decorators.length > 0) {
return locStart(decorators[0]);
}
}
return node.range ? node.range[0] : node.start;
};
var locEnd = function (node) {
var end = node.range ? node.range[1] : node.end;
return node.typeAnnotation ? Math.max(end, locEnd(node.typeAnnotation)) : end;
};
export var formatCode = function (code) {
try {
var filteredCode = code
.split('\n')
.filter(function (line) {
return !/\/(\*|\/)+.*((t|e)slint[-|:](dis|en)able|prettier-ignore)/.test(line);
})
.join('\n');
return prettier.format(filteredCode, {
parser: 'babel',
plugins: [
{
parsers: {
babel: {
astFormat: 'estree',
parse: babelParse,
locStart: locStart,
locEnd: locEnd,
},
},
},
],
singleQuote: true,
trailingComma: 'all',
});
}
catch (e) {
console.error('Unable to format code', e);
return code;
}
};
export var transformCode = function (code) {
var ast = babelParse(code);
traverse(ast, {
ImportDeclaration: function (path) {
path.remove();
},
ExportDefaultDeclaration: function (path) {
path.remove();
},
ExportNamedDeclaration: function (path) {
path.remove();
},
CallExpression: function (path) {
if (isIdentifier(path.node.callee, { name: 'require' })) {
var parent_1 = path.getStatementParent();
if (parent_1.type === 'VariableDeclaration') {
path.getStatementParent().remove();
}
}
},
});
var transformed = transformFromAst(ast, code, {
plugins: [
require('@babel/plugin-syntax-jsx'),
[require('@babel/plugin-proposal-class-properties'), { loose: true }],
],
});
return transformed.code;
};
//# sourceMappingURL=doctor-code.js.map