generate-typescript-docs.ts 5.3 KB

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