generate-typescript-docs.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. /* tslint:disable:no-console */
  2. import fs from 'fs-extra';
  3. import klawSync from 'klaw-sync';
  4. import path, { extname } from 'path';
  5. import { deleteGeneratedDocs } from './docgen-utils';
  6. import { TypeMap } from './typescript-docgen-types';
  7. import { TypescriptDocsParser } from './typescript-docs-parser';
  8. import { TypescriptDocsRenderer } from './typescript-docs-renderer';
  9. interface DocsSectionConfig {
  10. sourceDirs: string[];
  11. exclude?: RegExp[];
  12. outputPath: string;
  13. }
  14. const sections: DocsSectionConfig[] = [
  15. {
  16. sourceDirs: [
  17. 'packages/core/src/',
  18. 'packages/common/src/',
  19. 'packages/admin-ui-plugin/src/',
  20. 'packages/asset-server-plugin/src/',
  21. 'packages/email-plugin/src/',
  22. 'packages/elasticsearch-plugin/src/',
  23. 'packages/testing/src/',
  24. 'packages/ui-devkit/src/',
  25. ],
  26. exclude: [
  27. /generated-shop-types/,
  28. ],
  29. outputPath: 'typescript-api',
  30. },
  31. ];
  32. generateTypescriptDocs(sections);
  33. const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
  34. if (watchMode) {
  35. console.log(`Watching for changes to source files...`);
  36. sections.forEach(section => {
  37. section.sourceDirs.forEach(dir => {
  38. fs.watch(dir, { recursive: true }, (eventType, file) => {
  39. if (extname(file) === '.ts') {
  40. console.log(`Changes detected in ${dir}`);
  41. generateTypescriptDocs([section], true);
  42. }
  43. });
  44. });
  45. });
  46. }
  47. /**
  48. * Uses the TypeScript compiler API to parse the given files and extract out the documentation
  49. * into markdown files
  50. */
  51. function generateTypescriptDocs(config: DocsSectionConfig[], isWatchMode: boolean = false) {
  52. const timeStart = +new Date();
  53. // This map is used to cache types and their corresponding Hugo path. It is used to enable
  54. // hyperlinking from a member's "type" to the definition of that type.
  55. const globalTypeMap: TypeMap = new Map();
  56. if (!isWatchMode) {
  57. for (const { outputPath, sourceDirs } of config) {
  58. deleteGeneratedDocs(absOutputPath(outputPath));
  59. }
  60. }
  61. for (const { outputPath, sourceDirs, exclude } of config) {
  62. const sourceFilePaths = getSourceFilePaths(sourceDirs, exclude);
  63. const docsPages = new TypescriptDocsParser().parse(sourceFilePaths);
  64. for (const page of docsPages) {
  65. const { category, fileName, declarations } = page;
  66. for (const declaration of declarations) {
  67. const pathToTypeDoc = `${outputPath}/${category ? category + '/' : ''}${
  68. fileName === '_index' ? '' : fileName
  69. }#${toHash(declaration.title)}`;
  70. globalTypeMap.set(declaration.title, pathToTypeDoc);
  71. }
  72. }
  73. const docsUrl = `/docs`;
  74. const generatedCount = new TypescriptDocsRenderer().render(
  75. docsPages,
  76. docsUrl,
  77. absOutputPath(outputPath),
  78. globalTypeMap,
  79. );
  80. if (generatedCount) {
  81. console.log(
  82. `Generated ${generatedCount} typescript api docs for "${outputPath}" in ${+new Date() -
  83. timeStart}ms`,
  84. );
  85. }
  86. }
  87. }
  88. function toHash(title: string): string {
  89. return title.replace(/\s/g, '').toLowerCase();
  90. }
  91. function absOutputPath(outputPath: string): string {
  92. return path.join(__dirname, '../../docs/content/docs/', outputPath);
  93. }
  94. function getSourceFilePaths(sourceDirs: string[], excludePatterns: RegExp[] = []): string[] {
  95. return sourceDirs
  96. .map(scanPath =>
  97. klawSync(path.join(__dirname, '../../', scanPath), {
  98. nodir: true,
  99. filter: item => {
  100. if (path.extname(item.path) === '.ts') {
  101. for (const pattern of excludePatterns) {
  102. if (pattern.test(item.path)) {
  103. return false;
  104. }
  105. }
  106. return true;
  107. }
  108. return false;
  109. },
  110. traverseAll: true,
  111. }),
  112. )
  113. .reduce((allFiles, files) => [...allFiles, ...files], [])
  114. .map(item => item.path);
  115. }