-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
get-portable-stories-usage.ts
51 lines (44 loc) · 1.55 KB
/
get-portable-stories-usage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { readFile } from 'fs/promises';
import { join } from 'path';
import { glob } from 'glob';
import { createFileSystemCache, resolvePathInStorybookCache } from '@storybook/core-common';
const cache = createFileSystemCache({
basePath: resolvePathInStorybookCache('portable-stories'),
ns: 'storybook',
ttl: 24 * 60 * 60 * 1000,
});
export const containsPortableStories = async (filename: string) => {
if (/sb\-preview\/runtime.m?js$/i.test(filename)) return null;
const fileContent = await readFile(filename, 'utf-8');
const contains = /composeStor[y|ies]/g.test(fileContent);
return contains ? filename : null;
};
export const getPortableStoriesFiles = async (base: string) => {
const files = await glob('**/*.{js,mjs,cjs,jsx,ts,mts,cts,tsx}', {
ignore: ['**/node_modules/**', '**/storybook-static/**', '**/dist/**'],
dot: true,
cwd: base,
});
const hits = [];
const chunkSize = 10;
for (let i = 0; i < files.length; i += chunkSize) {
const chunk = files.slice(i, i + chunkSize);
const results = (
await Promise.all(chunk.map((f: string) => containsPortableStories(join(base, f))))
).filter(Boolean);
if (results.length > 0) {
hits.push(...results);
}
}
return hits as string[];
};
const CACHE_KEY = 'portableStories';
export const getPortableStoriesFileCount = async () => {
let cached = await cache.get(CACHE_KEY);
if (!cached) {
const files = await getPortableStoriesFiles(process.cwd());
cached = { usage: files.length };
await cache.set(CACHE_KEY, cached);
}
return cached.usage;
};