flagmint-vuejs-feature-flags
Version:
A Vue.js SDK for managing feature flags in Flagmint applications, supporting both Vue 2 and Vue 3.
65 lines (61 loc) • 2.14 kB
JavaScript
import { ref, inject, watch, onUnmounted } from 'vue';
const FLAGMINT_INIT = Symbol.for('FLAGMINT_INIT');
const FLAGMINT_READY = Symbol.for('FLAGMINT_READY');
const FLAGMINT_CLIENT = Symbol.for('FLAGMINT_CLIENT');
const flags = ref({});
let unsubscribe = null;
let subscriberCount = 0;
function useFlagmint() {
// inject() called synchronously at top level — safe because provides
// are registered before install() returns, before any component mounts
const clientRef = inject(FLAGMINT_CLIENT, ref(null));
const isReady = inject(FLAGMINT_READY, ref(false));
const init = inject(FLAGMINT_INIT, null);
let stopWatch = null;
const onReady = (ready) => {
if (ready) {
startSubscription();
stopWatch === null || stopWatch === void 0 ? void 0 : stopWatch();
}
};
const startSubscription = () => {
subscriberCount++;
const client = clientRef.value;
if (!client || unsubscribe)
return;
unsubscribe = client.subscribe((updatedFlags) => {
flags.value = updatedFlags;
});
};
// Watch isReady — handles both "already ready at mount" and "becomes ready later"
stopWatch = watch(() => isReady.value, onReady, { immediate: true });
onUnmounted(() => {
subscriberCount--;
stopWatch === null || stopWatch === void 0 ? void 0 : stopWatch();
if (unsubscribe && subscriberCount === 0) {
unsubscribe();
unsubscribe = null;
}
});
const getFlag = (key, fallback) => {
var _a;
return ((_a = flags.value[key]) !== null && _a !== void 0 ? _a : fallback);
};
const updateFlagmintContext = async (context) => {
const client = clientRef.value;
if (!client) {
console.warn('[Flagmint] updateFlagmintContext called before client was ready.');
return;
}
await client.updateContext(context);
};
return {
client: clientRef,
isReady,
init,
flags,
getFlag,
updateFlagmintContext
};
}
export { useFlagmint };