@rivinia/i18n 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -688,6 +688,370 @@ function resolveUrl(value, base) {
688
688
  return null;
689
689
  }
690
690
  }
691
+ var DocumentDirectionApplier = class {
692
+ _deps;
693
+ _applyCount = 0;
694
+ constructor(_deps) {
695
+ this._deps = _deps;
696
+ }
697
+ install(language) {
698
+ effect(() => this.applyDirection(language()));
699
+ }
700
+ applyDirection(language) {
701
+ const root = this._deps.document.documentElement;
702
+ if (!root) return;
703
+ root.dir = language.dir;
704
+ root.lang = language.locale ?? language.id;
705
+ }
706
+ apply(language, callback) {
707
+ const config = this._deps.config;
708
+ const service = this._deps.viewTransition;
709
+ this._applyCount++;
710
+ if (!(config?.enabled && (!config.skipInitialTransition || this._applyCount > 1) && service != null)) {
711
+ callback();
712
+ return;
713
+ }
714
+ const info = {
715
+ language: language.id,
716
+ direction: language.dir
717
+ };
718
+ config.onViewTransitionCreated?.(info);
719
+ service.run(callback);
720
+ }
721
+ };
722
+ var DictionaryStore = class {
723
+ _deps;
724
+ _visible = signal({}, ...ngDevMode ? [{ debugName: "_visible" }] : /* istanbul ignore next */ []);
725
+ _fallbackDict = signal(null, ...ngDevMode ? [{ debugName: "_fallbackDict" }] : /* istanbul ignore next */ []);
726
+ _loadingState = signal("idle", ...ngDevMode ? [{ debugName: "_loadingState" }] : /* istanbul ignore next */ []);
727
+ _loadingError = signal(null, ...ngDevMode ? [{ debugName: "_loadingError" }] : /* istanbul ignore next */ []);
728
+ _cache = /* @__PURE__ */ new Map();
729
+ _generations = /* @__PURE__ */ new Map();
730
+ _inflight = /* @__PURE__ */ new Map();
731
+ _loadingCount = 0;
732
+ _resolvedLoader = null;
733
+ visible = this._visible.asReadonly();
734
+ fallback = this._fallbackDict.asReadonly();
735
+ loadingState = this._loadingState.asReadonly();
736
+ loadingError = this._loadingError.asReadonly();
737
+ constructor(_deps) {
738
+ this._deps = _deps;
739
+ }
740
+ has(languageId) {
741
+ return this._cache.has(languageId) || this._deps.hasInline(languageId);
742
+ }
743
+ seedVisible(data) {
744
+ this._visible.set(data);
745
+ }
746
+ adoptTransferred(languageId, data) {
747
+ this._cache.set(languageId, data);
748
+ this._apply(languageId, data);
749
+ }
750
+ consumeTransfer(languageId) {
751
+ const transfer = this._deps.transfer;
752
+ if (!transfer) return null;
753
+ const key = this._transferKey(languageId);
754
+ if (!transfer.hasKey(key)) return null;
755
+ const dict = transfer.get(key, null);
756
+ transfer.remove(key);
757
+ return dict;
758
+ }
759
+ async load(languageId, opts) {
760
+ const background = opts?.background === true;
761
+ if (!opts?.force) {
762
+ const cached = this._cache.get(languageId);
763
+ if (cached) {
764
+ this._apply(languageId, cached);
765
+ return {
766
+ data: cached,
767
+ ok: true
768
+ };
769
+ }
770
+ }
771
+ let task = opts?.force ? void 0 : this._inflight.get(languageId);
772
+ if (!task) {
773
+ task = this._fetch(languageId, this._generationOf(languageId));
774
+ this._inflight.set(languageId, task);
775
+ }
776
+ if (!background) {
777
+ this._loadingCount++;
778
+ this._loadingState.set("loading");
779
+ }
780
+ try {
781
+ const result = await task;
782
+ if (result.ok) this._apply(languageId, result.data);
783
+ else if (!background && result.error !== void 0 && languageId === this._deps.currentLanguage()) {
784
+ this._loadingError.set(result.error);
785
+ this._loadingState.set("error");
786
+ }
787
+ return {
788
+ data: result.data,
789
+ ok: result.ok
790
+ };
791
+ } finally {
792
+ if (!background) {
793
+ this._loadingCount = Math.max(0, this._loadingCount - 1);
794
+ if (this._loadingCount === 0 && this._loadingState() === "loading") this._loadingState.set("idle");
795
+ }
796
+ }
797
+ }
798
+ reload(languageId) {
799
+ if (languageId !== void 0) {
800
+ if (!this._deps.languageIds().includes(languageId)) return Promise.resolve(false);
801
+ this._invalidate(languageId);
802
+ return this._reloadOne(languageId);
803
+ }
804
+ const currentId = this._deps.currentLanguage();
805
+ const fallbackId = this._deps.fallbackLanguage;
806
+ for (const cachedId of [...this._cache.keys()]) if (cachedId !== currentId && cachedId !== fallbackId) this._cache.delete(cachedId);
807
+ for (const language of this._deps.languageIds()) this._invalidate(language);
808
+ const currentLoad = this._reloadOne(currentId);
809
+ if (fallbackId !== null && fallbackId !== currentId) this._reloadOne(fallbackId);
810
+ return currentLoad;
811
+ }
812
+ ensureFallback() {
813
+ const fallbackId = this._deps.fallbackLanguage;
814
+ if (fallbackId === null || fallbackId === this._deps.currentLanguage()) return;
815
+ if (this.has(fallbackId)) return;
816
+ this.load(fallbackId, { background: true });
817
+ }
818
+ _reloadOne(languageId) {
819
+ return this.load(languageId, {
820
+ force: true,
821
+ background: languageId !== this._deps.currentLanguage()
822
+ }).then((result) => result.ok);
823
+ }
824
+ _apply(languageId, data) {
825
+ if (languageId === this._deps.currentLanguage()) {
826
+ this._visible.set(data);
827
+ this._loadingError.set(null);
828
+ if (this._loadingCount === 0 && this._loadingState() === "error") this._loadingState.set("idle");
829
+ }
830
+ if (languageId === this._deps.fallbackLanguage) this._fallbackDict.set(data);
831
+ }
832
+ _fetch(languageId, generation) {
833
+ let task;
834
+ task = (async () => {
835
+ const stale = () => this._generationOf(languageId) !== generation;
836
+ try {
837
+ if (!this._resolvedLoader) this._resolvedLoader = await this._deps.loader(this._deps.loaderContext);
838
+ const translations = await this._resolvedLoader.load(languageId, this._deps.loaderContext);
839
+ if (stale()) return {
840
+ data: {},
841
+ ok: false
842
+ };
843
+ this._cache.set(languageId, translations);
844
+ this._writeTransfer(languageId, translations);
845
+ return {
846
+ data: translations,
847
+ ok: true
848
+ };
849
+ } catch (error) {
850
+ if (stale()) return {
851
+ data: {},
852
+ ok: false
853
+ };
854
+ this._deps.onLoadError?.(languageId, error);
855
+ return {
856
+ data: {},
857
+ ok: false,
858
+ error
859
+ };
860
+ } finally {
861
+ if (this._inflight.get(languageId) === task) this._inflight.delete(languageId);
862
+ }
863
+ })();
864
+ return task;
865
+ }
866
+ _generationOf(languageId) {
867
+ return this._generations.get(languageId) ?? 0;
868
+ }
869
+ _invalidate(languageId) {
870
+ this._generations.set(languageId, this._generationOf(languageId) + 1);
871
+ }
872
+ _transferKey(languageId) {
873
+ return makeStateKey(`rivinia.i18n.dict.${languageId}`);
874
+ }
875
+ _writeTransfer(languageId, dict) {
876
+ if (!this._deps.request) return;
877
+ this._deps.transfer?.set(this._transferKey(languageId), dict);
878
+ }
879
+ };
880
+ var LanguageStorage = class {
881
+ _deps;
882
+ constructor(_deps) {
883
+ this._deps = _deps;
884
+ }
885
+ read() {
886
+ if (this._deps.strategy === "cookie") {
887
+ const header = this._deps.request?.headers.get("cookie") ?? null;
888
+ if (header !== null) return parseCookie(header, this._deps.key);
889
+ try {
890
+ return parseCookie(this._deps.document.cookie, this._deps.key);
891
+ } catch {
892
+ return null;
893
+ }
894
+ }
895
+ return safeGetItem(this._deps.key, this._deps.strategy);
896
+ }
897
+ write(id) {
898
+ if (this._deps.strategy === "cookie") {
899
+ if (this._deps.request) return;
900
+ try {
901
+ const location = this._deps.document?.location;
902
+ this._deps.document.cookie = serializeCookie(this._deps.key, id, { secure: shouldSecureCookie(location) });
903
+ } catch {}
904
+ return;
905
+ }
906
+ safeSetItem(this._deps.key, id, this._deps.strategy);
907
+ }
908
+ persistAfterSwitch(id) {
909
+ if (!this._deps.persist) return;
910
+ if (this.read() === id) return;
911
+ this.write(id);
912
+ }
913
+ resolveInitialLanguage() {
914
+ const stored = this.read();
915
+ const languages = this._deps.languages();
916
+ if (stored && languages.some((l) => l.id === stored)) return stored;
917
+ if (this._deps.detectBrowser) {
918
+ const detected = detectBrowserLanguage(languages.map((l) => l.id), this._deps.browserLanguages());
919
+ if (detected) return detected;
920
+ }
921
+ return this._deps.defaultLanguage;
922
+ }
923
+ };
924
+ var MissingKeyReporter = class {
925
+ _deps;
926
+ _missingKeys = signal([], ...ngDevMode ? [{ debugName: "_missingKeys" }] : /* istanbul ignore next */ []);
927
+ _reportedKeys = /* @__PURE__ */ new Set();
928
+ _pendingKeys = [];
929
+ _pendingKeyEvents = [];
930
+ _keyFlushQueued = false;
931
+ _reportedParams = /* @__PURE__ */ new Set();
932
+ _pendingParamEvents = [];
933
+ _paramFlushQueued = false;
934
+ missingKeys = this._missingKeys.asReadonly();
935
+ constructor(_deps) {
936
+ this._deps = _deps;
937
+ }
938
+ reportKey(key) {
939
+ if (!this._deps.hasDictionary(this._deps.language())) return;
940
+ if (this._reportedKeys.has(key)) return;
941
+ this._reportedKeys.add(key);
942
+ const language = this._deps.language();
943
+ const fallbackLanguage = this._deps.fallbackLanguage;
944
+ this._pendingKeys.push(key);
945
+ this._pendingKeyEvents.push(fallbackLanguage === null ? {
946
+ key,
947
+ language
948
+ } : {
949
+ key,
950
+ language,
951
+ fallbackLanguage
952
+ });
953
+ this._queueKeyFlush();
954
+ if (this._deps.warnOnMissingKey) console.warn(`[rivinia/i18n] Missing key "${key}" for language "${language}"` + (fallbackLanguage === null ? "." : ` (fallback "${fallbackLanguage}" has no value either).`));
955
+ }
956
+ reportParam(key, param) {
957
+ const dedupe = `${key}\u0000${param}`;
958
+ if (this._reportedParams.has(dedupe)) return;
959
+ this._reportedParams.add(dedupe);
960
+ const language = this._deps.language();
961
+ this._pendingParamEvents.push({
962
+ key,
963
+ param,
964
+ language
965
+ });
966
+ this._queueParamFlush();
967
+ if (this._deps.warnOnMissingParam) console.warn(`[rivinia/i18n] Missing parameter "${param}" for key "${key}" and language "${language}"; the placeholder was kept.`);
968
+ }
969
+ clearKeys() {
970
+ this._reportedKeys.clear();
971
+ this._pendingKeys.length = 0;
972
+ this._pendingKeyEvents.length = 0;
973
+ this._missingKeys.set([]);
974
+ }
975
+ clearParams() {
976
+ this._reportedParams.clear();
977
+ this._pendingParamEvents.length = 0;
978
+ }
979
+ _queueKeyFlush() {
980
+ if (this._keyFlushQueued) return;
981
+ this._keyFlushQueued = true;
982
+ queueMicrotask(() => {
983
+ this._keyFlushQueued = false;
984
+ const pending = this._pendingKeys.splice(0);
985
+ if (pending.length === 0) return;
986
+ this._missingKeys.update((current) => [...current, ...pending]);
987
+ const events = this._pendingKeyEvents.splice(0);
988
+ for (const event of events) this._deps.onMissingKey?.(event);
989
+ });
990
+ }
991
+ _queueParamFlush() {
992
+ if (this._paramFlushQueued) return;
993
+ this._paramFlushQueued = true;
994
+ queueMicrotask(() => {
995
+ this._paramFlushQueued = false;
996
+ const events = this._pendingParamEvents.splice(0);
997
+ for (const event of events) this._deps.onMissingParam?.(event);
998
+ });
999
+ }
1000
+ };
1001
+ const FORMATTER_CACHE_LIMIT = 40;
1002
+ var MessageFormatter = class {
1003
+ _deps;
1004
+ _capacity;
1005
+ _formatters = /* @__PURE__ */ new Map();
1006
+ constructor(_deps, _capacity = FORMATTER_CACHE_LIMIT) {
1007
+ this._deps = _deps;
1008
+ this._capacity = _capacity;
1009
+ }
1010
+ get cachedFormatterCount() {
1011
+ return this._formatters.size;
1012
+ }
1013
+ render(template, params, locale, key) {
1014
+ const quoting = template.includes("'");
1015
+ if (params === void 0 && !quoting) return template;
1016
+ if (!quoting && !template.includes("{")) return template;
1017
+ try {
1018
+ return formatIcu(template, params ?? {}, locale, { onMissingParam: (name) => this._deps.onMissingParam?.(key, name) });
1019
+ } catch {
1020
+ return template;
1021
+ }
1022
+ }
1023
+ formatNumber(value, options) {
1024
+ return this._numberFormatter(options).format(value);
1025
+ }
1026
+ formatDate(value, options) {
1027
+ return this._dateTimeFormatter(options).format(value);
1028
+ }
1029
+ _numberFormatter(options) {
1030
+ const locale = this._deps.locale();
1031
+ const key = `n|${locale}|${JSON.stringify(options ?? null)}`;
1032
+ return this._memo(key, () => new Intl.NumberFormat(locale, options));
1033
+ }
1034
+ _dateTimeFormatter(options) {
1035
+ const locale = this._deps.locale();
1036
+ const key = `d|${locale}|${JSON.stringify(options ?? null)}`;
1037
+ return this._memo(key, () => new Intl.DateTimeFormat(locale, options));
1038
+ }
1039
+ _memo(key, create) {
1040
+ const cached = this._formatters.get(key);
1041
+ if (cached) {
1042
+ this._formatters.delete(key);
1043
+ this._formatters.set(key, cached);
1044
+ return cached;
1045
+ }
1046
+ const created = create();
1047
+ if (this._formatters.size >= this._capacity) {
1048
+ const oldest = this._formatters.keys().next().value;
1049
+ if (oldest !== void 0) this._formatters.delete(oldest);
1050
+ }
1051
+ this._formatters.set(key, created);
1052
+ return created;
1053
+ }
1054
+ };
691
1055
  var ViewTransitionService = class ViewTransitionService {
692
1056
  _doc = inject(DOCUMENT);
693
1057
  run(callback) {
@@ -720,29 +1084,43 @@ i0.ɵɵngDeclareClassMetadata({
720
1084
  var RiviniaI18n = class RiviniaI18n {
721
1085
  _config = inject(RIVINIA_I18N_CONFIG);
722
1086
  _viewTransition = inject(ViewTransitionService, { optional: true });
723
- _storageKey = this._config.storageKey ?? "rivinia.i18n.language";
724
- _storageStrategy = this._config.storageStrategy ?? "local";
725
1087
  _autoApplyDirection = this._config.autoApplyDirection ?? true;
726
- _persist = this._config.persist ?? true;
727
1088
  _fallbackId = this._config.fallbackLanguage ?? null;
728
1089
  _doc = inject(DOCUMENT);
729
1090
  _request = inject(REQUEST, { optional: true });
730
1091
  _transfer = inject(TransferState, { optional: true });
1092
+ _direction = new DocumentDirectionApplier({
1093
+ document: this._doc,
1094
+ viewTransition: this._viewTransition,
1095
+ config: this._config.viewTransition
1096
+ });
731
1097
  loaderContext = createLoaderContext(this._request ?? null, this._doc);
732
- _currentLanguageId = signal(this._resolveInitialLanguage(), ...ngDevMode ? [{ debugName: "_currentLanguageId" }] : /* istanbul ignore next */ []);
733
1098
  _languages = signal(this._config.languages, ...ngDevMode ? [{ debugName: "_languages" }] : /* istanbul ignore next */ []);
734
- _loadedTranslations = signal({}, ...ngDevMode ? [{ debugName: "_loadedTranslations" }] : /* istanbul ignore next */ []);
735
- _fallbackDict = signal(null, ...ngDevMode ? [{ debugName: "_fallbackDict" }] : /* istanbul ignore next */ []);
736
- _getLoader = (context) => this._config.loader ? this._config.loader.resolve(context) : jsonLoader().resolve(context);
737
- _resolvedLoader = null;
738
- _translationsCache = /* @__PURE__ */ new Map();
739
- _generations = /* @__PURE__ */ new Map();
740
- _inflight = /* @__PURE__ */ new Map();
741
- _loadingCount = 0;
742
- _applyCount = 0;
1099
+ _languageStorage = new LanguageStorage({
1100
+ key: this._config.storageKey ?? "rivinia.i18n.language",
1101
+ strategy: this._config.storageStrategy ?? "local",
1102
+ languages: () => this._languages(),
1103
+ defaultLanguage: this._config.defaultLanguage,
1104
+ detectBrowser: this._config.detectBrowser ?? false,
1105
+ document: this._doc,
1106
+ request: this._request ?? null,
1107
+ persist: this._config.persist ?? true,
1108
+ browserLanguages
1109
+ });
1110
+ _currentLanguageId = signal(this._languageStorage.resolveInitialLanguage(), ...ngDevMode ? [{ debugName: "_currentLanguageId" }] : /* istanbul ignore next */ []);
1111
+ _store = new DictionaryStore({
1112
+ loader: (context) => this._config.loader ? this._config.loader.resolve(context) : jsonLoader().resolve(context),
1113
+ loaderContext: this.loaderContext,
1114
+ request: this._request ?? null,
1115
+ transfer: this._transfer,
1116
+ onLoadError: this._config.onLoadError,
1117
+ currentLanguage: () => this._currentLanguageId(),
1118
+ fallbackLanguage: this._fallbackId,
1119
+ languageIds: () => this._languages().map((l) => l.id),
1120
+ hasInline: (languageId) => this._config.translations?.[languageId] !== void 0
1121
+ });
743
1122
  _initialized = false;
744
1123
  _tasks = inject(PendingTasks, { optional: true });
745
- languageChanged = computed(() => this._currentLanguageId(), ...ngDevMode ? [{ debugName: "languageChanged" }] : /* istanbul ignore next */ []);
746
1124
  languages = this._languages.asReadonly();
747
1125
  currentLanguage = this._currentLanguageId.asReadonly();
748
1126
  currentLanguageObject = computed(() => {
@@ -751,45 +1129,32 @@ var RiviniaI18n = class RiviniaI18n {
751
1129
  }, ...ngDevMode ? [{ debugName: "currentLanguageObject" }] : /* istanbul ignore next */ []);
752
1130
  dir = computed(() => this.currentLanguageObject().dir, ...ngDevMode ? [{ debugName: "dir" }] : /* istanbul ignore next */ []);
753
1131
  isRtl = computed(() => this.dir() === "rtl", ...ngDevMode ? [{ debugName: "isRtl" }] : /* istanbul ignore next */ []);
754
- _loadingState = signal("idle", ...ngDevMode ? [{ debugName: "_loadingState" }] : /* istanbul ignore next */ []);
755
- _loadingError = signal(null, ...ngDevMode ? [{ debugName: "_loadingError" }] : /* istanbul ignore next */ []);
756
- loadingState = this._loadingState.asReadonly();
757
- loadingError = this._loadingError.asReadonly();
758
- isLoading = computed(() => this._loadingState() === "loading", ...ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []);
1132
+ loadingState = this._store.loadingState;
1133
+ loadingError = this._store.loadingError;
1134
+ isLoading = computed(() => this._store.loadingState() === "loading", ...ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []);
759
1135
  _ready = signal(false, ...ngDevMode ? [{ debugName: "_ready" }] : /* istanbul ignore next */ []);
760
1136
  ready = this._ready.asReadonly();
761
- _warnOnMissingKey = this._config.warnOnMissingKey ?? (isDevMode() && this._config.onMissingKey === void 0);
762
- _missingKeys = signal([], ...ngDevMode ? [{ debugName: "_missingKeys" }] : /* istanbul ignore next */ []);
763
- _reportedMissingKeys = /* @__PURE__ */ new Set();
764
- _pendingMissingKeys = [];
765
- _pendingMissingEvents = [];
766
- _missingFlushQueued = false;
767
- _warnOnMissingParam = this._config.warnOnMissingParam ?? (isDevMode() && this._config.onMissingParam === void 0);
768
- _reportedMissingParams = /* @__PURE__ */ new Set();
769
- _pendingMissingParams = [];
770
- _missingParamsFlushQueued = false;
771
- missingKeys = this._missingKeys.asReadonly();
1137
+ _missingKeyReporter = new MissingKeyReporter({
1138
+ language: () => this._currentLanguageId(),
1139
+ fallbackLanguage: this._fallbackId,
1140
+ hasDictionary: (language) => this._hasDictionary(language),
1141
+ onMissingKey: this._config.onMissingKey,
1142
+ onMissingParam: this._config.onMissingParam,
1143
+ warnOnMissingKey: this._config.warnOnMissingKey ?? (isDevMode() && this._config.onMissingKey === void 0),
1144
+ warnOnMissingParam: this._config.warnOnMissingParam ?? (isDevMode() && this._config.onMissingParam === void 0)
1145
+ });
1146
+ missingKeys = this._missingKeyReporter.missingKeys;
772
1147
  clearMissingKeys() {
773
- this._reportedMissingKeys.clear();
774
- this._pendingMissingKeys.length = 0;
775
- this._pendingMissingEvents.length = 0;
776
- this._missingKeys.set([]);
1148
+ this._missingKeyReporter.clearKeys();
777
1149
  }
778
1150
  clearMissingParams() {
779
- this._reportedMissingParams.clear();
780
- this._pendingMissingParams.length = 0;
1151
+ this._missingKeyReporter.clearParams();
781
1152
  }
782
1153
  constructor() {
783
1154
  if (this._config.languages.length === 0) throw new Error("[rivinia/i18n] At least one language must be provided in the languages array.");
784
1155
  if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) throw new Error(`[rivinia/i18n] defaultLanguage "${this._config.defaultLanguage}" must be one of the configured language IDs.`);
785
1156
  if (this._fallbackId !== null && !this._config.languages.some((l) => l.id === this._fallbackId)) throw new Error(`[rivinia/i18n] fallbackLanguage "${this._fallbackId}" must be one of the configured language IDs.`);
786
- if (this._autoApplyDirection) effect(() => {
787
- const lang = this.currentLanguageObject();
788
- const root = this._doc.documentElement;
789
- if (!root) return;
790
- root.dir = lang.dir;
791
- root.lang = lang.locale ?? lang.id;
792
- });
1157
+ if (this._autoApplyDirection) this._direction.install(() => this.currentLanguageObject());
793
1158
  }
794
1159
  getLanguage(id) {
795
1160
  return this._languages().find((l) => l.id === id);
@@ -803,28 +1168,20 @@ var RiviniaI18n = class RiviniaI18n {
803
1168
  const fallback = this._fallbackId;
804
1169
  const hasFallback = fallback !== null && fallback !== current;
805
1170
  const preload = this._config.preload ?? true;
806
- const transferred = this.readTransfer(current);
807
- if (transferred) {
808
- this._translationsCache.set(current, transferred);
809
- this._loadedTranslations.set(transferred);
810
- } else {
1171
+ const transferred = this._store.consumeTransfer(current);
1172
+ if (transferred) this._store.adoptTransferred(current, transferred);
1173
+ else {
811
1174
  const inline = this._config.translations?.[current];
812
- if (inline) this._loadedTranslations.set(inline);
1175
+ if (inline) this._store.seedVisible(inline);
813
1176
  }
814
1177
  let fallbackTransferred = null;
815
1178
  if (hasFallback) {
816
- fallbackTransferred = this.readTransfer(fallback);
817
- if (fallbackTransferred) {
818
- this._translationsCache.set(fallback, fallbackTransferred);
819
- this._fallbackDict.set(fallbackTransferred);
820
- }
1179
+ fallbackTransferred = this._store.consumeTransfer(fallback);
1180
+ if (fallbackTransferred) this._store.adoptTransferred(fallback, fallbackTransferred);
821
1181
  }
822
1182
  const loads = [];
823
- if (!transferred && preload) loads.push(this._loadTranslations(current));
824
- if (hasFallback && !fallbackTransferred && preload) loads.push(this._loadTranslations(fallback, {
825
- silent: true,
826
- background: true
827
- }));
1183
+ if (!transferred && preload) loads.push(this._store.load(current));
1184
+ if (hasFallback && !fallbackTransferred && preload) loads.push(this._store.load(fallback, { background: true }));
828
1185
  await Promise.all(loads);
829
1186
  } finally {
830
1187
  this._ready.set(true);
@@ -855,35 +1212,12 @@ var RiviniaI18n = class RiviniaI18n {
855
1212
  const fallback = defaultValue ?? key;
856
1213
  return params ? this.render(fallback, params, this.locale(), key) : fallback;
857
1214
  }
858
- loadedTranslations = this._loadedTranslations.asReadonly();
859
- async loadTranslations(languageId, opts) {
860
- return (await this._loadTranslations(languageId, opts)).data;
1215
+ loadedTranslations = this._store.visible;
1216
+ async loadTranslations(languageId) {
1217
+ return (await this._store.load(languageId)).data;
861
1218
  }
862
1219
  reload(languageId) {
863
- if (languageId !== void 0) {
864
- if (!this._languages().some((l) => l.id === languageId)) return Promise.resolve(false);
865
- this._invalidate(languageId);
866
- return this._reloadOne(languageId);
867
- }
868
- const currentId = this._currentLanguageId();
869
- const fallbackId = this._fallbackId;
870
- for (const cachedId of [...this._translationsCache.keys()]) if (cachedId !== currentId && cachedId !== fallbackId) this._translationsCache.delete(cachedId);
871
- for (const language of this._languages()) this._invalidate(language.id);
872
- const currentLoad = this._reloadOne(currentId);
873
- if (fallbackId !== null && fallbackId !== currentId) this._reloadOne(fallbackId);
874
- return currentLoad;
875
- }
876
- _reloadOne(languageId) {
877
- return this._loadTranslations(languageId, {
878
- force: true,
879
- background: languageId !== this._currentLanguageId()
880
- }).then((result) => result.ok);
881
- }
882
- _generationOf(languageId) {
883
- return this._generations.get(languageId) ?? 0;
884
- }
885
- _invalidate(languageId) {
886
- this._generations.set(languageId, this._generationOf(languageId) + 1);
1220
+ return this._store.reload(languageId);
887
1221
  }
888
1222
  toggle() {
889
1223
  const langs = this._languages();
@@ -914,82 +1248,46 @@ var RiviniaI18n = class RiviniaI18n {
914
1248
  async setLanguageAsync(id) {
915
1249
  if (id === this._currentLanguageId()) return;
916
1250
  if (!this._languages().some((l) => l.id === id)) return;
917
- const { ok } = await this._loadTranslations(id, { silent: true });
1251
+ const { ok } = await this._store.load(id);
918
1252
  if (!ok) return;
919
1253
  this.applyLanguage(id);
920
1254
  }
921
1255
  formatNumber(value, options) {
922
- return this.numberFormatter(options).format(value);
1256
+ return this._messageFormatter.formatNumber(value, options);
923
1257
  }
924
1258
  formatDate(value, options) {
925
- return this.dateTimeFormatter(options).format(value);
1259
+ return this._messageFormatter.formatDate(value, options);
926
1260
  }
927
1261
  locale = computed(() => {
928
1262
  return this.currentLanguageObject().locale ?? this._currentLanguageId();
929
1263
  }, ...ngDevMode ? [{ debugName: "locale" }] : /* istanbul ignore next */ []);
930
- _formatters = /* @__PURE__ */ new Map();
931
- numberFormatter(options) {
932
- const key = `n|${this.locale()}|${JSON.stringify(options ?? null)}`;
933
- let formatter = this._formatters.get(key);
934
- if (!formatter) {
935
- formatter = new Intl.NumberFormat(this.locale(), options);
936
- this._formatters.set(key, formatter);
937
- }
938
- return formatter;
939
- }
940
- dateTimeFormatter(options) {
941
- const key = `d|${this.locale()}|${JSON.stringify(options ?? null)}`;
942
- let formatter = this._formatters.get(key);
943
- if (!formatter) {
944
- formatter = new Intl.DateTimeFormat(this.locale(), options);
945
- this._formatters.set(key, formatter);
946
- }
947
- return formatter;
948
- }
1264
+ _messageFormatter = new MessageFormatter({
1265
+ locale: () => this.locale(),
1266
+ onMissingParam: (key, name) => untracked(() => this._reportMissingParam(key, name))
1267
+ });
949
1268
  applyLanguage(id, opts) {
950
1269
  if (id === this._currentLanguageId()) return;
951
1270
  const lang = this._languages().find((l) => l.id === id);
952
1271
  if (!lang) return;
953
- this._applyCount++;
954
- const apply = () => this._currentLanguageId.set(id);
955
- const vt = this._config.viewTransition;
956
- if (vt?.enabled && (!vt.skipInitialTransition || this._applyCount > 1) && this._viewTransition != null) {
957
- vt.onViewTransitionCreated?.({
958
- language: id,
959
- direction: lang.dir
960
- });
961
- this._viewTransition.run(apply);
962
- } else apply();
1272
+ this._direction.apply(lang, () => this._currentLanguageId.set(id));
963
1273
  if (!opts?.skipLoad) {
964
- this._loadTranslations(id);
965
- this._ensureFallback();
1274
+ this._store.load(id);
1275
+ this._store.ensureFallback();
966
1276
  }
967
- this._persistLanguage(id);
968
- }
969
- _persistLanguage(id) {
970
- if (!this._persist) return;
971
- if (this._readStored() === id) return;
972
- this._writeStored(id);
1277
+ this._languageStorage.persistAfterSwitch(id);
973
1278
  }
974
1279
  render(template, params, locale, key) {
975
- const quoting = template.includes("'");
976
- if (params === void 0 && !quoting) return template;
977
- if (!quoting && !template.includes("{")) return template;
978
- try {
979
- return formatIcu(template, params ?? {}, locale, { onMissingParam: (name) => untracked(() => this._reportMissingParam(key, name)) });
980
- } catch {
981
- return template;
982
- }
1280
+ return this._messageFormatter.render(template, params, locale, key);
983
1281
  }
984
1282
  _lookupKey(key) {
985
- const currentValue = this._resolveKey(this._loadedTranslations(), key);
1283
+ const currentValue = this._resolveKey(this._store.visible(), key);
986
1284
  if (currentValue !== void 0) return {
987
1285
  text: currentValue,
988
1286
  locale: this.locale()
989
1287
  };
990
1288
  const fallbackId = this._fallbackId;
991
1289
  if (fallbackId === null || fallbackId === this._currentLanguageId()) return void 0;
992
- const fallbackDict = this._fallbackDict() ?? this._config.translations?.[fallbackId] ?? null;
1290
+ const fallbackDict = this._store.fallback() ?? this._config.translations?.[fallbackId] ?? null;
993
1291
  if (!fallbackDict) return void 0;
994
1292
  const fallbackValue = this._resolveKey(fallbackDict, key);
995
1293
  if (fallbackValue === void 0) return void 0;
@@ -1001,205 +1299,20 @@ var RiviniaI18n = class RiviniaI18n {
1001
1299
  _localeOf(languageId) {
1002
1300
  return this._languages().find((l) => l.id === languageId)?.locale ?? languageId;
1003
1301
  }
1004
- _ensureFallback() {
1005
- const fallbackId = this._fallbackId;
1006
- if (fallbackId === null || fallbackId === this._currentLanguageId()) return;
1007
- if (this._hasDictionary(fallbackId)) return;
1008
- this._loadTranslations(fallbackId, {
1009
- silent: true,
1010
- background: true
1011
- });
1012
- }
1013
1302
  _hasDictionary(languageId) {
1014
- return this._translationsCache.has(languageId) || this._config.translations?.[languageId] !== void 0;
1303
+ return this._store.has(languageId);
1015
1304
  }
1016
1305
  _reportMissingKey(key) {
1017
- if (!this._hasDictionary(this._currentLanguageId())) return;
1018
- if (this._reportedMissingKeys.has(key)) return;
1019
- this._reportedMissingKeys.add(key);
1020
- const language = this._currentLanguageId();
1021
- const fallbackLanguage = this._fallbackId;
1022
- const event = fallbackLanguage === null ? {
1023
- key,
1024
- language
1025
- } : {
1026
- key,
1027
- language,
1028
- fallbackLanguage
1029
- };
1030
- this._pendingMissingKeys.push(key);
1031
- this._pendingMissingEvents.push(event);
1032
- this._queueMissingFlush();
1033
- if (this._warnOnMissingKey) console.warn(`[rivinia/i18n] Missing key "${key}" for language "${language}"` + (fallbackLanguage === null ? "." : ` (fallback "${fallbackLanguage}" has no value either).`));
1034
- }
1035
- _queueMissingFlush() {
1036
- if (this._missingFlushQueued) return;
1037
- this._missingFlushQueued = true;
1038
- queueMicrotask(() => {
1039
- this._missingFlushQueued = false;
1040
- const pending = this._pendingMissingKeys.splice(0);
1041
- if (pending.length === 0) return;
1042
- this._missingKeys.update((current) => [...current, ...pending]);
1043
- const events = this._pendingMissingEvents.splice(0);
1044
- for (const event of events) this._config.onMissingKey?.(event);
1045
- });
1306
+ this._missingKeyReporter.reportKey(key);
1046
1307
  }
1047
1308
  _reportMissingParam(key, param) {
1048
- const dedupe = `${key}\u0000${param}`;
1049
- if (this._reportedMissingParams.has(dedupe)) return;
1050
- this._reportedMissingParams.add(dedupe);
1051
- const language = this._currentLanguageId();
1052
- this._pendingMissingParams.push({
1053
- key,
1054
- param,
1055
- language
1056
- });
1057
- this._queueMissingParamsFlush();
1058
- if (this._warnOnMissingParam) console.warn(`[rivinia/i18n] Missing parameter "${param}" for key "${key}" and language "${language}"; the placeholder was kept.`);
1059
- }
1060
- _queueMissingParamsFlush() {
1061
- if (this._missingParamsFlushQueued) return;
1062
- this._missingParamsFlushQueued = true;
1063
- queueMicrotask(() => {
1064
- this._missingParamsFlushQueued = false;
1065
- const events = this._pendingMissingParams.splice(0);
1066
- for (const event of events) this._config.onMissingParam?.(event);
1067
- });
1068
- }
1069
- async _loadTranslations(languageId, opts) {
1070
- const background = opts?.background === true;
1071
- if (!opts?.force) {
1072
- const cached = this._translationsCache.get(languageId);
1073
- if (cached) {
1074
- this._applyDictionary(languageId, cached);
1075
- return {
1076
- data: cached,
1077
- ok: true
1078
- };
1079
- }
1080
- }
1081
- let task = opts?.force ? void 0 : this._inflight.get(languageId);
1082
- if (!task) {
1083
- task = this._fetchDictionary(languageId, this._generationOf(languageId));
1084
- this._inflight.set(languageId, task);
1085
- }
1086
- if (!background) {
1087
- this._loadingCount++;
1088
- this._loadingState.set("loading");
1089
- }
1090
- try {
1091
- const result = await task;
1092
- if (result.ok) this._applyDictionary(languageId, result.data);
1093
- else if (!background && result.error !== void 0 && languageId === this._currentLanguageId()) {
1094
- this._loadingError.set(result.error);
1095
- this._loadingState.set("error");
1096
- }
1097
- return {
1098
- data: result.data,
1099
- ok: result.ok
1100
- };
1101
- } finally {
1102
- if (!background) {
1103
- this._loadingCount = Math.max(0, this._loadingCount - 1);
1104
- if (this._loadingCount === 0 && this._loadingState() === "loading") this._loadingState.set("idle");
1105
- }
1106
- }
1107
- }
1108
- _applyDictionary(languageId, data) {
1109
- if (languageId === this._currentLanguageId()) {
1110
- this._loadedTranslations.set(data);
1111
- this._loadingError.set(null);
1112
- if (this._loadingCount === 0 && this._loadingState() === "error") this._loadingState.set("idle");
1113
- }
1114
- if (languageId === this._fallbackId) this._fallbackDict.set(data);
1115
- }
1116
- _fetchDictionary(languageId, generation) {
1117
- let task;
1118
- task = (async () => {
1119
- const stale = () => this._generationOf(languageId) !== generation;
1120
- try {
1121
- if (!this._resolvedLoader) this._resolvedLoader = await this._getLoader(this.loaderContext);
1122
- const translations = await this._resolvedLoader.load(languageId, this.loaderContext);
1123
- if (stale()) return {
1124
- data: {},
1125
- ok: false
1126
- };
1127
- this._translationsCache.set(languageId, translations);
1128
- this.writeTransfer(languageId, translations);
1129
- return {
1130
- data: translations,
1131
- ok: true
1132
- };
1133
- } catch (error) {
1134
- if (stale()) return {
1135
- data: {},
1136
- ok: false
1137
- };
1138
- this._config.onLoadError?.(languageId, error);
1139
- return {
1140
- data: {},
1141
- ok: false,
1142
- error
1143
- };
1144
- } finally {
1145
- if (this._inflight.get(languageId) === task) this._inflight.delete(languageId);
1146
- }
1147
- })();
1148
- return task;
1149
- }
1150
- _readStored() {
1151
- if (this._storageStrategy === "cookie") {
1152
- const header = this._request?.headers.get("cookie") ?? null;
1153
- if (header !== null) return parseCookie(header, this._storageKey);
1154
- try {
1155
- return parseCookie(this._doc.cookie, this._storageKey);
1156
- } catch {
1157
- return null;
1158
- }
1159
- }
1160
- return safeGetItem(this._storageKey, this._storageStrategy);
1161
- }
1162
- _writeStored(id) {
1163
- if (this._storageStrategy === "cookie") {
1164
- if (this._request) return;
1165
- try {
1166
- const location = this._doc?.location;
1167
- this._doc.cookie = serializeCookie(this._storageKey, id, { secure: shouldSecureCookie(location) });
1168
- } catch {}
1169
- return;
1170
- }
1171
- safeSetItem(this._storageKey, id, this._storageStrategy);
1172
- }
1173
- transferKey(languageId) {
1174
- return makeStateKey(`rivinia.i18n.dict.${languageId}`);
1175
- }
1176
- readTransfer(languageId) {
1177
- const transfer = this._transfer;
1178
- if (!transfer) return null;
1179
- const key = this.transferKey(languageId);
1180
- if (!transfer.hasKey(key)) return null;
1181
- const dict = transfer.get(key, null);
1182
- transfer.remove(key);
1183
- return dict;
1184
- }
1185
- writeTransfer(languageId, dict) {
1186
- if (!this._request) return;
1187
- this._transfer?.set(this.transferKey(languageId), dict);
1309
+ this._missingKeyReporter.reportParam(key, param);
1188
1310
  }
1189
1311
  _resolveKey(obj, path) {
1190
1312
  const value = Object.prototype.hasOwnProperty.call(obj, path) ? obj[path] : path.split(".").reduce((acc, segment) => acc && typeof acc === "object" ? acc[segment] : void 0, obj);
1191
1313
  if (typeof value === "string") return value;
1192
1314
  if (typeof value === "number" || typeof value === "boolean") return String(value);
1193
1315
  }
1194
- _resolveInitialLanguage() {
1195
- const stored = this._readStored();
1196
- if (stored && this._config.languages.some((l) => l.id === stored)) return stored;
1197
- if (this._config.detectBrowser) {
1198
- const detected = detectBrowserLanguage(this._config.languages.map((l) => l.id), browserLanguages());
1199
- if (detected) return detected;
1200
- }
1201
- return this._config.defaultLanguage;
1202
- }
1203
1316
  static ɵfac = i0.ɵɵngDeclareFactory({
1204
1317
  minVersion: "12.0.0",
1205
1318
  version: "22.2.3",
@@ -1248,7 +1361,7 @@ function defineRiviniaI18n(config) {
1248
1361
  inject: () => injectRiviniaI18n()
1249
1362
  };
1250
1363
  }
1251
- var RTranslatePipe = class RTranslatePipe {
1364
+ var RvTranslatePipe = class RvTranslatePipe {
1252
1365
  _i18n = inject(RiviniaI18n);
1253
1366
  transform(keyOrTranslations, defaultValueOrParams, maybeParams) {
1254
1367
  return this._i18n.translate(keyOrTranslations, defaultValueOrParams, maybeParams);
@@ -1257,7 +1370,7 @@ var RTranslatePipe = class RTranslatePipe {
1257
1370
  minVersion: "12.0.0",
1258
1371
  version: "22.2.3",
1259
1372
  ngImport: i0,
1260
- type: RTranslatePipe,
1373
+ type: RvTranslatePipe,
1261
1374
  deps: [],
1262
1375
  target: i0.ɵɵFactoryTarget.Pipe
1263
1376
  });
@@ -1265,9 +1378,9 @@ var RTranslatePipe = class RTranslatePipe {
1265
1378
  minVersion: "14.0.0",
1266
1379
  version: "22.2.3",
1267
1380
  ngImport: i0,
1268
- type: RTranslatePipe,
1381
+ type: RvTranslatePipe,
1269
1382
  isStandalone: true,
1270
- name: "rTranslate",
1383
+ name: "rvTranslate",
1271
1384
  pure: false
1272
1385
  });
1273
1386
  };
@@ -1275,15 +1388,15 @@ i0.ɵɵngDeclareClassMetadata({
1275
1388
  minVersion: "12.0.0",
1276
1389
  version: "22.2.3",
1277
1390
  ngImport: i0,
1278
- type: RTranslatePipe,
1391
+ type: RvTranslatePipe,
1279
1392
  decorators: [{
1280
1393
  type: Pipe,
1281
1394
  args: [{
1282
- name: "rTranslate",
1395
+ name: "rvTranslate",
1283
1396
  pure: false
1284
1397
  }]
1285
1398
  }]
1286
1399
  });
1287
- export { RTranslatePipe, RiviniaI18n, RiviniaLoadError, ViewTransitionService, browserLanguages, customLoader, defineRiviniaI18n, detectBrowserLanguage, formatIcu, httpLoader, injectRiviniaI18n, jsonLoader, parseCookie, provideRiviniaI18n, remoteLoader, serializeCookie };
1400
+ export { RiviniaI18n, RiviniaLoadError, RvTranslatePipe, ViewTransitionService, browserLanguages, customLoader, defineRiviniaI18n, detectBrowserLanguage, formatIcu, httpLoader, injectRiviniaI18n, jsonLoader, parseCookie, provideRiviniaI18n, remoteLoader, serializeCookie };
1288
1401
 
1289
1402
  //# sourceMappingURL=rivinia-i18n.mjs.map