import * as validation from "@jet/environment/json/validation";
import * as serverData from "./server-data";
const DERIVED_CACHE_KEY = "_jet-internal:derived-data";
export function value(data, key, generator) {
    if (!data) {
        return null;
    }
    return validation.context(key, () => {
        let computedDataStore = data[DERIVED_CACHE_KEY];
        let returnValue = null;
        if (!computedDataStore) {
            computedDataStore = {};
            data[DERIVED_CACHE_KEY] = computedDataStore;
            returnValue = generateValue(computedDataStore, key, generator);
        }
        else {
            returnValue = serverData.traverse(computedDataStore, key);
            if (!returnValue) {
                returnValue = generateValue(computedDataStore, key, generator);
            }
        }
        return returnValue;
    });
}
/**
 * Computes an unknown value and saves it back into computedDataStore
 * @param {JSONData} computedDataStore The dictionary in which to store the data
 * @param {string} key The key to store it with
 * @param {() => T} generator A function that will generate the value
 * @returns {T} The value that was generated
 */
function generateValue(computedDataStore, key, generator) {
    const generatedValue = generator();
    computedDataStore[key] = generatedValue;
    return generatedValue;
}
//# sourceMappingURL=derived-data.js.map