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.

6.7 KB
Raw Blame
import fs from "fs"
import path from "path"
import {
    normalizePath,
    getParserOptions,
    hasDefaultExport,
    crawlModuleFiles,
} from "./utils"
import {
    parse,
    traverse,
    isArrayExpression,
    isCallExpression,
    isIdentifier,
    isObjectExpression,
    isObjectProperty,
    isNumericLiteral,
    isStringLiteral,
    isUnaryExpression,
    isVariableDeclaration,
    isVariableDeclarator,
} from "./babel"
import { emitLayers, spreadLayers } from "./layers"
import type { BuiltMercurConfig } from "./types"

type WidgetInfo = {
    zones: string[]
    id?: string
    label?: string
    permissions: string[]
    section?: string
    order?: number
    replace?: string
}

function readNumber(value: any): number | undefined {
    if (isNumericLiteral(value)) return value.value
    if (isUnaryExpression(value) && value.operator === "-" && isNumericLiteral(value.argument)) {
        return -value.argument.value
    }
    return undefined
}

type WidgetResult = {
    import: string
    entry: string
}

function extractStrings(value: any, zones: string[]): void {
    if (isStringLiteral(value)) {
        zones.push(value.value)
    } else if (isArrayExpression(value)) {
        for (const el of value.elements) {
            if (isStringLiteral(el)) zones.push(el.value)
        }
    }
}

function readWidgetConfig(properties: any[]): WidgetInfo | null {
    const zones: string[] = []
    const permissions: string[] = []
    let id: string | undefined
    let label: string | undefined
    let section: string | undefined
    let order: number | undefined
    let replace: string | undefined

    for (const prop of properties) {
        if (!isObjectProperty(prop)) continue
        if (isIdentifier(prop.key, { name: "zone" })) {
            extractStrings(prop.value, zones)
        }
        if (isIdentifier(prop.key, { name: "permission" })) {
            extractStrings(prop.value, permissions)
        }
        if (isIdentifier(prop.key, { name: "id" }) && isStringLiteral(prop.value)) {
            id = prop.value.value
        }
        if (isIdentifier(prop.key, { name: "label" }) && isStringLiteral(prop.value)) {
            label = prop.value.value
        }
        if (isIdentifier(prop.key, { name: "section" }) && isStringLiteral(prop.value)) {
            section = prop.value.value
        }
        if (isIdentifier(prop.key, { name: "order" })) {
            order = readNumber(prop.value)
        }
        if (isIdentifier(prop.key, { name: "replace" }) && isStringLiteral(prop.value)) {
            replace = prop.value.value
        }
    }

    if (zones.length === 0) return null
    return { zones, id, label, permissions, section, order, replace }
}

function getConfigProperties(node: any): any[] | null {
    // `defineWidgetConfig({ ... })` or a bare `{ ... }`.
    if (isCallExpression(node) && node.arguments.length > 0 && isObjectExpression(node.arguments[0])) {
        return node.arguments[0].properties
    }
    if (isObjectExpression(node)) {
        return node.properties
    }
    return null
}

function getWidgetConfig(file: string): WidgetInfo | null {
    try {
        const code = fs.readFileSync(file, "utf-8")
        const ast = parse(code, getParserOptions(file))

        if (!hasDefaultExport(ast)) return null

        let info: WidgetInfo | null = null

        const visit = (declaration: any) => {
            if (info) return
            if (!isVariableDeclaration(declaration)) return
            for (const decl of declaration.declarations) {
                if (
                    isVariableDeclarator(decl) &&
                    isIdentifier(decl.id, { name: "config" })
                ) {
                    const props = getConfigProperties(decl.init)
                    if (props) info = readWidgetConfig(props)
                }
            }
        }

        traverse(ast, {
            ExportNamedDeclaration(p: any) {
                visit(p.node.declaration)
            },
            VariableDeclaration(p: any) {
                visit(p.node)
            },
        })

        return info
    } catch {
        return null
    }
}

function hashPath(relative: string): string {
    let hash = 0
    for (let i = 0; i < relative.length; i++) {
        hash = (hash << 5) - hash + relative.charCodeAt(i)
        hash |= 0
    }
    return Math.abs(hash).toString(36).slice(0, 6)
}

function widgetId(info: WidgetInfo, file: string, widgetsDir: string): string {
    if (info.id) return info.id
    const relative = normalizePath(path.relative(widgetsDir, file))
    return `Widget-${hashPath(relative)}`
}

function parseWidgetFile(
    file: string,
    widgetsDir: string,
    index: number
): WidgetResult | null {
    const info = getWidgetConfig(file)
    if (!info) return null

    const name = `Widget${index}`
    const importPath = normalizePath(file)
    const zonesLiteral = JSON.stringify(info.zones)
    const id = widgetId(info, file, widgetsDir)

    return {
        import: `import ${name} from "${importPath}"`,
        entry: `    { Component: ${name}, zone: ${zonesLiteral}, widgetId: ${JSON.stringify(
            id
        )}${info.label ? `, label: ${JSON.stringify(info.label)}` : ""}${
            info.permissions.length
                ? `, permission: ${JSON.stringify(info.permissions)}`
                : ""
        }${info.section ? `, section: ${JSON.stringify(info.section)}` : ""}${
            info.order !== undefined ? `, order: ${info.order}` : ""
        }${info.replace ? `, replace: ${JSON.stringify(info.replace)}` : ""} }`,
    }
}

/**
 * Crawl a `src/widgets` directory and return the import statements + inline
 * widget entries. Indices are offset so multiple crawls can share a namespace.
 */
export function collectWidgets(
    srcDir: string,
    startIndex = 0
): { imports: string[]; entries: string[] } {
    const widgetsDir = path.join(srcDir, "widgets")

    let index = startIndex
    const results: WidgetResult[] = []
    for (const file of crawlModuleFiles(widgetsDir)) {
        const result = parseWidgetFile(file, widgetsDir, index)
        if (result) {
            results.push(result)
            index++
        }
    }

    return {
        imports: results.map((r) => r.import),
        entries: results.map((r) => r.entry),
    }
}

/**
 * Widgets stack across layers; a later layer's widget with the same id replaces
 * the earlier one so a project can swap a plugin's widget without a new id.
 */
export function generateWidgets(config: BuiltMercurConfig): string {
    const { header, names } = emitLayers(config, ["widgetModule"])

    return `${header}

const byId = new Map()
for (const widget of [
${spreadLayers(names, "widgetModule", "widgets")}
]) {
    byId.set(widget.widgetId, widget)
}

export default { widgets: [...byId.values()] }`
}