generate-typescript-docs.ts 4.9 KB

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