'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var vue = require('vue');
var StyleContext = require('../StyleContext.cjs');
var useHMR = require('./useHMR.cjs');

function useClientCache(prefix, keyPath, cacheFn, onCacheRemove) {
  const styleContext = StyleContext.useStyleInject();
  const fullPathStr = vue.shallowRef("");
  const res = vue.shallowRef();
  vue.watchEffect(() => {
    fullPathStr.value = [prefix, ...keyPath.value].join("%");
  });
  const HMRUpdate = useHMR.default();
  const clearCache = (pathStr) => {
    styleContext.value.cache.update(pathStr, (prevCache) => {
      const [times = 0, cache] = prevCache || [];
      const nextCount = times - 1;
      if (nextCount === 0) {
        onCacheRemove == null ? void 0 : onCacheRemove(cache, false);
        return null;
      }
      return [times - 1, cache];
    });
  };
  vue.watch(
    fullPathStr,
    (newStr, oldStr) => {
      if (oldStr)
        clearCache(oldStr);
      styleContext.value.cache.update(newStr, (prevCache) => {
        const [times = 0, cache] = prevCache || [];
        let tmpCache = cache;
        if (process.env.NODE_ENV !== "production" && cache && HMRUpdate) {
          onCacheRemove == null ? void 0 : onCacheRemove(tmpCache, HMRUpdate);
          tmpCache = null;
        }
        const mergedCache = tmpCache || cacheFn();
        return [times + 1, mergedCache];
      });
      res.value = styleContext.value.cache.get(fullPathStr.value)[1];
    },
    { immediate: true }
  );
  vue.onBeforeUnmount(() => {
    clearCache(fullPathStr.value);
  });
  return res;
}

exports.default = useClientCache;
//# sourceMappingURL=useGlobalCache.cjs.map
