puppy-api-docs
Version:
Genernate material api docs from your comments.
47 lines (38 loc) • 1.9 kB
JavaScript
const CommentParseResult = require('../models/commentParseResult');
/**
* @param {String} input String extract the comments from.
* @returns {CommentParseResult} result: Parse result containing comments and errors.
*/
function extract(input) {
const regex = new RegExp(/(?:((["'])(?:(?:\\\\)|\\\2|(?!\\\2)\\|(?!\2).|[\n\r])*\2)|(\/\*(?:(?!\*\/).|[\n\r])*\*\/)|(\/\/[^\n\r]*(?:[\n\r]+|$))|((?:=|:)\s*(?:\/(?:(?:(?!\\*\/).)|\\\\|\\\/|[^\\]\[(?:\\\\|\\\]|[^]])+\])+\/))|((?:\/(?:(?:(?!\\*\/).)|\\\\|\\\/|[^\\]\[(?:\\\\|\\\]|[^]])+\])+\/)[gimy]?\.(?:exec|test|match|search|replace|split)\()|(\.(?:exec|test|match|search|replace|split)\((?:\/(?:(?:(?!\\*\/).)|\\\\|\\\/|[^\\]\[(?:\\\\|\\\]|[^]])+\])+\/))|(<!--(?:(?!-->).)*-->))/g);
const comments = [];
const errors = [];
while (true) {
const result = regex.exec(input);
if (result !== null) {
for (let commentIndex = 0; commentIndex < result[0].length; commentIndex++) {
const remainingString = result[0].substring(commentIndex);
const docStartIndex = remainingString.indexOf('@docstart');
const docEndIndex = remainingString.indexOf('@docend');
if (docStartIndex !== -1 && docEndIndex !== -1 && docStartIndex < docEndIndex) {
const code = remainingString.substring(docStartIndex + '@docstart'.length, docEndIndex).trim();
try {
comments.push(JSON.parse(code));
} catch (e) {
console.log(e);
}
commentIndex += docEndIndex;
} else {
break;
}
}
} else {
break;
}
}
return new CommentParseResult({
comments: comments,
errors: errors,
});
}
module.exports = extract;