{"version":3,"file":"IntlayerProvider.mjs","names":[],"sources":["../../../src/client/IntlayerProvider.tsx"],"sourcesContent":["'use client';\n\nimport { internationalization } from '@intlayer/config/built';\nimport { setIntlayerIdentifier } from '@intlayer/config/client';\nimport { localeResolver } from '@intlayer/core/localization';\nimport type {\n  LocalesValues,\n  ProviderVariant,\n} from '@intlayer/types/module_augmentation';\nimport {\n  createContext,\n  type FC,\n  type PropsWithChildren,\n  startTransition,\n  useCallback,\n  useContext,\n  useDeferredValue,\n  useEffect,\n  useMemo,\n  useState,\n} from 'react';\nimport { AnalyticsProvider } from '../analytics/AnalyticsProvider';\nimport { EditorProvider } from '../editor/EditorProvider';\nimport { getLocaleInStorage, setLocaleInStorage } from './useLocaleStorage';\n\ntype IntlayerValue = {\n  locale: LocalesValues;\n  setLocale: (newLocale: LocalesValues) => void;\n  /**\n   * Ambient variant applied to every dictionary read below the provider, the\n   * same way `locale` is. Overridden per call by an explicit selector.\n   */\n  variant?: ProviderVariant;\n  disableEditor?: boolean;\n  isCookieEnabled?: boolean;\n};\n\n/**\n * Context that stores the current locale on the client side.\n */\nexport const IntlayerClientContext = createContext<IntlayerValue>({\n  // Read on demand: only a tree rendered without a provider needs it\n  get locale() {\n    return getLocaleInStorage() ?? internationalization?.defaultLocale;\n  },\n  setLocale: () => null,\n  isCookieEnabled: true,\n});\n\n/**\n * Hook that provides the current Intlayer client context.\n *\n * @returns The current Intlayer context values.\n */\nexport const useIntlayerContext = () => useContext(IntlayerClientContext) ?? {};\n\n/**\n * Props for the IntlayerProvider component.\n */\nexport type IntlayerProviderProps = PropsWithChildren<{\n  /**\n   * The locale to use. If not provided, it will be detected from storage or configuration.\n   */\n  locale?: LocalesValues;\n  /**\n   * Ambient variant applied to every dictionary read below this provider — for\n   * a dimension that is fixed for the whole session (tenant, school type, plan\n   * tier…) and that therefore no component should have to pass by hand.\n   *\n   * Accepts three forms:\n   * - `variant=\"school1\"` — one named variant for every key\n   * - `variant={['school1', 'default']}` — an ordered preference chain: the\n   *   first variant the key actually declares wins\n   * - `variant={{ key1: 'school1', key2: ['school1', 'default'], default: 'base' }}`\n   *   — per dictionary key, with `default` covering every key not listed\n   *\n   * A plain object is always read as the per-key map. To pin a structured\n   * variant globally, nest it: `variant={{ default: { id: 'prod_abc' } }}`.\n   *\n   * A call-site selector always wins: `useIntlayer('key', { variant: 'x' })`\n   * replaces this default rather than extending it.\n   */\n  variant?: ProviderVariant;\n  /**\n   * The default locale to use as a fallback.\n   */\n  defaultLocale?: LocalesValues;\n  /**\n   * Function to set the locale.\n   */\n  setLocale?: (locale: LocalesValues) => void;\n  /**\n   * Whether to disable the editor.\n   */\n  disableEditor?: boolean;\n  /**\n   * Whether to enable cookies for storing the locale.\n   */\n  isCookieEnabled?: boolean;\n}>;\n\n/**\n * Provider that stores the current locale on the client side.\n *\n * This component is focused on content delivery without the editor features.\n *\n * @param props - The provider props.\n * @returns The provider component.\n */\nexport const IntlayerProviderContent: FC<IntlayerProviderProps> = ({\n  locale: localeProp,\n  defaultLocale: defaultLocaleProp,\n  variant,\n  children,\n  setLocale: setLocaleProp,\n  disableEditor,\n  isCookieEnabled,\n}) => {\n  const { locales: availableLocales, defaultLocale: defaultLocaleConfig } =\n    internationalization ?? {};\n\n  // A router usually changes the prop through a sync update, which would\n  // suspend on the new locale's dynamic dictionaries and hide the page behind\n  // the Suspense fallback. Deferred, the new locale renders in the background\n  // and the current UI stays until it is ready.\n  const deferredLocaleProp = useDeferredValue(localeProp);\n\n  // Storage is only read when no locale is passed, and only on mount\n  const [currentLocale, setCurrentLocale] = useState<LocalesValues>(\n    () =>\n      localeProp ??\n      getLocaleInStorage() ??\n      defaultLocaleProp ??\n      defaultLocaleConfig\n  );\n  const [adoptedLocaleProp, setAdoptedLocaleProp] =\n    useState(deferredLocaleProp);\n\n  // Adopt a new `locale` prop during render rather than in an effect: an\n  // effect commits the whole subtree once with the stale locale, then renders\n  // it again with the new one.\n  if (deferredLocaleProp !== adoptedLocaleProp) {\n    setAdoptedLocaleProp(deferredLocaleProp);\n\n    if (deferredLocaleProp && deferredLocaleProp !== currentLocale) {\n      setCurrentLocale(deferredLocaleProp);\n    }\n  }\n\n  useEffect(() => {\n    setIntlayerIdentifier();\n  }, []);\n\n  const setLocaleBase = useCallback(\n    (newLocale: LocalesValues) => {\n      if (currentLocale.toString() === newLocale.toString()) return;\n\n      if (!availableLocales?.map(String).includes(newLocale)) {\n        console.error(`Locale ${newLocale} is not available`);\n        return;\n      }\n\n      setCurrentLocale(newLocale);\n      setLocaleInStorage(newLocale, isCookieEnabled);\n    },\n    [currentLocale, availableLocales, isCookieEnabled]\n  );\n\n  const setLocale = useCallback(\n    (newLocale: LocalesValues) =>\n      startTransition(() => (setLocaleProp ?? setLocaleBase)(newLocale)),\n    [setLocaleProp, setLocaleBase]\n  );\n\n  // Resolve based on currentLocale (the state), not the prop directly\n  const resolvedLocale = localeResolver(currentLocale);\n\n  // Stable value so a parent re-render does not re-render every consumer\n  const contextValue = useMemo<IntlayerValue>(\n    () => ({\n      locale: resolvedLocale,\n      setLocale,\n      variant,\n      disableEditor,\n    }),\n    [resolvedLocale, setLocale, variant, disableEditor]\n  );\n\n  return (\n    <IntlayerClientContext.Provider value={contextValue}>\n      {children}\n    </IntlayerClientContext.Provider>\n  );\n};\n\n/**\n * Main provider for Intlayer in React applications.\n *\n * It includes the editor provider by default, allowing for live content editing\n * if configured.\n *\n * @param props - The provider props.\n * @returns The provider component with editor support.\n *\n * @example\n * ```tsx\n * import { IntlayerProvider } from 'react-intlayer';\n *\n * const App = () => (\n *   <IntlayerProvider>\n *     <MyComponent />\n *   </IntlayerProvider>\n * );\n * ```\n */\nexport const IntlayerProvider: FC<IntlayerProviderProps> = ({\n  children,\n  ...props\n}) => (\n  <IntlayerProviderContent {...props}>\n    {/* Build flags drop these, and their modules, when the feature is off */}\n    {process.env.INTLAYER_EDITOR_ENABLED !== 'false' && <EditorProvider />}\n    {process.env.INTLAYER_ANALYTICS_ENABLED !== 'false' && (\n      <Analy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