Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

3.5 KB
Raw Blame
import fs from "fs"
import { createRequire } from "module"
import path from "path"
import type { ParserOptions } from "@babel/parser"
import { traverse } from "./babel"
import { VALID_FILE_EXTENSIONS } from "./constants"

export function normalizePath(filePath: string): string {
    return filePath.replace(/\\/g, "/")
}

/**
 * Recursively collect component/config files under a surface folder, skipping
 * declaration files, barrels (`index.*`), and underscore-prefixed helpers.
 */
export function crawlModuleFiles(dir: string): string[] {
    const files: string[] = []
    if (!fs.existsSync(dir)) return files

    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const full = path.join(dir, entry.name)
        if (entry.isDirectory()) {
            files.push(...crawlModuleFiles(full))
        } else if (entry.isFile()) {
            const ext = path.extname(entry.name)
            const base = path.basename(entry.name, ext)
            if (base.endsWith(".d")) continue
            if (base.startsWith("_") || base === "index") continue
            if (VALID_FILE_EXTENSIONS.includes(ext)) files.push(full)
        }
    }
    return files
}

export function getParserOptions(file: string): ParserOptions {
    const options: ParserOptions = {
        sourceType: "module",
        plugins: ["jsx"],
    }

    if (file.endsWith(".ts") || file.endsWith(".tsx")) {
        options.plugins!.push("typescript")
    }

    return options
}

export function resolveExports(moduleExports: any) {
    if (
        "default" in moduleExports &&
        moduleExports.default &&
        "default" in moduleExports.default
    ) {
        return resolveExports(moduleExports.default)
    }
    return moduleExports
}

export async function getFileExports(path: string): Promise<any> {
    const { unregister } = await safeRegister()
    // The ESM build has no `require`; a CJS consumer gets one via the shim.
    const load = createRequire(import.meta.url)
    const module = load(path)
    unregister()

    return resolveExports(module)
}

export const safeRegister = async () => {
    const { register } = await import("esbuild-register/dist/node")
    let res: { unregister: () => void }
    try {
        res = register({
            format: "cjs",
            loader: "ts",
        })
    } catch {
        res = {
            unregister: () => {},
        }
    }

    return res
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function hasDefaultExport(ast: any): boolean {
    let found = false

    traverse(ast, {
        ExportDefaultDeclaration() {
            found = true
        },
        AssignmentExpression(path: any) {
            if (
                path.node.left.type === "MemberExpression" &&
                path.node.left.object.type === "Identifier" &&
                path.node.left.object.name === "exports" &&
                path.node.left.property.type === "Identifier" &&
                path.node.left.property.name === "default"
            ) {
                found = true
            }
        },
        ExportNamedDeclaration(path: any) {
            const specifiers = path.node.specifiers
            if (
                specifiers?.some(
                    (s: any) =>
                        s.type === "ExportSpecifier" &&
                        s.exported.type === "Identifier" &&
                        s.exported.name === "default"
                )
            ) {
                found = true
            }
        },
    })

    return found
}