storybook/scripts/combine-compodoc.ts

80 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-10-10 15:24:50 +11:00
// Compodoc does not follow symlinks (it ignores them and their contents entirely)
// So, we need to run a separate compodoc process on every symlink inside the project,
// then combine the results into one large documentation.json
2022-10-10 15:10:50 +11:00
import { join, resolve } from 'path';
import { realpath, readFile, writeFile, lstat } from 'fs-extra';
2023-04-19 12:01:07 -07:00
import { globSync } from 'glob';
import { execaCommand } from 'execa';
import { esMain } from './utils/esmain';
2024-08-07 12:25:59 +02:00
import { temporaryDirectory } from '../code/core/src/common/utils/cli';
2022-10-10 15:10:50 +11:00
const logger = console;
// Find all symlinks in a directory. There may be more efficient ways to do this, but this works.
async function findSymlinks(dir: string) {
2023-04-19 12:01:07 -07:00
const potentialDirs = await globSync(`${dir}/**/*/`);
2022-10-10 15:10:50 +11:00
return (
await Promise.all(
potentialDirs.map(
async (p) => [p, (await lstat(p.replace(/\/$/, ''))).isSymbolicLink()] as [string, boolean]
)
)
)
.filter(([, s]) => s)
.map(([p]) => p);
}
async function run(cwd: string) {
const dirs = [
cwd,
...(await findSymlinks(resolve(cwd, './src'))),
...(await findSymlinks(resolve(cwd, './stories'))),
...(await findSymlinks(resolve(cwd, './template-stories'))),
];
const docsArray: Record<string, any>[] = await Promise.all(
dirs.map(async (dir) => {
2024-08-07 12:25:59 +02:00
const outputDir = await temporaryDirectory();
2022-10-10 15:10:50 +11:00
const resolvedDir = await realpath(dir);
await execaCommand(
2022-10-10 15:10:50 +11:00
`yarn compodoc ${resolvedDir} -p ./tsconfig.json -e json -d ${outputDir}`,
2022-10-10 15:51:50 +11:00
{ cwd }
2022-10-10 15:10:50 +11:00
);
const contents = await readFile(join(outputDir, 'documentation.json'), 'utf8');
2022-10-10 15:24:50 +11:00
try {
return JSON.parse(contents);
} catch (err) {
logger.error(`Error parsing JSON at ${outputDir}\n\n`);
logger.error(contents);
throw err;
}
2022-10-10 15:10:50 +11:00
})
);
2022-10-10 15:24:50 +11:00
// Compose together any array entries, discard anything else (we happen to only read the array fields)
2022-10-10 15:10:50 +11:00
const documentation = docsArray.slice(1).reduce((acc, entry) => {
return Object.fromEntries(
Object.entries(acc).map(([key, accValue]) => {
if (Array.isArray(accValue)) {
return [key, [...accValue, ...entry[key]]];
}
return [key, accValue];
})
);
}, docsArray[0]);
await writeFile(join(cwd, 'documentation.json'), JSON.stringify(documentation));
}
if (esMain(import.meta.url)) {
2022-10-10 15:10:50 +11:00
run(resolve(process.argv[2]))
.then(() => process.exit(0))
.catch((err) => {
logger.error();
logger.error(err);
process.exit(1);
});
}