wix-storybook-utils
Version:
Utilities for automated component documentation within Storybook
45 lines • 1.68 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var types = tslib_1.__importStar(require("@babel/types"));
var parser = tslib_1.__importStar(require("@babel/parser"));
var generator_1 = tslib_1.__importDefault(require("@babel/generator"));
var traverse_1 = tslib_1.__importDefault(require("@babel/traverse"));
var ensureShorthandProperties = function (_a) {
var ast = _a.ast, parentPath = _a.parentPath, scope = _a.scope;
return (0, traverse_1.default)(ast, {
Property: function (path) {
var _a = path.node, key = _a.key, value = _a.value;
if (key.test === value.test) {
path.node.shorthand = true;
}
},
}, scope, parentPath);
};
var functionToString = function (prop) {
if (typeof prop !== 'function') {
return prop;
}
var asString = prop.toString();
try {
var ast = parser.parseExpression(asString);
if (types.isArrowFunctionExpression(ast)) {
return prop.toString();
}
var arrowFunctionBody = ast.body.body.length === 1 && types.isReturnStatement(ast.body.body[0])
? ast.body.body[0].argument
: ast.body;
ensureShorthandProperties({
ast: arrowFunctionBody,
parentPath: ast,
scope: ast,
});
var arrowFuncExpr = types.arrowFunctionExpression(ast.params, arrowFunctionBody);
return (0, generator_1.default)(arrowFuncExpr, { tabWidth: 2 }).code;
}
catch (e) {
return asString;
}
};
exports.default = functionToString;
//# sourceMappingURL=function-to-string.js.map