rollup-plugin-api-extractor
Version:
A rollupjs plugin for integrating with @microsoft/api-extractor
181 lines (167 loc) • 7.29 kB
JavaScript
Object.defineProperty(exports, '__esModule', { value: true });
var apiExtractor$1 = require('@microsoft/api-extractor');
var fs = require('fs');
var path = require('path');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
const fileSys = {
readFileSync: (path, encoding) => fs__default["default"].readFileSync(path, encoding),
existsSync: (path) => fs__default["default"].existsSync(path),
resolve: (...pathSegments) => path__default["default"].resolve(...pathSegments),
join: (...paths) => path__default["default"].join(...paths),
dirname: (p) => path__default["default"].dirname(p),
unlinkSync: (path) => fs__default["default"].unlinkSync(path),
statSync: (path) => fs__default["default"].statSync(path),
readdirSync: (path) => fs__default["default"].readdirSync(path),
rmdirSync: (path) => fs__default["default"].rmdirSync(path)
};
const getTypings = () => {
var _a, _b;
const packageFile = fileSys.resolve('package.json');
const packageJson = JSON.parse(fileSys.readFileSync(packageFile, 'utf8'));
let types = (_b = ((_a = packageJson.types) !== null && _a !== void 0 ? _a : packageJson.typings)) !== null && _b !== void 0 ? _b : packageJson.main;
if (types) {
if (!types.endsWith('.d.ts')) {
types = `${types.substr(0, types.lastIndexOf('.'))}.d.ts`;
}
}
if (!types) {
types = 'index.d.ts';
}
if (!fileSys.existsSync(fileSys.join(fileSys.dirname(packageFile), types))) {
return undefined;
}
return types;
};
const getApiExtractorConfig = (pluginOptions) => {
var _a;
const apiExtractorJsonPath = fileSys.resolve((_a = pluginOptions.configFile) !== null && _a !== void 0 ? _a : './config/api-extractor.json');
let aeConfig = {};
if (!fileSys.existsSync(apiExtractorJsonPath) && !pluginOptions.configuration) {
throw new Error(`configuration not specified and configuration file ${apiExtractorJsonPath} not found.`);
}
if (fileSys.existsSync(apiExtractorJsonPath)) {
aeConfig = Object.assign(Object.assign({}, apiExtractor$1.ExtractorConfig.loadFile(apiExtractorJsonPath)), pluginOptions.configuration);
}
else {
aeConfig = Object.assign({}, pluginOptions.configuration);
}
if (!aeConfig.mainEntryPointFilePath) {
const typingsFile = getTypings();
if (typingsFile) {
aeConfig = Object.assign(Object.assign(Object.assign({}, aeConfig), pluginOptions.configuration), { mainEntryPointFilePath: typingsFile });
}
else {
throw new Error('Unable to auto-resolve mainEntryPointFilePath. Please add typings it your package.json');
}
}
return aeConfig;
};
const handleApiExtractorMessages = (context, message) => {
var _a, _b;
message.handled = true;
if (message.logLevel === "none" /* None */) {
return;
}
if (message.category === "console" /* Console */ &&
(message.logLevel !== "error" /* Error */ && message.logLevel !== "warning" /* Warning */)) {
return;
}
const logFunc = message.logLevel === "error" /* Error */ ? context.error : context.warn;
logFunc(message.formatMessageWithLocation(__dirname), {
column: (_a = message.sourceFileColumn) !== null && _a !== void 0 ? _a : -1,
line: (_b = message.sourceFileLine) !== null && _b !== void 0 ? _b : -1
});
};
const invokeApiExtractor = (context, apiExtractorConfig, pluginOptions) => {
var _a, _b;
const packageJsonPath = fileSys.resolve('package.json');
const prepareOptions = {
configObject: apiExtractorConfig,
configObjectFullPath: undefined,
packageJsonFullPath: packageJsonPath
};
const extractorConfig = apiExtractor$1.ExtractorConfig.prepare(prepareOptions);
const extractorResult = apiExtractor$1.Extractor.invoke(extractorConfig, {
localBuild: ((_a = pluginOptions.local) !== null && _a !== void 0 ? _a : (_b = context.meta) === null || _b === void 0 ? void 0 : _b.watchMode),
showVerboseMessages: pluginOptions.verbose,
showDiagnostics: pluginOptions.diagnostics,
typescriptCompilerFolder: pluginOptions.typescriptFolder,
messageCallback: (message) => handleApiExtractorMessages(context, message)
});
return { extractorResult, extractorConfig };
};
const removeEmptyFolders = (folder) => {
const isDir = fileSys.statSync(folder).isDirectory();
if (!isDir) {
return;
}
let files = fileSys.readdirSync(folder);
if (files.length > 0) {
files.forEach(function (file) {
const fullPath = fileSys.join(folder, file);
removeEmptyFolders(fullPath);
});
files = fileSys.readdirSync(folder);
}
if (files.length === 0) {
fileSys.rmdirSync(folder);
}
};
const performDtsRollupCleanup = (bundle, extractorConfig, options) => {
var _a;
if (!bundle || !extractorConfig.rollupEnabled) {
return;
}
const outDir = fileSys.resolve((_a = options.dir) !== null && _a !== void 0 ? _a : './');
const outDefs = [];
pushIfDefined(extractorConfig.untrimmedFilePath, outDir, outDefs);
pushIfDefined(extractorConfig.betaTrimmedFilePath, outDir, outDefs);
pushIfDefined(extractorConfig.publicTrimmedFilePath, outDir, outDefs);
Object.keys(bundle).filter((key) => key.match(/\.d\.ts/)).forEach((def) => {
const defRef = bundle[def];
if (defRef) {
const fileName = fileSys.resolve(outDir, defRef.fileName);
if (!outDefs.includes(fileName)) {
fileSys.unlinkSync(fileName);
}
}
});
removeEmptyFolders(outDir);
};
const pushIfDefined = (filePath, outDir, outDefs) => {
if (filePath) {
outDefs.push(fileSys.resolve(outDir, filePath));
}
};
/**
* adds \@microsoft/api-extractor to you rollupjs pipeline.
* @public
* @param pluginOptions - The configuration options for the rollupjs plugin {@link ApiExtractorPluginOptions}
* @returns the api-extractor plugin function
*/
const apiExtractor = (pluginOptions = {}) => {
return {
name: 'api-extractor',
writeBundle(options, bundle) {
var _a;
const aeConfig = getApiExtractorConfig(pluginOptions);
const { extractorResult, extractorConfig } = invokeApiExtractor(this, aeConfig, pluginOptions);
if (!extractorResult.succeeded) {
if (extractorResult.errorCount > 0) {
this.error(`API Extractor completed with ${extractorResult.errorCount} errors and ${extractorResult.warningCount} warnings`);
}
else {
this.warn(`API Extractor completed with ${extractorResult.warningCount} warnings`);
}
return;
}
if ((_a = pluginOptions.cleanUpRollup) !== null && _a !== void 0 ? _a : true) {
performDtsRollupCleanup(bundle, extractorConfig, options);
}
}
};
};
exports.apiExtractor = apiExtractor;
;