import { getPreloadedDictionary } from '@intlayer/core/dictionaryManipulator'; import { resolveInterpreterLocale } from '@intlayer/core/interpreter'; import type { Dictionary } from '@intlayer/types/dictionary'; import type { LocalesValues, StrictModeLocaleMap, } from '@intlayer/types/module_augmentation'; import { computed, inject, type MaybeRefOrGetter, ref, toValue, watch, } from 'vue'; import { INTLAYER_SYMBOL, type IntlayerProvider } from './installIntlayer'; import { useDictionary } from './useDictionary'; /** * On the server side, Hook that transform a dictionary and return the content * * If the locale is not provided, it will use the locale from the client context */ export const useDictionaryAsync = async ( dictionaryPromise: StrictModeLocaleMap<() => Promise>, locale?: MaybeRefOrGetter ) => { const intlayer = inject(INTLAYER_SYMBOL); const localeTarget = computed( () => toValue(locale) ?? intlayer?.locale?.value ?? resolveInterpreterLocale() ); // A build-tool plugin may have started this locale's chunk while the entry // point evaluated, and it may already have landed. Taking it directly leaves this function with no await // point at all, so an async `setup()` resolves in the same tick and // `` never falls back. const preloadedDictionary = getPreloadedDictionary( dictionaryPromise, localeTarget.value ); const dictionary = ref( (preloadedDictionary as T) ?? ((await dictionaryPromise[ localeTarget.value as keyof typeof dictionaryPromise ]?.()) as T) ); watch( () => localeTarget.value, async (locale) => { const newDictionary = await dictionaryPromise[locale as keyof typeof dictionaryPromise]?.(); if (newDictionary) { dictionary.value = newDictionary as T; } } ); return useDictionary(dictionary, localeTarget as any); };