@compodoc/compodoc
Version:
The missing documentation tool for your Angular application
1,274 lines (1,260 loc) • 2.21 MB
JavaScript
'use strict';
var logger = require('./logger-kbUbohEP.js');
var fs = require('fs-extra');
var path = require('path');
var tsMorph = require('ts-morph');
var LiveServer = require('@compodoc/live-server');
var _ = require('lodash');
var ts = require('typescript');
var semver = require('semver');
var JSON5 = require('json5');
var htmlEntities = require('html-entities');
var cheerio = require('cheerio');
var uuid = require('uuid');
var cosmiconfig = require('cosmiconfig');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
var LiveServer__namespace = /*#__PURE__*/_interopNamespaceDefault(LiveServer);
var ___namespace = /*#__PURE__*/_interopNamespaceDefault(_);
var ts__namespace = /*#__PURE__*/_interopNamespaceDefault(ts);
var semver__namespace = /*#__PURE__*/_interopNamespaceDefault(semver);
var JSON5__namespace = /*#__PURE__*/_interopNamespaceDefault(JSON5);
var cheerio__namespace = /*#__PURE__*/_interopNamespaceDefault(cheerio);
var COMPODOC_DEFAULTS = {
title: 'Application documentation',
additionalEntryName: 'Additional documentation',
additionalEntryPath: 'additional-documentation',
folder: './documentation/',
hostname: '127.0.0.1',
port: 8080,
theme: 'gitbook',
exportFormat: 'html',
exportFormatsSupported: ['html', 'json'],
base: '/',
defaultCoverageThreshold: 70,
defaultCoverageMinimumPerFile: 0,
coverageTestThresholdFail: true,
toggleMenuItems: ['all'],
navTabConfig: [],
disableSearch: false,
disableSourceCode: false,
disableDomTree: false,
disableTemplateTab: false,
disableStyleTab: false,
disableGraph: false,
disableMainGraph: false,
disableCoverage: false,
disablePrivate: false,
disableProtected: false,
disableInternal: false,
disableLifeCycleHooks: false,
disableConstructors: false,
disableRoutesGraph: false,
disableDependencies: false,
disableProperties: false,
disableFilePath: false,
disableOverview: false,
hideGenerator: false,
hideDarkModeToggle: false,
minimal: false,
silent: false,
serve: false,
watch: false,
PAGE_TYPES: {
ROOT: 'root',
INTERNAL: 'internal'
},
gaSite: 'auto',
coverageTestShowOnlyFailed: false,
language: 'en-US',
maxSearchResults: 15
};
var Configuration = /** @class */ (function () {
function Configuration() {
this._pages = [];
this._mainData = {
output: COMPODOC_DEFAULTS.folder,
theme: COMPODOC_DEFAULTS.theme,
extTheme: '',
serve: false,
templatePlayground: false,
hostname: COMPODOC_DEFAULTS.hostname,
host: '',
port: COMPODOC_DEFAULTS.port,
open: false,
assetsFolder: '',
documentationMainName: COMPODOC_DEFAULTS.title,
documentationMainDescription: '',
base: COMPODOC_DEFAULTS.base,
hideGenerator: false,
hideDarkModeToggle: false,
hasFilesToCoverage: false,
modules: [],
readme: false,
changelog: '',
contributing: '',
license: '',
todo: '',
markdowns: [],
additionalPages: [],
pipes: [],
classes: [],
interfaces: [],
components: [],
controllers: [],
entities: [],
directives: [],
injectables: [],
interceptors: [],
guards: [],
miscellaneous: [],
routes: [],
tsconfig: '',
toggleMenuItems: COMPODOC_DEFAULTS.toggleMenuItems,
navTabConfig: [],
templates: '',
includes: '',
includesName: COMPODOC_DEFAULTS.additionalEntryName,
includesFolder: COMPODOC_DEFAULTS.additionalEntryPath,
disableSourceCode: COMPODOC_DEFAULTS.disableSourceCode,
disableDomTree: COMPODOC_DEFAULTS.disableDomTree,
disableTemplateTab: COMPODOC_DEFAULTS.disableTemplateTab,
disableStyleTab: COMPODOC_DEFAULTS.disableStyleTab,
disableGraph: COMPODOC_DEFAULTS.disableGraph,
disableMainGraph: COMPODOC_DEFAULTS.disableMainGraph,
disableCoverage: COMPODOC_DEFAULTS.disableCoverage,
disablePrivate: COMPODOC_DEFAULTS.disablePrivate,
disableInternal: COMPODOC_DEFAULTS.disableInternal,
disableProtected: COMPODOC_DEFAULTS.disableProtected,
disableLifeCycleHooks: COMPODOC_DEFAULTS.disableLifeCycleHooks,
disableConstructors: COMPODOC_DEFAULTS.disableConstructors,
disableRoutesGraph: COMPODOC_DEFAULTS.disableRoutesGraph,
disableSearch: false,
disableDependencies: COMPODOC_DEFAULTS.disableDependencies,
disableProperties: COMPODOC_DEFAULTS.disableProperties,
disableFilePath: COMPODOC_DEFAULTS.disableFilePath,
disableOverview: COMPODOC_DEFAULTS.disableOverview,
watch: false,
mainGraph: '',
coverageTest: false,
coverageTestThreshold: COMPODOC_DEFAULTS.defaultCoverageThreshold,
coverageTestThresholdFail: COMPODOC_DEFAULTS.coverageTestThresholdFail,
coverageTestPerFile: false,
coverageMinimumPerFile: COMPODOC_DEFAULTS.defaultCoverageMinimumPerFile,
unitTestCoverage: '',
unitTestData: undefined,
coverageTestShowOnlyFailed: COMPODOC_DEFAULTS.coverageTestShowOnlyFailed,
routesLength: 0,
angularVersion: '',
exportFormat: COMPODOC_DEFAULTS.exportFormat,
coverageData: {},
customFavicon: '',
customLogo: '',
packageDependencies: [],
packagePeerDependencies: [],
packageProperties: {},
gaID: '',
gaSite: '',
angularProject: false,
angularJSProject: false,
language: COMPODOC_DEFAULTS.language,
maxSearchResults: 15
};
}
Configuration.getInstance = function () {
if (!Configuration.instance) {
Configuration.instance = new Configuration();
}
return Configuration.instance;
};
Configuration.prototype.addPage = function (page) {
var indexPage = ___namespace.findIndex(this._pages, { name: page.name });
if (indexPage === -1) {
this._pages.push(page);
}
};
Configuration.prototype.hasPage = function (name) {
var indexPage = ___namespace.findIndex(this._pages, { name: name });
return indexPage !== -1;
};
Configuration.prototype.addAdditionalPage = function (page) {
this._mainData.additionalPages.push(page);
};
Configuration.prototype.getAdditionalPageById = function (id) {
return this._mainData.additionalPages.find(function (page) { return page.id === id; });
};
Configuration.prototype.resetPages = function () {
this._pages = [];
};
Configuration.prototype.resetAdditionalPages = function () {
this._mainData.additionalPages = [];
};
Configuration.prototype.resetRootMarkdownPages = function () {
var indexPage = ___namespace.findIndex(this._pages, { name: 'index' });
this._pages.splice(indexPage, 1);
indexPage = ___namespace.findIndex(this._pages, { name: 'changelog' });
this._pages.splice(indexPage, 1);
indexPage = ___namespace.findIndex(this._pages, { name: 'contributing' });
this._pages.splice(indexPage, 1);
indexPage = ___namespace.findIndex(this._pages, { name: 'license' });
this._pages.splice(indexPage, 1);
indexPage = ___namespace.findIndex(this._pages, { name: 'todo' });
this._pages.splice(indexPage, 1);
this._mainData.markdowns = [];
};
Object.defineProperty(Configuration.prototype, "pages", {
get: function () {
return this._pages;
},
set: function (pages) {
this._pages = [];
},
enumerable: false,
configurable: true
});
Object.defineProperty(Configuration.prototype, "markDownPages", {
get: function () {
return this._pages.filter(function (page) { return page.markdown; });
},
enumerable: false,
configurable: true
});
Object.defineProperty(Configuration.prototype, "mainData", {
get: function () {
return this._mainData;
},
set: function (data) {
Object.assign(this._mainData, data);
},
enumerable: false,
configurable: true
});
return Configuration;
}());
var Configuration$1 = Configuration.getInstance();
var AngularAPIs = require('../src/data/api-list.json');
var AngularApiUtil = /** @class */ (function () {
function AngularApiUtil() {
}
AngularApiUtil.getInstance = function () {
if (!AngularApiUtil.instance) {
AngularApiUtil.instance = new AngularApiUtil();
}
return AngularApiUtil.instance;
};
AngularApiUtil.prototype.findApi = function (type) {
var foundedApi;
___namespace.forEach(AngularAPIs, function (mainApi) {
___namespace.forEach(mainApi.items, function (api) {
if (api.title === type) {
foundedApi = api;
}
});
});
return {
source: 'external',
data: foundedApi
};
};
return AngularApiUtil;
}());
var AngularApiUtil$1 = AngularApiUtil.getInstance();
function extractLeadingText(string, completeTag) {
var tagIndex = string.indexOf(completeTag);
var leadingText = undefined;
var leadingTextRegExp = /\[(.+?)\]/g;
var leadingTextInfo = leadingTextRegExp.exec(string);
// did we find leading text, and if so, does it immediately precede the tag?
while (leadingTextInfo && leadingTextInfo.length) {
if (leadingTextInfo.index + leadingTextInfo[0].length === tagIndex) {
string = string.replace(leadingTextInfo[0], '');
leadingText = leadingTextInfo[1];
break;
}
leadingTextInfo = leadingTextRegExp.exec(string);
}
return {
leadingText: leadingText,
string: string
};
}
function splitLinkText(text) {
var linkText;
var target;
var splitIndex;
// if a pipe is not present, we split on the first space
splitIndex = text.indexOf('|');
if (splitIndex === -1) {
splitIndex = text.search(/\s/);
}
if (splitIndex !== -1) {
linkText = text.substr(splitIndex + 1);
// Normalize subsequent newlines to a single space.
linkText = linkText.replace(/\n+/, ' ');
target = text.substr(0, splitIndex);
}
return {
linkText: linkText,
target: target || text
};
}
var LinkParser = (function () {
var processTheLink = function (string, tagInfo, leadingText) {
var leading = extractLeadingText(string, tagInfo.completeTag), linkText, split, target, stringtoReplace;
linkText = leadingText ? leadingText : leading.leadingText || '';
split = splitLinkText(tagInfo.text);
target = split.target;
if (leading.leadingText !== undefined) {
stringtoReplace = '[' + leading.leadingText + ']' + tagInfo.completeTag;
}
else if (typeof split.linkText !== 'undefined') {
stringtoReplace = tagInfo.completeTag;
linkText = split.linkText;
}
if (linkText === '' || linkText == null || target == null) {
return string;
}
return string.replace(stringtoReplace, '[' + linkText + '](' + target + ')');
};
/**
* Convert
* {@link http://www.google.com|Google} or {@link https://github.com GitHub} or [Github]{@link https://github.com} to [Github](https://github.com)
*/
var replaceLinkTag = function (str) {
if (typeof str === 'undefined') {
return {
newString: ''
};
}
// new RegExp('\\[((?:.|\n)+?)]\\{@link\\s+((?:.|\n)+?)\\}', 'i').exec('ee [TO DO]{@link Todo} fo') -> "[TO DO]{@link Todo}", "TO DO", "Todo"
// new RegExp('\\{@link\\s+((?:.|\n)+?)\\}', 'i').exec('ee [TODO]{@link Todo} fo') -> "{@link Todo}", "Todo"
var tagRegExpLight = new RegExp('\\{@link\\s+((?:.|\n)+?)\\}', 'i'), tagRegExpFull = new RegExp('\\{@link\\s+((?:.|\n)+?)\\}', 'i'), tagRegExp, matches, previousString;
tagRegExp = str.indexOf(']{') !== -1 ? tagRegExpFull : tagRegExpLight;
function replaceMatch(replacer, tag, match, text, linkText) {
var matchedTag = {
completeTag: match,
tag: tag,
text: text
};
if (linkText) {
return replacer(str, matchedTag, linkText);
}
else {
return replacer(str, matchedTag);
}
}
do {
matches = tagRegExp.exec(str);
if (matches) {
previousString = str;
if (matches.length === 2) {
str = replaceMatch(processTheLink, 'link', matches[0], matches[1]);
}
if (matches.length === 3) {
str = replaceMatch(processTheLink, 'link', matches[0], matches[2], matches[1]);
}
}
} while (matches && previousString !== str);
return {
newString: str
};
};
var _resolveLinks = function (str) {
return replaceLinkTag(str).newString;
};
return {
resolveLinks: _resolveLinks
};
})();
var AngularLifecycleHooks;
(function (AngularLifecycleHooks) {
AngularLifecycleHooks[AngularLifecycleHooks["ngOnChanges"] = 0] = "ngOnChanges";
AngularLifecycleHooks[AngularLifecycleHooks["ngOnInit"] = 1] = "ngOnInit";
AngularLifecycleHooks[AngularLifecycleHooks["ngDoCheck"] = 2] = "ngDoCheck";
AngularLifecycleHooks[AngularLifecycleHooks["ngAfterContentInit"] = 3] = "ngAfterContentInit";
AngularLifecycleHooks[AngularLifecycleHooks["ngAfterContentChecked"] = 4] = "ngAfterContentChecked";
AngularLifecycleHooks[AngularLifecycleHooks["ngAfterViewInit"] = 5] = "ngAfterViewInit";
AngularLifecycleHooks[AngularLifecycleHooks["ngAfterViewChecked"] = 6] = "ngAfterViewChecked";
AngularLifecycleHooks[AngularLifecycleHooks["ngOnDestroy"] = 7] = "ngOnDestroy";
})(AngularLifecycleHooks || (AngularLifecycleHooks = {}));
var KindType;
(function (KindType) {
KindType["UNKNOWN"] = "unknown";
KindType["STRING"] = "string";
KindType["NUMBER"] = "number";
KindType["ARRAY"] = "[]";
KindType["VOID"] = "void";
KindType["FUNCTION"] = "function";
KindType["TEMPLATE_LITERAL"] = "template literal type";
KindType["LITERAL"] = "literal type";
KindType["BOOLEAN"] = "boolean";
KindType["ANY"] = "any";
KindType["NULL"] = "null";
KindType["SYMBOL"] = "symbol";
KindType["NEVER"] = "never";
KindType["UNDEFINED"] = "undefined";
KindType["OBJECT"] = "object";
})(KindType || (KindType = {}));
var IsKindType = {
ANY: function (kind) {
return kindToType(kind) === KindType.ANY;
},
ARRAY: function (kind) {
return kindToType(kind) === KindType.ARRAY;
},
BOOLEAN: function (kind) {
return kindToType(kind) === KindType.BOOLEAN;
},
FUNCTION: function (kind) {
return kindToType(kind) === KindType.FUNCTION;
},
LITERAL: function (kind) {
return kindToType(kind) === KindType.LITERAL;
},
NEVER: function (kind) {
return kindToType(kind) === KindType.NEVER;
},
NULL: function (kind) {
return kindToType(kind) === KindType.NULL;
},
NUMBER: function (kind) {
return kindToType(kind) === KindType.NUMBER;
},
OBJECT: function (kind) {
return kindToType(kind) === KindType.OBJECT;
},
STRING: function (kind) {
return kindToType(kind) === KindType.STRING;
},
SYMBOL: function (kind) {
return kindToType(kind) === KindType.SYMBOL;
},
TEMPLATE_LITERAL: function (kind) {
return kindToType(kind) === KindType.TEMPLATE_LITERAL;
},
UNDEFINED: function (kind) {
return kindToType(kind) === KindType.UNDEFINED;
},
UNKNOWN: function (kind) {
return kindToType(kind) === KindType.UNKNOWN;
},
VOID: function (kind) {
return kindToType(kind) === KindType.VOID;
}
};
function kindToType(kind) {
var _type = KindType.UNKNOWN;
switch (kind) {
case tsMorph.SyntaxKind.StringKeyword:
case tsMorph.SyntaxKind.StringLiteral:
_type = KindType.STRING;
break;
case tsMorph.SyntaxKind.NumberKeyword:
case tsMorph.SyntaxKind.NumericLiteral:
_type = KindType.NUMBER;
break;
case tsMorph.SyntaxKind.ArrayType:
case tsMorph.SyntaxKind.ArrayLiteralExpression:
_type = KindType.ARRAY;
break;
case tsMorph.SyntaxKind.VoidKeyword:
_type = KindType.VOID;
break;
case tsMorph.SyntaxKind.FunctionType:
_type = KindType.FUNCTION;
break;
case tsMorph.SyntaxKind.TemplateLiteralType:
_type = KindType.TEMPLATE_LITERAL;
break;
case tsMorph.SyntaxKind.TypeLiteral:
_type = KindType.LITERAL;
break;
case tsMorph.SyntaxKind.BooleanKeyword:
_type = KindType.BOOLEAN;
break;
case tsMorph.SyntaxKind.AnyKeyword:
_type = KindType.ANY;
break;
case tsMorph.SyntaxKind.NullKeyword:
_type = KindType.NULL;
break;
case tsMorph.SyntaxKind.SymbolKeyword:
_type = KindType.SYMBOL;
break;
case tsMorph.SyntaxKind.NeverKeyword:
_type = KindType.NEVER;
break;
case tsMorph.SyntaxKind.UnknownKeyword:
_type = KindType.UNKNOWN;
break;
case tsMorph.SyntaxKind.UndefinedKeyword:
_type = KindType.UNDEFINED;
break;
case tsMorph.SyntaxKind.ObjectKeyword:
case tsMorph.SyntaxKind.ObjectLiteralExpression:
_type = KindType.OBJECT;
break;
}
return _type;
}
var tsany = ts__namespace;
// https://github.com/Microsoft/TypeScript/blob/v2.1.4/src/compiler/utilities.ts#L1423
function getJSDocCommentRanges(node, text) {
return tsany.getJSDocCommentRanges.apply(this, arguments);
}
var JsdocParserUtil = /** @class */ (function () {
function JsdocParserUtil() {
}
JsdocParserUtil.prototype.isVariableLike = function (node) {
if (node) {
switch (node.kind) {
case tsMorph.SyntaxKind.BindingElement:
case tsMorph.SyntaxKind.EnumMember:
case tsMorph.SyntaxKind.Parameter:
case tsMorph.SyntaxKind.PropertyAssignment:
case tsMorph.SyntaxKind.PropertyDeclaration:
case tsMorph.SyntaxKind.PropertySignature:
case tsMorph.SyntaxKind.ShorthandPropertyAssignment:
case tsMorph.SyntaxKind.VariableDeclaration:
return true;
}
}
return false;
};
JsdocParserUtil.prototype.isTopmostModuleDeclaration = function (node) {
if (node.nextContainer && node.nextContainer.kind === tsMorph.ts.SyntaxKind.ModuleDeclaration) {
var next = node.nextContainer;
if (node.name.end + 1 === next.name.pos) {
return false;
}
}
return true;
};
JsdocParserUtil.prototype.getRootModuleDeclaration = function (node) {
while (node.parent && node.parent.kind === tsMorph.ts.SyntaxKind.ModuleDeclaration) {
var parent = node.parent;
if (node.name.pos === parent.name.end + 1) {
node = parent;
}
else {
break;
}
}
return node;
};
JsdocParserUtil.prototype.getMainCommentOfNode = function (node, sourceFile) {
var description = '';
if (node.parent && node.parent.kind === tsMorph.ts.SyntaxKind.VariableDeclarationList) {
node = node.parent.parent;
}
else if (node.kind === tsMorph.ts.SyntaxKind.ModuleDeclaration) {
if (!this.isTopmostModuleDeclaration(node)) {
return null;
}
else {
node = this.getRootModuleDeclaration(node);
}
}
var comments = getJSDocCommentRanges(node, sourceFile.text);
if (comments && comments.length) {
var comment = void 0;
if (node.kind === tsMorph.ts.SyntaxKind.SourceFile) {
if (comments.length === 1) {
return null;
}
comment = comments[0];
}
else {
comment = comments[comments.length - 1];
}
description = sourceFile.text.substring(comment.pos, comment.end);
}
return description;
};
JsdocParserUtil.prototype.parseComment = function (text) {
var comment = '';
function readBareLine(line) {
comment += '\n' + line;
}
var CODE_FENCE = /^\s*```(?!.*```)/;
var inCode = false;
var inExample = false; // first line with @example, end line with empty string or string or */
var exampleHasCodeFence = false; // track if the example already has code fences
function readLine(line, index) {
line = line.replace(/^\s*\*? ?/, '');
line = line.replace(/\s*$/, '');
if (CODE_FENCE.test(line)) {
inCode = !inCode;
if (inExample) {
exampleHasCodeFence = true;
}
}
if (line.indexOf('@example') !== -1) {
inExample = true;
exampleHasCodeFence = false;
// Check if the next non-empty line has a code fence
var lines = text.split(/\r\n?|\n/);
for (var i = index + 1; i < lines.length; i++) {
var nextLine = lines[i].replace(/^\s*\*? ?/, '').replace(/\s*$/, '');
if (nextLine === '')
continue; // Skip empty lines
if (CODE_FENCE.test(nextLine)) {
exampleHasCodeFence = true;
}
break; // Only check the first non-empty line
}
if (!exampleHasCodeFence) {
line = '```html';
}
else {
// Skip the @example line if it already has code fences
return;
}
}
// Preserve empty lines within code blocks by using a placeholder
if (inCode && inExample && exampleHasCodeFence && line === '') {
line = '___COMPODOC_EMPTY_LINE___';
}
if (inExample && line === '') {
inExample = false;
if (!exampleHasCodeFence) {
line = '```';
}
else {
// Don't add closing fence if example has its own
return;
}
}
if (!inCode) {
var tag = /^@(\S+)/.exec(line);
var SeeTag = /^@see/.exec(line);
if (SeeTag) {
line = line.replace(/^@see/, 'See');
}
if (tag && !SeeTag) {
return;
}
}
readBareLine(line);
}
text = text.replace(/^\s*\/\*+/, '');
text = text.replace(/\*+\/\s*$/, '');
text.split(/\r\n?|\n/).forEach(function (line, index) { return readLine(line, index); });
return comment;
};
JsdocParserUtil.prototype.getJSDocTags = function (node, kind) {
var e_1, _a;
var docs = this.getJSDocs(node);
if (docs) {
var result = [];
try {
for (var docs_1 = logger.__values(docs), docs_1_1 = docs_1.next(); !docs_1_1.done; docs_1_1 = docs_1.next()) {
var doc = docs_1_1.value;
if (tsMorph.ts.isJSDocParameterTag(doc)) {
if (doc.kind === kind) {
result.push(doc);
}
}
else if (tsMorph.ts.isJSDoc(doc)) {
result.push.apply(result, logger.__spreadArray([], logger.__read(___namespace.filter(doc.tags, function (tag) { return tag.kind === kind; })), false));
}
else {
throw new Error('Unexpected type');
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (docs_1_1 && !docs_1_1.done && (_a = docs_1.return)) _a.call(docs_1);
}
finally { if (e_1) throw e_1.error; }
}
return result;
}
};
JsdocParserUtil.prototype.getJSDocs = function (node) {
// TODO: jsDocCache is internal, see if there's a way around it
var cache = node.jsDocCache;
if (!cache) {
cache = this.getJSDocsWorker(node, []).filter(function (x) { return x; });
node.jsDocCache = cache;
}
return cache;
};
// Try to recognize this pattern when node is initializer
// of variable declaration and JSDoc comments are on containing variable statement.
// /**
// * @param {number} name
// * @returns {number}
// */
// var x = function(name) { return name.length; }
JsdocParserUtil.prototype.getJSDocsWorker = function (node, cache) {
var parent = node.parent;
var isInitializerOfVariableDeclarationInStatement = this.isVariableLike(parent) &&
parent.initializer === node &&
tsMorph.ts.isVariableStatement(parent.parent.parent);
var isVariableOfVariableDeclarationStatement = this.isVariableLike(node) && tsMorph.ts.isVariableStatement(parent.parent);
var variableStatementNode = isInitializerOfVariableDeclarationInStatement
? parent.parent.parent
: isVariableOfVariableDeclarationStatement
? parent.parent
: undefined;
if (variableStatementNode) {
cache = this.getJSDocsWorker(variableStatementNode, cache);
}
// Also recognize when the node is the RHS of an assignment expression
var isSourceOfAssignmentExpressionStatement = parent &&
parent.parent &&
tsMorph.ts.isBinaryExpression(parent) &&
parent.operatorToken.kind === tsMorph.SyntaxKind.EqualsToken &&
tsMorph.ts.isExpressionStatement(parent.parent);
if (isSourceOfAssignmentExpressionStatement) {
cache = this.getJSDocsWorker(parent.parent, cache);
}
var isModuleDeclaration = tsMorph.ts.isModuleDeclaration(node) && parent && tsMorph.ts.isModuleDeclaration(parent);
var isPropertyAssignmentExpression = parent && tsMorph.ts.isPropertyAssignment(parent);
if (isModuleDeclaration || isPropertyAssignmentExpression) {
cache = this.getJSDocsWorker(parent, cache);
}
// Pull parameter comments from declaring function as well
if (tsMorph.ts.isParameter(node)) {
cache = ___namespace.concat(cache, this.getJSDocParameterTags(node));
}
if (this.isVariableLike(node) && node.initializer) {
cache = ___namespace.concat(cache, node.initializer.jsDoc);
}
cache = ___namespace.concat(cache, node.jsDoc);
return cache;
};
JsdocParserUtil.prototype.getJSDocParameterTags = function (param) {
var func = param.parent;
var tags = this.getJSDocTags(func, tsMorph.SyntaxKind.JSDocParameterTag);
if (!param.name) {
// this is an anonymous jsdoc param from a `function(type1, type2): type3` specification
var i = func.parameters.indexOf(param);
var paramTags = ___namespace.filter(tags, function (tag) { return tsMorph.ts.isJSDocParameterTag(tag); });
if (paramTags && 0 <= i && i < paramTags.length) {
return [paramTags[i]];
}
}
else if (tsMorph.ts.isIdentifier(param.name)) {
var name_1 = param.name.text;
return ___namespace.filter(tags, function (tag) {
if (tsMorph.ts && tsMorph.ts.isJSDocParameterTag(tag)) {
var t = tag;
if (typeof t.parameterName !== 'undefined') {
return t.parameterName.text === name_1;
}
else if (typeof t.name !== 'undefined') {
if (typeof t.name.escapedText !== 'undefined') {
return t.name.escapedText === name_1;
}
}
}
});
}
else {
// TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines
// But multi-line object types aren't supported yet either
return undefined;
}
};
JsdocParserUtil.prototype.parseJSDocNode = function (node) {
var rawDescription = '';
if (typeof node.comment === 'string') {
rawDescription += node.comment;
}
else {
if (node.comment) {
var len = node.comment.length;
for (var i = 0; i < len; i++) {
var JSDocNode = node.comment[i];
switch (JSDocNode.kind) {
case tsMorph.SyntaxKind.JSDocComment:
rawDescription += JSDocNode.comment;
break;
case tsMorph.SyntaxKind.JSDocText:
rawDescription += JSDocNode.text;
break;
case tsMorph.SyntaxKind.JSDocLink:
if (JSDocNode.name) {
var text = JSDocNode.name.escapedText;
if (text === undefined &&
JSDocNode.name.left &&
JSDocNode.name.right) {
text =
JSDocNode.name.left.escapedText +
'.' +
JSDocNode.name.right.escapedText;
}
rawDescription += JSDocNode.text + '{@link ' + text + '}';
}
break;
}
}
}
}
return rawDescription;
};
return JsdocParserUtil;
}());
var marked = require('marked').marked;
marked.use({
mangle: false,
headerIds: false
});
var markedAcl = marked;
var getCurrentDirectory = tsMorph.ts.sys.getCurrentDirectory;
var useCaseSensitiveFileNames = tsMorph.ts.sys.useCaseSensitiveFileNames;
var newLine = tsMorph.ts.sys.newLine;
function getNewLine() {
return newLine;
}
function cleanNameWithoutSpaceAndToLowerCase(name) {
return name.toLowerCase().replace(/ /g, '-');
}
function getCanonicalFileName(fileName) {
return useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
var formatDiagnosticsHost = {
getCurrentDirectory: getCurrentDirectory,
getCanonicalFileName: getCanonicalFileName,
getNewLine: getNewLine
};
function markedtags(tags) {
var jsdocParserUtil = new JsdocParserUtil();
var mtags = tags;
___namespace.forEach(mtags, function (tag) {
var rawComment = jsdocParserUtil.parseJSDocNode(tag);
tag.comment = markedAcl(LinkParser.resolveLinks(rawComment));
});
return mtags;
}
function mergeTagsAndArgs(args, jsdoctags) {
var margs = ___namespace.cloneDeep(args);
___namespace.forEach(margs, function (arg) {
arg.tagName = {
text: 'param'
};
if (jsdoctags) {
___namespace.forEach(jsdoctags, function (jsdoctag) {
if (jsdoctag.name && jsdoctag.name.text === arg.name) {
arg.tagName = jsdoctag.tagName;
arg.name = jsdoctag.name;
arg.comment = jsdoctag.comment;
arg.typeExpression = jsdoctag.typeExpression;
}
});
}
});
// Add example & returns & private
if (jsdoctags) {
___namespace.forEach(jsdoctags, function (jsdoctag) {
if (jsdoctag.tagName &&
(jsdoctag.tagName.text === 'example' || jsdoctag.tagName.text === 'private')) {
margs.push({
tagName: jsdoctag.tagName,
comment: jsdoctag.comment
});
}
if (jsdoctag.tagName &&
(jsdoctag.tagName.text === 'returns' || jsdoctag.tagName.text === 'return')) {
var ret = {
tagName: jsdoctag.tagName,
comment: jsdoctag.comment
};
if (jsdoctag.typeExpression && jsdoctag.typeExpression.type) {
ret.returnType = kindToType(jsdoctag.typeExpression.type.kind);
}
margs.push(ret);
}
});
}
return margs;
}
function readConfig(configFile) {
var result = tsMorph.ts.readConfigFile(configFile, tsMorph.ts.sys.readFile);
if (result.error) {
var message = tsMorph.ts.formatDiagnostics([result.error], formatDiagnosticsHost);
throw new Error(message);
}
return result.config;
}
function stripBom(source) {
if (source.charCodeAt(0) === 0xfeff) {
return source.slice(1);
}
return source;
}
function hasBom(source) {
return source.charCodeAt(0) === 0xfeff;
}
function cleanLifecycleHooksFromMethods(methods) {
var result = [];
if (typeof methods !== 'undefined') {
var i = 0;
var len = methods.length;
for (i; i < len; i++) {
if (!(methods[i].name in AngularLifecycleHooks)) {
result.push(methods[i]);
}
}
}
return result;
}
function cleanSourcesForWatch(list) {
return list.filter(function (element) {
if (fs__namespace.existsSync(process.cwd() + path__namespace.sep + element)) {
return element;
}
});
}
function getNamesCompareFn(name) {
/**
* Copyright https://github.com/ng-bootstrap/ng-bootstrap
*/
name = name || 'name';
var t = function (a, b) {
if (a[name]) {
return a[name].localeCompare(b[name]);
}
else {
return 0;
}
};
return t;
}
function isIgnore(member) {
var e_1, _a, e_2, _b;
if (member.jsDoc) {
try {
for (var _c = logger.__values(member.jsDoc), _d = _c.next(); !_d.done; _d = _c.next()) {
var doc = _d.value;
if (doc.tags) {
try {
for (var _e = (e_2 = void 0, logger.__values(doc.tags)), _f = _e.next(); !_f.done; _f = _e.next()) {
var tag = _f.value;
if (tag.tagName.text.indexOf('ignore') > -1) {
return true;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
}
finally { if (e_2) throw e_2.error; }
}
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
}
return false;
}
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function (searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return (x === y ||
(typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)));
}
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
if (sameValueZero(o[k], searchElement)) {
return true;
}
// c. Increase k by 1.
k++;
}
// 8. Return false
return false;
}
});
}
function findMainSourceFolder(files) {
var mainFolder = '';
var mainFolderCount = 0;
var rawFolders = files.map(function (filepath) {
var shortPath = filepath.replace(process.cwd() + path__namespace.sep, '');
return path__namespace.dirname(shortPath);
});
var folders = {};
rawFolders = ___namespace.uniq(rawFolders);
for (var i = 0; i < rawFolders.length; i++) {
var sep = rawFolders[i].split(path__namespace.sep);
sep.forEach(function (folder) {
if (folders[folder]) {
folders[folder] += 1;
}
else {
folders[folder] = 1;
}
});
}
for (var f in folders) {
if (folders[f] > mainFolderCount) {
mainFolderCount = folders[f];
mainFolder = f;
}
}
return mainFolder;
}
// Create a compilerHost object to allow the compiler to read and write files
function compilerHost(transpileOptions) {
var inputFileName = transpileOptions.fileName || (transpileOptions.jsx ? 'module.tsx' : 'module.ts');
var toReturn = {
getSourceFile: function (fileName) {
if (fileName.lastIndexOf('.ts') !== -1 || fileName.lastIndexOf('.js') !== -1) {
if (fileName === 'lib.d.ts') {
return undefined;
}
if (fileName.substr(-5) === '.d.ts') {
return undefined;
}
if (path__namespace.isAbsolute(fileName) === false) {
fileName = path__namespace.join(transpileOptions.tsconfigDirectory, fileName);
}
if (!fs__namespace.existsSync(fileName)) {
return undefined;
}
var libSource = '';
try {
libSource = fs__namespace.readFileSync(fileName).toString();
if (hasBom(libSource)) {
libSource = stripBom(libSource);
}
}
catch (e) {
logger.logger.debug(e, fileName);
}
return tsMorph.ts.createSourceFile(fileName, libSource, transpileOptions.target, false);
}
return undefined;
},
writeFile: function (name, text) { },
getDefaultLibFileName: function () { return 'lib.d.ts'; },
useCaseSensitiveFileNames: function () { return false; },
getCanonicalFileName: function (fileName) { return fileName; },
getCurrentDirectory: function () { return ''; },
getNewLine: function () { return '\n'; },
fileExists: function (fileName) { return fileName === inputFileName; },
readFile: function () { return ''; },
directoryExists: function () { return true; },
getDirectories: function () { return []; }
};
return toReturn;
}
function detectIndent(str, count) {
var stripIndent = function (stripedString) {
var match = stripedString.match(/^[ \t]*(?=\S)/gm);
if (!match) {
return stripedString;
}
var indent = Math.min.apply(Math, logger.__spreadArray([], logger.__read(match.map(function (x) { return x.length; })), false));
var re = new RegExp("^[ \\t]{".concat(indent, "}"), 'gm');
return indent > 0 ? stripedString.replace(re, '') : stripedString;
};
var repeating = function (n, repeatString) {
repeatString = repeatString === undefined ? ' ' : repeatString;
if (typeof repeatString !== 'string') {
throw new TypeError("Expected `input` to be a `string`, got `".concat(typeof repeatString, "`"));
}
if (n < 0) {
throw new TypeError("Expected `count` to be a positive finite number, got `".concat(n, "`"));
}
var ret = '';
do {
if (n & 1) {
ret += repeatString;
}
repeatString += repeatString;
} while ((n >>= 1));
return ret;
};
var indentString = function (indentedString, indentCount) {
var indent = ' ';
indentCount = indentCount === undefined ? 1 : indentCount;
if (typeof indentedString !== 'string') {
throw new TypeError("Expected `input` to be a `string`, got `".concat(typeof indentedString, "`"));
}
if (typeof indentCount !== 'number') {
throw new TypeError("Expected `count` to be a `number`, got `".concat(typeof indentCount, "`"));
}
if (typeof indent !== 'string') {
throw new TypeError("Expected `indent` to be a `string`, got `".concat(typeof indent, "`"));
}
if (indentCount === 0) {
return indentedString;
}
indent = indentCount > 1 ? repeating(indentCount, indent) : indent;
return indentedString.replace(/^(?!\s*$)/gm, indent);
};
return indentString(stripIndent(str), 0);
}
var INCLUDE_PATTERNS = ['**/*.ts', '**/*.tsx'];
var EXCLUDE_PATTERNS = ['**/.git', '**/node_modules', '**/*.d.ts', '**/*.spec.ts'];
var traverse$3 = require('neotraverse/legacy');
var DependenciesEngine = /** @class */ (function () {
function DependenciesEngine() {
this.miscellaneous = {
variables: [],
functions: [],
typealiases: [],
enumerations: [],
groupedVariables: [],
groupedFunctions: [],
groupedEnumerations: [],
groupedTypeAliases: []
};
}
DependenciesEngine.getInstance = function () {
if (!DependenciesEngine.instance) {
DependenciesEngine.instance = new DependenciesEngine();
}
return DependenciesEngine.instance;
};
DependenciesEngine.prototype.updateModulesDeclarationsExportsTypes = function () {
var _this = this;
var mergeTypes = function (entry) {
var directive = _this.findInCompodocDependencies(entry.name, _this.directives, entry.file);
if (typeof directive.data !== 'undefined') {
entry.type = 'directive';
entry.id = directive.data.id;
}
var component = _this.findInCompodocDependencies(entry.name, _this.components, entry.file);
if (typeof component.data !== 'undefined') {
entry.type = 'component';
entry.id = component.data.id;
}
var pipe = _this.findInCompodocDependencies(entry.name, _this.pipes, entry.file);
if (typeof pipe.data !== 'undefined') {
entry.type = 'pipe';
entry.id = pipe.data.id;
}
};
this.modules.forEach(function (module) {
module.declarations.forEach(function (declaration) {
mergeTypes(declaration);
});
module.exports.forEach(function (expt) {
mergeTypes(expt);
});
module.entryComponents.forEach(function (ent) {
mergeTypes(ent);
});
});
};
DependenciesEngine.prototype.init = function (data) {
traverse$3(data).forEach(function (node) {
if (node) {
if (node.parent) {
delete node.parent;
}
if (node.initializer) {
delete node.initializer;
}
}
});
this.rawData = data;
this.modules = ___namespace.sortBy(this.rawData.modules, [function (el) { return el.name.toLowerCase(); }]);
this.rawModulesForOverview = ___namespace.sortBy(data.modulesForGraph, [function (el) { return el.name.toLowerCase(); }]);
this.rawModules = ___namespace.sortBy(data.modulesForGraph, [function (el) { return el.name.toLowerCase(); }]);
this.components = ___namespace.sortBy(this.rawData.components, [function (el) { return el.name.toLowerCase(); }]);
this.controllers = ___namespace.sortBy(this.rawData.controllers, [function (el) { return el.name.toLowerCase(); }]);
this.entities = ___namespace.sortBy(this.rawData.entities, [function (el) { return el.name.toLowerCase(); }]);
this.directives = ___namespace.sortBy(this.rawData.directives, [function (el) { return el.name.toLowerCase(); }]);
this.injectables = ___namespace.sortBy(this.rawData.injectables, [function (el) { return el.name.toLowerCase(); }]);
this.interceptors = ___namespace.sortBy(this.rawData.interceptors, [function (el) { return el.name.toLowerCase(); }]);
this.guards = ___namespace.sortBy(this.rawData.guards, [function (el) { return el.name.toLowerCase(); }]);
this.interfaces = ___namespace.sortBy(this.rawData.interfaces, [function (el) { return el.name.toLowerCase(); }]);
this.pipes = ___namespace.sortBy(this.rawData.pipes, [function (el) { return el.name.toLowerCase(); }]);
this.classes = ___namespace.sortBy(this.rawData.classes, [function (el) { return el.name.toLowerCase(); }]);
this.miscellaneous = this.rawData.miscellaneous;
this.prepareMiscellaneous();
this.updateModulesDeclarationsExportsTypes();
this.routes = this.rawData.routesTree;
this.manageDuplicatesName();
this.cleanRawModulesNames();
};
DependenciesEngine.prototype.cleanRawModulesNames = function () {
this.rawModulesForOverview = this.rawModulesForOverview.map(function (module) {
module.name = module.name.replace('$', '');
return module;
});
};
DependenciesEngine.prototype.findInCompodocDependencies = function (name, data, file) {
var _result = {
source: 'internal',
data: undefined,
score: 0
};
var nameFoundCounter = 0;
if (data && data.length > 0) {
for (var i = 0; i < data.length; i++) {
if (typeof name !== 'undefined') {
if (typeof file !== 'undefined') {
if (name === data[i].name &&
file.replace(/\\/g, '/').indexOf(data[i].file) !== -1) {
nameFoundCounter += 1;
_result.data = data[i];
_result.score = 2;
}
else if (name.indexOf(data[i].name) !== -1 &&
file.replace(/\\/g, '/').indexOf(data[i].file) !== -1) {
nameFoundCounter += 1;
_result.data = data[i];
_result.score = 1;
}
}
else {
if (name === data[i].name) {
nameFoundCounter += 1;
_result.data =