generate-typescript-docs.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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/telemetry-plugin/src/'],
  63. outputPath: '',
  64. },
  65. {
  66. sourceDirs: ['packages/admin-ui/src/lib/', 'packages/ui-devkit/src/'],
  67. exclude: [/generated-types/],
  68. outputPath: 'admin-ui-api',
  69. },
  70. ];
  71. generateTypescriptDocs(sections);
  72. const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
  73. if (watchMode) {
  74. console.log(`Watching for changes to source files...`);
  75. sections.forEach(section => {
  76. section.sourceDirs.forEach(dir => {
  77. fs.watch(dir, { recursive: true }, (eventType, file) => {
  78. if (file && extname(file) === '.ts') {
  79. console.log(`Changes detected in ${dir}`);
  80. generateTypescriptDocs([section], true);
  81. }
  82. });
  83. });
  84. });
  85. }
  86. /**
  87. * Uses the TypeScript compiler API to parse the given files and extract out the documentation
  88. * into markdown files
  89. */
  90. function generateTypescriptDocs(config: DocsSectionConfig[], isWatchMode: boolean = false) {
  91. const timeStart = +new Date();
  92. // This map is used to cache types and their corresponding Hugo path. It is used to enable
  93. // hyperlinking from a member's "type" to the definition of that type.
  94. const globalTypeMap: TypeMap = new Map();
  95. if (!isWatchMode) {
  96. for (const { outputPath, sourceDirs } of config) {
  97. deleteGeneratedDocs(absOutputPath(outputPath));
  98. }
  99. }
  100. for (const { outputPath, sourceDirs, exclude } of config) {
  101. const sourceFilePaths = getSourceFilePaths(sourceDirs, exclude);
  102. const docsPages = new TypescriptDocsParser().parse(sourceFilePaths);
  103. for (const page of docsPages) {
  104. const { category, fileName, declarations } = page;
  105. for (const declaration of declarations) {
  106. const pathToTypeDoc = `reference/${outputPath ? `${outputPath}/` : ''}${
  107. category ? category.map(part => normalizeForUrlPart(part)).join('/') + '/' : ''
  108. }${fileName === 'index' ? '' : fileName}#${toHash(declaration.title)}`;
  109. globalTypeMap.set(declaration.title, pathToTypeDoc);
  110. }
  111. }
  112. const docsUrl = ``;
  113. const generatedCount = new TypescriptDocsRenderer().render(
  114. docsPages,
  115. docsUrl,
  116. absOutputPath(outputPath),
  117. globalTypeMap,
  118. );
  119. if (generatedCount) {
  120. console.log(
  121. `Generated ${generatedCount} typescript api docs for "${outputPath}" in ${
  122. +new Date() - timeStart
  123. }ms`,
  124. );
  125. }
  126. }
  127. }
  128. function toHash(title: string): string {
  129. return title.replace(/\s/g, '').toLowerCase();
  130. }
  131. function absOutputPath(outputPath: string): string {
  132. return path.join(__dirname, '../../docs/docs/reference/', outputPath);
  133. }
  134. function getSourceFilePaths(sourceDirs: string[], excludePatterns: RegExp[] = []): string[] {
  135. return sourceDirs
  136. .map(scanPath =>
  137. klawSync(path.join(__dirname, '../../', scanPath), {
  138. nodir: true,
  139. filter: item => {
  140. const ext = path.extname(item.path);
  141. if (ext === '.ts' || ext === '.tsx') {
  142. for (const pattern of excludePatterns) {
  143. if (pattern.test(item.path)) {
  144. return false;
  145. }
  146. }
  147. return true;
  148. }
  149. return false;
  150. },
  151. traverseAll: true,
  152. }),
  153. )
  154. .reduce((allFiles, files) => [...allFiles, ...files], [])
  155. .map(item => item.path);
  156. }