UNPKG

@intlayer/core

Version:

Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.

59 lines (57 loc) 1.99 kB
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs'); let _intlayer_types = require("@intlayer/types"); //#region src/utils/intl.ts /** * Optimized Cache Key Generator * 1. Fast path: If no options, just use the locale string. * 2. Normal path: JSON.stringify for deterministic object comparison. */ const getCacheKey = (locales, options) => { const localeKey = locales ? String(locales) : _intlayer_types.Locales.ENGLISH; if (!options) return localeKey; return `${localeKey}|${JSON.stringify(options)}`; }; /** * Generic wrapper for any `new Intl.*()` constructor. */ const createCachedConstructor = (Ctor) => { const cache = /* @__PURE__ */ new Map(); const MAX_CACHE_SIZE = 50; function Wrapped(locales, options) { if (Ctor.name === "DisplayNames" && typeof Intl?.DisplayNames !== "function") return locales; const key = getCacheKey(locales, options); let instance = cache.get(key); if (instance) return instance; instance = new Ctor(locales, options); if (cache.size >= MAX_CACHE_SIZE) { const oldestKey = cache.keys().next().value; if (oldestKey) cache.delete(oldestKey); } cache.set(key, instance); return instance; } Wrapped.prototype = Ctor.prototype; return Wrapped; }; /** * Factory that turns the global `Intl` into a cached clone. */ const createCachedIntl = () => { const constructorCache = /* @__PURE__ */ new Map(); return new Proxy(Intl, { get: (target, prop, receiver) => { if (constructorCache.has(prop)) return constructorCache.get(prop); const value = Reflect.get(target, prop, receiver); if (typeof value === "function" && typeof prop === "string" && /^[A-Z]/.test(prop)) { const wrapped = createCachedConstructor(value); constructorCache.set(prop, wrapped); return wrapped; } return value; } }); }; const CachedIntl = createCachedIntl(); //#endregion exports.CachedIntl = CachedIntl; exports.Intl = CachedIntl; exports.createCachedIntl = createCachedIntl; //# sourceMappingURL=intl.cjs.map