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/job-queue-plugin/src/',
  24. 'packages/testing/src/',
  25. 'packages/ui-devkit/src/',
  26. ],
  27. exclude: [/generated-shop-types/],
  28. outputPath: 'typescript-api',
  29. },
  30. ];
  31. generateTypescriptDocs(sections);
  32. const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
  33. if (watchMode) {
  34. console.log(`Watching for changes to source files...`);
  35. sections.forEach(section => {
  36. section.sourceDirs.forEach(dir => {
  37. fs.watch(dir, { recursive: true }, (eventType, file) => {
  38. if (extname(file) === '.ts') {
  39. console.log(`Changes detected in ${dir}`);
  40. generateTypescriptDocs([section], true);
  41. }
  42. });
  43. });
  44. });
  45. }
  46. /**
  47. * Uses the TypeScript compiler API to parse the given files and extract out the documentation
  48. * into markdown files
  49. */
  50. function generateTypescriptDocs(config: DocsSectionConfig[], isWatchMode: boolean = false) {
  51. const timeStart = +new Date();
  52. // This map is used to cache types and their corresponding Hugo path. It is used to enable
  53. // hyperlinking from a member's "type" to the definition of that type.
  54. const globalTypeMap: TypeMap = new Map();
  55. if (!isWatchMode) {
  56. for (const { outputPath, sourceDirs } of config) {
  57. deleteGeneratedDocs(absOutputPath(outputPath));
  58. }
  59. }
  60. for (const { outputPath, sourceDirs, exclude } of config) {
  61. const sourceFilePaths = getSourceFilePaths(sourceDirs, exclude);
  62. const docsPages = new TypescriptDocsParser().parse(sourceFilePaths);
  63. for (const page of docsPages) {
  64. const { category, fileName, declarations } = page;
  65. for (const declaration of declarations) {
  66. const pathToTypeDoc = `${outputPath}/${category ? category + '/' : ''}${
  67. fileName === '_index' ? '' : fileName
  68. }#${toHash(declaration.title)}`;
  69. globalTypeMap.set(declaration.title, pathToTypeDoc);
  70. }
  71. }
  72. const docsUrl = `/docs`;
  73. const generatedCount = new TypescriptDocsRenderer().render(
  74. docsPages,
  75. docsUrl,
  76. absOutputPath(outputPath),
  77. globalTypeMap,
  78. );
  79. if (generatedCount) {
  80. console.log(
  81. `Generated ${generatedCount} typescript api docs for "${outputPath}" in ${
  82. +new Date() - timeStart
  83. }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/', 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. }