gulp-validateTypedoc.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. 'use strict';
  2. var fs = require('fs');
  3. var Vinyl = require('vinyl');
  4. var through = require('through2');
  5. var PluginError = require('plugin-error');
  6. var nodeColorConsole = require('../../NodeHelpers/colorConsole');
  7. const log = nodeColorConsole.log;
  8. const warn = nodeColorConsole.warn;
  9. const err = nodeColorConsole.error;
  10. const success = nodeColorConsole.success;
  11. // ______________________________________________ VALIDATION ____________________________________________
  12. function unixStylePath(filePath) {
  13. return filePath.replace(/\\/g, '/');
  14. }
  15. function Validate(validationBaselineFileName, namespaceName, validateNamingConvention, generateBaseLine) {
  16. this.validationBaselineFileName = validationBaselineFileName;
  17. this.namespaceName = namespaceName;
  18. this.validateNamingConvention = validateNamingConvention;
  19. this.generateBaseLine = generateBaseLine;
  20. this.previousResults = {};
  21. this.results = {
  22. errors: 0
  23. };
  24. }
  25. Validate.hasTag = function (node, tagName) {
  26. tagName = tagName.trim().toLowerCase();
  27. if (node.comment && node.comment.tags) {
  28. for (var i = 0; i < node.comment.tags.length; i++) {
  29. if (node.comment.tags[i].tag === tagName) {
  30. return true;
  31. }
  32. }
  33. }
  34. return false;
  35. }
  36. Validate.position = function (node) {
  37. if (!node.sources) {
  38. log(node);
  39. }
  40. return node.sources[0].fileName + ':' + node.sources[0].line;
  41. }
  42. Validate.upperCase = new RegExp("^[A-Z_]*$");
  43. Validate.pascalCase = new RegExp("^[A-Z][a-zA-Z0-9_]*$");
  44. Validate.camelCase = new RegExp("^[a-z][a-zA-Z0-9_]*$");
  45. Validate.underscoreCamelCase = new RegExp("^_[a-z][a-zA-Z0-9_]*$");
  46. Validate.underscorePascalCase = new RegExp("^_[A-Z][a-zA-Z0-9_]*$");
  47. Validate.prototype.errorCallback = function (parent, node, nodeKind, category, type, msg, position) {
  48. this.results[this.filePath] = this.results[this.filePath] || { errors: 0 };
  49. var results = this.results[this.filePath];
  50. if (node === "toString") {
  51. node = "ToString";
  52. }
  53. // Checks against previous results.
  54. var previousResults = this.previousResults[this.filePath];
  55. if (previousResults) {
  56. var previousRootName = parent ? parent : node;
  57. var needCheck = true;
  58. if (Array.isArray(previousRootName)) {
  59. while (previousRootName.length > 1) {
  60. var previousFirst = previousRootName.shift();
  61. previousResults = previousResults[previousFirst];
  62. if (!previousResults) {
  63. needCheck = false;
  64. break;
  65. }
  66. }
  67. previousRootName = previousRootName.shift();
  68. }
  69. if (needCheck) {
  70. var previousNode = previousResults[previousRootName];
  71. if (previousNode) {
  72. var previousNodeKind = previousNode[nodeKind];
  73. if (previousNodeKind) {
  74. if (parent) {
  75. previousNode = previousNodeKind[node];
  76. }
  77. else {
  78. previousNode = previousNodeKind;
  79. }
  80. if (previousNode) {
  81. var previousCategory = previousNode[category];
  82. if (previousCategory) {
  83. var previousType = previousCategory[type];
  84. if (previousType) {
  85. // Early exit as it was already in the previous build.
  86. return;
  87. }
  88. }
  89. }
  90. }
  91. }
  92. }
  93. }
  94. // Write Error in output JSON.
  95. var rootName = parent ? parent : node;
  96. var current = results;
  97. if (Array.isArray(rootName)) {
  98. while (rootName.length > 1) {
  99. var first = rootName.shift();
  100. current = current[first] = current[first] || {};
  101. }
  102. rootName = rootName.shift();
  103. }
  104. current = current[rootName] = current[rootName] || {};
  105. current = current[nodeKind] = current[nodeKind] || {};
  106. if (parent) {
  107. current = current[node] = current[node] || {};
  108. }
  109. current = current[category] = current[category] || {};
  110. current = current[type] = true;
  111. results.errors++;
  112. if (!this.generateBaseLine) {
  113. err(msg, position);
  114. }
  115. }
  116. Validate.prototype.init = function (cb) {
  117. var self = this;
  118. if (!this.generateBaseLine && fs.existsSync(this.validationBaselineFileName)) {
  119. fs.readFile(this.validationBaselineFileName, "utf-8", function (err, data) {
  120. self.previousResults = JSON.parse(data);
  121. cb();
  122. });
  123. }
  124. else {
  125. cb();
  126. }
  127. }
  128. Validate.prototype.add = function (filePath, content) {
  129. this.filePath = filePath && unixStylePath(filePath);
  130. if (!Buffer.isBuffer(content)) {
  131. content = Buffer.from(content);
  132. }
  133. var contentString = content.toString();
  134. var json = JSON.parse(contentString);
  135. this.validateTypedoc(json);
  136. if (this.results[this.filePath]) {
  137. this.results.errors += this.results[this.filePath].errors;
  138. }
  139. }
  140. Validate.prototype.getResults = function () {
  141. return this.results;
  142. }
  143. Validate.prototype.getContents = function () {
  144. return Buffer.from(JSON.stringify(this.results));
  145. }
  146. /**
  147. * Validate a TypeDoc JSON file
  148. */
  149. Validate.prototype.validateTypedoc = function (json) {
  150. for (var i = 0; i < json.children.length; i++) {
  151. var namespaces = json.children[i].children;
  152. this.validateTypedocNamespaces(namespaces);
  153. }
  154. }
  155. /**
  156. * Validate namespaces attach to a declaration file from a TypeDoc JSON file
  157. */
  158. Validate.prototype.validateTypedocNamespaces = function (namespaces) {
  159. var namespace = null;
  160. // Check for BABYLON namespace
  161. for (var child in namespaces) {
  162. if (namespaces[child].name === this.namespaceName) {
  163. namespace = namespaces[child];
  164. break;
  165. }
  166. }
  167. // Exit if not BABYLON related.
  168. if (!namespace || !namespace.children) {
  169. return;
  170. }
  171. // Validate the namespace.
  172. this.validateTypedocNamespace(namespace);
  173. }
  174. /**
  175. * Validate classes and modules attach to a declaration file from a TypeDoc JSON file
  176. */
  177. Validate.prototype.validateTypedocNamespace = function (namespace) {
  178. var containerNode;
  179. var childNode;
  180. var children;
  181. var signatures;
  182. var signatureNode;
  183. var tags;
  184. var isPublic;
  185. for (var a in namespace.children) {
  186. containerNode = namespace.children[a];
  187. // Validate Sub Module
  188. if (containerNode.kindString === "Module") {
  189. this.validateTypedocNamespace(containerNode);
  190. continue;
  191. }
  192. // else Validate Classes
  193. // Account for undefined access modifiers.
  194. if (!containerNode.flags.isPublic &&
  195. !containerNode.flags.isPrivate &&
  196. !containerNode.flags.isProtected) {
  197. containerNode.flags.isPublic = true;
  198. }
  199. isPublic = containerNode.flags.isPublic;
  200. // Validate naming.
  201. this.validateNaming(null, containerNode);
  202. // Validate Comments.
  203. if (isPublic && !this.validateComment(containerNode)) {
  204. this.errorCallback(null,
  205. containerNode.name,
  206. containerNode.kindString,
  207. "Comments",
  208. "MissingText",
  209. "Missing text for " + containerNode.kindString + " : " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(containerNode));
  210. }
  211. children = containerNode.children;
  212. //Validate Properties
  213. if (children) {
  214. for (var b in children) {
  215. childNode = children[b];
  216. // Account for undefined access modifiers.
  217. if (!childNode.flags.isPublic &&
  218. !childNode.flags.isPrivate &&
  219. !childNode.flags.isProtected) {
  220. childNode.flags.isPublic = true;
  221. }
  222. isPublic = childNode.flags.isPublic;
  223. // Validate Naming.
  224. this.validateNaming(containerNode, childNode);
  225. if (isPublic) {
  226. tags = this.validateTags(childNode);
  227. if (tags) {
  228. this.errorCallback(containerNode.name,
  229. childNode.name,
  230. childNode.kindString,
  231. "Tags",
  232. tags,
  233. "Unrecognized tag " + tags + " at " + childNode.name + " (id: " + childNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  234. }
  235. }
  236. if (!this.validateComment(childNode)) {
  237. //Validate Signatures
  238. signatures = childNode.signatures;
  239. if (signatures) {
  240. for (var c in signatures) {
  241. signatureNode = signatures[c];
  242. if (isPublic) {
  243. if (!this.validateComment(signatureNode)) {
  244. this.errorCallback(containerNode.name,
  245. signatureNode.name,
  246. childNode.kindString,
  247. "Comments",
  248. "MissingText",
  249. "Missing text for " + childNode.kindString + " : " + signatureNode.name + " (id: " + signatureNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  250. }
  251. tags = this.validateTags(signatureNode);
  252. if (tags) {
  253. this.errorCallback(containerNode.name,
  254. signatureNode.name,
  255. childNode.kindString,
  256. "Tags",
  257. tags,
  258. "Unrecognized tag " + tags + " at " + signatureNode.name + " (id: " + signatureNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  259. }
  260. if (signatureNode.type.name !== "void" && signatureNode.comment && !signatureNode.comment.returns) {
  261. this.errorCallback(containerNode.name,
  262. signatureNode.name,
  263. childNode.kindString,
  264. "Comments",
  265. "MissingReturn",
  266. "No Return Comment at " + signatureNode.name + " (id: " + signatureNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  267. }
  268. if (signatureNode.type.name === "void" && signatureNode.comment && signatureNode.comment.returns) {
  269. this.errorCallback(containerNode.name,
  270. signatureNode.name,
  271. childNode.kindString,
  272. "Comments",
  273. "UselessReturn",
  274. "No Return Comment Needed at " + signatureNode.name + " (id: " + signatureNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  275. }
  276. }
  277. this.validateParameters(containerNode, childNode, signatureNode, signatureNode.parameters, isPublic);
  278. }
  279. } else {
  280. this.errorCallback(containerNode.name,
  281. childNode.name,
  282. childNode.kindString,
  283. "Comments",
  284. "MissingText",
  285. "Missing text for " + childNode.kindString + " : " + childNode.name + " (id: " + childNode.id + ") in " + containerNode.name + " (id: " + containerNode.id + ")", Validate.position(childNode));
  286. }
  287. }
  288. // this.validateParameters(containerNode, childNode, childNode.parameters, isPublic);
  289. }
  290. }
  291. }
  292. }
  293. /**
  294. * Validate that tags are recognized
  295. */
  296. Validate.prototype.validateTags = function (node) {
  297. var tags;
  298. var errorTags = [];
  299. if (node.comment) {
  300. tags = node.comment.tags;
  301. if (tags) {
  302. for (var i = 0; i < tags.length; i++) {
  303. var tag = tags[i];
  304. var validTags = ["constructor", "throw", "type", "deprecated", "example", "examples", "remark", "see", "remarks", "ignorenaming"]
  305. if (validTags.indexOf(tag.tag) === -1) {
  306. errorTags.push(tag.tag);
  307. }
  308. }
  309. }
  310. }
  311. return errorTags.join(",");
  312. }
  313. /**
  314. * Validate that a JSON node has the correct TypeDoc comments
  315. */
  316. Validate.prototype.validateComment = function (node) {
  317. // Return-only methods are allowed to just have a @return tag
  318. if ((node.kindString === "Call signature" || node.kindString === "Accessor") && !node.parameters && node.comment && node.comment.returns) {
  319. return true;
  320. }
  321. // Return true for private properties (dont validate)
  322. if ((node.kindString === "Property" || node.kindString === "Object literal") && (node.flags.isPrivate || node.flags.isProtected)) {
  323. return true;
  324. }
  325. // Return true for inherited properties
  326. if (node.inheritedFrom) {
  327. return true;
  328. }
  329. // Return true for overwrited properties
  330. if (node.overwrites) {
  331. return true;
  332. }
  333. // Check comments.
  334. if (node.comment) {
  335. if (node.comment.text || node.comment.shortText) {
  336. return true;
  337. }
  338. return false;
  339. }
  340. // Return true for inherited properties (need to check signatures)
  341. if (node.kindString === "Function") {
  342. return true;
  343. }
  344. return false;
  345. }
  346. /**
  347. * Validate comments for paramters on a node
  348. */
  349. Validate.prototype.validateParameters = function (containerNode, method, signature, parameters, isPublic) {
  350. var parametersNode;
  351. for (var parameter in parameters) {
  352. parametersNode = parameters[parameter];
  353. if (isPublic && !this.validateComment(parametersNode)) {
  354. // throw containerNode.name + " " + method.kindString + " " + method.name + " " + parametersNode.name + " " + parametersNode.kindString;
  355. this.errorCallback([containerNode.name, method.kindString, signature.name],
  356. parametersNode.name,
  357. parametersNode.kindString,
  358. "Comments",
  359. "MissingText",
  360. "Missing text for parameter " + parametersNode.name + " (id: " + parametersNode.id + ") of " + method.name + " (id: " + method.id + ")", Validate.position(method));
  361. }
  362. if (this.validateNamingConvention && !Validate.camelCase.test(parametersNode.name)) {
  363. this.errorCallback([containerNode.name, method.kindString, signature.name],
  364. parametersNode.name,
  365. parametersNode.kindString,
  366. "Naming",
  367. "NotCamelCase",
  368. "Parameter " + parametersNode.name + " should be Camel Case (id: " + method.id + ")", Validate.position(method));
  369. }
  370. }
  371. }
  372. /**
  373. * Validate naming conventions of a node
  374. */
  375. Validate.prototype.validateNaming = function (parent, node) {
  376. if (!this.validateNamingConvention) {
  377. return;
  378. }
  379. // Ignore Naming Tag Check
  380. if (Validate.hasTag(node, 'ignoreNaming')) {
  381. return;
  382. } else {
  383. if (node.signatures) {
  384. for (var index = 0; index < node.signatures.length; index++) {
  385. var signature = node.signatures[index];
  386. if (Validate.hasTag(signature, 'ignoreNaming')) {
  387. return;
  388. }
  389. }
  390. }
  391. }
  392. if (node.inheritedFrom) {
  393. return;
  394. }
  395. // Internals are not subject to the public visibility policy.
  396. if (node.name && node.name.length > 0 && node.name[0] === "_") {
  397. return;
  398. }
  399. if ((node.flags.isPrivate || node.flags.isProtected) && node.flags.isStatic) {
  400. if (!Validate.underscorePascalCase.test(node.name)) {
  401. this.errorCallback(parent ? parent.name : null,
  402. node.name,
  403. node.kindString,
  404. "Naming",
  405. "NotUnderscorePascalCase",
  406. node.name + " should be Underscore Pascal Case (id: " + node.id + ")", Validate.position(node));
  407. }
  408. }
  409. else if (node.flags.isPrivate || node.flags.isProtected) {
  410. if (!Validate.underscoreCamelCase.test(node.name)) {
  411. this.errorCallback(parent ? parent.name : null,
  412. node.name,
  413. node.kindString,
  414. "Naming",
  415. "NotUnderscoreCamelCase",
  416. node.name + " should be Underscore Camel Case (id: " + node.id + ")", Validate.position(node));
  417. }
  418. }
  419. else if (node.flags.isStatic) {
  420. if (!Validate.pascalCase.test(node.name)) {
  421. this.errorCallback(parent ? parent.name : null,
  422. node.name,
  423. node.kindString,
  424. "Naming",
  425. "NotPascalCase",
  426. node.name + " should be Pascal Case (id: " + node.id + ")", Validate.position(node));
  427. }
  428. }
  429. else if (node.kindString == "Module") {
  430. if (!(Validate.upperCase.test(node.name) || Validate.pascalCase.test(node.name))) {
  431. this.errorCallback(parent ? parent.name : null,
  432. node.name,
  433. node.kindString,
  434. "Naming",
  435. "NotUpperCase",
  436. "Module is not Upper Case or Pascal Case " + node.name + " (id: " + node.id + ")", Validate.position(node));
  437. }
  438. }
  439. else if (node.kindString == "Interface" ||
  440. node.kindString == "Class" ||
  441. node.kindString == "Enumeration" ||
  442. node.kindString == "Enumeration member" ||
  443. node.kindString == "Accessor" ||
  444. node.kindString == "Type alias") {
  445. if (!Validate.pascalCase.test(node.name)) {
  446. this.errorCallback(parent ? parent.name : null,
  447. node.name,
  448. node.kindString,
  449. "Naming",
  450. "NotPascalCase",
  451. node.name + " should be Pascal Case (id: " + node.id + ")", Validate.position(node));
  452. }
  453. }
  454. else if (node.kindString == "Method" ||
  455. node.kindString == "Property" ||
  456. node.kindString == "Object literal") {
  457. // Only warn here as special properties such as FOV may be better capitalized
  458. if (!Validate.camelCase.test(node.name)) {
  459. this.errorCallback(parent ? parent.name : null,
  460. node.name,
  461. node.kindString,
  462. "Naming",
  463. "NotCamelCase",
  464. node.name + " should be Camel Case (id: " + node.id + ")", Validate.position(node));
  465. }
  466. }
  467. else if (node.kindString == "Variable") {
  468. this.errorCallback(parent ? parent.name : null,
  469. node.name,
  470. node.kindString,
  471. "Naming",
  472. "ShouldNotBeLooseVariable",
  473. node.name + " should not be a variable (id: " + node.id + ")", Validate.position(node));
  474. }
  475. else if (node.kindString === "Function") {
  476. if (!Validate.camelCase.test(node.name)) {
  477. this.errorCallback(parent ? parent.name : null,
  478. node.name,
  479. node.kindString,
  480. "Naming",
  481. "NotCamelCase",
  482. node.name + " should be Camel Case (id: " + node.id + ")", Validate.position(node));
  483. }
  484. }
  485. else if (node.kindString == "Constructor") {
  486. // Do Nothing Here, this is handled through the class name.
  487. }
  488. else {
  489. this.errorCallback(parent ? parent.name : null,
  490. node.name,
  491. node.kindString,
  492. "Naming",
  493. "UnknownNamingConvention",
  494. "Unknown naming convention for " + node.kindString + " at " + node.name + " (id: " + node.id + ")", Validate.position(node));
  495. }
  496. }
  497. // ______________________________________________ PLUGIN ____________________________________________
  498. // consts
  499. const PLUGIN_NAME = 'gulp-validateTypedoc';
  500. // plugin level function (dealing with files)
  501. function gulpValidateTypedoc(validationBaselineFileName, namespaceName, validateNamingConvention, generateBaseLine) {
  502. if (!validationBaselineFileName) {
  503. throw new PluginError(PLUGIN_NAME, 'Missing validation filename!');
  504. }
  505. if (typeof validationBaselineFileName !== "string") {
  506. throw new PluginError(PLUGIN_NAME, 'Validation filename must be a string!');
  507. }
  508. var validate;
  509. var latestFile;
  510. function bufferContents(file, enc, cb) {
  511. // ignore empty files
  512. if (file.isNull()) {
  513. cb();
  514. return;
  515. }
  516. // we don't do streams (yet)
  517. if (file.isStream()) {
  518. this.emit('error', new Error('gulp-validatTypedoc: Streaming not supported'));
  519. cb();
  520. return;
  521. }
  522. // set latest file if not already set,
  523. // or if the current file was modified more recently.
  524. latestFile = file;
  525. // What will happen once all set.
  526. var done = function () {
  527. // add file to concat instance
  528. validate.add(file.relative, file.contents);
  529. cb();
  530. }
  531. // Do the validation.
  532. if (!validate) {
  533. validate = new Validate(validationBaselineFileName, namespaceName, validateNamingConvention, generateBaseLine);
  534. validate.init(done);
  535. }
  536. else {
  537. done();
  538. }
  539. }
  540. function endStream(cb) {
  541. // no files passed in, no file goes out
  542. if (!latestFile) {
  543. var error = new PluginError(PLUGIN_NAME, 'gulp-validatTypedoc: No Baseline found.');
  544. this.emit('error', error);
  545. cb();
  546. return;
  547. }
  548. var results = validate.getResults();
  549. var buffer = Buffer.from(JSON.stringify(results, null, 2))
  550. if (generateBaseLine) {
  551. fs.writeFileSync(validationBaselineFileName, buffer || '');
  552. }
  553. var jsFile = new Vinyl({
  554. base: null,
  555. path: validationBaselineFileName,
  556. contents: buffer
  557. });
  558. this.push(jsFile);
  559. var action = generateBaseLine ? "baseline generation" : "validation";
  560. var self = this;
  561. var error = function (message) {
  562. generateBaseLine ? warn : err;
  563. if (generateBaseLine) {
  564. warn(message);
  565. }
  566. else {
  567. err(message);
  568. var error = new PluginError(PLUGIN_NAME, message);
  569. self.emit('error', error);
  570. }
  571. }
  572. if (results.errors > 1) {
  573. var message = results.errors + " errors have been detected during the " + action + " !";
  574. error(message);
  575. }
  576. else if (results.errors === 1) {
  577. var message = "1 error has been detected during the " + action + " !";
  578. error(message);
  579. }
  580. else {
  581. var message = "All formatting check passed successfully during the " + action + " !";
  582. success(message);
  583. }
  584. cb();
  585. }
  586. return through.obj(bufferContents, endStream);
  587. };
  588. // exporting the plugin main function
  589. module.exports = gulpValidateTypedoc;