1 import { FlagSettings } from "@medusajs/types"
2 import { readdir } from "fs/promises"
3 import { join, normalize } from "path"
4 import { dynamicImport, isString, readDirRecursive } from "../common"
5
6 const excludedFiles = ["index.js", "index.ts"]
7 const excludedExtensions = [".d.ts", ".d.ts.map", ".js.map"]
8
9 function isFeatureFlag(flag: unknown): flag is FlagSettings {
10 const f = flag as any
11 return !!f && isString(f.key) && isString(f.env_key)
12 }
13
14 /**
15 * Discover feature flag definitions from a directory and subdirectories
16 */
17 export async function discoverFeatureFlagsFromDir(
18 sourcePath?: string,
19 maxDepth: number = 2
20 ): Promise<FlagSettings[]> {
21 if (!sourcePath) {
22 return []
23 }
24
25 const root = normalize(sourcePath)
26 const discovered: FlagSettings[] = []
27
28 const allEntries = await readDirRecursive(root, {
29 ignoreMissing: true,
30 maxDepth,
31 })
32
33 const featureFlagDirs = allEntries
34 .filter((e) => e.isDirectory() && e.name === "feature-flags")
35 .map((e) => join((e as any).path as string, e.name))
36
37 if (!featureFlagDirs.length) {
38 return discovered
39 }
40
41 await Promise.all(
42 featureFlagDirs.map(async (scanDir) => {
43 const entries = await readdir(scanDir, { withFileTypes: true })
44 await Promise.all(
45 entries.map(async (entry) => {
46 if (entry.isDirectory()) {
47 return
48 }
49
50 if (
51 excludedExtensions.some((ext) => entry.name.endsWith(ext)) ||
52 excludedFiles.includes(entry.name)
53 ) {
54 return
55 }
56
57 const fileExports = await dynamicImport(join(scanDir, entry.name))
58 const values = Object.values(fileExports)
59 for (const value of values) {
60 if (isFeatureFlag(value)) {
61 discovered.push(value)
62 }
63 }
64 })
65 )
66 })
67 )
68
69 return discovered
70 }