dts-bundle-generator
Advanced tools
Comparing version 6.13.0 to 7.0.0
@@ -1,2 +0,2 @@ | ||
// Generated by dts-bundle-generator v6.13.0 | ||
// Generated by dts-bundle-generator v7.0.0 | ||
@@ -3,0 +3,0 @@ export interface CompilationOptions { |
#!/usr/bin/env node | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var path = require("path"); | ||
var ts = require("typescript"); | ||
var yargs = require("yargs"); | ||
var load_config_file_1 = require("../config-file/load-config-file"); | ||
var bundle_generator_1 = require("../bundle-generator"); | ||
var check_diagnostics_errors_1 = require("../helpers/check-diagnostics-errors"); | ||
var get_compiler_options_1 = require("../get-compiler-options"); | ||
var fix_path_1 = require("../helpers/fix-path"); | ||
var measure_time_1 = require("../helpers/measure-time"); | ||
var logger_1 = require("../logger"); | ||
const path = require("path"); | ||
const ts = require("typescript"); | ||
const yargs = require("yargs"); | ||
const load_config_file_1 = require("../config-file/load-config-file"); | ||
const bundle_generator_1 = require("../bundle-generator"); | ||
const check_diagnostics_errors_1 = require("../helpers/check-diagnostics-errors"); | ||
const get_compiler_options_1 = require("../get-compiler-options"); | ||
const fix_path_1 = require("../helpers/fix-path"); | ||
const measure_time_1 = require("../helpers/measure-time"); | ||
const logger_1 = require("../logger"); | ||
function toStringsArray(data) { | ||
@@ -19,3 +19,3 @@ if (data === undefined) { | ||
if (!Array.isArray(data)) { | ||
throw new Error("".concat(data, " is not a array")); | ||
throw new Error(`${data} is not a array`); | ||
} | ||
@@ -137,3 +137,3 @@ return data.map(String); | ||
function generateOutFileName(inputFilePath) { | ||
var inputFileName = path.parse(inputFilePath).name; | ||
const inputFileName = path.parse(inputFilePath).name; | ||
return (0, fix_path_1.fixPath)(path.join(inputFilePath, '..', inputFileName + '.d.ts')); | ||
@@ -143,3 +143,3 @@ } | ||
function main() { | ||
var args = parseArgs(); | ||
const args = parseArgs(); | ||
if (args.silent && args.verbose) { | ||
@@ -154,5 +154,5 @@ throw new Error('Cannot use both silent and verbose options at the same time'); | ||
} | ||
var bundlerConfig; | ||
let bundlerConfig; | ||
if (args.config !== undefined) { | ||
(0, logger_1.verboseLog)("Trying to load config from ".concat(args.config, " file...")); | ||
(0, logger_1.verboseLog)(`Trying to load config from ${args.config} file...`); | ||
bundlerConfig = (0, load_config_file_1.loadConfigFile)(args.config); | ||
@@ -168,3 +168,3 @@ } | ||
bundlerConfig = { | ||
entries: args._.map(function (entryPath) { | ||
entries: args._.map((entryPath) => { | ||
return { | ||
@@ -197,9 +197,9 @@ filePath: String(entryPath), | ||
} | ||
(0, logger_1.verboseLog)("Total entries count=".concat(bundlerConfig.entries.length)); | ||
var generatedDts = (0, bundle_generator_1.generateDtsBundle)(bundlerConfig.entries, bundlerConfig.compilationOptions); | ||
var outFilesToCheck = []; | ||
for (var i = 0; i < bundlerConfig.entries.length; ++i) { | ||
var entry = bundlerConfig.entries[i]; | ||
var outFile = entry.outFile !== undefined ? entry.outFile : generateOutFileName(entry.filePath); | ||
(0, logger_1.normalLog)("Writing ".concat(entry.filePath, " -> ").concat(outFile)); | ||
(0, logger_1.verboseLog)(`Total entries count=${bundlerConfig.entries.length}`); | ||
const generatedDts = (0, bundle_generator_1.generateDtsBundle)(bundlerConfig.entries, bundlerConfig.compilationOptions); | ||
const outFilesToCheck = []; | ||
for (let i = 0; i < bundlerConfig.entries.length; ++i) { | ||
const entry = bundlerConfig.entries[i]; | ||
const outFile = entry.outFile !== undefined ? entry.outFile : generateOutFileName(entry.filePath); | ||
(0, logger_1.normalLog)(`Writing ${entry.filePath} -> ${outFile}`); | ||
ts.sys.writeFile(outFile, generatedDts[i]); | ||
@@ -215,4 +215,4 @@ if (!entry.noCheck) { | ||
(0, logger_1.normalLog)('Checking generated files...'); | ||
var preferredConfigFile = bundlerConfig.compilationOptions !== undefined ? bundlerConfig.compilationOptions.preferredConfigPath : undefined; | ||
var compilerOptions = (0, get_compiler_options_1.getCompilerOptions)(outFilesToCheck, preferredConfigFile); | ||
const preferredConfigFile = bundlerConfig.compilationOptions !== undefined ? bundlerConfig.compilationOptions.preferredConfigPath : undefined; | ||
const compilerOptions = (0, get_compiler_options_1.getCompilerOptions)(outFilesToCheck, preferredConfigFile); | ||
if (compilerOptions.skipLibCheck) { | ||
@@ -222,13 +222,13 @@ compilerOptions.skipLibCheck = false; | ||
} | ||
var program = ts.createProgram(outFilesToCheck, compilerOptions); | ||
const program = ts.createProgram(outFilesToCheck, compilerOptions); | ||
(0, check_diagnostics_errors_1.checkProgramDiagnosticsErrors)(program); | ||
} | ||
try { | ||
var executionTime = (0, measure_time_1.measureTime)(main); | ||
(0, logger_1.normalLog)("Done in ".concat((executionTime / 1000).toFixed(2), "s")); | ||
const executionTime = (0, measure_time_1.measureTime)(main); | ||
(0, logger_1.normalLog)(`Done in ${(executionTime / 1000).toFixed(2)}s`); | ||
} | ||
catch (ex) { | ||
(0, logger_1.normalLog)(''); | ||
(0, logger_1.errorLog)("Error: ".concat(ex.message)); | ||
(0, logger_1.errorLog)(`Error: ${ex.message}`); | ||
process.exit(1); | ||
} |
@@ -1,2 +0,2 @@ | ||
// Generated by dts-bundle-generator v6.13.0 | ||
// Generated by dts-bundle-generator v7.0.0 | ||
@@ -3,0 +3,0 @@ export interface CompilationOptions { |
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.generateDtsBundle = void 0; | ||
var ts = require("typescript"); | ||
var path = require("path"); | ||
var compile_dts_1 = require("./compile-dts"); | ||
var types_usage_evaluator_1 = require("./types-usage-evaluator"); | ||
var typescript_1 = require("./helpers/typescript"); | ||
var fix_path_1 = require("./helpers/fix-path"); | ||
var module_info_1 = require("./module-info"); | ||
var generate_output_1 = require("./generate-output"); | ||
var logger_1 = require("./logger"); | ||
function generateDtsBundle(entries, options) { | ||
if (options === void 0) { options = {}; } | ||
const ts = require("typescript"); | ||
const path = require("path"); | ||
const compile_dts_1 = require("./compile-dts"); | ||
const types_usage_evaluator_1 = require("./types-usage-evaluator"); | ||
const typescript_1 = require("./helpers/typescript"); | ||
const fix_path_1 = require("./helpers/fix-path"); | ||
const module_info_1 = require("./module-info"); | ||
const generate_output_1 = require("./generate-output"); | ||
const logger_1 = require("./logger"); | ||
function generateDtsBundle(entries, options = {}) { | ||
(0, logger_1.normalLog)('Compiling input files...'); | ||
var _a = (0, compile_dts_1.compileDts)(entries.map(function (entry) { return entry.filePath; }), options.preferredConfigPath, options.followSymlinks), program = _a.program, rootFilesRemapping = _a.rootFilesRemapping; | ||
var typeChecker = program.getTypeChecker(); | ||
var typeRoots = ts.getEffectiveTypeRoots(program.getCompilerOptions(), {}); | ||
var sourceFiles = program.getSourceFiles().filter(function (file) { | ||
const { program, rootFilesRemapping } = (0, compile_dts_1.compileDts)(entries.map((entry) => entry.filePath), options.preferredConfigPath, options.followSymlinks); | ||
const typeChecker = program.getTypeChecker(); | ||
const typeRoots = ts.getEffectiveTypeRoots(program.getCompilerOptions(), {}); | ||
const sourceFiles = program.getSourceFiles().filter((file) => { | ||
return !program.isSourceFileDefaultLibrary(file); | ||
}); | ||
(0, logger_1.verboseLog)("Input source files:\n ".concat(sourceFiles.map(function (file) { return file.fileName; }).join('\n '))); | ||
var typesUsageEvaluator = new types_usage_evaluator_1.TypesUsageEvaluator(sourceFiles, typeChecker); | ||
return entries.map(function (entry) { | ||
(0, logger_1.normalLog)("Processing ".concat(entry.filePath)); | ||
var newRootFilePath = rootFilesRemapping.get(entry.filePath); | ||
(0, logger_1.verboseLog)(`Input source files:\n ${sourceFiles.map((file) => file.fileName).join('\n ')}`); | ||
const typesUsageEvaluator = new types_usage_evaluator_1.TypesUsageEvaluator(sourceFiles, typeChecker); | ||
return entries.map((entry) => { | ||
(0, logger_1.normalLog)(`Processing ${entry.filePath}`); | ||
const newRootFilePath = rootFilesRemapping.get(entry.filePath); | ||
if (newRootFilePath === undefined) { | ||
throw new Error("Cannot remap root source file ".concat(entry.filePath)); | ||
throw new Error(`Cannot remap root source file ${entry.filePath}`); | ||
} | ||
var rootSourceFile = getRootSourceFile(program, newRootFilePath); | ||
var rootSourceFileSymbol = typeChecker.getSymbolAtLocation(rootSourceFile); | ||
const rootSourceFile = getRootSourceFile(program, newRootFilePath); | ||
const rootSourceFileSymbol = typeChecker.getSymbolAtLocation(rootSourceFile); | ||
if (rootSourceFileSymbol === undefined) { | ||
throw new Error("Symbol for root source file ".concat(newRootFilePath, " not found")); | ||
throw new Error(`Symbol for root source file ${newRootFilePath} not found`); | ||
} | ||
var librariesOptions = entry.libraries || {}; | ||
var criteria = { | ||
const librariesOptions = entry.libraries || {}; | ||
const criteria = { | ||
allowedTypesLibraries: librariesOptions.allowedTypesLibraries, | ||
importedLibraries: librariesOptions.importedLibraries, | ||
inlinedLibraries: librariesOptions.inlinedLibraries || [], | ||
typeRoots: typeRoots, | ||
typeRoots, | ||
}; | ||
var rootFileExports = (0, typescript_1.getExportsForSourceFile)(typeChecker, rootSourceFileSymbol); | ||
var rootFileExportSymbols = rootFileExports.map(function (exp) { return exp.symbol; }); | ||
var collectionResult = { | ||
const rootFileExports = (0, typescript_1.getExportsForSourceFile)(typeChecker, rootSourceFileSymbol); | ||
const rootFileExportSymbols = rootFileExports.map((exp) => exp.symbol); | ||
const collectionResult = { | ||
typesReferences: new Set(), | ||
@@ -61,11 +49,11 @@ imports: new Map(), | ||
}; | ||
var outputOptions = entry.output || {}; | ||
var updateResultCommonParams = { | ||
isStatementUsed: function (statement) { return isNodeUsed(statement, rootFileExportSymbols, typesUsageEvaluator, typeChecker); }, | ||
shouldStatementBeImported: function (statement) { | ||
const outputOptions = entry.output || {}; | ||
const updateResultCommonParams = { | ||
isStatementUsed: (statement) => isNodeUsed(statement, rootFileExportSymbols, typesUsageEvaluator, typeChecker), | ||
shouldStatementBeImported: (statement) => { | ||
return shouldNodeBeImported(statement, rootFileExportSymbols, typesUsageEvaluator, typeChecker, program.isSourceFileDefaultLibrary.bind(program), criteria); | ||
}, | ||
shouldDeclareGlobalBeInlined: function (currentModule) { return Boolean(outputOptions.inlineDeclareGlobals) && currentModule.type === 0 /* ModuleType.ShouldBeInlined */; }, | ||
shouldDeclareExternalModuleBeInlined: function () { return Boolean(outputOptions.inlineDeclareExternals); }, | ||
getModuleInfo: function (fileNameOrModuleLike) { | ||
shouldDeclareGlobalBeInlined: (currentModule) => Boolean(outputOptions.inlineDeclareGlobals) && currentModule.type === 0 /* ModuleType.ShouldBeInlined */, | ||
shouldDeclareExternalModuleBeInlined: () => Boolean(outputOptions.inlineDeclareExternals), | ||
getModuleInfo: (fileNameOrModuleLike) => { | ||
if (typeof fileNameOrModuleLike !== 'string') { | ||
@@ -76,29 +64,38 @@ return getModuleLikeInfo(fileNameOrModuleLike, criteria); | ||
}, | ||
resolveIdentifier: function (identifier) { return (0, typescript_1.resolveIdentifier)(typeChecker, identifier); }, | ||
getDeclarationsForExportedAssignment: function (exportAssignment) { | ||
var symbolForExpression = typeChecker.getSymbolAtLocation(exportAssignment.expression); | ||
resolveIdentifier: (identifier) => (0, typescript_1.resolveIdentifier)(typeChecker, identifier), | ||
getDeclarationsForExportedAssignment: (exportAssignment) => { | ||
const symbolForExpression = typeChecker.getSymbolAtLocation(exportAssignment.expression); | ||
if (symbolForExpression === undefined) { | ||
return []; | ||
} | ||
var symbol = (0, typescript_1.getActualSymbol)(symbolForExpression, typeChecker); | ||
const symbol = (0, typescript_1.getActualSymbol)(symbolForExpression, typeChecker); | ||
return (0, typescript_1.getDeclarationsForSymbol)(symbol); | ||
}, | ||
getDeclarationUsagesSourceFiles: function (declaration) { | ||
getDeclarationUsagesSourceFiles: (declaration) => { | ||
return getDeclarationUsagesSourceFiles(declaration, rootFileExportSymbols, typesUsageEvaluator, typeChecker, criteria); | ||
}, | ||
areDeclarationSame: function (left, right) { | ||
var leftSymbols = (0, typescript_1.splitTransientSymbol)(getNodeSymbol(left, typeChecker), typeChecker); | ||
var rightSymbols = (0, typescript_1.splitTransientSymbol)(getNodeSymbol(right, typeChecker), typeChecker); | ||
return leftSymbols.some(function (leftSymbol) { return rightSymbols.includes(leftSymbol); }); | ||
areDeclarationSame: (left, right) => { | ||
const leftSymbols = (0, typescript_1.splitTransientSymbol)(getNodeSymbol(left, typeChecker), typeChecker); | ||
const rightSymbols = (0, typescript_1.splitTransientSymbol)(getNodeSymbol(right, typeChecker), typeChecker); | ||
return leftSymbols.some((leftSymbol) => rightSymbols.includes(leftSymbol)); | ||
}, | ||
resolveReferencedModule: function (node) { | ||
var moduleName = ts.isExportDeclaration(node) ? node.moduleSpecifier : node.name; | ||
resolveReferencedModule: (node) => { | ||
let moduleName; | ||
if (ts.isExportDeclaration(node)) { | ||
moduleName = node.moduleSpecifier; | ||
} | ||
else if (ts.isModuleDeclaration(node)) { | ||
moduleName = node.name; | ||
} | ||
else if (ts.isLiteralTypeNode(node.argument) && ts.isStringLiteral(node.argument.literal)) { | ||
moduleName = node.argument.literal; | ||
} | ||
if (moduleName === undefined) { | ||
return null; | ||
} | ||
var moduleSymbol = typeChecker.getSymbolAtLocation(moduleName); | ||
const moduleSymbol = typeChecker.getSymbolAtLocation(moduleName); | ||
if (moduleSymbol === undefined) { | ||
return null; | ||
} | ||
var symbol = (0, typescript_1.getActualSymbol)(moduleSymbol, typeChecker); | ||
const symbol = (0, typescript_1.getActualSymbol)(moduleSymbol, typeChecker); | ||
if (symbol.valueDeclaration === undefined) { | ||
@@ -113,9 +110,12 @@ return null; | ||
}; | ||
for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { | ||
var sourceFile = sourceFiles_1[_i]; | ||
(0, logger_1.verboseLog)("\n\n======= Preparing file: ".concat(sourceFile.fileName, " =======")); | ||
var prevStatementsCount = collectionResult.statements.length; | ||
var updateFn = sourceFile === rootSourceFile ? updateResultForRootSourceFile : updateResult; | ||
var currentModule = (0, module_info_1.getModuleInfo)(sourceFile.fileName, criteria); | ||
var params = __assign(__assign({}, updateResultCommonParams), { currentModule: currentModule, statements: sourceFile.statements }); | ||
for (const sourceFile of sourceFiles) { | ||
(0, logger_1.verboseLog)(`\n\n======= Preparing file: ${sourceFile.fileName} =======`); | ||
const prevStatementsCount = collectionResult.statements.length; | ||
const updateFn = sourceFile === rootSourceFile ? updateResultForRootSourceFile : updateResult; | ||
const currentModule = (0, module_info_1.getModuleInfo)(sourceFile.fileName, criteria); | ||
const params = { | ||
...updateResultCommonParams, | ||
currentModule, | ||
statements: sourceFile.statements, | ||
}; | ||
updateFn(params, collectionResult); | ||
@@ -127,22 +127,25 @@ // handle `import * as module` usage if it's used as whole module | ||
if (collectionResult.statements.length === prevStatementsCount) { | ||
(0, logger_1.verboseLog)("No output for file: ".concat(sourceFile.fileName)); | ||
(0, logger_1.verboseLog)(`No output for file: ${sourceFile.fileName}`); | ||
} | ||
} | ||
if (entry.failOnClass) { | ||
var classes = collectionResult.statements.filter(ts.isClassDeclaration); | ||
const classes = collectionResult.statements.filter(ts.isClassDeclaration); | ||
if (classes.length !== 0) { | ||
var classesNames = classes.map(function (c) { return c.name === undefined ? 'anonymous class' : c.name.text; }); | ||
throw new Error("".concat(classes.length, " class statement(s) are found in generated dts: ").concat(classesNames.join(', '))); | ||
const classesNames = classes.map((c) => c.name === undefined ? 'anonymous class' : c.name.text); | ||
throw new Error(`${classes.length} class statement(s) are found in generated dts: ${classesNames.join(', ')}`); | ||
} | ||
} | ||
// by default this option should be enabled | ||
var exportReferencedTypes = outputOptions.exportReferencedTypes !== false; | ||
return (0, generate_output_1.generateOutput)(__assign(__assign({}, collectionResult), { needStripDefaultKeywordForStatement: function (statement) { | ||
var statementExports = (0, typescript_1.getExportsForStatement)(rootFileExports, typeChecker, statement); | ||
const exportReferencedTypes = outputOptions.exportReferencedTypes !== false; | ||
return (0, generate_output_1.generateOutput)({ | ||
...collectionResult, | ||
needStripDefaultKeywordForStatement: (statement) => { | ||
const statementExports = (0, typescript_1.getExportsForStatement)(rootFileExports, typeChecker, statement); | ||
// a statement should have a 'default' keyword only if it it declared in the root source file | ||
// otherwise it will be re-exported via `export { name as default }` | ||
var defaultExport = statementExports.find(function (exp) { return exp.exportedName === 'default'; }); | ||
const defaultExport = statementExports.find((exp) => exp.exportedName === 'default'); | ||
return defaultExport === undefined || defaultExport.originalName !== 'default' && statement.getSourceFile() !== rootSourceFile; | ||
}, shouldStatementHasExportKeyword: function (statement) { | ||
var statementExports = (0, typescript_1.getExportsForStatement)(rootFileExports, typeChecker, statement); | ||
}, | ||
shouldStatementHasExportKeyword: (statement) => { | ||
const statementExports = (0, typescript_1.getExportsForStatement)(rootFileExports, typeChecker, statement); | ||
// If true, then no direct export was found. That means that node might have | ||
@@ -152,4 +155,4 @@ // an export keyword (like interface, type, etc) otherwise, if there are | ||
// to put export keyword for this statement because we'll re-export it in the way | ||
var hasStatementedDefaultKeyword = (0, typescript_1.hasNodeModifier)(statement, ts.SyntaxKind.DefaultKeyword); | ||
var result = statementExports.length === 0 || statementExports.find(function (exp) { | ||
const hasStatementedDefaultKeyword = (0, typescript_1.hasNodeModifier)(statement, ts.SyntaxKind.DefaultKeyword); | ||
let result = statementExports.length === 0 || statementExports.find((exp) => { | ||
// "directly" means "without renaming" or "without additional node/statement" | ||
@@ -159,3 +162,3 @@ // for instance, `class A {} export default A;` - here `statement` is `class A {}` | ||
// so we shouldn't add this either | ||
var shouldBeDefaultExportedDirectly = exp.exportedName === 'default' && hasStatementedDefaultKeyword && statement.getSourceFile() === rootSourceFile; | ||
const shouldBeDefaultExportedDirectly = exp.exportedName === 'default' && hasStatementedDefaultKeyword && statement.getSourceFile() === rootSourceFile; | ||
return shouldBeDefaultExportedDirectly || exp.exportedName === exp.originalName; | ||
@@ -167,3 +170,3 @@ }) !== undefined; | ||
// but if `exportReferencedTypes` option is disabled we have to check direct export for them either | ||
var onlyDirectlyExportedShouldBeExported = !exportReferencedTypes | ||
const onlyDirectlyExportedShouldBeExported = !exportReferencedTypes | ||
|| ts.isClassDeclaration(statement) | ||
@@ -182,7 +185,8 @@ || (ts.isEnumDeclaration(statement) && !(0, typescript_1.hasNodeModifier)(statement, ts.SyntaxKind.ConstKeyword)) | ||
return result; | ||
}, needStripConstFromConstEnum: function (constEnum) { | ||
}, | ||
needStripConstFromConstEnum: (constEnum) => { | ||
if (!program.getCompilerOptions().preserveConstEnums || !outputOptions.respectPreserveConstEnum) { | ||
return false; | ||
} | ||
var enumSymbol = getNodeSymbol(constEnum, typeChecker); | ||
const enumSymbol = getNodeSymbol(constEnum, typeChecker); | ||
if (enumSymbol === null) { | ||
@@ -192,3 +196,4 @@ return false; | ||
return rootFileExportSymbols.includes(enumSymbol); | ||
}, needStripImportFromImportTypeNode: function (node) { | ||
}, | ||
needStripImportFromImportTypeNode: (node) => { | ||
if (node.qualifier === undefined) { | ||
@@ -200,6 +205,9 @@ return false; | ||
} | ||
// we don't need to specify exact file here since we need to figure out whether a file is external or internal one | ||
var moduleFileName = resolveModuleFileName(rootSourceFile.fileName, node.argument.literal.text); | ||
return !(0, module_info_1.getModuleInfo)(moduleFileName, criteria).isExternal; | ||
} }), { | ||
const resolvedModule = updateResultCommonParams.resolveReferencedModule(node); | ||
if (resolvedModule === null) { | ||
return false; | ||
} | ||
return !updateResultCommonParams.getModuleInfo(resolvedModule).isExternal; | ||
}, | ||
}, { | ||
sortStatements: outputOptions.sortNodes, | ||
@@ -212,3 +220,3 @@ umdModuleName: outputOptions.umdModuleName, | ||
exports.generateDtsBundle = generateDtsBundle; | ||
var skippedNodes = [ | ||
const skippedNodes = [ | ||
ts.SyntaxKind.ExportDeclaration, | ||
@@ -220,4 +228,3 @@ ts.SyntaxKind.ImportDeclaration, | ||
function updateResult(params, result) { | ||
for (var _i = 0, _a = params.statements; _i < _a.length; _i++) { | ||
var statement = _a[_i]; | ||
for (const statement of params.statements) { | ||
// we should skip import and exports statements | ||
@@ -243,3 +250,3 @@ if (skippedNodes.indexOf(statement.kind) !== -1) { | ||
if (!params.isStatementUsed(statement)) { | ||
(0, logger_1.verboseLog)("Skip file member: ".concat(statement.getText().replace(/(\n|\r)/g, '').slice(0, 50), "...")); | ||
(0, logger_1.verboseLog)(`Skip file member: ${statement.getText().replace(/(\n|\r)/g, '').slice(0, 50)}...`); | ||
continue; | ||
@@ -266,3 +273,3 @@ } | ||
} | ||
var resolvedModule = params.resolveReferencedModule(statement); | ||
const resolvedModule = params.resolveReferencedModule(statement); | ||
if (resolvedModule === null) { | ||
@@ -275,4 +282,3 @@ return false; | ||
// add skipped by `updateResult` exports | ||
for (var _i = 0, _a = params.statements; _i < _a.length; _i++) { | ||
var statement = _a[_i]; | ||
for (const statement of params.statements) { | ||
// "export =" or "export {} from 'importable-package'" | ||
@@ -290,8 +296,8 @@ if (ts.isExportAssignment(statement) && statement.isExportEquals || isReExportFromImportableModule(statement)) { | ||
} | ||
var exportedNameNode = params.resolveIdentifier(statement.expression); | ||
const exportedNameNode = params.resolveIdentifier(statement.expression); | ||
if (exportedNameNode === undefined) { | ||
continue; | ||
} | ||
var originalName = exportedNameNode.getText(); | ||
result.renamedExports.push("".concat(originalName, " as default")); | ||
const originalName = exportedNameNode.getText(); | ||
result.renamedExports.push(`${originalName} as default`); | ||
continue; | ||
@@ -301,12 +307,11 @@ } | ||
if (ts.isExportDeclaration(statement) && statement.exportClause !== undefined && ts.isNamedExports(statement.exportClause)) { | ||
for (var _b = 0, _c = statement.exportClause.elements; _b < _c.length; _b++) { | ||
var exportItem = _c[_b]; | ||
var exportedNameNode = params.resolveIdentifier(exportItem.name); | ||
for (const exportItem of statement.exportClause.elements) { | ||
const exportedNameNode = params.resolveIdentifier(exportItem.name); | ||
if (exportedNameNode === undefined) { | ||
continue; | ||
} | ||
var originalName = exportedNameNode.getText(); | ||
var exportedName = exportItem.name.getText(); | ||
const originalName = exportedNameNode.getText(); | ||
const exportedName = exportItem.name.getText(); | ||
if (originalName !== exportedName) { | ||
result.renamedExports.push("".concat(originalName, " as ").concat(exportedName)); | ||
result.renamedExports.push(`${originalName} as ${exportedName}`); | ||
} | ||
@@ -318,14 +323,16 @@ } | ||
function updateResultForExternalEqExportAssignment(exportAssignment, params, result) { | ||
var moduleDeclarations = params.getDeclarationsForExportedAssignment(exportAssignment) | ||
const moduleDeclarations = params.getDeclarationsForExportedAssignment(exportAssignment) | ||
.filter(typescript_1.isNamespaceStatement) | ||
.filter(function (s) { return s.getSourceFile() === exportAssignment.getSourceFile(); }); | ||
.filter((s) => s.getSourceFile() === exportAssignment.getSourceFile()); | ||
// if we have `export =` somewhere so we can decide that every declaration of exported symbol in this way | ||
// is "part of the exported module" and we need to update result according every member of each declaration | ||
// but treat they as current module (we do not need to update module info) | ||
for (var _i = 0, moduleDeclarations_1 = moduleDeclarations; _i < moduleDeclarations_1.length; _i++) { | ||
var moduleDeclaration = moduleDeclarations_1[_i]; | ||
for (const moduleDeclaration of moduleDeclarations) { | ||
if (moduleDeclaration.body === undefined || !ts.isModuleBlock(moduleDeclaration.body)) { | ||
continue; | ||
} | ||
updateResult(__assign(__assign({}, params), { statements: moduleDeclaration.body.statements }), result); | ||
updateResult({ | ||
...params, | ||
statements: moduleDeclaration.body.statements, | ||
}, result); | ||
} | ||
@@ -337,3 +344,3 @@ } | ||
} | ||
var moduleInfo; | ||
let moduleInfo; | ||
if (!ts.isStringLiteral(moduleDecl.name)) { | ||
@@ -344,11 +351,11 @@ // this is an old behavior of handling `declare module Name` statements | ||
// but it might be a breaking change to let's not break it yet | ||
var moduleFileName = resolveModuleFileName(params.currentModule.fileName, moduleDecl.name.text); | ||
const moduleFileName = resolveModuleFileName(params.currentModule.fileName, moduleDecl.name.text); | ||
moduleInfo = params.getModuleInfo(moduleFileName); | ||
} | ||
else { | ||
var referencedModule = params.resolveReferencedModule(moduleDecl); | ||
const referencedModule = params.resolveReferencedModule(moduleDecl); | ||
if (referencedModule === null) { | ||
return; | ||
} | ||
var moduleFilePath = ts.isSourceFile(referencedModule) | ||
const moduleFilePath = ts.isSourceFile(referencedModule) | ||
? referencedModule.fileName | ||
@@ -366,10 +373,14 @@ : resolveModuleFileName(referencedModule.getSourceFile().fileName, referencedModule.name.text); | ||
} | ||
updateResult(__assign(__assign({}, params), { currentModule: moduleInfo, statements: moduleDecl.body.statements }), result); | ||
updateResult({ | ||
...params, | ||
currentModule: moduleInfo, | ||
statements: moduleDecl.body.statements, | ||
}, result); | ||
} | ||
function resolveModuleFileName(currentFileName, moduleName) { | ||
return moduleName.startsWith('.') ? (0, fix_path_1.fixPath)(path.join(currentFileName, '..', moduleName)) : "node_modules/".concat(moduleName, "/"); | ||
return moduleName.startsWith('.') ? (0, fix_path_1.fixPath)(path.join(currentFileName, '..', moduleName)) : `node_modules/${moduleName}/`; | ||
} | ||
function addTypesReference(library, typesReferences) { | ||
if (!typesReferences.has(library)) { | ||
(0, logger_1.normalLog)("Library \"".concat(library, "\" will be added via reference directive")); | ||
(0, logger_1.normalLog)(`Library "${library}" will be added via reference directive`); | ||
typesReferences.add(library); | ||
@@ -382,5 +393,4 @@ } | ||
} | ||
var statementsToImport = ts.isVariableStatement(statement) ? statement.declarationList.declarations : [statement]; | ||
for (var _i = 0, statementsToImport_1 = statementsToImport; _i < statementsToImport_1.length; _i++) { | ||
var statementToImport = statementsToImport_1[_i]; | ||
const statementsToImport = ts.isVariableStatement(statement) ? statement.declarationList.declarations : [statement]; | ||
for (const statementToImport of statementsToImport) { | ||
if (params.shouldStatementBeImported(statementToImport)) { | ||
@@ -396,4 +406,4 @@ addImport(statementToImport, params, result.imports); | ||
// e.g. @types/node has declaration for "packages" events, fs, path and so on | ||
var sourceFile = statementToImport.getSourceFile(); | ||
var moduleInfo = params.getModuleInfo(sourceFile.fileName); | ||
const sourceFile = statementToImport.getSourceFile(); | ||
const moduleInfo = params.getModuleInfo(sourceFile.fileName); | ||
if (moduleInfo.type === 2 /* ModuleType.ShouldBeReferencedAsTypes */) { | ||
@@ -415,4 +425,4 @@ addTypesReference(moduleInfo.typesLibraryName, result.typesReferences); | ||
return new Set(getExportedSymbolsUsingStatement(declaration, rootFileExports, typesUsageEvaluator, typeChecker, criteria) | ||
.map(function (symbol) { return (0, typescript_1.getDeclarationsForSymbol)(symbol); }) | ||
.reduce(function (acc, val) { return acc.concat(val); }, []) | ||
.map((symbol) => (0, typescript_1.getDeclarationsForSymbol)(symbol)) | ||
.reduce((acc, val) => acc.concat(val), []) | ||
.map(getClosestModuleLikeNode)); | ||
@@ -422,3 +432,3 @@ } | ||
if (ts.isImportDeclaration(imp)) { | ||
var importClause = imp.importClause; | ||
const importClause = imp.importClause; | ||
if (importClause === undefined) { | ||
@@ -431,3 +441,3 @@ return null; | ||
if (!ts.isStringLiteral(imp.moduleReference.expression)) { | ||
(0, logger_1.warnLog)("Cannot handle non string-literal-like import expression: ".concat(imp.moduleReference.expression.getText())); | ||
(0, logger_1.warnLog)(`Cannot handle non string-literal-like import expression: ${imp.moduleReference.expression.getText()}`); | ||
return null; | ||
@@ -441,17 +451,17 @@ } | ||
if (statement.name === undefined) { | ||
throw new Error("Import/usage unnamed declaration: ".concat(statement.getText())); | ||
throw new Error(`Import/usage unnamed declaration: ${statement.getText()}`); | ||
} | ||
params.getDeclarationUsagesSourceFiles(statement).forEach(function (sourceFile) { | ||
var statements = ts.isSourceFile(sourceFile) | ||
params.getDeclarationUsagesSourceFiles(statement).forEach((sourceFile) => { | ||
const statements = ts.isSourceFile(sourceFile) | ||
? sourceFile.statements | ||
: sourceFile.body.statements; | ||
statements.forEach(function (st) { | ||
statements.forEach((st) => { | ||
if (!ts.isImportEqualsDeclaration(st) && !ts.isImportDeclaration(st)) { | ||
return; | ||
} | ||
var importModuleSpecifier = getImportModuleName(st); | ||
const importModuleSpecifier = getImportModuleName(st); | ||
if (importModuleSpecifier === null) { | ||
return; | ||
} | ||
var importItem = imports.get(importModuleSpecifier); | ||
let importItem = imports.get(importModuleSpecifier); | ||
if (importItem === undefined) { | ||
@@ -472,3 +482,3 @@ importItem = { | ||
} | ||
var importClause = st.importClause; | ||
const importClause = st.importClause; | ||
if (importClause.name !== undefined && params.areDeclarationSame(statement, importClause)) { | ||
@@ -483,4 +493,4 @@ // import name from 'module'; | ||
.filter(params.areDeclarationSame.bind(params, statement)) | ||
.forEach(function (specifier) { | ||
var importName = specifier.getText(); | ||
.forEach((specifier) => { | ||
let importName = specifier.getText(); | ||
if (specifier.isTypeOnly) { | ||
@@ -503,7 +513,7 @@ // let's fallback all the imports to ones without "type" specifier | ||
if (program.getRootFileNames().indexOf(rootFileName) === -1) { | ||
throw new Error("There is no such root file ".concat(rootFileName)); | ||
throw new Error(`There is no such root file ${rootFileName}`); | ||
} | ||
var sourceFile = program.getSourceFile(rootFileName); | ||
const sourceFile = program.getSourceFile(rootFileName); | ||
if (sourceFile === undefined) { | ||
throw new Error("Cannot get source file for root file ".concat(rootFileName)); | ||
throw new Error(`Cannot get source file for root file ${rootFileName}`); | ||
} | ||
@@ -514,10 +524,10 @@ return sourceFile; | ||
if ((0, typescript_1.isNodeNamedDeclaration)(node)) { | ||
var nodeSymbol_1 = getNodeSymbol(node, typeChecker); | ||
if (nodeSymbol_1 === null) { | ||
const nodeSymbol = getNodeSymbol(node, typeChecker); | ||
if (nodeSymbol === null) { | ||
return false; | ||
} | ||
return rootFileExports.some(function (rootExport) { return typesUsageEvaluator.isSymbolUsedBySymbol(nodeSymbol_1, rootExport); }); | ||
return rootFileExports.some((rootExport) => typesUsageEvaluator.isSymbolUsedBySymbol(nodeSymbol, rootExport)); | ||
} | ||
else if (ts.isVariableStatement(node)) { | ||
return node.declarationList.declarations.some(function (declaration) { | ||
return node.declarationList.declarations.some((declaration) => { | ||
return isNodeUsed(declaration, rootFileExports, typesUsageEvaluator, typeChecker); | ||
@@ -529,8 +539,8 @@ }); | ||
function shouldNodeBeImported(node, rootFileExports, typesUsageEvaluator, typeChecker, isDefaultLibrary, criteria) { | ||
var nodeSymbol = getNodeSymbol(node, typeChecker); | ||
const nodeSymbol = getNodeSymbol(node, typeChecker); | ||
if (nodeSymbol === null) { | ||
return false; | ||
} | ||
var symbolDeclarations = (0, typescript_1.getDeclarationsForSymbol)(nodeSymbol); | ||
var isSymbolDeclaredInDefaultLibrary = symbolDeclarations.some(function (declaration) { return isDefaultLibrary(declaration.getSourceFile()); }); | ||
const symbolDeclarations = (0, typescript_1.getDeclarationsForSymbol)(nodeSymbol); | ||
const isSymbolDeclaredInDefaultLibrary = symbolDeclarations.some((declaration) => isDefaultLibrary(declaration.getSourceFile())); | ||
if (isSymbolDeclaredInDefaultLibrary) { | ||
@@ -553,7 +563,7 @@ // we shouldn't import a node declared in the default library (such dom, es2015) | ||
function getExportedSymbolsUsingStatement(node, rootFileExports, typesUsageEvaluator, typeChecker, criteria) { | ||
var nodeSymbol = getNodeSymbol(node, typeChecker); | ||
const nodeSymbol = getNodeSymbol(node, typeChecker); | ||
if (nodeSymbol === null) { | ||
return []; | ||
} | ||
var symbolsUsingNode = typesUsageEvaluator.getSymbolsUsingSymbol(nodeSymbol); | ||
const symbolsUsingNode = typesUsageEvaluator.getSymbolsUsingSymbol(nodeSymbol); | ||
if (symbolsUsingNode === null) { | ||
@@ -563,5 +573,5 @@ throw new Error('Something went wrong - value cannot be null'); | ||
// we should import only symbols which are used in types directly | ||
return Array.from(symbolsUsingNode).filter(function (symbol) { | ||
var symbolsDeclarations = (0, typescript_1.getDeclarationsForSymbol)(symbol); | ||
if (symbolsDeclarations.length === 0 || symbolsDeclarations.every(function (decl) { | ||
return Array.from(symbolsUsingNode).filter((symbol) => { | ||
const symbolsDeclarations = (0, typescript_1.getDeclarationsForSymbol)(symbol); | ||
if (symbolsDeclarations.length === 0 || symbolsDeclarations.every((decl) => { | ||
// we need to make sure that at least 1 declaration is inlined | ||
@@ -572,7 +582,7 @@ return getModuleLikeInfo(getClosestModuleLikeNode(decl), criteria).type !== 0 /* ModuleType.ShouldBeInlined */; | ||
} | ||
return rootFileExports.some(function (rootSymbol) { return typesUsageEvaluator.isSymbolUsedBySymbol(symbol, rootSymbol); }); | ||
return rootFileExports.some((rootSymbol) => typesUsageEvaluator.isSymbolUsedBySymbol(symbol, rootSymbol)); | ||
}); | ||
} | ||
function getNodeSymbol(node, typeChecker) { | ||
var nodeName = (0, typescript_1.getNodeName)(node); | ||
const nodeName = (0, typescript_1.getNodeName)(node); | ||
if (nodeName === undefined) { | ||
@@ -584,3 +594,3 @@ return null; | ||
function getModuleLikeInfo(moduleLike, criteria) { | ||
var fileName = ts.isSourceFile(moduleLike) | ||
const fileName = ts.isSourceFile(moduleLike) | ||
? moduleLike.fileName | ||
@@ -587,0 +597,0 @@ : resolveModuleFileName(moduleLike.getSourceFile().fileName, moduleLike.name.text); |
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.compileDts = void 0; | ||
var path = require("path"); | ||
var ts = require("typescript"); | ||
var logger_1 = require("./logger"); | ||
var get_compiler_options_1 = require("./get-compiler-options"); | ||
var get_absolute_path_1 = require("./helpers/get-absolute-path"); | ||
var check_diagnostics_errors_1 = require("./helpers/check-diagnostics-errors"); | ||
function compileDts(rootFiles, preferredConfigPath, followSymlinks) { | ||
if (followSymlinks === void 0) { followSymlinks = true; } | ||
var compilerOptions = (0, get_compiler_options_1.getCompilerOptions)(rootFiles, preferredConfigPath); | ||
const path = require("path"); | ||
const ts = require("typescript"); | ||
const logger_1 = require("./logger"); | ||
const get_compiler_options_1 = require("./get-compiler-options"); | ||
const get_absolute_path_1 = require("./helpers/get-absolute-path"); | ||
const check_diagnostics_errors_1 = require("./helpers/check-diagnostics-errors"); | ||
function compileDts(rootFiles, preferredConfigPath, followSymlinks = true) { | ||
const compilerOptions = (0, get_compiler_options_1.getCompilerOptions)(rootFiles, preferredConfigPath); | ||
// currently we don't support these compiler options | ||
@@ -32,17 +20,17 @@ // and removing them shouldn't affect generated code | ||
if (compilerOptions.composite) { | ||
(0, logger_1.warnLog)("Composite projects aren't supported at the time. Prefer to use non-composite project to generate declarations instead or just ignore this message if everything works fine. See https://github.com/timocov/dts-bundle-generator/issues/93"); | ||
(0, logger_1.warnLog)(`Composite projects aren't supported at the time. Prefer to use non-composite project to generate declarations instead or just ignore this message if everything works fine. See https://github.com/timocov/dts-bundle-generator/issues/93`); | ||
compilerOptions.composite = undefined; | ||
} | ||
var dtsFiles = getDeclarationFiles(rootFiles, compilerOptions); | ||
(0, logger_1.verboseLog)("dts cache:\n ".concat(Object.keys(dtsFiles).join('\n '), "\n")); | ||
var host = ts.createCompilerHost(compilerOptions); | ||
const dtsFiles = getDeclarationFiles(rootFiles, compilerOptions); | ||
(0, logger_1.verboseLog)(`dts cache:\n ${Object.keys(dtsFiles).join('\n ')}\n`); | ||
const host = ts.createCompilerHost(compilerOptions); | ||
if (!followSymlinks) { | ||
host.realpath = function (p) { return p; }; | ||
host.realpath = (p) => p; | ||
} | ||
host.resolveModuleNames = function (moduleNames, containingFile) { | ||
return moduleNames.map(function (moduleName) { | ||
var resolvedModule = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host).resolvedModule; | ||
host.resolveModuleNames = (moduleNames, containingFile) => { | ||
return moduleNames.map((moduleName) => { | ||
const resolvedModule = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host).resolvedModule; | ||
if (resolvedModule && !resolvedModule.isExternalLibraryImport && resolvedModule.extension !== ts.Extension.Dts) { | ||
resolvedModule.extension = ts.Extension.Dts; | ||
(0, logger_1.verboseLog)("Change module from .ts to .d.ts: ".concat(resolvedModule.resolvedFileName)); | ||
(0, logger_1.verboseLog)(`Change module from .ts to .d.ts: ${resolvedModule.resolvedFileName}`); | ||
resolvedModule.resolvedFileName = changeExtensionToDts(resolvedModule.resolvedFileName); | ||
@@ -53,23 +41,23 @@ } | ||
}; | ||
var originalGetSourceFile = host.getSourceFile; | ||
host.getSourceFile = function (fileName, languageVersion, onError) { | ||
var absolutePath = (0, get_absolute_path_1.getAbsolutePath)(fileName); | ||
var storedValue = dtsFiles.get(absolutePath); | ||
const originalGetSourceFile = host.getSourceFile; | ||
host.getSourceFile = (fileName, languageVersion, onError) => { | ||
const absolutePath = (0, get_absolute_path_1.getAbsolutePath)(fileName); | ||
const storedValue = dtsFiles.get(absolutePath); | ||
if (storedValue !== undefined) { | ||
(0, logger_1.verboseLog)("dts cache match: ".concat(absolutePath)); | ||
(0, logger_1.verboseLog)(`dts cache match: ${absolutePath}`); | ||
return ts.createSourceFile(fileName, storedValue, languageVersion); | ||
} | ||
(0, logger_1.verboseLog)("dts cache mismatch: ".concat(absolutePath, " (").concat(fileName, ")")); | ||
(0, logger_1.verboseLog)(`dts cache mismatch: ${absolutePath} (${fileName})`); | ||
return originalGetSourceFile(fileName, languageVersion, onError); | ||
}; | ||
var rootFilesRemapping = new Map(); | ||
var inputFiles = rootFiles.map(function (rootFile) { | ||
var rootDtsFile = changeExtensionToDts(rootFile); | ||
const rootFilesRemapping = new Map(); | ||
const inputFiles = rootFiles.map((rootFile) => { | ||
const rootDtsFile = changeExtensionToDts(rootFile); | ||
rootFilesRemapping.set(rootFile, rootDtsFile); | ||
return rootDtsFile; | ||
}); | ||
var program = ts.createProgram(inputFiles, compilerOptions, host); | ||
const program = ts.createProgram(inputFiles, compilerOptions, host); | ||
(0, check_diagnostics_errors_1.checkProgramDiagnosticsErrors)(program); | ||
warnAboutTypeScriptFilesInProgram(program); | ||
return { program: program, rootFilesRemapping: rootFilesRemapping }; | ||
return { program, rootFilesRemapping }; | ||
} | ||
@@ -82,3 +70,3 @@ exports.compileDts = compileDts; | ||
// .ts, .tsx | ||
var ext = path.extname(fileName); | ||
const ext = path.extname(fileName); | ||
return fileName.slice(0, -ext.length) + '.d.ts'; | ||
@@ -95,6 +83,11 @@ } | ||
// error TS5055: Cannot write file '<filename>' because it would overwrite input file. | ||
compilerOptions = __assign(__assign({}, compilerOptions), { noEmit: false, declaration: true, emitDeclarationOnly: true }); | ||
var program = ts.createProgram(rootFiles, compilerOptions); | ||
var allFilesAreDeclarations = program.getSourceFiles().every(function (s) { return s.isDeclarationFile; }); | ||
var declarations = new Map(); | ||
compilerOptions = { | ||
...compilerOptions, | ||
noEmit: false, | ||
declaration: true, | ||
emitDeclarationOnly: true, | ||
}; | ||
const program = ts.createProgram(rootFiles, compilerOptions); | ||
const allFilesAreDeclarations = program.getSourceFiles().every((s) => s.isDeclarationFile); | ||
const declarations = new Map(); | ||
if (allFilesAreDeclarations) { | ||
@@ -107,3 +100,3 @@ // if all files are declarations we don't need to compile the project twice | ||
(0, check_diagnostics_errors_1.checkProgramDiagnosticsErrors)(program); | ||
var emitResult = program.emit(undefined, function (fileName, data) { return declarations.set((0, get_absolute_path_1.getAbsolutePath)(fileName), data); }, undefined, true); | ||
const emitResult = program.emit(undefined, (fileName, data) => declarations.set((0, get_absolute_path_1.getAbsolutePath)(fileName), data), undefined, true); | ||
(0, check_diagnostics_errors_1.checkDiagnosticsErrors)(emitResult.diagnostics, 'Errors while emitting declarations'); | ||
@@ -113,6 +106,10 @@ return declarations; | ||
function warnAboutTypeScriptFilesInProgram(program) { | ||
var nonDeclarationFiles = program.getSourceFiles().filter(function (file) { return !file.isDeclarationFile; }); | ||
const nonDeclarationFiles = program.getSourceFiles().filter((file) => !file.isDeclarationFile); | ||
if (nonDeclarationFiles.length !== 0) { | ||
(0, logger_1.warnLog)("WARNING: It seems that some files in the compilation still are not declaration files.\nFor more information see https://github.com/timocov/dts-bundle-generator/issues/53.\nIf you think this is a mistake, feel free to open new issue or just ignore this warning.\n ".concat(nonDeclarationFiles.map(function (file) { return file.fileName; }).join('\n '), "\n")); | ||
(0, logger_1.warnLog)(`WARNING: It seems that some files in the compilation still are not declaration files. | ||
For more information see https://github.com/timocov/dts-bundle-generator/issues/53. | ||
If you think this is a mistake, feel free to open new issue or just ignore this warning. | ||
${nonDeclarationFiles.map((file) => file.fileName).join('\n ')} | ||
`); | ||
} | ||
} |
@@ -11,3 +11,3 @@ "use strict"; | ||
}; | ||
var schemaRequiredValues = new Set([ | ||
const schemaRequiredValues = new Set([ | ||
exports.schemaPrimitiveValues.requiredBoolean, | ||
@@ -27,10 +27,10 @@ exports.schemaPrimitiveValues.requiredString, | ||
if (typeof schema === 'boolean' || typeof schema === 'string') { | ||
var schemeType = typeof schema; | ||
const schemeType = typeof schema; | ||
if (value === undefined && schemaRequiredValues.has(schema)) { | ||
errors.push("Value for \"".concat(prefix, "\" is required and must have type \"").concat(schemeType, "\"")); | ||
errors.push(`Value for "${prefix}" is required and must have type "${schemeType}"`); | ||
return false; | ||
} | ||
var valueType = typeof value; | ||
const valueType = typeof value; | ||
if (value !== undefined && typeof schema !== valueType) { | ||
errors.push("Type of values for \"".concat(prefix, "\" is not the same, expected=").concat(schemeType, ", actual=").concat(valueType)); | ||
errors.push(`Type of values for "${prefix}" is not the same, expected=${schemeType}, actual=${valueType}`); | ||
return false; | ||
@@ -47,21 +47,19 @@ } | ||
} | ||
var result_1 = true; | ||
for (var i = 0; i < value.length; ++i) { | ||
if (!checkSchemaMatchRecursively(value[i], schema[0], "".concat(prefix, "[").concat(i, "]"), errors)) { | ||
result_1 = false; | ||
let result = true; | ||
for (let i = 0; i < value.length; ++i) { | ||
if (!checkSchemaMatchRecursively(value[i], schema[0], `${prefix}[${i}]`, errors)) { | ||
result = false; | ||
} | ||
} | ||
return result_1; | ||
return result; | ||
} | ||
var result = true; | ||
for (var _i = 0, _a = Object.keys(value); _i < _a.length; _i++) { | ||
var valueKey = _a[_i]; | ||
let result = true; | ||
for (const valueKey of Object.keys(value)) { | ||
if (schema[valueKey] === undefined) { | ||
errors.push("Exceeded property \"".concat(valueKey, "\" found in ").concat(prefix.length === 0 ? 'the root' : prefix)); | ||
errors.push(`Exceeded property "${valueKey}" found in ${prefix.length === 0 ? 'the root' : prefix}`); | ||
result = false; | ||
} | ||
} | ||
for (var _b = 0, _c = Object.keys(schema); _b < _c.length; _b++) { | ||
var schemaKey = _c[_b]; | ||
var isSubValueSchemeMatched = checkSchemaMatchRecursively(value[schemaKey], schema[schemaKey], prefix.length === 0 ? schemaKey : "".concat(prefix, ".").concat(schemaKey), errors); | ||
for (const schemaKey of Object.keys(schema)) { | ||
const isSubValueSchemeMatched = checkSchemaMatchRecursively(value[schemaKey], schema[schemaKey], prefix.length === 0 ? schemaKey : `${prefix}.${schemaKey}`, errors); | ||
result = result && isSubValueSchemeMatched; | ||
@@ -68,0 +66,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.loadConfigFile = void 0; | ||
var path = require("path"); | ||
var logger_1 = require("../logger"); | ||
var get_absolute_path_1 = require("../helpers/get-absolute-path"); | ||
var check_schema_match_1 = require("./check-schema-match"); | ||
const path = require("path"); | ||
const logger_1 = require("../logger"); | ||
const get_absolute_path_1 = require("../helpers/get-absolute-path"); | ||
const check_schema_match_1 = require("./check-schema-match"); | ||
/** | ||
@@ -13,4 +13,4 @@ * @internal Do not output this function in generated dts for the npm package | ||
// eslint-disable-next-line @typescript-eslint/no-var-requires | ||
var possibleConfig = require((0, get_absolute_path_1.getAbsolutePath)(configPath)); | ||
var errors = []; | ||
const possibleConfig = require((0, get_absolute_path_1.getAbsolutePath)(configPath)); | ||
const errors = []; | ||
if (!(0, check_schema_match_1.checkSchemaMatch)(possibleConfig, configScheme, errors)) { | ||
@@ -23,4 +23,4 @@ (0, logger_1.errorLog)(errors.join('\n')); | ||
} | ||
var configFolder = path.dirname(configPath); | ||
possibleConfig.entries.forEach(function (entry) { | ||
const configFolder = path.dirname(configPath); | ||
possibleConfig.entries.forEach((entry) => { | ||
entry.filePath = (0, get_absolute_path_1.getAbsolutePath)(entry.filePath, configFolder); | ||
@@ -37,3 +37,3 @@ if (entry.outFile !== undefined) { | ||
exports.loadConfigFile = loadConfigFile; | ||
var configScheme = { | ||
const configScheme = { | ||
compilationOptions: { | ||
@@ -40,0 +40,0 @@ followSymlinks: check_schema_match_1.schemaPrimitiveValues.boolean, |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.generateOutput = void 0; | ||
var ts = require("typescript"); | ||
var typescript_1 = require("./helpers/typescript"); | ||
var package_version_1 = require("./helpers/package-version"); | ||
function generateOutput(params, options) { | ||
if (options === void 0) { options = {}; } | ||
var resultOutput = ''; | ||
const ts = require("typescript"); | ||
const package_version_1 = require("./helpers/package-version"); | ||
const typescript_1 = require("./helpers/typescript"); | ||
function generateOutput(params, options = {}) { | ||
let resultOutput = ''; | ||
if (!options.noBanner) { | ||
resultOutput += "// Generated by dts-bundle-generator v".concat((0, package_version_1.packageVersion)(), "\n\n"); | ||
resultOutput += `// Generated by dts-bundle-generator v${(0, package_version_1.packageVersion)()}\n\n`; | ||
} | ||
if (params.typesReferences.size !== 0) { | ||
var header = generateReferenceTypesDirective(Array.from(params.typesReferences)); | ||
resultOutput += "".concat(header, "\n\n"); | ||
const header = generateReferenceTypesDirective(Array.from(params.typesReferences)); | ||
resultOutput += `${header}\n\n`; | ||
} | ||
if (params.imports.size !== 0) { | ||
// we need to have sorted imports of libraries to have more "stable" output | ||
var sortedEntries = Array.from(params.imports.entries()).sort(function (firstEntry, secondEntry) { | ||
const sortedEntries = Array.from(params.imports.entries()).sort((firstEntry, secondEntry) => { | ||
return firstEntry[0].localeCompare(secondEntry[0]); | ||
}); | ||
var importsArray = []; | ||
for (var _i = 0, sortedEntries_1 = sortedEntries; _i < sortedEntries_1.length; _i++) { | ||
var _a = sortedEntries_1[_i], libraryName = _a[0], libraryImports = _a[1]; | ||
importsArray.push.apply(importsArray, generateImports(libraryName, libraryImports)); | ||
const importsArray = []; | ||
for (const [libraryName, libraryImports] of sortedEntries) { | ||
importsArray.push(...generateImports(libraryName, libraryImports)); | ||
} | ||
if (importsArray.length !== 0) { | ||
resultOutput += "".concat(importsArray.join('\n'), "\n\n"); | ||
resultOutput += `${importsArray.join('\n')}\n\n`; | ||
} | ||
} | ||
var statements = params.statements.map(function (statement) { return getStatementText(statement, params); }); | ||
const statements = params.statements.map((statement) => getStatementText(statement, Boolean(options.sortStatements), params)); | ||
if (options.sortStatements) { | ||
statements.sort(compareStatementText); | ||
} | ||
resultOutput += statementsTextToString(statements, params); | ||
resultOutput += statementsTextToString(statements); | ||
if (params.renamedExports.length !== 0) { | ||
resultOutput += "\n\nexport {\n\t".concat(params.renamedExports.sort().join(',\n\t'), ",\n};"); | ||
resultOutput += `\n\nexport {\n\t${params.renamedExports.sort().join(',\n\t')},\n};`; | ||
} | ||
if (options.umdModuleName !== undefined) { | ||
resultOutput += "\n\nexport as namespace ".concat(options.umdModuleName, ";"); | ||
resultOutput += `\n\nexport as namespace ${options.umdModuleName};`; | ||
} | ||
// this is used to prevent importing non-exported nodes | ||
// see https://stackoverflow.com/questions/52583603/intentional-that-export-shuts-off-automatic-export-of-all-symbols-from-a-ty | ||
resultOutput += "\n\nexport {};\n"; | ||
resultOutput += `\n\nexport {};\n`; | ||
return resultOutput; | ||
} | ||
exports.generateOutput = generateOutput; | ||
function statementTextToString(s) { | ||
if (s.leadingComment === undefined) { | ||
return s.text; | ||
} | ||
return "".concat(s.leadingComment, "\n").concat(s.text); | ||
function statementsTextToString(statements) { | ||
const statementsText = statements.map(statement => statement.text).join('\n'); | ||
return spacesToTabs(prettifyStatementsText(statementsText)); | ||
} | ||
function statementsTextToString(statements, helpers) { | ||
var statementsText = statements.map(statementTextToString).join('\n'); | ||
return spacesToTabs(prettifyStatementsText(statementsText, helpers)); | ||
} | ||
function prettifyStatementsText(statementsText, helpers) { | ||
var sourceFile = ts.createSourceFile('output.d.ts', statementsText, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS); | ||
var printer = ts.createPrinter({ | ||
function prettifyStatementsText(statementsText) { | ||
const sourceFile = ts.createSourceFile('output.d.ts', statementsText, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS); | ||
const printer = ts.createPrinter({ | ||
newLine: ts.NewLineKind.LineFeed, | ||
removeComments: false, | ||
}, { | ||
substituteNode: function (hint, node) { | ||
// `import('module').Qualifier` or `typeof import('module').Qualifier` | ||
if (ts.isImportTypeNode(node) && node.qualifier !== undefined && helpers.needStripImportFromImportTypeNode(node)) { | ||
if (node.isTypeOf) { | ||
// I personally don't like this solution because it spreads the logic of modifying nodes in the code | ||
// I'd prefer to have it somewhere near getStatementText or so | ||
// but at the moment it seems that it's the fastest and most easiest way to remove `import('./module').` form the code | ||
// if you read this and know how to make it better - feel free to share your ideas/PR with fixes | ||
// tslint:disable-next-line:deprecation | ||
return ts.createTypeQueryNode(node.qualifier); | ||
} | ||
return ts.createTypeReferenceNode(node.qualifier, node.typeArguments); | ||
} | ||
return node; | ||
}, | ||
}); | ||
@@ -83,6 +59,6 @@ return printer.printFile(sourceFile).trim(); | ||
function compareStatementText(a, b) { | ||
if (a.text > b.text) { | ||
if (a.sortingValue > b.sortingValue) { | ||
return 1; | ||
} | ||
else if (a.text < b.text) { | ||
else if (a.sortingValue < b.sortingValue) { | ||
return -1; | ||
@@ -92,62 +68,77 @@ } | ||
} | ||
function needAddDeclareKeyword(statement, nodeText) { | ||
// for some reason TypeScript allows to not write `declare` keyword for ClassDeclaration, FunctionDeclaration and VariableDeclaration | ||
// if it already has `export` keyword - so we need to add it | ||
// to avoid TS1046: Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier. | ||
if (ts.isClassDeclaration(statement) && (/^class\b/.test(nodeText) || /^abstract\b/.test(nodeText))) { | ||
return true; | ||
function getStatementText(statement, includeSortingValue, helpers) { | ||
const shouldStatementHasExportKeyword = helpers.shouldStatementHasExportKeyword(statement); | ||
const needStripDefaultKeyword = helpers.needStripDefaultKeywordForStatement(statement); | ||
const printer = ts.createPrinter({ | ||
newLine: ts.NewLineKind.LineFeed, | ||
removeComments: false, | ||
}, { | ||
// eslint-disable-next-line complexity | ||
substituteNode: (hint, node) => { | ||
// `import('module').Qualifier` or `typeof import('module').Qualifier` | ||
if (ts.isImportTypeNode(node) && node.qualifier !== undefined && helpers.needStripImportFromImportTypeNode(node)) { | ||
if (node.isTypeOf) { | ||
return ts.factory.createTypeQueryNode(node.qualifier); | ||
} | ||
return ts.factory.createTypeReferenceNode(node.qualifier, node.typeArguments); | ||
} | ||
if (node !== statement) { | ||
return node; | ||
} | ||
const modifiersMap = (0, typescript_1.modifiersToMap)((0, typescript_1.getModifiers)(node)); | ||
if (ts.isEnumDeclaration(node) | ||
&& modifiersMap[ts.SyntaxKind.ConstKeyword] | ||
&& helpers.needStripConstFromConstEnum(node)) { | ||
modifiersMap[ts.SyntaxKind.ConstKeyword] = false; | ||
} | ||
// strip the `default` keyword from node | ||
if (modifiersMap[ts.SyntaxKind.DefaultKeyword] && needStripDefaultKeyword) { | ||
// we need just to remove `default` from any node except class node | ||
// for classes we need to replace `default` with `declare` instead | ||
modifiersMap[ts.SyntaxKind.DefaultKeyword] = false; | ||
if (ts.isClassDeclaration(node)) { | ||
modifiersMap[ts.SyntaxKind.DeclareKeyword] = true; | ||
} | ||
} | ||
if (!shouldStatementHasExportKeyword) { | ||
modifiersMap[ts.SyntaxKind.ExportKeyword] = false; | ||
} | ||
else { | ||
modifiersMap[ts.SyntaxKind.ExportKeyword] = true; | ||
} | ||
// for some reason TypeScript allows to not write `declare` keyword for ClassDeclaration, FunctionDeclaration and VariableDeclaration | ||
// if it already has `export` keyword - so we need to add it | ||
// to avoid TS1046: Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier. | ||
if (!modifiersMap[ts.SyntaxKind.ExportKeyword] && | ||
(ts.isClassDeclaration(node) | ||
|| ts.isFunctionDeclaration(node) | ||
|| ts.isVariableStatement(node) | ||
|| ts.isEnumDeclaration(node))) { | ||
modifiersMap[ts.SyntaxKind.DeclareKeyword] = true; | ||
} | ||
return (0, typescript_1.recreateRootLevelNodeWithModifiers)(node, modifiersMap, shouldStatementHasExportKeyword); | ||
}, | ||
}); | ||
const statementText = printer.printNode(ts.EmitHint.Unspecified, statement, statement.getSourceFile()).trim(); | ||
let sortingValue = ''; | ||
if (includeSortingValue) { | ||
// it looks like there is no way to get node's text without a comment at the same time as printing it | ||
// so to get the actual node text we have to parse it again | ||
// hopefully it shouldn't take too long (we don't need to do type check, just parse the AST) | ||
// also let's do it opt-in so if someone isn't using node sorting it won't affect them | ||
const tempSourceFile = ts.createSourceFile('temp.d.ts', statementText, ts.ScriptTarget.ESNext); | ||
// we certainly know that there should be 1 statement at the root level (the printed statement) | ||
sortingValue = tempSourceFile.getChildren()[0].getText(); | ||
} | ||
if (ts.isFunctionDeclaration(statement) && /^function\b/.test(nodeText)) { | ||
return true; | ||
} | ||
if (ts.isVariableStatement(statement) && /^(const|let|var)\b/.test(nodeText)) { | ||
return true; | ||
} | ||
if (ts.isEnumDeclaration(statement) && (/^(const)\b/.test(nodeText) || /^(enum)\b/.test(nodeText))) { | ||
return true; | ||
} | ||
return false; | ||
return { text: statementText, sortingValue }; | ||
} | ||
function getStatementText(statement, helpers) { | ||
var shouldStatementHasExportKeyword = helpers.shouldStatementHasExportKeyword(statement); | ||
var needStripDefaultKeyword = helpers.needStripDefaultKeywordForStatement(statement); | ||
var hasStatementExportKeyword = ts.isExportAssignment(statement) || (0, typescript_1.hasNodeModifier)(statement, ts.SyntaxKind.ExportKeyword); | ||
var nodeText = getTextAccordingExport(statement.getText(), hasStatementExportKeyword, shouldStatementHasExportKeyword); | ||
if (ts.isEnumDeclaration(statement) | ||
&& (0, typescript_1.hasNodeModifier)(statement, ts.SyntaxKind.ConstKeyword) | ||
&& helpers.needStripConstFromConstEnum(statement)) { | ||
nodeText = nodeText.replace(/\bconst\s/, ''); | ||
} | ||
// strip the `default` keyword from node | ||
if ((0, typescript_1.hasNodeModifier)(statement, ts.SyntaxKind.DefaultKeyword) && needStripDefaultKeyword) { | ||
// we need just to remove `default` from any node except class node | ||
// for classes we need to replace `default` with `declare` instead | ||
nodeText = nodeText.replace(/\bdefault\s/, ts.isClassDeclaration(statement) ? 'declare ' : ''); | ||
} | ||
if (needAddDeclareKeyword(statement, nodeText)) { | ||
nodeText = "declare ".concat(nodeText); | ||
} | ||
var result = { | ||
text: nodeText, | ||
}; | ||
// add jsdoc for exported nodes only | ||
if (shouldStatementHasExportKeyword) { | ||
var start = statement.getStart(); | ||
var jsDocStart = statement.getStart(undefined, true); | ||
var nodeJSDoc = statement.getSourceFile().getFullText().substring(jsDocStart, start).trim(); | ||
if (nodeJSDoc.length !== 0) { | ||
result.leadingComment = nodeJSDoc; | ||
} | ||
} | ||
return result; | ||
} | ||
function generateImports(libraryName, imports) { | ||
var fromEnding = "from '".concat(libraryName, "';"); | ||
var result = []; | ||
const fromEnding = `from '${libraryName}';`; | ||
const result = []; | ||
// sort to make output more "stable" | ||
Array.from(imports.starImports).sort().forEach(function (importName) { return result.push("import * as ".concat(importName, " ").concat(fromEnding)); }); | ||
Array.from(imports.requireImports).sort().forEach(function (importName) { return result.push("import ".concat(importName, " = require('").concat(libraryName, "');")); }); | ||
Array.from(imports.defaultImports).sort().forEach(function (importName) { return result.push("import ".concat(importName, " ").concat(fromEnding)); }); | ||
Array.from(imports.starImports).sort().forEach((importName) => result.push(`import * as ${importName} ${fromEnding}`)); | ||
Array.from(imports.requireImports).sort().forEach((importName) => result.push(`import ${importName} = require('${libraryName}');`)); | ||
Array.from(imports.defaultImports).sort().forEach((importName) => result.push(`import ${importName} ${fromEnding}`)); | ||
if (imports.namedImports.size !== 0) { | ||
result.push("import { ".concat(Array.from(imports.namedImports).sort().join(', '), " } ").concat(fromEnding)); | ||
result.push(`import { ${Array.from(imports.namedImports).sort().join(', ')} } ${fromEnding}`); | ||
} | ||
@@ -157,20 +148,11 @@ return result; | ||
function generateReferenceTypesDirective(libraries) { | ||
return libraries.sort().map(function (library) { | ||
return "/// <reference types=\"".concat(library, "\" />"); | ||
return libraries.sort().map((library) => { | ||
return `/// <reference types="${library}" />`; | ||
}).join('\n'); | ||
} | ||
function getTextAccordingExport(nodeText, isNodeExported, shouldNodeBeExported) { | ||
if (shouldNodeBeExported && !isNodeExported) { | ||
return 'export ' + nodeText; | ||
} | ||
else if (isNodeExported && !shouldNodeBeExported) { | ||
return nodeText.slice('export '.length); | ||
} | ||
return nodeText; | ||
} | ||
function spacesToTabs(text) { | ||
// eslint-disable-next-line no-regex-spaces | ||
return text.replace(/^( )+/gm, function (substring) { | ||
return text.replace(/^( )+/gm, (substring) => { | ||
return '\t'.repeat(substring.length / 4); | ||
}); | ||
} |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getCompilerOptions = void 0; | ||
var ts = require("typescript"); | ||
var path = require("path"); | ||
var get_absolute_path_1 = require("./helpers/get-absolute-path"); | ||
var check_diagnostics_errors_1 = require("./helpers/check-diagnostics-errors"); | ||
var logger_1 = require("./logger"); | ||
var parseConfigHost = { | ||
const ts = require("typescript"); | ||
const path = require("path"); | ||
const get_absolute_path_1 = require("./helpers/get-absolute-path"); | ||
const check_diagnostics_errors_1 = require("./helpers/check-diagnostics-errors"); | ||
const logger_1 = require("./logger"); | ||
const parseConfigHost = { | ||
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames, | ||
@@ -16,11 +16,11 @@ readDirectory: ts.sys.readDirectory, | ||
function getCompilerOptions(inputFileNames, preferredConfigPath) { | ||
var configFileName = preferredConfigPath !== undefined ? preferredConfigPath : findConfig(inputFileNames); | ||
(0, logger_1.verboseLog)("Using config: ".concat(configFileName)); | ||
var configParseResult = ts.readConfigFile(configFileName, ts.sys.readFile); | ||
const configFileName = preferredConfigPath !== undefined ? preferredConfigPath : findConfig(inputFileNames); | ||
(0, logger_1.verboseLog)(`Using config: ${configFileName}`); | ||
const configParseResult = ts.readConfigFile(configFileName, ts.sys.readFile); | ||
(0, check_diagnostics_errors_1.checkDiagnosticsErrors)(configParseResult.error !== undefined ? [configParseResult.error] : [], 'Error while processing tsconfig file'); | ||
var compilerOptionsParseResult = ts.parseJsonConfigFileContent(configParseResult.config, parseConfigHost, path.resolve(path.dirname(configFileName)), undefined, (0, get_absolute_path_1.getAbsolutePath)(configFileName)); | ||
const compilerOptionsParseResult = ts.parseJsonConfigFileContent(configParseResult.config, parseConfigHost, path.resolve(path.dirname(configFileName)), undefined, (0, get_absolute_path_1.getAbsolutePath)(configFileName)); | ||
// we don't want to raise an error if no inputs found in a config file | ||
// because this error is mostly for CLI, but we'll pass an inputs in createProgram | ||
var diagnostics = compilerOptionsParseResult.errors | ||
.filter(function (d) { return d.code !== 18003 /* Constants.NoInputsWereFoundDiagnosticCode */; }); | ||
const diagnostics = compilerOptionsParseResult.errors | ||
.filter((d) => d.code !== 18003 /* Constants.NoInputsWereFoundDiagnosticCode */); | ||
(0, check_diagnostics_errors_1.checkDiagnosticsErrors)(diagnostics, 'Error while processing tsconfig compiler options'); | ||
@@ -37,8 +37,8 @@ return compilerOptionsParseResult.options; | ||
// so we have to provide absolute path to find config until the root | ||
var searchPath = (0, get_absolute_path_1.getAbsolutePath)(inputFiles[0]); | ||
var configFileName = ts.findConfigFile(searchPath, ts.sys.fileExists); | ||
const searchPath = (0, get_absolute_path_1.getAbsolutePath)(inputFiles[0]); | ||
const configFileName = ts.findConfigFile(searchPath, ts.sys.fileExists); | ||
if (!configFileName) { | ||
throw new Error("Cannot find config file for file ".concat(searchPath)); | ||
throw new Error(`Cannot find config file for file ${searchPath}`); | ||
} | ||
return configFileName; | ||
} |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.checkDiagnosticsErrors = exports.checkProgramDiagnosticsErrors = void 0; | ||
var ts = require("typescript"); | ||
var logger_1 = require("../logger"); | ||
var formatDiagnosticsHost = { | ||
getCanonicalFileName: function (fileName) { return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); }, | ||
const ts = require("typescript"); | ||
const logger_1 = require("../logger"); | ||
const formatDiagnosticsHost = { | ||
getCanonicalFileName: (fileName) => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(), | ||
getCurrentDirectory: ts.sys.getCurrentDirectory, | ||
getNewLine: function () { return ts.sys.newLine; }, | ||
getNewLine: () => ts.sys.newLine, | ||
}; | ||
@@ -11,0 +11,0 @@ function checkProgramDiagnosticsErrors(program) { |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getAbsolutePath = void 0; | ||
var path = require("path"); | ||
var process = require("process"); | ||
var fix_path_1 = require("./fix-path"); | ||
const path = require("path"); | ||
const process = require("process"); | ||
const fix_path_1 = require("./fix-path"); | ||
function getAbsolutePath(fileName, cwd) { | ||
@@ -8,0 +8,0 @@ if (!path.isAbsolute(fileName)) { |
@@ -9,5 +9,5 @@ "use strict"; | ||
function measureTime(func) { | ||
var startAt = process.hrtime(); | ||
const startAt = process.hrtime(); | ||
func(); | ||
var resultValue = process.hrtime(startAt); | ||
const resultValue = process.hrtime(startAt); | ||
return secondsToMs(resultValue[0]) + nanosecondsToMs(resultValue[1]); | ||
@@ -14,0 +14,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getTypesLibraryName = exports.getLibraryName = void 0; | ||
var nodeModulesFolderName = 'node_modules/'; | ||
var libraryNameRegex = /node_modules\/((?:(?=@)[^/]+\/[^/]+|[^/]+))\//; | ||
const nodeModulesFolderName = 'node_modules/'; | ||
const libraryNameRegex = /node_modules\/((?:(?=@)[^/]+\/[^/]+|[^/]+))\//; | ||
function getLibraryName(fileName) { | ||
var lastNodeModulesIndex = fileName.lastIndexOf(nodeModulesFolderName); | ||
const lastNodeModulesIndex = fileName.lastIndexOf(nodeModulesFolderName); | ||
if (lastNodeModulesIndex === -1) { | ||
return null; | ||
} | ||
var match = libraryNameRegex.exec(fileName.slice(lastNodeModulesIndex)); | ||
const match = libraryNameRegex.exec(fileName.slice(lastNodeModulesIndex)); | ||
if (match === null) { | ||
@@ -19,7 +19,7 @@ return null; | ||
function getTypesLibraryName(path) { | ||
var libraryName = getLibraryName(path); | ||
const libraryName = getLibraryName(path); | ||
if (libraryName === null) { | ||
return null; | ||
} | ||
var typesFolderPrefix = '@types/'; | ||
const typesFolderPrefix = '@types/'; | ||
if (!libraryName.startsWith(typesFolderPrefix)) { | ||
@@ -26,0 +26,0 @@ return null; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.packageVersion = void 0; | ||
var fs = require("fs"); | ||
var path = require("path"); | ||
const fs = require("fs"); | ||
const path = require("path"); | ||
function packageVersion() { | ||
var dirName = __dirname; | ||
let dirName = __dirname; | ||
while (dirName.length !== 0) { | ||
var packageJsonFilePath = path.join(dirName, 'package.json'); | ||
const packageJsonFilePath = path.join(dirName, 'package.json'); | ||
if (fs.existsSync(packageJsonFilePath)) { | ||
@@ -16,4 +16,4 @@ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-var-requires | ||
} | ||
throw new Error("Cannot find up package.json in ".concat(__dirname)); | ||
throw new Error(`Cannot find up package.json in ${__dirname}`); | ||
} | ||
exports.packageVersion = packageVersion; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isNamedTupleMember = exports.getExportsForStatement = exports.resolveIdentifier = exports.getExportsForSourceFile = exports.getDeclarationsForSymbol = exports.isNamespaceStatement = exports.isDeclareGlobalStatement = exports.isDeclareModule = exports.isAmbientModule = exports.splitTransientSymbol = exports.getDeclarationNameSymbol = exports.getActualSymbol = exports.getNodeName = exports.hasNodeModifier = exports.isNodeNamedDeclaration = void 0; | ||
var ts = require("typescript"); | ||
var namedDeclarationKinds = [ | ||
exports.getModifiers = exports.recreateRootLevelNodeWithModifiers = exports.modifiersMapToArray = exports.modifiersToMap = exports.getExportsForStatement = exports.resolveIdentifier = exports.getExportsForSourceFile = exports.getDeclarationsForSymbol = exports.isNamespaceStatement = exports.isDeclareGlobalStatement = exports.isDeclareModule = exports.isAmbientModule = exports.splitTransientSymbol = exports.getDeclarationNameSymbol = exports.getActualSymbol = exports.getNodeName = exports.hasNodeModifier = exports.isNodeNamedDeclaration = void 0; | ||
const ts = require("typescript"); | ||
const namedDeclarationKinds = [ | ||
ts.SyntaxKind.InterfaceDeclaration, | ||
@@ -20,10 +20,11 @@ ts.SyntaxKind.ClassDeclaration, | ||
function hasNodeModifier(node, modifier) { | ||
return Boolean(node.modifiers && node.modifiers.some(function (nodeModifier) { return nodeModifier.kind === modifier; })); | ||
const modifiers = getModifiers(node); | ||
return Boolean(modifiers && modifiers.some((nodeModifier) => nodeModifier.kind === modifier)); | ||
} | ||
exports.hasNodeModifier = hasNodeModifier; | ||
function getNodeName(node) { | ||
var _a; | ||
var nodeName = node.name; | ||
const nodeName = node.name; | ||
if (nodeName === undefined) { | ||
var defaultModifier = (_a = node.modifiers) === null || _a === void 0 ? void 0 : _a.find(function (mod) { return mod.kind === ts.SyntaxKind.DefaultKeyword; }); | ||
const modifiers = getModifiers(node); | ||
const defaultModifier = modifiers?.find((mod) => mod.kind === ts.SyntaxKind.DefaultKeyword); | ||
if (defaultModifier !== undefined) { | ||
@@ -44,3 +45,3 @@ return defaultModifier; | ||
function getDeclarationNameSymbol(name, typeChecker) { | ||
var symbol = typeChecker.getSymbolAtLocation(name); | ||
const symbol = typeChecker.getSymbolAtLocation(name); | ||
if (symbol === undefined) { | ||
@@ -63,10 +64,9 @@ return null; | ||
// but it seems that it works for now ¯\_(ツ)_/¯ | ||
var declarations = getDeclarationsForSymbol(symbol); | ||
var result = []; | ||
for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { | ||
var declaration = declarations_1[_i]; | ||
const declarations = getDeclarationsForSymbol(symbol); | ||
const result = []; | ||
for (const declaration of declarations) { | ||
if (!isNodeNamedDeclaration(declaration) || declaration.name === undefined) { | ||
continue; | ||
} | ||
var sym = typeChecker.getSymbolAtLocation(declaration.name); | ||
const sym = typeChecker.getSymbolAtLocation(declaration.name); | ||
if (sym === undefined) { | ||
@@ -118,10 +118,6 @@ continue; | ||
function getDeclarationsForSymbol(symbol) { | ||
var result = []; | ||
// Disabling tslint is for backward compat with TypeScript < 3 | ||
// tslint:disable-next-line:strict-type-predicates | ||
const result = []; | ||
if (symbol.declarations !== undefined) { | ||
result.push.apply(result, symbol.declarations); | ||
result.push(...symbol.declarations); | ||
} | ||
// Disabling tslint is for backward compat with TypeScript < 3 | ||
// tslint:disable-next-line:strict-type-predicates | ||
if (symbol.valueDeclaration !== undefined) { | ||
@@ -139,8 +135,8 @@ // push valueDeclaration might be already in declarations array | ||
if (sourceFileSymbol.exports !== undefined) { | ||
var commonJsExport = sourceFileSymbol.exports.get(ts.InternalSymbolName.ExportEquals); | ||
const commonJsExport = sourceFileSymbol.exports.get(ts.InternalSymbolName.ExportEquals); | ||
if (commonJsExport !== undefined) { | ||
var symbol = getActualSymbol(commonJsExport, typeChecker); | ||
const symbol = getActualSymbol(commonJsExport, typeChecker); | ||
return [ | ||
{ | ||
symbol: symbol, | ||
symbol, | ||
type: 0 /* ExportType.CommonJS */, | ||
@@ -153,9 +149,9 @@ exportedName: '', | ||
} | ||
var result = typeChecker | ||
const result = typeChecker | ||
.getExportsOfModule(sourceFileSymbol) | ||
.map(function (symbol) { return ({ symbol: symbol, exportedName: symbol.escapedName, type: 1 /* ExportType.ES6Named */, originalName: '' }); }); | ||
.map((symbol) => ({ symbol, exportedName: symbol.escapedName, type: 1 /* ExportType.ES6Named */, originalName: '' })); | ||
if (sourceFileSymbol.exports !== undefined) { | ||
var defaultExportSymbol_1 = sourceFileSymbol.exports.get(ts.InternalSymbolName.Default); | ||
if (defaultExportSymbol_1 !== undefined) { | ||
var defaultExport = result.find(function (exp) { return exp.symbol === defaultExportSymbol_1; }); | ||
const defaultExportSymbol = sourceFileSymbol.exports.get(ts.InternalSymbolName.Default); | ||
if (defaultExportSymbol !== undefined) { | ||
const defaultExport = result.find((exp) => exp.symbol === defaultExportSymbol); | ||
if (defaultExport !== undefined) { | ||
@@ -168,3 +164,3 @@ defaultExport.type = 2 /* ExportType.ES6Default */; | ||
result.push({ | ||
symbol: defaultExportSymbol_1, | ||
symbol: defaultExportSymbol, | ||
type: 2 /* ExportType.ES6Default */, | ||
@@ -177,5 +173,5 @@ exportedName: 'default', | ||
} | ||
result.forEach(function (exp) { | ||
result.forEach((exp) => { | ||
exp.symbol = getActualSymbol(exp.symbol, typeChecker); | ||
var resolvedIdentifier = resolveIdentifierBySymbol(exp.symbol); | ||
const resolvedIdentifier = resolveIdentifierBySymbol(exp.symbol); | ||
exp.originalName = resolvedIdentifier !== undefined ? resolvedIdentifier.getText() : exp.symbol.escapedName; | ||
@@ -187,3 +183,3 @@ }); | ||
function resolveIdentifier(typeChecker, identifier) { | ||
var symbol = getDeclarationNameSymbol(identifier, typeChecker); | ||
const symbol = getDeclarationNameSymbol(identifier, typeChecker); | ||
if (symbol === null) { | ||
@@ -196,7 +192,7 @@ return undefined; | ||
function resolveIdentifierBySymbol(identifierSymbol) { | ||
var declarations = getDeclarationsForSymbol(identifierSymbol); | ||
const declarations = getDeclarationsForSymbol(identifierSymbol); | ||
if (declarations.length === 0) { | ||
return undefined; | ||
} | ||
var decl = declarations[0]; | ||
const decl = declarations[0]; | ||
if (!isNodeNamedDeclaration(decl)) { | ||
@@ -212,8 +208,7 @@ return undefined; | ||
} | ||
var firstDeclarationExports_1 = getExportsForName(exportedSymbols, typeChecker, statement.declarationList.declarations[0].name); | ||
var allDeclarationsHaveSameExportType = statement.declarationList.declarations.every(function (variableDecl) { | ||
var _a, _b; | ||
const firstDeclarationExports = getExportsForName(exportedSymbols, typeChecker, statement.declarationList.declarations[0].name); | ||
const allDeclarationsHaveSameExportType = statement.declarationList.declarations.every((variableDecl) => { | ||
// all declaration should have the same export type | ||
// TODO: for now it's not supported to have different type of exports | ||
return ((_a = getExportsForName(exportedSymbols, typeChecker, variableDecl.name)[0]) === null || _a === void 0 ? void 0 : _a.type) === ((_b = firstDeclarationExports_1[0]) === null || _b === void 0 ? void 0 : _b.type); | ||
return getExportsForName(exportedSymbols, typeChecker, variableDecl.name)[0]?.type === firstDeclarationExports[0]?.type; | ||
}); | ||
@@ -224,5 +219,5 @@ if (!allDeclarationsHaveSameExportType) { | ||
} | ||
return firstDeclarationExports_1; | ||
return firstDeclarationExports; | ||
} | ||
var nodeName = getNodeName(statement); | ||
const nodeName = getNodeName(statement); | ||
if (nodeName === undefined) { | ||
@@ -240,13 +235,143 @@ return []; | ||
} | ||
var declarationSymbol = typeChecker.getSymbolAtLocation(name); | ||
return exportedSymbols.filter(function (rootExport) { return rootExport.symbol === declarationSymbol; }); | ||
const declarationSymbol = typeChecker.getSymbolAtLocation(name); | ||
return exportedSymbols.filter((rootExport) => rootExport.symbol === declarationSymbol); | ||
} | ||
function isNamedTupleMember(node) { | ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion | ||
var compatTs = ts; | ||
if (!compatTs.isNamedTupleMember) { | ||
return false; | ||
const modifiersPriority = { | ||
[ts.SyntaxKind.ExportKeyword]: 4, | ||
[ts.SyntaxKind.DefaultKeyword]: 3, | ||
[ts.SyntaxKind.DeclareKeyword]: 2, | ||
[ts.SyntaxKind.AsyncKeyword]: 1, | ||
[ts.SyntaxKind.ConstKeyword]: 1, | ||
}; | ||
function modifiersToMap(modifiers) { | ||
modifiers = modifiers || []; | ||
return modifiers.reduce((result, modifier) => { | ||
result[modifier.kind] = true; | ||
return result; | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions | ||
{}); | ||
} | ||
exports.modifiersToMap = modifiersToMap; | ||
function modifiersMapToArray(modifiersMap) { | ||
return Object.entries(modifiersMap) | ||
.filter(([kind, include]) => include) | ||
.map(([kind]) => { | ||
// we don't care about decorators here as it is not possible to have them in declaration files | ||
return ts.factory.createModifier(Number(kind)); | ||
}) | ||
.sort((a, b) => { | ||
// note `|| 0` is here as a fallback in the case if the compiler adds a new modifier | ||
// but the tool isn't updated yet | ||
const aValue = modifiersPriority[a.kind] || 0; | ||
const bValue = modifiersPriority[b.kind] || 0; | ||
return bValue - aValue; | ||
}); | ||
} | ||
exports.modifiersMapToArray = modifiersMapToArray; | ||
function recreateRootLevelNodeWithModifiers(node, modifiersMap, keepComments = true) { | ||
const newNode = recreateRootLevelNodeWithModifiersImpl(node, modifiersMap); | ||
if (keepComments) { | ||
ts.setCommentRange(newNode, ts.getCommentRange(node)); | ||
} | ||
return compatTs.isNamedTupleMember(node); | ||
return newNode; | ||
} | ||
exports.isNamedTupleMember = isNamedTupleMember; | ||
exports.recreateRootLevelNodeWithModifiers = recreateRootLevelNodeWithModifiers; | ||
function prependEmptyDecoratorsIfNeeded(func, ...args) { | ||
const tsVersion = parseFloat(ts.versionMajorMinor); | ||
if (tsVersion < 4.8) { | ||
// decorators don't exist in the declaration files anyway so we can ignore them | ||
return func([], ...args); | ||
} | ||
else { | ||
// just pass args as is in | ||
// eslint-disable-next-line prefer-spread | ||
return func.apply(null, args); | ||
} | ||
} | ||
// eslint-disable-next-line complexity | ||
function recreateRootLevelNodeWithModifiersImpl(node, modifiersMap) { | ||
const modifiers = modifiersMapToArray(modifiersMap); | ||
if (ts.isArrowFunction(node)) { | ||
return ts.factory.createArrowFunction(modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body); | ||
} | ||
if (ts.isClassDeclaration(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createClassDeclaration, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members); | ||
} | ||
if (ts.isClassExpression(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createClassExpression, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members); | ||
} | ||
if (ts.isEnumDeclaration(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createEnumDeclaration, modifiers, node.name, node.members); | ||
} | ||
if (ts.isExportAssignment(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createExportAssignment, modifiers, node.isExportEquals, node.expression); | ||
} | ||
if (ts.isExportDeclaration(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createExportDeclaration, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause); | ||
} | ||
if (ts.isFunctionDeclaration(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createFunctionDeclaration, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); | ||
} | ||
if (ts.isFunctionExpression(node)) { | ||
return ts.factory.createFunctionExpression(modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); | ||
} | ||
if (ts.isImportDeclaration(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createImportDeclaration, modifiers, node.importClause, node.moduleSpecifier, node.assertClause); | ||
} | ||
if (ts.isImportEqualsDeclaration(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createImportEqualsDeclaration, modifiers, node.isTypeOnly, node.name, node.moduleReference); | ||
} | ||
if (ts.isInterfaceDeclaration(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createInterfaceDeclaration, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members); | ||
} | ||
if (ts.isModuleDeclaration(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createModuleDeclaration, modifiers, node.name, node.body, node.flags); | ||
} | ||
if (ts.isTypeAliasDeclaration(node)) { | ||
return prependEmptyDecoratorsIfNeeded( | ||
// eslint-disable-next-line deprecation/deprecation | ||
ts.factory.createTypeAliasDeclaration, modifiers, node.name, node.typeParameters, node.type); | ||
} | ||
if (ts.isVariableStatement(node)) { | ||
return ts.factory.createVariableStatement(modifiers, node.declarationList); | ||
} | ||
throw new Error(`Unknown top-level node kind (with modifiers): ${ts.SyntaxKind[node.kind]}. | ||
If you're seeing this error, please report a bug on https://github.com/timocov/dts-bundle-generator/issues`); | ||
} | ||
function canHaveModifiersCompat(node) { | ||
const compatTs = ts; | ||
return compatTs.canHaveModifiers !== undefined ? compatTs.canHaveModifiers(node) : true; | ||
} | ||
function getModifiersCompat(node) { | ||
const compatTs = ts; | ||
// eslint-disable-next-line deprecation/deprecation | ||
return compatTs.getModifiers !== undefined ? compatTs.getModifiers(node) : node.modifiers; | ||
} | ||
function getModifiers(node) { | ||
if (!canHaveModifiersCompat(node)) { | ||
throw new Error(`Node kind=${ts.SyntaxKind[node.kind]} cannot have modifiers`); | ||
} | ||
return getModifiersCompat(node); | ||
} | ||
exports.getModifiers = getModifiers; |
@@ -20,3 +20,3 @@ "use strict"; | ||
exports.errorLog = errorLog; | ||
var currentLogLevel = 3 /* LogLevel.Error */; | ||
let currentLogLevel = 3 /* LogLevel.Error */; | ||
function enableVerbose() { | ||
@@ -31,4 +31,3 @@ currentLogLevel = 0 /* LogLevel.Verbose */; | ||
exports.enableNormalLog = enableNormalLog; | ||
function logMessage(message, level) { | ||
if (level === void 0) { level = 0 /* LogLevel.Verbose */; } | ||
function logMessage(message, level = 0 /* LogLevel.Verbose */) { | ||
if (level < currentLogLevel) { | ||
@@ -41,7 +40,7 @@ return; | ||
// eslint-disable-next-line no-console | ||
console.error("\u001B[0;31m".concat(message, "\u001B[0m")); | ||
console.error(`\x1b[0;31m${message}\x1b[0m`); | ||
break; | ||
case 2 /* LogLevel.Warning */: | ||
// eslint-disable-next-line no-console | ||
console.warn("\u001B[1;33m".concat(message, "\u001B[0m")); | ||
console.warn(`\x1b[1;33m${message}\x1b[0m`); | ||
break; | ||
@@ -48,0 +47,0 @@ case 1 /* LogLevel.Normal */: |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getModuleInfo = void 0; | ||
var path = require("path"); | ||
var node_modules_1 = require("./helpers/node-modules"); | ||
var fix_path_1 = require("./helpers/fix-path"); | ||
const path = require("path"); | ||
const node_modules_1 = require("./helpers/node-modules"); | ||
const fix_path_1 = require("./helpers/fix-path"); | ||
function getModuleInfo(fileName, criteria) { | ||
@@ -17,8 +17,7 @@ return getModuleInfoImpl(fileName, fileName, criteria); | ||
function getModuleInfoImpl(currentFilePath, originalFileName, criteria) { | ||
var npmLibraryName = (0, node_modules_1.getLibraryName)(currentFilePath); | ||
const npmLibraryName = (0, node_modules_1.getLibraryName)(currentFilePath); | ||
if (npmLibraryName === null) { | ||
if (criteria.typeRoots !== undefined) { | ||
for (var _i = 0, _a = criteria.typeRoots; _i < _a.length; _i++) { | ||
var root = _a[_i]; | ||
var relativePath = (0, fix_path_1.fixPath)(path.relative(root, originalFileName)); | ||
for (const root of criteria.typeRoots) { | ||
const relativePath = (0, fix_path_1.fixPath)(path.relative(root, originalFileName)); | ||
if (!relativePath.startsWith('../')) { | ||
@@ -33,3 +32,3 @@ // relativePath is path relative to type root | ||
} | ||
var typesLibraryName = (0, node_modules_1.getTypesLibraryName)(currentFilePath); | ||
const typesLibraryName = (0, node_modules_1.getTypesLibraryName)(currentFilePath); | ||
if (shouldLibraryBeInlined(npmLibraryName, typesLibraryName, criteria.inlinedLibraries)) { | ||
@@ -42,3 +41,3 @@ return { type: 0 /* ModuleType.ShouldBeInlined */, fileName: originalFileName, isExternal: true }; | ||
if (typesLibraryName !== null && isLibraryAllowed(typesLibraryName, criteria.allowedTypesLibraries)) { | ||
return { type: 2 /* ModuleType.ShouldBeReferencedAsTypes */, fileName: originalFileName, typesLibraryName: typesLibraryName, isExternal: true }; | ||
return { type: 2 /* ModuleType.ShouldBeReferencedAsTypes */, fileName: originalFileName, typesLibraryName, isExternal: true }; | ||
} | ||
@@ -66,3 +65,3 @@ return { type: 3 /* ModuleType.ShouldBeUsedForModulesOnly */, fileName: originalFileName, isExternal: true }; | ||
function remapToTypesFromNodeModules(pathRelativeToTypesRoot) { | ||
return "node_modules/@types/".concat(pathRelativeToTypesRoot); | ||
return `node_modules/@types/${pathRelativeToTypesRoot}`; | ||
} |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.TypesUsageEvaluator = void 0; | ||
var ts = require("typescript"); | ||
var typescript_1 = require("./helpers/typescript"); | ||
var TypesUsageEvaluator = /** @class */ (function () { | ||
function TypesUsageEvaluator(files, typeChecker) { | ||
const ts = require("typescript"); | ||
const typescript_1 = require("./helpers/typescript"); | ||
class TypesUsageEvaluator { | ||
constructor(files, typeChecker) { | ||
this.nodesParentsMap = new Map(); | ||
@@ -12,16 +12,15 @@ this.typeChecker = typeChecker; | ||
} | ||
TypesUsageEvaluator.prototype.isSymbolUsedBySymbol = function (symbol, by) { | ||
isSymbolUsedBySymbol(symbol, by) { | ||
return this.isSymbolUsedBySymbolImpl(this.getActualSymbol(symbol), this.getActualSymbol(by), new Set()); | ||
}; | ||
TypesUsageEvaluator.prototype.getSymbolsUsingSymbol = function (symbol) { | ||
} | ||
getSymbolsUsingSymbol(symbol) { | ||
return this.nodesParentsMap.get(this.getActualSymbol(symbol)) || null; | ||
}; | ||
TypesUsageEvaluator.prototype.isSymbolUsedBySymbolImpl = function (fromSymbol, toSymbol, visitedSymbols) { | ||
} | ||
isSymbolUsedBySymbolImpl(fromSymbol, toSymbol, visitedSymbols) { | ||
if (fromSymbol === toSymbol) { | ||
return true; | ||
} | ||
var reachableNodes = this.nodesParentsMap.get(fromSymbol); | ||
const reachableNodes = this.nodesParentsMap.get(fromSymbol); | ||
if (reachableNodes !== undefined) { | ||
for (var _i = 0, _a = Array.from(reachableNodes); _i < _a.length; _i++) { | ||
var symbol = _a[_i]; | ||
for (const symbol of Array.from(reachableNodes)) { | ||
if (visitedSymbols.has(symbol)) { | ||
@@ -38,14 +37,12 @@ continue; | ||
return false; | ||
}; | ||
TypesUsageEvaluator.prototype.computeUsages = function (files) { | ||
} | ||
computeUsages(files) { | ||
this.nodesParentsMap.clear(); | ||
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { | ||
var file = files_1[_i]; | ||
for (const file of files) { | ||
ts.forEachChild(file, this.computeUsageForNode.bind(this)); | ||
} | ||
}; | ||
TypesUsageEvaluator.prototype.computeUsageForNode = function (node) { | ||
} | ||
computeUsageForNode(node) { | ||
if ((0, typescript_1.isDeclareModule)(node) && node.body !== undefined && ts.isModuleBlock(node.body)) { | ||
for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { | ||
var statement = _a[_i]; | ||
for (const statement of node.body.statements) { | ||
this.computeUsageForNode(statement); | ||
@@ -55,31 +52,28 @@ } | ||
else if ((0, typescript_1.isNodeNamedDeclaration)(node) && node.name) { | ||
var childSymbol = this.getSymbol(node.name); | ||
const childSymbol = this.getSymbol(node.name); | ||
this.computeUsagesRecursively(node, childSymbol); | ||
} | ||
else if (ts.isVariableStatement(node)) { | ||
for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) { | ||
var varDeclaration = _c[_b]; | ||
for (const varDeclaration of node.declarationList.declarations) { | ||
this.computeUsageForNode(varDeclaration); | ||
} | ||
} | ||
}; | ||
TypesUsageEvaluator.prototype.computeUsagesRecursively = function (parent, parentSymbol) { | ||
var queue = parent.getChildren(); | ||
for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { | ||
var child = queue_1[_i]; | ||
} | ||
computeUsagesRecursively(parent, parentSymbol) { | ||
const queue = parent.getChildren(); | ||
for (const child of queue) { | ||
// eslint-disable-next-line deprecation/deprecation | ||
if (child.kind === ts.SyntaxKind.JSDocComment) { | ||
continue; | ||
} | ||
queue.push.apply(queue, child.getChildren()); | ||
queue.push(...child.getChildren()); | ||
if (ts.isIdentifier(child)) { | ||
// identifiers in labelled tuples don't have symbols for their labels | ||
// so let's just skip them from collecting | ||
// since this feature is for TypeScript > 4, we have to check that a function exist before accessing it | ||
if ((0, typescript_1.isNamedTupleMember)(child.parent) && child.parent.name === child) { | ||
if (ts.isNamedTupleMember(child.parent) && child.parent.name === child) { | ||
continue; | ||
} | ||
var childSymbols = (0, typescript_1.splitTransientSymbol)(this.getSymbol(child), this.typeChecker); | ||
for (var _a = 0, childSymbols_1 = childSymbols; _a < childSymbols_1.length; _a++) { | ||
var childSymbol = childSymbols_1[_a]; | ||
var symbols = this.nodesParentsMap.get(childSymbol); | ||
const childSymbols = (0, typescript_1.splitTransientSymbol)(this.getSymbol(child), this.typeChecker); | ||
for (const childSymbol of childSymbols) { | ||
let symbols = this.nodesParentsMap.get(childSymbol); | ||
if (symbols === undefined) { | ||
@@ -96,15 +90,14 @@ symbols = new Set(); | ||
} | ||
}; | ||
TypesUsageEvaluator.prototype.getSymbol = function (node) { | ||
var nodeSymbol = this.typeChecker.getSymbolAtLocation(node); | ||
} | ||
getSymbol(node) { | ||
const nodeSymbol = this.typeChecker.getSymbolAtLocation(node); | ||
if (nodeSymbol === undefined) { | ||
throw new Error("Cannot find symbol for node: ".concat(node.getText())); | ||
throw new Error(`Cannot find symbol for node: ${node.getText()}`); | ||
} | ||
return this.getActualSymbol(nodeSymbol); | ||
}; | ||
TypesUsageEvaluator.prototype.getActualSymbol = function (symbol) { | ||
} | ||
getActualSymbol(symbol) { | ||
return (0, typescript_1.getActualSymbol)(symbol, this.typeChecker); | ||
}; | ||
return TypesUsageEvaluator; | ||
}()); | ||
} | ||
} | ||
exports.TypesUsageEvaluator = TypesUsageEvaluator; |
{ | ||
"name": "dts-bundle-generator", | ||
"version": "6.13.0", | ||
"version": "7.0.0", | ||
"description": "DTS Bundle Generator", | ||
@@ -19,4 +19,4 @@ "main": "dist/bundle-generator.js", | ||
"dependencies": { | ||
"typescript": ">=3.0.1", | ||
"yargs": "^17.2.1" | ||
"typescript": ">=4.5.2", | ||
"yargs": "^17.6.0" | ||
}, | ||
@@ -30,4 +30,4 @@ "license": "MIT", | ||
"engines": { | ||
"node": ">=12.0.0" | ||
"node": ">=14.0.0" | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
109198
2086
52175
Updatedtypescript@>=4.5.2
Updatedyargs@^17.6.0