UNPKG

vue-styleguidist

Version:
316 lines (295 loc) 12.2 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _typeof = require("@babel/runtime/helpers/typeof"); Object.defineProperty(exports, "__esModule", { value: true }); exports.commandBuild = commandBuild; exports.commandHelp = commandHelp; exports.commandServer = commandServer; exports.printErrorWithLink = printErrorWithLink; exports.updateConfig = updateConfig; exports.verbose = verbose; var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _qI = require("q-i"); var _readline = require("readline"); var _webpack = require("webpack"); var kleur = _interopRequireWildcard(require("kleur")); var _formatWebpackMessages = _interopRequireDefault(require("react-dev-utils/formatWebpackMessages")); var _WebpackDevServerUtils = _interopRequireDefault(require("react-dev-utils/WebpackDevServerUtils")); var _openBrowser = _interopRequireDefault(require("react-dev-utils/openBrowser")); var _logger = _interopRequireDefault(require("react-styleguidist/lib/scripts/logger")); var _glogg = _interopRequireDefault(require("glogg")); var _cliProgress = require("cli-progress"); var _server2 = _interopRequireDefault(require("./server")); var _build = _interopRequireDefault(require("./build")); var _consts = _interopRequireDefault(require("./consts")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /* eslint-disable no-console */ var logger = (0, _glogg["default"])('rsg'); /** * @param {object} config * @return {object} */ function updateConfig(config) { // Set verbose mode from config option or command line switch config.verbose = config.verbose || !!process.env.VUESG_VERBOSE; // Setup logger *before* config validation (because validations may use logger to print warnings) (0, _logger["default"])(config.logger, config.verbose); return config; } var getProgressPlugin = function getProgressPlugin(msg) { var bar = new _cliProgress.Bar({ format: "".concat(msg, " ").concat(kleur.green('{bar}'), " {percentage}%") }, _cliProgress.Presets.rect); var ProgressPlugin = process.env.VSG_WEBPACK_PATH ? // eslint-disable-next-line @typescript-eslint/no-var-requires require(process.env.VSG_WEBPACK_PATH).ProgressPlugin : _webpack.ProgressPlugin; return { plugin: new ProgressPlugin(function (percentage) { bar.update(percentage); }), bar: bar }; }; function commandBuild(config) { var bar; var ProgressPlugin = process.env.VSG_WEBPACK_PATH ? // eslint-disable-next-line @typescript-eslint/no-var-requires require(process.env.VSG_WEBPACK_PATH).ProgressPlugin : _webpack.ProgressPlugin; if (config.progressBar !== false && !(config.webpackConfig.plugins || []).some(function (p) { return p.constructor === ProgressPlugin; })) { var _getProgressPlugin = getProgressPlugin('Building style guide'), plugin = _getProgressPlugin.plugin, localBar = _getProgressPlugin.bar; bar = localBar; config.webpackConfig.plugins = [].concat((0, _toConsumableArray2["default"])(config.webpackConfig.plugins || []), [plugin]); bar.start(1, 0); } var compiler = (0, _build["default"])(config, function (err) { if (err) { console.error(err); process.exit(1); } else if (config.printBuildInstructions) { config.printBuildInstructions(config); } else { printBuildInstructions(config); } }); verbose('Webpack config:', compiler.options); // Custom error reporting compiler.hooks.done.tap('vsrDoneBuilding', function (stats) { var messages = (0, _formatWebpackMessages["default"])(stats.toJson({}, true)); var hasErrors = printAllErrorsAndWarnings(messages, stats.compilation); if (bar) { bar.stop(); (0, _readline.moveCursor)(process.stdout, 0, -1); (0, _readline.clearLine)(process.stdout, 0); } if (hasErrors) { process.exit(1); } }); // in order to have the caller be able to interact // with the compiler when i's hot return compiler; } function commandServer(config, open) { var bar; var ProgressPlugin = process.env.VSG_WEBPACK_PATH ? // eslint-disable-next-line @typescript-eslint/no-var-requires require(process.env.VSG_WEBPACK_PATH).ProgressPlugin : _webpack.ProgressPlugin; if (config.progressBar !== false && !(config.webpackConfig && config.webpackConfig.plugins || []).some(function (p) { return p.constructor === ProgressPlugin; })) { var _getProgressPlugin2 = getProgressPlugin('Compiling'), plugin = _getProgressPlugin2.plugin, localBar = _getProgressPlugin2.bar; bar = localBar; config.webpackConfig.plugins = [].concat((0, _toConsumableArray2["default"])(config.webpackConfig.plugins || []), [plugin]); } var _server = (0, _server2["default"])(config, function (err) { if (err) { console.error(err); } else { var isHttps = compiler.options.devServer && compiler.options.devServer.https; var urls = _WebpackDevServerUtils["default"].prepareUrls(isHttps ? 'https' : 'http', config.serverHost, config.serverPort); if (config.printServerInstructions) { config.printServerInstructions(config, { isHttps: !!isHttps }); } else { printServerInstructions(urls, compiler.options.devServer && compiler.options.devServer.publicPath ? compiler.options.devServer.publicPath.replace(/^\//, '') : ''); } if (bar) { bar.start(1, 0); } if (open) { (0, _openBrowser["default"])(urls.localUrlForBrowser); } } }), app = _server.app, compiler = _server.compiler; verbose('Webpack config:', compiler.options); // Custom error reporting compiler.hooks.done.tap('vsgErrorDone', function (stats) { if (bar) { bar.stop(); (0, _readline.moveCursor)(process.stdout, 0, -1); (0, _readline.clearLine)(process.stdout, 0); } var messages = (0, _formatWebpackMessages["default"])(stats.toJson({}, true)); if (!messages.errors.length && !messages.warnings.length) { printStatus('Compiled successfully!', 'success'); } printAllErrorsAndWarnings(messages, stats.compilation); }) // kill ghosted threads on exit ; ['SIGINT', 'SIGTERM'].forEach(function (signal) { process.on(signal, function () { app.close(function () { process.exit(0); }); }); }); // in order to have the caller be able to interact // with the app when it's hot return { app: app, compiler: compiler }; } function commandHelp() { console.log([kleur.underline('Usage'), '', ' ' + kleur.bold('styleguidist') + ' ' + kleur.cyan('<command>') + ' ' + kleur.yellow('[<options>]'), '', kleur.underline('Commands'), '', ' ' + kleur.cyan('build') + ' Build style guide', ' ' + kleur.cyan('server') + ' Run development server', ' ' + kleur.cyan('help') + ' Display React Styleguidist help', '', kleur.underline('Options'), '', ' ' + kleur.yellow('--config') + ' Config file path', ' ' + kleur.yellow('--open') + ' Open Styleguidist in the default browser', ' ' + kleur.yellow('--verbose') + ' Print debug information'].join('\n')); } /** * @param {object} urls * @param {string} publicPath */ function printServerInstructions(urls, publicPath) { console.log(); console.log("You can now view your style guide in the browser:"); console.log(); console.log(" ".concat(kleur.bold('Local:'), " ").concat(urls.localUrlForTerminal + publicPath)); if (urls.lanUrlForTerminal) { console.log(" ".concat(kleur.bold('On your network:'), " ").concat(urls.lanUrlForTerminal + publicPath)); } console.log(); } /** * @param {object} config */ function printBuildInstructions(config) { console.log('Style guide published to:\n' + kleur.underline(config.styleguideDir || '')); } /** * @param {string} message * @param {string} linkTitle * @param {string} linkUrl */ function printErrorWithLink(message, linkTitle, linkUrl) { console.error("".concat(kleur.bold().red(message), "\n\n").concat(linkTitle, "\n").concat(kleur.underline(linkUrl), "\n")); } /** * @param {string} header * @param {object} errors * @param {object} originalErrors * @param {'success'|'error'|'warning'} type */ function printErrors(header, errors, originalErrors, type) { printStatus(header, type); console.error(); var messages = process.env.VUESG_VERBOSE ? originalErrors : errors; messages.forEach(function (message) { console.error(typeof message === 'string' ? message : message.message); }); } /** * @param {string} text * @param {'success'|'error'|'warning'} type */ function printStatus(text, type) { if (type === 'success') { console.log(kleur.inverse().bold().green(' DONE ') + ' ' + text); } else if (type === 'error') { console.error(kleur.inverse().bold().red(' FAIL ') + ' ' + kleur.red(text)); } else { console.error(kleur.inverse().bold().yellow(' WARN ') + ' ' + kleur.yellow(text)); } } /** * @param {object} messages * @param {object} compilation * @return {boolean} */ function printAllErrorsAndWarnings(messages, compilation) { // If errors exist, only show errors if (messages.errors.length) { printAllErrors(messages.errors, compilation.errors); return true; } // Show warnings if no errors were found if (messages.warnings.length) { printAllWarnings(messages.warnings, compilation.warnings); } return false; } /** * @param {object} errors * @param {object} originalErrors */ function printAllErrors(errors, originalErrors) { printStyleguidistError(errors); printNoLoaderError(errors); printErrors('Failed to compile', errors, originalErrors, 'error'); } /** * @param {object} warnings * @param {object} originalWarnings */ function printAllWarnings(warnings, originalWarnings) { printErrors('Compiled with warnings', warnings, originalWarnings, 'warning'); } /** * @param {object} errors */ function printStyleguidistError(errors) { var styleguidistError = errors.find(function (message) { return message.includes('Module build failed: Error: Styleguidist:'); }); if (!styleguidistError) { return; } var m = styleguidistError.match(/Styleguidist: (.*?)\n/); if (m) { printErrorWithLink(m[1], 'Learn how to configure your style guide:', _consts["default"].DOCS_CONFIG); } process.exit(1); } /** * @param {object} errors */ function printNoLoaderError(errors) { if (process.env.VUESG_VERBOSE) { return; } var noLoaderError = errors.find(function (message) { return message.includes('You may need an appropriate loader'); }); if (!noLoaderError) { return; } printErrorWithLink(noLoaderError, 'Learn how to add webpack loaders to your style guide:', _consts["default"].DOCS_WEBPACK); process.exit(1); } /** * @param {string} header * @param {object} object */ function verbose(header, object) { logger.debug(kleur.bold(header) + '\n\n' + (0, _qI.stringify)(object)); }