import { isValidElement, useContext } from "react";
import { Schema, SchemaExpressionScopeContext, SchemaOptionsContext } from "@tachybase/schema";
const compileCache = {};
const useCompile = function() {
    let { noCache } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {
        noCache: false
    };
    const options = useContext(SchemaOptionsContext);
    const scope = useContext(SchemaExpressionScopeContext);
    return (source, ext)=>{
        let shouldCompile = false;
        let cacheKey;
        if ('string' == typeof source && source.startsWith('{{')) {
            shouldCompile = true;
            cacheKey = source;
        }
        if (source && 'object' == typeof source && !isValidElement(source)) {
            shouldCompile = true;
            cacheKey = JSON.stringify(source);
        }
        if (Array.isArray(source)) shouldCompile = true;
        if (shouldCompile) {
            const mergedScope = {
                ...options.scope,
                ...scope,
                ...ext
            };
            if (!cacheKey) return Schema.compile(source, mergedScope);
            try {
                if (noCache) return Schema.compile(source, mergedScope);
                compileCache[cacheKey] = compileCache[cacheKey] || Schema.compile(source, mergedScope);
                return compileCache[cacheKey];
            } catch (e) {
                return Schema.compile(source, mergedScope);
            }
        }
        return source;
    };
};
export { useCompile };
