import { ref, getCurrentInstance, inject, computed, provide, unref } from 'vue';
import { configProviderContextKey, ImportMetaEnvKey } from '../../../constants/key.mjs';
import { keysOf } from '../../../utils/src/objects.mjs';

const globalConfig = ref();
function useGlobalConfig(key, defaultValue = void 0) {
  const config = getCurrentInstance() ? inject(configProviderContextKey, globalConfig) : globalConfig;
  if (key) {
    return computed(() => config.value?.[key] ?? defaultValue);
  } else {
    return config;
  }
}
const provideGlobalConfig = (config, app, global = false) => {
  const inSetup = !!getCurrentInstance();
  const oldConfig = inSetup ? useGlobalConfig() : void 0;
  const provideFn = app?.provide ?? (inSetup ? provide : void 0);
  if (!provideFn) {
    return;
  }
  const context = computed(() => {
    const cfg = unref(config) ?? {};
    if (!oldConfig?.value) return cfg;
    return mergeConfig(oldConfig.value, cfg);
  });
  if (app?.provide) {
    app.provide(configProviderContextKey, context);
  } else if (inSetup) {
    provide(configProviderContextKey, context);
  }
  if (global || !globalConfig.value) {
    globalConfig.value = context.value;
  }
  if (app?.provide) {
    app.provide(ImportMetaEnvKey, context.value.env);
  } else if (inSetup) {
    provide(ImportMetaEnvKey, context.value.env);
  }
  return context;
};
const mergeConfig = (a, b) => {
  const keys = [.../* @__PURE__ */ new Set([...keysOf(a), ...keysOf(b)])];
  const obj = {};
  for (const key of keys) {
    obj[key] = b[key] ?? a[key];
  }
  return obj;
};

export { provideGlobalConfig, useGlobalConfig };
//# sourceMappingURL=index.mjs.map
