UNPKG

flagmint-vuejs-feature-flags

Version:

A Vue.js SDK for managing feature flags in Flagmint applications, supporting both Vue 2 and Vue 3.

89 lines (85 loc) 3.46 kB
import { isVue3, isVue2 } from 'vue-demi'; import { FlagClient } from 'flagmint-js-sdk'; import { ref, readonly } from 'vue'; const FLAGMINT_INIT = Symbol.for('FLAGMINT_INIT'); const FLAGMINT_READY = Symbol.for('FLAGMINT_READY'); const FLAGMINT_CLIENT = Symbol.for('FLAGMINT_CLIENT'); // Reactive references const flagClientRef = ref(null); const readyRef = ref(false); const createFeatureFlagPlugin = (options) => ({ install(appOrVue) { // Provide early so inject() sees them before init if (isVue3) { appOrVue.provide(FLAGMINT_READY, readonly(readyRef)); appOrVue.provide(FLAGMINT_CLIENT, flagClientRef); } // Init function const init = async () => { if (flagClientRef.value) return flagClientRef.value; // Avoid re-init const client = new FlagClient(options); await client.ready(); flagClientRef.value = client; readyRef.value = true; if (isVue3) { appOrVue.config.globalProperties.$flagmint = flagClientRef; appOrVue.config.globalProperties.$flagmintReady = readyRef; } else if (isVue2) { // Use Vue.observable to make the state reactive in Vue 2 const Vue = appOrVue.constructor; if (Vue.observable && !Vue.prototype.$flagmintState) { Vue.prototype.$flagmintState = Vue.observable({ flagClientRef, readyRef, }); } if (!Object.getOwnPropertyDescriptor(Vue.prototype, "$flagmint")) { Object.defineProperty(Vue.prototype, "$flagmint", { configurable: true, get() { var _a; return (_a = Vue.prototype.$flagmintState.flagClientRef.value) !== null && _a !== void 0 ? _a : null; }, }); } if (!Object.getOwnPropertyDescriptor(Vue.prototype, "$flagmintReady")) { Object.defineProperty(Vue.prototype, "$flagmintReady", { configurable: true, get() { var _a; return (_a = Vue.prototype.$flagmintState.readyRef.value) !== null && _a !== void 0 ? _a : null; }, }); } if (!Object.getOwnPropertyDescriptor(Vue.prototype, "$flagmintInit")) { Object.defineProperty(Vue.prototype, "$flagmintInit", { configurable: true, value: init, }); } } return client; }; // Provide init if (isVue3) { appOrVue.provide(FLAGMINT_INIT, init); } else if (isVue2) { // Use Vue.prototype for Vue 2 appOrVue.prototype.$flagmintInit = init; } // Auto-init if not deferred if (!options.deferInitialization) { void init(); } }, }); function useFlagClient() { return flagClientRef; } function useFlagmintReady() { return readyRef; } export { FLAGMINT_CLIENT, FLAGMINT_INIT, FLAGMINT_READY, createFeatureFlagPlugin, useFlagClient, useFlagmintReady };