use-intl 2.20.1 → 2.21.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.
@@ -1 +1 @@
1
- {"version":3,"file":"use-intl.cjs.production.min.js","sources":["../src/core/IntlError.tsx","../src/core/convertFormatsToIntlMessageFormat.tsx","../src/core/defaults.tsx","../src/core/createBaseTranslator.tsx","../src/core/resolveNamespace.tsx","../src/core/createFormatter.tsx","../src/core/createIntl.tsx","../src/react/IntlContext.tsx","../src/react/getInitializedConfig.tsx","../src/react/useIntlContext.tsx","../src/react/useNow.tsx","../src/react/useIntl.tsx","../src/react/IntlProvider.tsx","../src/core/createTranslator.tsx","../src/core/createTranslatorImpl.tsx","../src/react/useFormatter.tsx","../src/react/useLocale.tsx","../src/react/useMessages.tsx","../src/react/useTimeZone.tsx","../src/react/useTranslations.tsx","../src/react/useTranslationsImpl.tsx"],"sourcesContent":["export enum IntlErrorCode {\n MISSING_MESSAGE = 'MISSING_MESSAGE',\n MISSING_FORMAT = 'MISSING_FORMAT',\n INSUFFICIENT_PATH = 'INSUFFICIENT_PATH',\n INVALID_MESSAGE = 'INVALID_MESSAGE',\n INVALID_KEY = 'INVALID_KEY',\n FORMATTING_ERROR = 'FORMATTING_ERROR'\n}\n\nexport default class IntlError extends Error {\n public readonly code: IntlErrorCode;\n public readonly originalMessage: string | undefined;\n\n constructor(code: IntlErrorCode, originalMessage?: string) {\n let message: string = code;\n if (originalMessage) {\n message += ': ' + originalMessage;\n }\n super(message);\n\n this.code = code;\n if (originalMessage) {\n this.originalMessage = originalMessage;\n }\n }\n}\n","// eslint-disable-next-line import/no-named-as-default -- False positive\nimport IntlMessageFormat, {Formats as IntlFormats} from 'intl-messageformat';\nimport DateTimeFormatOptions from './DateTimeFormatOptions';\nimport Formats from './Formats';\nimport TimeZone from './TimeZone';\n\nfunction setTimeZoneInFormats(\n formats: Record<string, DateTimeFormatOptions> | undefined,\n timeZone: TimeZone\n) {\n if (!formats) return formats;\n\n // The only way to set a time zone with `intl-messageformat` is to merge it into the formats\n // https://github.com/formatjs/formatjs/blob/8256c5271505cf2606e48e3c97ecdd16ede4f1b5/packages/intl/src/message.ts#L15\n return Object.keys(formats).reduce(\n (acc: Record<string, DateTimeFormatOptions>, key) => {\n acc[key] = {\n timeZone,\n ...formats[key]\n };\n return acc;\n },\n {}\n );\n}\n\n/**\n * `intl-messageformat` uses separate keys for `date` and `time`, but there's\n * only one native API: `Intl.DateTimeFormat`. Additionally you might want to\n * include both a time and a date in a value, therefore the separation doesn't\n * seem so useful. We offer a single `dateTime` namespace instead, but we have\n * to convert the format before `intl-messageformat` can be used.\n */\nexport default function convertFormatsToIntlMessageFormat(\n formats: Partial<Formats>,\n timeZone?: TimeZone\n): Partial<IntlFormats> {\n const formatsWithTimeZone = timeZone\n ? {...formats, dateTime: setTimeZoneInFormats(formats.dateTime, timeZone)}\n : formats;\n\n const mfDateDefaults = IntlMessageFormat.formats.date as Formats['dateTime'];\n const defaultDateFormats = timeZone\n ? setTimeZoneInFormats(mfDateDefaults, timeZone)\n : mfDateDefaults;\n\n const mfTimeDefaults = IntlMessageFormat.formats.time as Formats['dateTime'];\n const defaultTimeFormats = timeZone\n ? setTimeZoneInFormats(mfTimeDefaults, timeZone)\n : mfTimeDefaults;\n\n return {\n ...formatsWithTimeZone,\n date: {\n ...defaultDateFormats,\n ...formatsWithTimeZone?.dateTime\n },\n time: {\n ...defaultTimeFormats,\n ...formatsWithTimeZone?.dateTime\n }\n };\n}\n","import IntlError from './IntlError';\n\n/**\n * Contains defaults that are used for all entry points into the core.\n * See also `InitializedIntlConfiguration`.\n */\n\nexport function defaultGetMessageFallback(props: {\n error: IntlError;\n key: string;\n namespace?: string;\n}) {\n return [props.namespace, props.key].filter((part) => part != null).join('.');\n}\n\nexport function defaultOnError(error: IntlError) {\n console.error(error);\n}\n","// eslint-disable-next-line import/no-named-as-default -- False positive\nimport IntlMessageFormat from 'intl-messageformat';\nimport {\n cloneElement,\n isValidElement,\n ReactElement,\n ReactNode,\n ReactNodeArray\n} from 'react';\nimport AbstractIntlMessages from './AbstractIntlMessages';\nimport Formats from './Formats';\nimport {InitializedIntlConfig} from './IntlConfig';\nimport IntlError, {IntlErrorCode} from './IntlError';\nimport MessageFormatCache from './MessageFormatCache';\nimport TranslationValues, {RichTranslationValues} from './TranslationValues';\nimport convertFormatsToIntlMessageFormat from './convertFormatsToIntlMessageFormat';\nimport {defaultGetMessageFallback, defaultOnError} from './defaults';\nimport MessageKeys from './utils/MessageKeys';\nimport NestedKeyOf from './utils/NestedKeyOf';\nimport NestedValueOf from './utils/NestedValueOf';\n\nfunction resolvePath(\n messages: AbstractIntlMessages | undefined,\n key: string,\n namespace?: string\n) {\n if (!messages) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `No messages available at \\`${namespace}\\`.`\n : undefined\n );\n }\n\n let message = messages;\n\n key.split('.').forEach((part) => {\n const next = (message as any)[part];\n\n if (part == null || next == null) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `Could not resolve \\`${key}\\` in ${\n namespace ? `\\`${namespace}\\`` : 'messages'\n }.`\n : undefined\n );\n }\n\n message = next;\n });\n\n return message;\n}\n\nfunction prepareTranslationValues(values: RichTranslationValues) {\n if (Object.keys(values).length === 0) return undefined;\n\n // Workaround for https://github.com/formatjs/formatjs/issues/1467\n const transformedValues: RichTranslationValues = {};\n Object.keys(values).forEach((key) => {\n let index = 0;\n const value = values[key];\n\n let transformed;\n if (typeof value === 'function') {\n transformed = (chunks: ReactNode) => {\n const result = value(chunks);\n\n return isValidElement(result)\n ? cloneElement(result, {key: key + index++})\n : result;\n };\n } else {\n transformed = value;\n }\n\n transformedValues[key] = transformed;\n });\n\n return transformedValues;\n}\n\nexport function getMessagesOrError<Messages extends AbstractIntlMessages>({\n messages,\n namespace,\n onError = defaultOnError\n}: {\n messages: Messages;\n namespace?: string;\n onError?(error: IntlError): void;\n}) {\n try {\n if (!messages) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `No messages were configured on the provider.`\n : undefined\n );\n }\n\n const retrievedMessages = namespace\n ? resolvePath(messages, namespace)\n : messages;\n\n if (!retrievedMessages) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `No messages for namespace \\`${namespace}\\` found.`\n : undefined\n );\n }\n\n return retrievedMessages;\n } catch (error) {\n const intlError = new IntlError(\n IntlErrorCode.MISSING_MESSAGE,\n (error as Error).message\n );\n onError(intlError);\n return intlError;\n }\n}\n\nexport type CreateBaseTranslatorProps<Messages> = InitializedIntlConfig & {\n messageFormatCache?: MessageFormatCache;\n defaultTranslationValues?: RichTranslationValues;\n namespace?: string;\n messagesOrError: Messages | IntlError;\n};\n\nfunction getPlainMessage(candidate: string, values?: unknown) {\n if (values) return undefined;\n\n const unescapedMessage = candidate.replace(/'([{}])/gi, '$1');\n\n // Placeholders can be in the message if there are default values,\n // or if the user has forgotten to provide values. In the latter\n // case we need to compile the message to receive an error.\n const hasPlaceholders = /<|{/.test(unescapedMessage);\n\n if (!hasPlaceholders) {\n return unescapedMessage;\n }\n\n return undefined;\n}\n\nexport default function createBaseTranslator<\n Messages extends AbstractIntlMessages,\n NestedKey extends NestedKeyOf<Messages>\n>({\n defaultTranslationValues,\n formats: globalFormats,\n getMessageFallback = defaultGetMessageFallback,\n locale,\n messageFormatCache,\n messagesOrError,\n namespace,\n onError,\n timeZone\n}: CreateBaseTranslatorProps<Messages>) {\n function getFallbackFromErrorAndNotify(\n key: string,\n code: IntlErrorCode,\n message?: string\n ) {\n const error = new IntlError(code, message);\n onError(error);\n return getMessageFallback({error, key, namespace});\n }\n\n function translateBaseFn(\n /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */\n key: string,\n /** Key value pairs for values to interpolate into the message. */\n values?: RichTranslationValues,\n /** Provide custom formats for numbers, dates and times. */\n formats?: Partial<Formats>\n ): string | ReactElement | ReactNodeArray {\n if (messagesOrError instanceof IntlError) {\n // We have already warned about this during render\n return getMessageFallback({\n error: messagesOrError,\n key,\n namespace\n });\n }\n const messages = messagesOrError;\n\n let message;\n try {\n message = resolvePath(messages, key, namespace);\n } catch (error) {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.MISSING_MESSAGE,\n (error as Error).message\n );\n }\n\n function joinPath(parts: Array<string | undefined>) {\n return parts.filter((part) => part != null).join('.');\n }\n\n const cacheKey = joinPath([locale, namespace, key, String(message)]);\n\n let messageFormat: IntlMessageFormat;\n if (messageFormatCache?.has(cacheKey)) {\n messageFormat = messageFormatCache.get(cacheKey)!;\n } else {\n if (typeof message === 'object') {\n let code, errorMessage;\n if (Array.isArray(message)) {\n code = IntlErrorCode.INVALID_MESSAGE;\n if (process.env.NODE_ENV !== 'production') {\n errorMessage = `Message at \\`${joinPath([\n namespace,\n key\n ])}\\` resolved to an array, but only strings are supported. See https://next-intl-docs.vercel.app/docs/usage/messages#arrays-of-messages`;\n }\n } else {\n code = IntlErrorCode.INSUFFICIENT_PATH;\n if (process.env.NODE_ENV !== 'production') {\n errorMessage = `Message at \\`${joinPath([\n namespace,\n key\n ])}\\` resolved to an object, but only strings are supported. Use a \\`.\\` to retrieve nested messages. See https://next-intl-docs.vercel.app/docs/usage/messages#structuring-messages`;\n }\n }\n\n return getFallbackFromErrorAndNotify(key, code, errorMessage);\n }\n\n // Hot path that avoids creating an `IntlMessageFormat` instance\n const plainMessage = getPlainMessage(message as string, values);\n if (plainMessage) return plainMessage;\n\n try {\n messageFormat = new IntlMessageFormat(\n message,\n locale,\n convertFormatsToIntlMessageFormat(\n {...globalFormats, ...formats},\n timeZone\n )\n );\n } catch (error) {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.INVALID_MESSAGE,\n (error as Error).message\n );\n }\n\n messageFormatCache?.set(cacheKey, messageFormat);\n }\n\n try {\n const formattedMessage = messageFormat.format(\n // @ts-ignore `intl-messageformat` expects a different format\n // for rich text elements since a recent minor update. This\n // needs to be evaluated in detail, possibly also in regards\n // to be able to format to parts.\n prepareTranslationValues({...defaultTranslationValues, ...values})\n );\n\n if (formattedMessage == null) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `Unable to format \\`${key}\\` in ${\n namespace ? `namespace \\`${namespace}\\`` : 'messages'\n }`\n : undefined\n );\n }\n\n // Limit the function signature to return strings or React elements\n return isValidElement(formattedMessage) ||\n // Arrays of React elements\n Array.isArray(formattedMessage) ||\n typeof formattedMessage === 'string'\n ? formattedMessage\n : String(formattedMessage);\n } catch (error) {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.FORMATTING_ERROR,\n (error as Error).message\n );\n }\n }\n\n function translateFn<\n TargetKey extends MessageKeys<\n NestedValueOf<Messages, NestedKey>,\n NestedKeyOf<NestedValueOf<Messages, NestedKey>>\n >\n >(\n /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */\n key: TargetKey,\n /** Key value pairs for values to interpolate into the message. */\n values?: TranslationValues,\n /** Provide custom formats for numbers, dates and times. */\n formats?: Partial<Formats>\n ): string {\n const result = translateBaseFn(key, values, formats);\n\n if (typeof result !== 'string') {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.INVALID_MESSAGE,\n process.env.NODE_ENV !== 'production'\n ? `The message \\`${key}\\` in ${\n namespace ? `namespace \\`${namespace}\\`` : 'messages'\n } didn't resolve to a string. If you want to format rich text, use \\`t.rich\\` instead.`\n : undefined\n );\n }\n\n return result;\n }\n\n translateFn.rich = translateBaseFn;\n\n translateFn.raw = (\n /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */\n key: string\n ): any => {\n if (messagesOrError instanceof IntlError) {\n // We have already warned about this during render\n return getMessageFallback({\n error: messagesOrError,\n key,\n namespace\n });\n }\n const messages = messagesOrError;\n\n try {\n return resolvePath(messages, key, namespace);\n } catch (error) {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.MISSING_MESSAGE,\n (error as Error).message\n );\n }\n };\n\n return translateFn;\n}\n","/**\n * For the strictly typed messages to work we have to wrap the namespace into\n * a mandatory prefix. See https://stackoverflow.com/a/71529575/343045\n */\nexport default function resolveNamespace(\n namespace: string,\n namespacePrefix: string\n) {\n return namespace === namespacePrefix\n ? undefined\n : namespace.slice((namespacePrefix + '.').length);\n}\n","import DateTimeFormatOptions from './DateTimeFormatOptions';\nimport Formats from './Formats';\nimport IntlError, {IntlErrorCode} from './IntlError';\nimport NumberFormatOptions from './NumberFormatOptions';\nimport TimeZone from './TimeZone';\nimport {defaultOnError} from './defaults';\n\nconst MINUTE = 60;\nconst HOUR = MINUTE * 60;\nconst DAY = HOUR * 24;\nconst WEEK = DAY * 7;\nconst MONTH = DAY * (365 / 12); // Approximation\nconst YEAR = DAY * 365;\n\nfunction getRelativeTimeFormatConfig(seconds: number) {\n const absValue = Math.abs(seconds);\n let value, unit: Intl.RelativeTimeFormatUnit;\n\n // We have to round the resulting values, as `Intl.RelativeTimeFormat`\n // will include fractions like '2.1 hours ago'.\n\n if (absValue < MINUTE) {\n unit = 'second';\n value = Math.round(seconds);\n } else if (absValue < HOUR) {\n unit = 'minute';\n value = Math.round(seconds / MINUTE);\n } else if (absValue < DAY) {\n unit = 'hour';\n value = Math.round(seconds / HOUR);\n } else if (absValue < WEEK) {\n unit = 'day';\n value = Math.round(seconds / DAY);\n } else if (absValue < MONTH) {\n unit = 'week';\n value = Math.round(seconds / WEEK);\n } else if (absValue < YEAR) {\n unit = 'month';\n value = Math.round(seconds / MONTH);\n } else {\n unit = 'year';\n value = Math.round(seconds / YEAR);\n }\n\n return {value, unit};\n}\n\ntype Props = {\n locale: string;\n timeZone?: TimeZone;\n onError?(error: IntlError): void;\n formats?: Partial<Formats>;\n now?: Date;\n};\n\nexport default function createFormatter({\n formats,\n locale,\n now: globalNow,\n onError = defaultOnError,\n timeZone\n}: Props) {\n function resolveFormatOrOptions<Options>(\n typeFormats: Record<string, Options> | undefined,\n formatOrOptions?: string | Options\n ) {\n let options;\n if (typeof formatOrOptions === 'string') {\n const formatName = formatOrOptions;\n options = typeFormats?.[formatName];\n\n if (!options) {\n const error = new IntlError(\n IntlErrorCode.MISSING_FORMAT,\n process.env.NODE_ENV !== 'production'\n ? `Format \\`${formatName}\\` is not available. You can configure it on the provider or provide custom options.`\n : undefined\n );\n onError(error);\n throw error;\n }\n } else {\n options = formatOrOptions;\n }\n\n return options;\n }\n\n function getFormattedValue<Value, Options>(\n value: Value,\n formatOrOptions: string | Options | undefined,\n typeFormats: Record<string, Options> | undefined,\n formatter: (options?: Options) => string\n ) {\n let options;\n try {\n options = resolveFormatOrOptions(typeFormats, formatOrOptions);\n } catch (error) {\n return String(value);\n }\n\n try {\n return formatter(options);\n } catch (error) {\n onError(\n new IntlError(IntlErrorCode.FORMATTING_ERROR, (error as Error).message)\n );\n return String(value);\n }\n }\n\n function dateTime(\n /** If a number is supplied, this is interpreted as a UTC timestamp. */\n value: Date | number,\n /** If a time zone is supplied, the `value` is converted to that time zone.\n * Otherwise the user time zone will be used. */\n formatOrOptions?: string | DateTimeFormatOptions\n ) {\n return getFormattedValue(\n value,\n formatOrOptions,\n formats?.dateTime,\n (options) => {\n if (timeZone && !options?.timeZone) {\n options = {...options, timeZone};\n }\n\n return new Intl.DateTimeFormat(locale, options).format(value);\n }\n );\n }\n\n function number(\n value: number | bigint,\n formatOrOptions?: string | NumberFormatOptions\n ) {\n return getFormattedValue(\n value,\n formatOrOptions,\n formats?.number,\n (options) => new Intl.NumberFormat(locale, options).format(value)\n );\n }\n\n function relativeTime(\n /** The date time that needs to be formatted. */\n date: number | Date,\n /** The reference point in time to which `date` will be formatted in relation to. */\n now?: number | Date\n ) {\n try {\n if (!now) {\n if (globalNow) {\n now = globalNow;\n } else {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `The \\`now\\` parameter wasn't provided and there was no global fallback configured on the provider.`\n : undefined\n );\n }\n }\n\n const dateDate = date instanceof Date ? date : new Date(date);\n const nowDate = now instanceof Date ? now : new Date(now);\n\n const seconds = (dateDate.getTime() - nowDate.getTime()) / 1000;\n const {unit, value} = getRelativeTimeFormatConfig(seconds);\n\n return new Intl.RelativeTimeFormat(locale, {\n numeric: 'auto'\n }).format(value, unit);\n } catch (error) {\n onError(\n new IntlError(IntlErrorCode.FORMATTING_ERROR, (error as Error).message)\n );\n return String(date);\n }\n }\n\n function list(\n value: Iterable<string>,\n formatOrOptions?: string | Intl.ListFormatOptions\n ) {\n return getFormattedValue(value, formatOrOptions, formats?.list, (options) =>\n new Intl.ListFormat(locale, options).format(value)\n );\n }\n\n return {dateTime, number, relativeTime, list};\n}\n","import createFormatter from './createFormatter';\n\n/** @deprecated Switch to `createFormatter` */\nexport default function createIntl(\n ...args: Parameters<typeof createFormatter>\n) {\n const formatter = createFormatter(...args);\n return {\n formatDateTime: formatter.dateTime,\n formatNumber: formatter.number,\n formatRelativeTime: formatter.relativeTime\n };\n}\n","import {createContext} from 'react';\nimport {InitializedIntlConfig} from '../core/IntlConfig';\nimport MessageFormatCache from '../core/MessageFormatCache';\n\nconst IntlContext = createContext<\n | (InitializedIntlConfig & {\n messageFormatCache?: MessageFormatCache;\n })\n | undefined\n>(undefined);\n\nexport default IntlContext;\n","import IntlConfig from '../core/IntlConfig';\nimport {defaultGetMessageFallback, defaultOnError} from '../core/defaults';\nimport validateMessages from '../core/validateMessages';\n\n/**\n * Enhances the incoming props with defaults.\n */\nexport default function getInitializedConfig<\n // This is a generic to allow for stricter typing. E.g.\n // the RSC integration always provides a `now` value.\n Props extends Omit<IntlConfig, 'children'>\n>({getMessageFallback, messages, onError, ...rest}: Props) {\n const finalOnError = onError || defaultOnError;\n const finalGetMessageFallback =\n getMessageFallback || defaultGetMessageFallback;\n\n if (process.env.NODE_ENV !== 'production') {\n if (messages) {\n validateMessages(messages, finalOnError);\n }\n }\n\n return {\n ...rest,\n messages,\n onError: finalOnError,\n getMessageFallback: finalGetMessageFallback\n };\n}\n","import {useContext} from 'react';\nimport IntlContext from './IntlContext';\n\nexport default function useIntlContext() {\n const context = useContext(IntlContext);\n\n if (!context) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? 'No intl context found. Have you configured the provider?'\n : undefined\n );\n }\n\n return context;\n}\n","import {useState, useEffect} from 'react';\nimport useIntlContext from './useIntlContext';\n\ntype Options = {\n updateInterval?: number;\n};\n\nfunction getNow() {\n return new Date();\n}\n\n/**\n * Reading the current date via `new Date()` in components should be avoided, as\n * it causes components to be impure and can lead to flaky tests. Instead, this\n * hook can be used.\n *\n * By default, it returns the time when the component mounts. If `updateInterval`\n * is specified, the value will be updated based on the interval.\n *\n * You can however also return a static value from this hook, if you\n * configure the `now` parameter on the context provider. Note however,\n * that if `updateInterval` is configured in this case, the component\n * will initialize with the global value, but will afterwards update\n * continuously based on the interval.\n *\n * For unit tests, this can be mocked to a constant value. For end-to-end\n * testing, an environment parameter can be passed to the `now` parameter\n * of the provider to mock this to a static value.\n */\nexport default function useNow(options?: Options) {\n const updateInterval = options?.updateInterval;\n\n const {now: globalNow} = useIntlContext();\n const [now, setNow] = useState(globalNow || getNow());\n\n useEffect(() => {\n if (!updateInterval) return;\n\n const intervalId = setInterval(() => {\n setNow(getNow());\n }, updateInterval);\n\n return () => {\n clearInterval(intervalId);\n };\n }, [globalNow, updateInterval]);\n\n return now;\n}\n","import {useMemo} from 'react';\nimport createIntl from '../core/createIntl';\nimport useIntlContext from './useIntlContext';\n\nlet hasWarned = false;\n\n/** @deprecated Switch to `useFormatter` instead. */\nexport default function useIntl() {\n const {formats, locale, now: globalNow, onError, timeZone} = useIntlContext();\n\n if (!hasWarned) {\n hasWarned = true;\n console.warn(\n '`useIntl()` is deprecated and will be removed in the next major version. Please switch to `useFormatter()`.'\n );\n }\n\n return useMemo(\n () =>\n createIntl({\n formats,\n locale,\n now: globalNow,\n onError,\n timeZone\n }),\n [formats, globalNow, locale, onError, timeZone]\n );\n}\n","import React, {ReactNode, useState} from 'react';\nimport IntlConfig from '../core/IntlConfig';\nimport IntlContext from './IntlContext';\nimport getInitializedConfig from './getInitializedConfig';\n\ntype Props = IntlConfig & {\n children: ReactNode;\n};\n\nexport default function IntlProvider({children, ...props}: Props) {\n const [messageFormatCache] = useState(() => new Map());\n\n return (\n <IntlContext.Provider\n value={{\n ...getInitializedConfig(props),\n messageFormatCache\n }}\n >\n {children}\n </IntlContext.Provider>\n );\n}\n","import Formats from './Formats';\nimport IntlConfig from './IntlConfig';\nimport TranslationValues from './TranslationValues';\nimport createTranslatorImpl, {\n CoreRichTranslationValues\n} from './createTranslatorImpl';\nimport {defaultGetMessageFallback, defaultOnError} from './defaults';\nimport MessageKeys from './utils/MessageKeys';\nimport NamespaceKeys from './utils/NamespaceKeys';\nimport NestedKeyOf from './utils/NestedKeyOf';\nimport NestedValueOf from './utils/NestedValueOf';\n\n/**\n * Translates messages from the given namespace by using the ICU syntax.\n * See https://formatjs.io/docs/core-concepts/icu-syntax.\n *\n * If no namespace is provided, all available messages are returned.\n * The namespace can also indicate nesting by using a dot\n * (e.g. `namespace.Component`).\n */\nexport default function createTranslator<\n NestedKey extends NamespaceKeys<\n IntlMessages,\n NestedKeyOf<IntlMessages>\n > = never\n>({\n getMessageFallback = defaultGetMessageFallback,\n messages,\n namespace,\n onError = defaultOnError,\n ...rest\n}: Omit<IntlConfig<IntlMessages>, 'defaultTranslationValues' | 'messages'> & {\n messages: NonNullable<IntlConfig<IntlMessages>['messages']>;\n namespace?: NestedKey;\n}): // Explicitly defining the return type is necessary as TypeScript would get it wrong\n{\n // Default invocation\n <\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey,\n values?: TranslationValues,\n formats?: Partial<Formats>\n ): string;\n\n // `rich`\n rich<\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey,\n values?: CoreRichTranslationValues,\n formats?: Partial<Formats>\n ): string;\n\n // `raw`\n raw<\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey\n ): any;\n} {\n // We have to wrap the actual function so the type inference for the optional\n // namespace works correctly. See https://stackoverflow.com/a/71529575/343045\n // The prefix (\"!\") is arbitrary.\n return createTranslatorImpl<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >(\n {\n ...rest,\n onError,\n getMessageFallback,\n messages: {'!': messages},\n namespace: namespace ? `!.${namespace}` : '!'\n },\n '!'\n );\n}\n","import AbstractIntlMessages from './AbstractIntlMessages';\nimport {InitializedIntlConfig} from './IntlConfig';\nimport IntlError, {IntlErrorCode} from './IntlError';\nimport {RichTranslationValues, TranslationValue} from './TranslationValues';\nimport createBaseTranslator, {getMessagesOrError} from './createBaseTranslator';\nimport resolveNamespace from './resolveNamespace';\nimport NestedKeyOf from './utils/NestedKeyOf';\n\nexport type CoreRichTranslationValues = Record<\n string,\n TranslationValue | ((chunks: string) => string)\n>;\n\nexport type CreateTranslatorImplProps<Messages> = Omit<\n InitializedIntlConfig,\n 'messages'\n> & {\n namespace: string;\n messages: Messages;\n};\n\nexport default function createTranslatorImpl<\n Messages extends AbstractIntlMessages,\n NestedKey extends NestedKeyOf<Messages>\n>(\n {\n getMessageFallback,\n messages,\n namespace,\n onError,\n ...rest\n }: CreateTranslatorImplProps<Messages>,\n namespacePrefix: string\n) {\n // The `namespacePrefix` is part of the type system.\n // See the comment in the function invocation.\n messages = messages[namespacePrefix] as Messages;\n namespace = resolveNamespace(namespace, namespacePrefix) as NestedKey;\n\n const translator = createBaseTranslator<Messages, NestedKey>({\n ...rest,\n onError,\n getMessageFallback,\n messagesOrError: getMessagesOrError({\n messages,\n namespace,\n onError\n }) as Messages | IntlError\n });\n\n const originalRich = translator.rich;\n\n function base(...args: Parameters<typeof translator>) {\n return translator(...args);\n }\n\n // Augment `t.rich` to return plain strings\n base.rich = (\n key: Parameters<typeof originalRich>[0],\n /** Key value pairs for values to interpolate into the message. */\n values: CoreRichTranslationValues,\n formats?: Parameters<typeof originalRich>[2]\n ): string => {\n // `chunks` is returned as a string when no React element\n // is used, therefore it's safe to cast this type.\n const result = originalRich(key, values as RichTranslationValues, formats);\n\n // When only string chunks are provided to the parser, only strings should be returned here.\n if (typeof result !== 'string') {\n const error = new IntlError(\n IntlErrorCode.FORMATTING_ERROR,\n process.env.NODE_ENV !== 'production'\n ? \"`createTranslator` only accepts functions for rich text formatting that receive and return strings.\\n\\nE.g. t.rich('rich', {b: (chunks) => `<b>${chunks}</b>`})\"\n : undefined\n );\n\n onError(error);\n return getMessageFallback({error, key, namespace});\n }\n\n return result;\n };\n\n base.raw = translator.raw;\n\n return base;\n}\n","import {useMemo} from 'react';\nimport createFormatter from '../core/createFormatter';\nimport useIntlContext from './useIntlContext';\n\nexport default function useFormatter() {\n const {formats, locale, now: globalNow, onError, timeZone} = useIntlContext();\n\n return useMemo(\n () =>\n createFormatter({\n formats,\n locale,\n now: globalNow,\n onError,\n timeZone\n }),\n [formats, globalNow, locale, onError, timeZone]\n );\n}\n","import useIntlContext from './useIntlContext';\n\nexport default function useLocale() {\n return useIntlContext().locale;\n}\n","import useIntlContext from './useIntlContext';\n\nexport default function useMessages() {\n return useIntlContext().messages;\n}\n","import useIntlContext from './useIntlContext';\n\nexport default function useTimeZone() {\n return useIntlContext().timeZone;\n}\n","import {ReactElement, ReactNodeArray} from 'react';\nimport Formats from '../core/Formats';\nimport TranslationValues, {\n RichTranslationValues\n} from '../core/TranslationValues';\nimport MessageKeys from '../core/utils/MessageKeys';\nimport NamespaceKeys from '../core/utils/NamespaceKeys';\nimport NestedKeyOf from '../core/utils/NestedKeyOf';\nimport NestedValueOf from '../core/utils/NestedValueOf';\nimport useIntlContext from './useIntlContext';\nimport useTranslationsImpl from './useTranslationsImpl';\n\n/**\n * Translates messages from the given namespace by using the ICU syntax.\n * See https://formatjs.io/docs/core-concepts/icu-syntax.\n *\n * If no namespace is provided, all available messages are returned.\n * The namespace can also indicate nesting by using a dot\n * (e.g. `namespace.Component`).\n */\nexport default function useTranslations<\n NestedKey extends NamespaceKeys<\n IntlMessages,\n NestedKeyOf<IntlMessages>\n > = never\n>(\n namespace?: NestedKey\n): // Explicitly defining the return type is necessary as TypeScript would get it wrong\n{\n // Default invocation\n <\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey,\n values?: TranslationValues,\n formats?: Partial<Formats>\n ): string;\n\n // `rich`\n rich<\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey,\n values?: RichTranslationValues,\n formats?: Partial<Formats>\n ): string | ReactElement | ReactNodeArray;\n\n // `raw`\n raw<\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey\n ): any;\n} {\n const context = useIntlContext();\n const messages = context.messages as IntlMessages;\n\n // We have to wrap the actual hook so the type inference for the optional\n // namespace works correctly. See https://stackoverflow.com/a/71529575/343045\n // The prefix (\"!\") is arbitrary.\n return useTranslationsImpl<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >(\n {'!': messages},\n // @ts-expect-error\n namespace ? `!.${namespace}` : '!',\n '!'\n );\n}\n","import {useMemo} from 'react';\nimport AbstractIntlMessages from '../core/AbstractIntlMessages';\nimport createBaseTranslator, {\n getMessagesOrError\n} from '../core/createBaseTranslator';\nimport resolveNamespace from '../core/resolveNamespace';\nimport NestedKeyOf from '../core/utils/NestedKeyOf';\nimport useIntlContext from './useIntlContext';\n\nexport default function useTranslationsImpl<\n Messages extends AbstractIntlMessages,\n NestedKey extends NestedKeyOf<Messages>\n>(allMessages: Messages, namespace: NestedKey, namespacePrefix: string) {\n const {\n defaultTranslationValues,\n formats: globalFormats,\n getMessageFallback,\n locale,\n messageFormatCache,\n onError,\n timeZone\n } = useIntlContext();\n\n // The `namespacePrefix` is part of the type system.\n // See the comment in the hook invocation.\n allMessages = allMessages[namespacePrefix] as Messages;\n namespace = resolveNamespace(namespace, namespacePrefix) as NestedKey;\n\n const messagesOrError = useMemo(\n () => getMessagesOrError({messages: allMessages, namespace, onError}),\n [allMessages, namespace, onError]\n );\n\n const translate = useMemo(\n () =>\n createBaseTranslator({\n messageFormatCache,\n getMessageFallback,\n messagesOrError,\n defaultTranslationValues,\n namespace,\n onError,\n formats: globalFormats,\n locale,\n timeZone\n }),\n [\n messageFormatCache,\n getMessageFallback,\n messagesOrError,\n defaultTranslationValues,\n namespace,\n onError,\n globalFormats,\n locale,\n timeZone\n ]\n );\n\n return translate;\n}\n"],"names":["IntlErrorCode","IntlError","_Error","code","originalMessage","_this","message","call","this","_wrapNativeSuper","Error","setTimeZoneInFormats","formats","timeZone","Object","keys","reduce","acc","key","_extends","defaultGetMessageFallback","props","namespace","filter","part","join","defaultOnError","error","console","resolvePath","messages","undefined","split","forEach","next","getMessagesOrError","_ref","_ref$onError","onError","retrievedMessages","intlError","MISSING_MESSAGE","createBaseTranslator","_ref2","defaultTranslationValues","globalFormats","_ref2$getMessageFallb","getMessageFallback","locale","messageFormatCache","messagesOrError","getFallbackFromErrorAndNotify","translateBaseFn","values","messageFormat","cacheKey","String","has","get","Array","isArray","INVALID_MESSAGE","INSUFFICIENT_PATH","errorMessage","plainMessage","candidate","unescapedMessage","replace","test","getPlainMessage","IntlMessageFormat","formatsWithTimeZone","dateTime","mfDateDefaults","date","defaultDateFormats","mfTimeDefaults","time","defaultTimeFormats","convertFormatsToIntlMessageFormat","set","formattedMessage","format","length","transformedValues","index","value","chunks","result","isValidElement","cloneElement","prepareTranslationValues","FORMATTING_ERROR","translateFn","rich","raw","resolveNamespace","namespacePrefix","slice","MINUTE","HOUR","DAY","WEEK","MONTH","YEAR","createFormatter","globalNow","now","getFormattedValue","formatOrOptions","typeFormats","formatter","options","MISSING_FORMAT","resolveFormatOrOptions","_options","Intl","DateTimeFormat","number","NumberFormat","relativeTime","dateDate","Date","nowDate","_getRelativeTimeForma","seconds","unit","absValue","Math","abs","round","getRelativeTimeFormatConfig","getTime","RelativeTimeFormat","numeric","list","ListFormat","createIntl","apply","arguments","formatDateTime","formatNumber","formatRelativeTime","IntlContext","createContext","getInitializedConfig","_objectWithoutPropertiesLoose","_excluded","useIntlContext","context","useContext","getNow","hasWarned","children","useState","Map","React","createElement","Provider","_ref$getMessageFallba","rest","translator","originalRich","base","createTranslatorImpl","_useIntlContext","useMemo","warn","updateInterval","_useState","setNow","useEffect","intervalId","setInterval","clearInterval","allMessages","useTranslationsImpl"],"mappings":"uMAAYA,giDAAAA,QAOXA,mBAAA,GAPWA,EAAAA,wBAAAA,QAAAA,cAOX,CAAA,IANC,gBAAA,kBACAA,EAAA,eAAA,iBACAA,EAAA,kBAAA,oBACAA,EAAA,gBAAA,kBACAA,EAAA,YAAA,cACAA,EAAA,iBAAA,mBAGmBC,IAAAA,WAAUC,WAI7B,SAAA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,EACAG,EACAnC,GAKN,CDiCSmK,CAIL,CAAC,IAVa5B,IACStH,UAWvBR,OAAiBA,EAAc,IAGnC"}
1
+ {"version":3,"file":"use-intl.cjs.production.min.js","sources":["../src/core/IntlError.tsx","../src/core/convertFormatsToIntlMessageFormat.tsx","../src/core/defaults.tsx","../src/core/createBaseTranslator.tsx","../src/core/resolveNamespace.tsx","../src/core/createFormatter.tsx","../src/core/createIntl.tsx","../src/react/IntlContext.tsx","../src/react/getInitializedConfig.tsx","../src/react/useIntlContext.tsx","../src/react/useNow.tsx","../src/react/useIntl.tsx","../src/react/IntlProvider.tsx","../src/core/createTranslator.tsx","../src/core/createTranslatorImpl.tsx","../src/react/useFormatter.tsx","../src/react/useLocale.tsx","../src/react/useMessages.tsx","../src/react/useTimeZone.tsx","../src/react/useTranslations.tsx","../src/react/useTranslationsImpl.tsx"],"sourcesContent":["export enum IntlErrorCode {\n MISSING_MESSAGE = 'MISSING_MESSAGE',\n MISSING_FORMAT = 'MISSING_FORMAT',\n ENVIRONMENT_FALLBACK = 'ENVIRONMENT_FALLBACK',\n INSUFFICIENT_PATH = 'INSUFFICIENT_PATH',\n INVALID_MESSAGE = 'INVALID_MESSAGE',\n INVALID_KEY = 'INVALID_KEY',\n FORMATTING_ERROR = 'FORMATTING_ERROR'\n}\n\nexport default class IntlError extends Error {\n public readonly code: IntlErrorCode;\n public readonly originalMessage: string | undefined;\n\n constructor(code: IntlErrorCode, originalMessage?: string) {\n let message: string = code;\n if (originalMessage) {\n message += ': ' + originalMessage;\n }\n super(message);\n\n this.code = code;\n if (originalMessage) {\n this.originalMessage = originalMessage;\n }\n }\n}\n","// eslint-disable-next-line import/no-named-as-default -- False positive\nimport IntlMessageFormat, {Formats as IntlFormats} from 'intl-messageformat';\nimport DateTimeFormatOptions from './DateTimeFormatOptions';\nimport Formats from './Formats';\nimport TimeZone from './TimeZone';\n\nfunction setTimeZoneInFormats(\n formats: Record<string, DateTimeFormatOptions> | undefined,\n timeZone: TimeZone\n) {\n if (!formats) return formats;\n\n // The only way to set a time zone with `intl-messageformat` is to merge it into the formats\n // https://github.com/formatjs/formatjs/blob/8256c5271505cf2606e48e3c97ecdd16ede4f1b5/packages/intl/src/message.ts#L15\n return Object.keys(formats).reduce(\n (acc: Record<string, DateTimeFormatOptions>, key) => {\n acc[key] = {\n timeZone,\n ...formats[key]\n };\n return acc;\n },\n {}\n );\n}\n\n/**\n * `intl-messageformat` uses separate keys for `date` and `time`, but there's\n * only one native API: `Intl.DateTimeFormat`. Additionally you might want to\n * include both a time and a date in a value, therefore the separation doesn't\n * seem so useful. We offer a single `dateTime` namespace instead, but we have\n * to convert the format before `intl-messageformat` can be used.\n */\nexport default function convertFormatsToIntlMessageFormat(\n formats: Partial<Formats>,\n timeZone?: TimeZone\n): Partial<IntlFormats> {\n const formatsWithTimeZone = timeZone\n ? {...formats, dateTime: setTimeZoneInFormats(formats.dateTime, timeZone)}\n : formats;\n\n const mfDateDefaults = IntlMessageFormat.formats.date as Formats['dateTime'];\n const defaultDateFormats = timeZone\n ? setTimeZoneInFormats(mfDateDefaults, timeZone)\n : mfDateDefaults;\n\n const mfTimeDefaults = IntlMessageFormat.formats.time as Formats['dateTime'];\n const defaultTimeFormats = timeZone\n ? setTimeZoneInFormats(mfTimeDefaults, timeZone)\n : mfTimeDefaults;\n\n return {\n ...formatsWithTimeZone,\n date: {\n ...defaultDateFormats,\n ...formatsWithTimeZone?.dateTime\n },\n time: {\n ...defaultTimeFormats,\n ...formatsWithTimeZone?.dateTime\n }\n };\n}\n","import IntlError from './IntlError';\n\n/**\n * Contains defaults that are used for all entry points into the core.\n * See also `InitializedIntlConfiguration`.\n */\n\nexport function defaultGetMessageFallback(props: {\n error: IntlError;\n key: string;\n namespace?: string;\n}) {\n return [props.namespace, props.key].filter((part) => part != null).join('.');\n}\n\nexport function defaultOnError(error: IntlError) {\n console.error(error);\n}\n","// eslint-disable-next-line import/no-named-as-default -- False positive\nimport IntlMessageFormat from 'intl-messageformat';\nimport {\n cloneElement,\n isValidElement,\n ReactElement,\n ReactNode,\n ReactNodeArray\n} from 'react';\nimport AbstractIntlMessages from './AbstractIntlMessages';\nimport Formats from './Formats';\nimport {InitializedIntlConfig} from './IntlConfig';\nimport IntlError, {IntlErrorCode} from './IntlError';\nimport MessageFormatCache from './MessageFormatCache';\nimport TranslationValues, {RichTranslationValues} from './TranslationValues';\nimport convertFormatsToIntlMessageFormat from './convertFormatsToIntlMessageFormat';\nimport {defaultGetMessageFallback, defaultOnError} from './defaults';\nimport MessageKeys from './utils/MessageKeys';\nimport NestedKeyOf from './utils/NestedKeyOf';\nimport NestedValueOf from './utils/NestedValueOf';\n\nfunction resolvePath(\n messages: AbstractIntlMessages | undefined,\n key: string,\n namespace?: string\n) {\n if (!messages) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `No messages available at \\`${namespace}\\`.`\n : undefined\n );\n }\n\n let message = messages;\n\n key.split('.').forEach((part) => {\n const next = (message as any)[part];\n\n if (part == null || next == null) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `Could not resolve \\`${key}\\` in ${\n namespace ? `\\`${namespace}\\`` : 'messages'\n }.`\n : undefined\n );\n }\n\n message = next;\n });\n\n return message;\n}\n\nfunction prepareTranslationValues(values: RichTranslationValues) {\n if (Object.keys(values).length === 0) return undefined;\n\n // Workaround for https://github.com/formatjs/formatjs/issues/1467\n const transformedValues: RichTranslationValues = {};\n Object.keys(values).forEach((key) => {\n let index = 0;\n const value = values[key];\n\n let transformed;\n if (typeof value === 'function') {\n transformed = (chunks: ReactNode) => {\n const result = value(chunks);\n\n return isValidElement(result)\n ? cloneElement(result, {key: key + index++})\n : result;\n };\n } else {\n transformed = value;\n }\n\n transformedValues[key] = transformed;\n });\n\n return transformedValues;\n}\n\nexport function getMessagesOrError<Messages extends AbstractIntlMessages>({\n messages,\n namespace,\n onError = defaultOnError\n}: {\n messages: Messages;\n namespace?: string;\n onError?(error: IntlError): void;\n}) {\n try {\n if (!messages) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `No messages were configured on the provider.`\n : undefined\n );\n }\n\n const retrievedMessages = namespace\n ? resolvePath(messages, namespace)\n : messages;\n\n if (!retrievedMessages) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `No messages for namespace \\`${namespace}\\` found.`\n : undefined\n );\n }\n\n return retrievedMessages;\n } catch (error) {\n const intlError = new IntlError(\n IntlErrorCode.MISSING_MESSAGE,\n (error as Error).message\n );\n onError(intlError);\n return intlError;\n }\n}\n\nexport type CreateBaseTranslatorProps<Messages> = InitializedIntlConfig & {\n messageFormatCache?: MessageFormatCache;\n defaultTranslationValues?: RichTranslationValues;\n namespace?: string;\n messagesOrError: Messages | IntlError;\n};\n\nfunction getPlainMessage(candidate: string, values?: unknown) {\n if (values) return undefined;\n\n const unescapedMessage = candidate.replace(/'([{}])/gi, '$1');\n\n // Placeholders can be in the message if there are default values,\n // or if the user has forgotten to provide values. In the latter\n // case we need to compile the message to receive an error.\n const hasPlaceholders = /<|{/.test(unescapedMessage);\n\n if (!hasPlaceholders) {\n return unescapedMessage;\n }\n\n return undefined;\n}\n\nexport default function createBaseTranslator<\n Messages extends AbstractIntlMessages,\n NestedKey extends NestedKeyOf<Messages>\n>({\n defaultTranslationValues,\n formats: globalFormats,\n getMessageFallback = defaultGetMessageFallback,\n locale,\n messageFormatCache,\n messagesOrError,\n namespace,\n onError,\n timeZone\n}: CreateBaseTranslatorProps<Messages>) {\n function getFallbackFromErrorAndNotify(\n key: string,\n code: IntlErrorCode,\n message?: string\n ) {\n const error = new IntlError(code, message);\n onError(error);\n return getMessageFallback({error, key, namespace});\n }\n\n function translateBaseFn(\n /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */\n key: string,\n /** Key value pairs for values to interpolate into the message. */\n values?: RichTranslationValues,\n /** Provide custom formats for numbers, dates and times. */\n formats?: Partial<Formats>\n ): string | ReactElement | ReactNodeArray {\n if (messagesOrError instanceof IntlError) {\n // We have already warned about this during render\n return getMessageFallback({\n error: messagesOrError,\n key,\n namespace\n });\n }\n const messages = messagesOrError;\n\n let message;\n try {\n message = resolvePath(messages, key, namespace);\n } catch (error) {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.MISSING_MESSAGE,\n (error as Error).message\n );\n }\n\n function joinPath(parts: Array<string | undefined>) {\n return parts.filter((part) => part != null).join('.');\n }\n\n const cacheKey = joinPath([locale, namespace, key, String(message)]);\n\n let messageFormat: IntlMessageFormat;\n if (messageFormatCache?.has(cacheKey)) {\n messageFormat = messageFormatCache.get(cacheKey)!;\n } else {\n if (typeof message === 'object') {\n let code, errorMessage;\n if (Array.isArray(message)) {\n code = IntlErrorCode.INVALID_MESSAGE;\n if (process.env.NODE_ENV !== 'production') {\n errorMessage = `Message at \\`${joinPath([\n namespace,\n key\n ])}\\` resolved to an array, but only strings are supported. See https://next-intl-docs.vercel.app/docs/usage/messages#arrays-of-messages`;\n }\n } else {\n code = IntlErrorCode.INSUFFICIENT_PATH;\n if (process.env.NODE_ENV !== 'production') {\n errorMessage = `Message at \\`${joinPath([\n namespace,\n key\n ])}\\` resolved to an object, but only strings are supported. Use a \\`.\\` to retrieve nested messages. See https://next-intl-docs.vercel.app/docs/usage/messages#structuring-messages`;\n }\n }\n\n return getFallbackFromErrorAndNotify(key, code, errorMessage);\n }\n\n // Hot path that avoids creating an `IntlMessageFormat` instance\n const plainMessage = getPlainMessage(message as string, values);\n if (plainMessage) return plainMessage;\n\n try {\n messageFormat = new IntlMessageFormat(\n message,\n locale,\n convertFormatsToIntlMessageFormat(\n {...globalFormats, ...formats},\n timeZone\n )\n );\n } catch (error) {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.INVALID_MESSAGE,\n (error as Error).message\n );\n }\n\n messageFormatCache?.set(cacheKey, messageFormat);\n }\n\n try {\n const formattedMessage = messageFormat.format(\n // @ts-ignore `intl-messageformat` expects a different format\n // for rich text elements since a recent minor update. This\n // needs to be evaluated in detail, possibly also in regards\n // to be able to format to parts.\n prepareTranslationValues({...defaultTranslationValues, ...values})\n );\n\n if (formattedMessage == null) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? `Unable to format \\`${key}\\` in ${\n namespace ? `namespace \\`${namespace}\\`` : 'messages'\n }`\n : undefined\n );\n }\n\n // Limit the function signature to return strings or React elements\n return isValidElement(formattedMessage) ||\n // Arrays of React elements\n Array.isArray(formattedMessage) ||\n typeof formattedMessage === 'string'\n ? formattedMessage\n : String(formattedMessage);\n } catch (error) {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.FORMATTING_ERROR,\n (error as Error).message\n );\n }\n }\n\n function translateFn<\n TargetKey extends MessageKeys<\n NestedValueOf<Messages, NestedKey>,\n NestedKeyOf<NestedValueOf<Messages, NestedKey>>\n >\n >(\n /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */\n key: TargetKey,\n /** Key value pairs for values to interpolate into the message. */\n values?: TranslationValues,\n /** Provide custom formats for numbers, dates and times. */\n formats?: Partial<Formats>\n ): string {\n const result = translateBaseFn(key, values, formats);\n\n if (typeof result !== 'string') {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.INVALID_MESSAGE,\n process.env.NODE_ENV !== 'production'\n ? `The message \\`${key}\\` in ${\n namespace ? `namespace \\`${namespace}\\`` : 'messages'\n } didn't resolve to a string. If you want to format rich text, use \\`t.rich\\` instead.`\n : undefined\n );\n }\n\n return result;\n }\n\n translateFn.rich = translateBaseFn;\n\n translateFn.raw = (\n /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */\n key: string\n ): any => {\n if (messagesOrError instanceof IntlError) {\n // We have already warned about this during render\n return getMessageFallback({\n error: messagesOrError,\n key,\n namespace\n });\n }\n const messages = messagesOrError;\n\n try {\n return resolvePath(messages, key, namespace);\n } catch (error) {\n return getFallbackFromErrorAndNotify(\n key,\n IntlErrorCode.MISSING_MESSAGE,\n (error as Error).message\n );\n }\n };\n\n return translateFn;\n}\n","/**\n * For the strictly typed messages to work we have to wrap the namespace into\n * a mandatory prefix. See https://stackoverflow.com/a/71529575/343045\n */\nexport default function resolveNamespace(\n namespace: string,\n namespacePrefix: string\n) {\n return namespace === namespacePrefix\n ? undefined\n : namespace.slice((namespacePrefix + '.').length);\n}\n","import DateTimeFormatOptions from './DateTimeFormatOptions';\nimport Formats from './Formats';\nimport IntlError, {IntlErrorCode} from './IntlError';\nimport NumberFormatOptions from './NumberFormatOptions';\nimport RelativeTimeFormatOptions from './RelativeTimeFormatOptions';\nimport TimeZone from './TimeZone';\nimport {defaultOnError} from './defaults';\n\nconst SECOND = 1;\nconst MINUTE = SECOND * 60;\nconst HOUR = MINUTE * 60;\nconst DAY = HOUR * 24;\nconst WEEK = DAY * 7;\nconst MONTH = DAY * (365 / 12); // Approximation\nconst QUARTER = MONTH * 3;\nconst YEAR = DAY * 365;\n\nconst UNIT_SECONDS: Record<Intl.RelativeTimeFormatUnit, number> = {\n second: SECOND,\n seconds: SECOND,\n minute: MINUTE,\n minutes: MINUTE,\n hour: HOUR,\n hours: HOUR,\n day: DAY,\n days: DAY,\n week: WEEK,\n weeks: WEEK,\n month: MONTH,\n months: MONTH,\n quarter: QUARTER,\n quarters: QUARTER,\n year: YEAR,\n years: YEAR\n} as const;\n\nfunction resolveRelativeTimeUnit(seconds: number) {\n const absValue = Math.abs(seconds);\n\n if (absValue < MINUTE) {\n return 'second';\n } else if (absValue < HOUR) {\n return 'minute';\n } else if (absValue < DAY) {\n return 'hour';\n } else if (absValue < WEEK) {\n return 'day';\n } else if (absValue < MONTH) {\n return 'week';\n } else if (absValue < YEAR) {\n return 'month';\n }\n return 'year';\n}\n\nfunction calculateRelativeTimeValue(\n seconds: number,\n unit: Intl.RelativeTimeFormatUnit\n) {\n // We have to round the resulting values, as `Intl.RelativeTimeFormat`\n // will include fractions like '2.1 hours ago'.\n return Math.round(seconds / UNIT_SECONDS[unit]);\n}\n\ntype Props = {\n locale: string;\n timeZone?: TimeZone;\n onError?(error: IntlError): void;\n formats?: Partial<Formats>;\n now?: Date;\n};\n\nexport default function createFormatter({\n formats,\n locale,\n now: globalNow,\n onError = defaultOnError,\n timeZone: globalTimeZone\n}: Props) {\n function resolveFormatOrOptions<Options>(\n typeFormats: Record<string, Options> | undefined,\n formatOrOptions?: string | Options\n ) {\n let options;\n if (typeof formatOrOptions === 'string') {\n const formatName = formatOrOptions;\n options = typeFormats?.[formatName];\n\n if (!options) {\n const error = new IntlError(\n IntlErrorCode.MISSING_FORMAT,\n process.env.NODE_ENV !== 'production'\n ? `Format \\`${formatName}\\` is not available. You can configure it on the provider or provide custom options.`\n : undefined\n );\n onError(error);\n throw error;\n }\n } else {\n options = formatOrOptions;\n }\n\n return options;\n }\n\n function getFormattedValue<Value, Options>(\n value: Value,\n formatOrOptions: string | Options | undefined,\n typeFormats: Record<string, Options> | undefined,\n formatter: (options?: Options) => string\n ) {\n let options;\n try {\n options = resolveFormatOrOptions(typeFormats, formatOrOptions);\n } catch (error) {\n return String(value);\n }\n\n try {\n return formatter(options);\n } catch (error) {\n onError(\n new IntlError(IntlErrorCode.FORMATTING_ERROR, (error as Error).message)\n );\n return String(value);\n }\n }\n\n function dateTime(\n /** If a number is supplied, this is interpreted as a UTC timestamp. */\n value: Date | number,\n /** If a time zone is supplied, the `value` is converted to that time zone.\n * Otherwise the user time zone will be used. */\n formatOrOptions?: string | DateTimeFormatOptions\n ) {\n return getFormattedValue(\n value,\n formatOrOptions,\n formats?.dateTime,\n (options) => {\n if (!options?.timeZone) {\n if (globalTimeZone) {\n options = {...options, timeZone: globalTimeZone};\n } else {\n onError(\n new IntlError(\n IntlErrorCode.ENVIRONMENT_FALLBACK,\n process.env.NODE_ENV !== 'production'\n ? `The \\`timeZone\\` parameter wasn't provided and there is no global default configured. Consider adding a global default to avoid markup mismatches caused by environment differences. Learn more: https://next-intl-docs.vercel.app/docs/configuration#time-zone`\n : undefined\n )\n );\n }\n }\n\n return new Intl.DateTimeFormat(locale, options).format(value);\n }\n );\n }\n\n function number(\n value: number | bigint,\n formatOrOptions?: string | NumberFormatOptions\n ) {\n return getFormattedValue(\n value,\n formatOrOptions,\n formats?.number,\n (options) => new Intl.NumberFormat(locale, options).format(value)\n );\n }\n\n function getGlobalNow() {\n if (globalNow) {\n return globalNow;\n } else {\n onError(\n new IntlError(\n IntlErrorCode.ENVIRONMENT_FALLBACK,\n process.env.NODE_ENV !== 'production'\n ? `The \\`now\\` parameter wasn't provided and there is no global default configured. Consider adding a global default to avoid markup mismatches caused by environment differences. Learn more: https://next-intl-docs.vercel.app/docs/configuration#now`\n : undefined\n )\n );\n return new Date();\n }\n }\n\n function extractNowDate(\n nowOrOptions?: RelativeTimeFormatOptions['now'] | RelativeTimeFormatOptions\n ) {\n if (nowOrOptions instanceof Date || typeof nowOrOptions === 'number') {\n return new Date(nowOrOptions);\n }\n if (nowOrOptions?.now !== undefined) {\n return new Date(nowOrOptions.now);\n }\n return getGlobalNow();\n }\n\n function relativeTime(\n /** The date time that needs to be formatted. */\n date: number | Date,\n /** The reference point in time to which `date` will be formatted in relation to. */\n nowOrOptions?: RelativeTimeFormatOptions['now'] | RelativeTimeFormatOptions\n ) {\n try {\n const dateDate = new Date(date);\n const nowDate = extractNowDate(nowOrOptions);\n const seconds = (dateDate.getTime() - nowDate.getTime()) / 1000;\n\n const unit =\n typeof nowOrOptions === 'number' ||\n nowOrOptions instanceof Date ||\n nowOrOptions?.unit === undefined\n ? resolveRelativeTimeUnit(seconds)\n : nowOrOptions.unit;\n\n const value = calculateRelativeTimeValue(seconds, unit);\n\n return new Intl.RelativeTimeFormat(locale, {\n numeric: 'auto'\n }).format(value, unit);\n } catch (error) {\n onError(\n new IntlError(IntlErrorCode.FORMATTING_ERROR, (error as Error).message)\n );\n return String(date);\n }\n }\n\n function list(\n value: Iterable<string>,\n formatOrOptions?: string | Intl.ListFormatOptions\n ) {\n return getFormattedValue(value, formatOrOptions, formats?.list, (options) =>\n new Intl.ListFormat(locale, options).format(value)\n );\n }\n\n return {dateTime, number, relativeTime, list};\n}\n","import createFormatter from './createFormatter';\n\n/** @deprecated Switch to `createFormatter` */\nexport default function createIntl(\n ...args: Parameters<typeof createFormatter>\n) {\n const formatter = createFormatter(...args);\n return {\n formatDateTime: formatter.dateTime,\n formatNumber: formatter.number,\n formatRelativeTime: formatter.relativeTime\n };\n}\n","import {createContext} from 'react';\nimport {InitializedIntlConfig} from '../core/IntlConfig';\nimport MessageFormatCache from '../core/MessageFormatCache';\n\nconst IntlContext = createContext<\n | (InitializedIntlConfig & {\n messageFormatCache?: MessageFormatCache;\n })\n | undefined\n>(undefined);\n\nexport default IntlContext;\n","import IntlConfig from '../core/IntlConfig';\nimport {defaultGetMessageFallback, defaultOnError} from '../core/defaults';\nimport validateMessages from '../core/validateMessages';\n\n/**\n * Enhances the incoming props with defaults.\n */\nexport default function getInitializedConfig<\n // This is a generic to allow for stricter typing. E.g.\n // the RSC integration always provides a `now` value.\n Props extends Omit<IntlConfig, 'children'>\n>({getMessageFallback, messages, onError, ...rest}: Props) {\n const finalOnError = onError || defaultOnError;\n const finalGetMessageFallback =\n getMessageFallback || defaultGetMessageFallback;\n\n if (process.env.NODE_ENV !== 'production') {\n if (messages) {\n validateMessages(messages, finalOnError);\n }\n }\n\n return {\n ...rest,\n messages,\n onError: finalOnError,\n getMessageFallback: finalGetMessageFallback\n };\n}\n","import {useContext} from 'react';\nimport IntlContext from './IntlContext';\n\nexport default function useIntlContext() {\n const context = useContext(IntlContext);\n\n if (!context) {\n throw new Error(\n process.env.NODE_ENV !== 'production'\n ? 'No intl context found. Have you configured the provider?'\n : undefined\n );\n }\n\n return context;\n}\n","import {useState, useEffect} from 'react';\nimport useIntlContext from './useIntlContext';\n\ntype Options = {\n updateInterval?: number;\n};\n\nfunction getNow() {\n return new Date();\n}\n\n/**\n * Reading the current date via `new Date()` in components should be avoided, as\n * it causes components to be impure and can lead to flaky tests. Instead, this\n * hook can be used.\n *\n * By default, it returns the time when the component mounts. If `updateInterval`\n * is specified, the value will be updated based on the interval.\n *\n * You can however also return a static value from this hook, if you\n * configure the `now` parameter on the context provider. Note however,\n * that if `updateInterval` is configured in this case, the component\n * will initialize with the global value, but will afterwards update\n * continuously based on the interval.\n *\n * For unit tests, this can be mocked to a constant value. For end-to-end\n * testing, an environment parameter can be passed to the `now` parameter\n * of the provider to mock this to a static value.\n */\nexport default function useNow(options?: Options) {\n const updateInterval = options?.updateInterval;\n\n const {now: globalNow} = useIntlContext();\n const [now, setNow] = useState(globalNow || getNow());\n\n useEffect(() => {\n if (!updateInterval) return;\n\n const intervalId = setInterval(() => {\n setNow(getNow());\n }, updateInterval);\n\n return () => {\n clearInterval(intervalId);\n };\n }, [globalNow, updateInterval]);\n\n return now;\n}\n","import {useMemo} from 'react';\nimport createIntl from '../core/createIntl';\nimport useIntlContext from './useIntlContext';\n\nlet hasWarned = false;\n\n/** @deprecated Switch to `useFormatter` instead. */\nexport default function useIntl() {\n const {formats, locale, now: globalNow, onError, timeZone} = useIntlContext();\n\n if (!hasWarned) {\n hasWarned = true;\n console.warn(\n '`useIntl()` is deprecated and will be removed in the next major version. Please switch to `useFormatter()`.'\n );\n }\n\n return useMemo(\n () =>\n createIntl({\n formats,\n locale,\n now: globalNow,\n onError,\n timeZone\n }),\n [formats, globalNow, locale, onError, timeZone]\n );\n}\n","import React, {ReactNode, useState} from 'react';\nimport IntlConfig from '../core/IntlConfig';\nimport IntlContext from './IntlContext';\nimport getInitializedConfig from './getInitializedConfig';\n\ntype Props = IntlConfig & {\n children: ReactNode;\n};\n\nexport default function IntlProvider({children, ...props}: Props) {\n const [messageFormatCache] = useState(() => new Map());\n\n return (\n <IntlContext.Provider\n value={{\n ...getInitializedConfig(props),\n messageFormatCache\n }}\n >\n {children}\n </IntlContext.Provider>\n );\n}\n","import Formats from './Formats';\nimport IntlConfig from './IntlConfig';\nimport TranslationValues from './TranslationValues';\nimport createTranslatorImpl, {\n CoreRichTranslationValues\n} from './createTranslatorImpl';\nimport {defaultGetMessageFallback, defaultOnError} from './defaults';\nimport MessageKeys from './utils/MessageKeys';\nimport NamespaceKeys from './utils/NamespaceKeys';\nimport NestedKeyOf from './utils/NestedKeyOf';\nimport NestedValueOf from './utils/NestedValueOf';\n\n/**\n * Translates messages from the given namespace by using the ICU syntax.\n * See https://formatjs.io/docs/core-concepts/icu-syntax.\n *\n * If no namespace is provided, all available messages are returned.\n * The namespace can also indicate nesting by using a dot\n * (e.g. `namespace.Component`).\n */\nexport default function createTranslator<\n NestedKey extends NamespaceKeys<\n IntlMessages,\n NestedKeyOf<IntlMessages>\n > = never\n>({\n getMessageFallback = defaultGetMessageFallback,\n messages,\n namespace,\n onError = defaultOnError,\n ...rest\n}: Omit<IntlConfig<IntlMessages>, 'defaultTranslationValues' | 'messages'> & {\n messages: NonNullable<IntlConfig<IntlMessages>['messages']>;\n namespace?: NestedKey;\n}): // Explicitly defining the return type is necessary as TypeScript would get it wrong\n{\n // Default invocation\n <\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey,\n values?: TranslationValues,\n formats?: Partial<Formats>\n ): string;\n\n // `rich`\n rich<\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey,\n values?: CoreRichTranslationValues,\n formats?: Partial<Formats>\n ): string;\n\n // `raw`\n raw<\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey\n ): any;\n} {\n // We have to wrap the actual function so the type inference for the optional\n // namespace works correctly. See https://stackoverflow.com/a/71529575/343045\n // The prefix (\"!\") is arbitrary.\n return createTranslatorImpl<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >(\n {\n ...rest,\n onError,\n getMessageFallback,\n messages: {'!': messages},\n namespace: namespace ? `!.${namespace}` : '!'\n },\n '!'\n );\n}\n","import AbstractIntlMessages from './AbstractIntlMessages';\nimport {InitializedIntlConfig} from './IntlConfig';\nimport IntlError, {IntlErrorCode} from './IntlError';\nimport {RichTranslationValues, TranslationValue} from './TranslationValues';\nimport createBaseTranslator, {getMessagesOrError} from './createBaseTranslator';\nimport resolveNamespace from './resolveNamespace';\nimport NestedKeyOf from './utils/NestedKeyOf';\n\nexport type CoreRichTranslationValues = Record<\n string,\n TranslationValue | ((chunks: string) => string)\n>;\n\nexport type CreateTranslatorImplProps<Messages> = Omit<\n InitializedIntlConfig,\n 'messages'\n> & {\n namespace: string;\n messages: Messages;\n};\n\nexport default function createTranslatorImpl<\n Messages extends AbstractIntlMessages,\n NestedKey extends NestedKeyOf<Messages>\n>(\n {\n getMessageFallback,\n messages,\n namespace,\n onError,\n ...rest\n }: CreateTranslatorImplProps<Messages>,\n namespacePrefix: string\n) {\n // The `namespacePrefix` is part of the type system.\n // See the comment in the function invocation.\n messages = messages[namespacePrefix] as Messages;\n namespace = resolveNamespace(namespace, namespacePrefix) as NestedKey;\n\n const translator = createBaseTranslator<Messages, NestedKey>({\n ...rest,\n onError,\n getMessageFallback,\n messagesOrError: getMessagesOrError({\n messages,\n namespace,\n onError\n }) as Messages | IntlError\n });\n\n const originalRich = translator.rich;\n\n function base(...args: Parameters<typeof translator>) {\n return translator(...args);\n }\n\n // Augment `t.rich` to return plain strings\n base.rich = (\n key: Parameters<typeof originalRich>[0],\n /** Key value pairs for values to interpolate into the message. */\n values: CoreRichTranslationValues,\n formats?: Parameters<typeof originalRich>[2]\n ): string => {\n // `chunks` is returned as a string when no React element\n // is used, therefore it's safe to cast this type.\n const result = originalRich(key, values as RichTranslationValues, formats);\n\n // When only string chunks are provided to the parser, only strings should be returned here.\n if (typeof result !== 'string') {\n const error = new IntlError(\n IntlErrorCode.FORMATTING_ERROR,\n process.env.NODE_ENV !== 'production'\n ? \"`createTranslator` only accepts functions for rich text formatting that receive and return strings.\\n\\nE.g. t.rich('rich', {b: (chunks) => `<b>${chunks}</b>`})\"\n : undefined\n );\n\n onError(error);\n return getMessageFallback({error, key, namespace});\n }\n\n return result;\n };\n\n base.raw = translator.raw;\n\n return base;\n}\n","import {useMemo} from 'react';\nimport createFormatter from '../core/createFormatter';\nimport useIntlContext from './useIntlContext';\n\nexport default function useFormatter() {\n const {formats, locale, now: globalNow, onError, timeZone} = useIntlContext();\n\n return useMemo(\n () =>\n createFormatter({\n formats,\n locale,\n now: globalNow,\n onError,\n timeZone\n }),\n [formats, globalNow, locale, onError, timeZone]\n );\n}\n","import useIntlContext from './useIntlContext';\n\nexport default function useLocale() {\n return useIntlContext().locale;\n}\n","import useIntlContext from './useIntlContext';\n\nexport default function useMessages() {\n return useIntlContext().messages;\n}\n","import useIntlContext from './useIntlContext';\n\nexport default function useTimeZone() {\n return useIntlContext().timeZone;\n}\n","import {ReactElement, ReactNodeArray} from 'react';\nimport Formats from '../core/Formats';\nimport TranslationValues, {\n RichTranslationValues\n} from '../core/TranslationValues';\nimport MessageKeys from '../core/utils/MessageKeys';\nimport NamespaceKeys from '../core/utils/NamespaceKeys';\nimport NestedKeyOf from '../core/utils/NestedKeyOf';\nimport NestedValueOf from '../core/utils/NestedValueOf';\nimport useIntlContext from './useIntlContext';\nimport useTranslationsImpl from './useTranslationsImpl';\n\n/**\n * Translates messages from the given namespace by using the ICU syntax.\n * See https://formatjs.io/docs/core-concepts/icu-syntax.\n *\n * If no namespace is provided, all available messages are returned.\n * The namespace can also indicate nesting by using a dot\n * (e.g. `namespace.Component`).\n */\nexport default function useTranslations<\n NestedKey extends NamespaceKeys<\n IntlMessages,\n NestedKeyOf<IntlMessages>\n > = never\n>(\n namespace?: NestedKey\n): // Explicitly defining the return type is necessary as TypeScript would get it wrong\n{\n // Default invocation\n <\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey,\n values?: TranslationValues,\n formats?: Partial<Formats>\n ): string;\n\n // `rich`\n rich<\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey,\n values?: RichTranslationValues,\n formats?: Partial<Formats>\n ): string | ReactElement | ReactNodeArray;\n\n // `raw`\n raw<\n TargetKey extends MessageKeys<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >,\n NestedKeyOf<\n NestedValueOf<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >\n >\n >\n >(\n key: TargetKey\n ): any;\n} {\n const context = useIntlContext();\n const messages = context.messages as IntlMessages;\n\n // We have to wrap the actual hook so the type inference for the optional\n // namespace works correctly. See https://stackoverflow.com/a/71529575/343045\n // The prefix (\"!\") is arbitrary.\n return useTranslationsImpl<\n {'!': IntlMessages},\n [NestedKey] extends [never] ? '!' : `!.${NestedKey}`\n >(\n {'!': messages},\n // @ts-expect-error\n namespace ? `!.${namespace}` : '!',\n '!'\n );\n}\n","import {useMemo} from 'react';\nimport AbstractIntlMessages from '../core/AbstractIntlMessages';\nimport createBaseTranslator, {\n getMessagesOrError\n} from '../core/createBaseTranslator';\nimport resolveNamespace from '../core/resolveNamespace';\nimport NestedKeyOf from '../core/utils/NestedKeyOf';\nimport useIntlContext from './useIntlContext';\n\nexport default function useTranslationsImpl<\n Messages extends AbstractIntlMessages,\n NestedKey extends NestedKeyOf<Messages>\n>(allMessages: Messages, namespace: NestedKey, namespacePrefix: string) {\n const {\n defaultTranslationValues,\n formats: globalFormats,\n getMessageFallback,\n locale,\n messageFormatCache,\n onError,\n timeZone\n } = useIntlContext();\n\n // The `namespacePrefix` is part of the type system.\n // See the comment in the hook invocation.\n allMessages = allMessages[namespacePrefix] as Messages;\n namespace = resolveNamespace(namespace, namespacePrefix) as NestedKey;\n\n const messagesOrError = useMemo(\n () => getMessagesOrError({messages: allMessages, namespace, onError}),\n [allMessages, namespace, onError]\n );\n\n const translate = useMemo(\n () =>\n createBaseTranslator({\n messageFormatCache,\n getMessageFallback,\n messagesOrError,\n defaultTranslationValues,\n namespace,\n onError,\n formats: globalFormats,\n locale,\n timeZone\n }),\n [\n messageFormatCache,\n getMessageFallback,\n messagesOrError,\n defaultTranslationValues,\n namespace,\n onError,\n globalFormats,\n locale,\n timeZone\n ]\n );\n\n return translate;\n}\n"],"names":["IntlErrorCode","IntlError","_Error","code","originalMessage","_this","message","call","this","_wrapNativeSuper","Error","setTimeZoneInFormats","formats","timeZone","Object","keys","reduce","acc","key","_extends","defaultGetMessageFallback","props","namespace","filter","part","join","defaultOnError","error","console","resolvePath","messages","undefined","split","forEach","next","getMessagesOrError","_ref","_ref$onError","onError","retrievedMessages","intlError","MISSING_MESSAGE","createBaseTranslator","_ref2","defaultTranslationValues","globalFormats","_ref2$getMessageFallb","getMessageFallback","locale","messageFormatCache","messagesOrError","getFallbackFromErrorAndNotify","translateBaseFn","values","messageFormat","cacheKey","String","has","get","Array","isArray","INVALID_MESSAGE","INSUFFICIENT_PATH","errorMessage","plainMessage","candidate","unescapedMessage","replace","test","getPlainMessage","IntlMessageFormat","formatsWithTimeZone","dateTime","mfDateDefaults","date","defaultDateFormats","mfTimeDefaults","time","defaultTimeFormats","convertFormatsToIntlMessageFormat","set","formattedMessage","format","length","transformedValues","index","value","chunks","result","isValidElement","cloneElement","prepareTranslationValues","FORMATTING_ERROR","translateFn","rich","raw","resolveNamespace","namespacePrefix","slice","MINUTE","SECOND","HOUR","DAY","WEEK","MONTH","QUARTER","YEAR","UNIT_SECONDS","second","seconds","minute","minutes","hour","hours","day","days","week","weeks","month","months","quarter","quarters","year","years","createFormatter","globalNow","now","globalTimeZone","getFormattedValue","formatOrOptions","typeFormats","formatter","options","MISSING_FORMAT","resolveFormatOrOptions","_options","ENVIRONMENT_FALLBACK","Intl","DateTimeFormat","number","NumberFormat","relativeTime","nowOrOptions","dateDate","Date","nowDate","extractNowDate","getTime","unit","absValue","Math","abs","resolveRelativeTimeUnit","round","calculateRelativeTimeValue","RelativeTimeFormat","numeric","list","ListFormat","createIntl","apply","arguments","formatDateTime","formatNumber","formatRelativeTime","IntlContext","createContext","getInitializedConfig","_objectWithoutPropertiesLoose","_excluded","useIntlContext","context","useContext","getNow","hasWarned","children","useState","Map","React","createElement","Provider","_ref$getMessageFallba","rest","translator","originalRich","base","createTranslatorImpl","_useIntlContext","useMemo","warn","updateInterval","_useState","setNow","useEffect","intervalId","setInterval","clearInterval","allMessages","useTranslationsImpl"],"mappings":"uMAAYA,giDAAAA,QAQXA,mBAAA,GARWA,EAAAA,wBAAAA,QAAAA,cAQX,CAAA,IAPC,gBAAA,kBACAA,EAAA,eAAA,iBACAA,EAAA,qBAAA,uBACAA,EAAA,kBAAA,oBACAA,EAAA,gBAAA,kBACAA,EAAA,YAAA,cACAA,EAAA,iBAAA,mBAGmBC,IAAAA,WAAUC,WAI7B,SAAAD,EAAYE,EAAqBC,GAAwB,IAAAC,EACnDC,EAAkBH,EASrB,OARGC,IACFE,GAAW,KAAOF,IAEpBC,EAAAH,EAAAK,KAAAC,KAAMF,IAAQE,MARAL,UAAI,EAAAE,EACJD,qBAAe,EAS7BC,EAAKF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oC,EACAF,EACAG,EACAN,EACAtB,EACAgB,EACAO,EACAG,EACAnC,GAKN,CDiCSyL,CAIL,CAAC,IAVa5B,IACS5I,UAWvBR,OAAiBA,EAAc,IAGnC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "use-intl",
3
- "version": "2.20.1",
3
+ "version": "2.21.0",
4
4
  "sideEffects": false,
5
5
  "author": "Jan Amann <jan@amann.work>",
6
6
  "description": "Minimal, but complete solution for managing internationalization in React apps.",
@@ -72,5 +72,5 @@
72
72
  "engines": {
73
73
  "node": ">=10"
74
74
  },
75
- "gitHead": "5b733547739240f301136bb3957c49e782fbe2b4"
75
+ "gitHead": "0b5e0fe7b16505fa02ea3b472a5b87e91c75a7a1"
76
76
  }
@@ -1,6 +1,7 @@
1
1
  export enum IntlErrorCode {
2
2
  MISSING_MESSAGE = 'MISSING_MESSAGE',
3
3
  MISSING_FORMAT = 'MISSING_FORMAT',
4
+ ENVIRONMENT_FALLBACK = 'ENVIRONMENT_FALLBACK',
4
5
  INSUFFICIENT_PATH = 'INSUFFICIENT_PATH',
5
6
  INVALID_MESSAGE = 'INVALID_MESSAGE',
6
7
  INVALID_KEY = 'INVALID_KEY',
@@ -0,0 +1,6 @@
1
+ type RelativeTimeFormatOptions = {
2
+ now?: number | Date;
3
+ unit?: Intl.RelativeTimeFormatUnit;
4
+ };
5
+
6
+ export default RelativeTimeFormatOptions;
@@ -2,47 +2,64 @@ import DateTimeFormatOptions from './DateTimeFormatOptions';
2
2
  import Formats from './Formats';
3
3
  import IntlError, {IntlErrorCode} from './IntlError';
4
4
  import NumberFormatOptions from './NumberFormatOptions';
5
+ import RelativeTimeFormatOptions from './RelativeTimeFormatOptions';
5
6
  import TimeZone from './TimeZone';
6
7
  import {defaultOnError} from './defaults';
7
8
 
8
- const MINUTE = 60;
9
+ const SECOND = 1;
10
+ const MINUTE = SECOND * 60;
9
11
  const HOUR = MINUTE * 60;
10
12
  const DAY = HOUR * 24;
11
13
  const WEEK = DAY * 7;
12
14
  const MONTH = DAY * (365 / 12); // Approximation
15
+ const QUARTER = MONTH * 3;
13
16
  const YEAR = DAY * 365;
14
17
 
15
- function getRelativeTimeFormatConfig(seconds: number) {
18
+ const UNIT_SECONDS: Record<Intl.RelativeTimeFormatUnit, number> = {
19
+ second: SECOND,
20
+ seconds: SECOND,
21
+ minute: MINUTE,
22
+ minutes: MINUTE,
23
+ hour: HOUR,
24
+ hours: HOUR,
25
+ day: DAY,
26
+ days: DAY,
27
+ week: WEEK,
28
+ weeks: WEEK,
29
+ month: MONTH,
30
+ months: MONTH,
31
+ quarter: QUARTER,
32
+ quarters: QUARTER,
33
+ year: YEAR,
34
+ years: YEAR
35
+ } as const;
36
+
37
+ function resolveRelativeTimeUnit(seconds: number) {
16
38
  const absValue = Math.abs(seconds);
17
- let value, unit: Intl.RelativeTimeFormatUnit;
18
-
19
- // We have to round the resulting values, as `Intl.RelativeTimeFormat`
20
- // will include fractions like '2.1 hours ago'.
21
39
 
22
40
  if (absValue < MINUTE) {
23
- unit = 'second';
24
- value = Math.round(seconds);
41
+ return 'second';
25
42
  } else if (absValue < HOUR) {
26
- unit = 'minute';
27
- value = Math.round(seconds / MINUTE);
43
+ return 'minute';
28
44
  } else if (absValue < DAY) {
29
- unit = 'hour';
30
- value = Math.round(seconds / HOUR);
45
+ return 'hour';
31
46
  } else if (absValue < WEEK) {
32
- unit = 'day';
33
- value = Math.round(seconds / DAY);
47
+ return 'day';
34
48
  } else if (absValue < MONTH) {
35
- unit = 'week';
36
- value = Math.round(seconds / WEEK);
49
+ return 'week';
37
50
  } else if (absValue < YEAR) {
38
- unit = 'month';
39
- value = Math.round(seconds / MONTH);
40
- } else {
41
- unit = 'year';
42
- value = Math.round(seconds / YEAR);
51
+ return 'month';
43
52
  }
53
+ return 'year';
54
+ }
44
55
 
45
- return {value, unit};
56
+ function calculateRelativeTimeValue(
57
+ seconds: number,
58
+ unit: Intl.RelativeTimeFormatUnit
59
+ ) {
60
+ // We have to round the resulting values, as `Intl.RelativeTimeFormat`
61
+ // will include fractions like '2.1 hours ago'.
62
+ return Math.round(seconds / UNIT_SECONDS[unit]);
46
63
  }
47
64
 
48
65
  type Props = {
@@ -58,7 +75,7 @@ export default function createFormatter({
58
75
  locale,
59
76
  now: globalNow,
60
77
  onError = defaultOnError,
61
- timeZone
78
+ timeZone: globalTimeZone
62
79
  }: Props) {
63
80
  function resolveFormatOrOptions<Options>(
64
81
  typeFormats: Record<string, Options> | undefined,
@@ -121,8 +138,19 @@ export default function createFormatter({
121
138
  formatOrOptions,
122
139
  formats?.dateTime,
123
140
  (options) => {
124
- if (timeZone && !options?.timeZone) {
125
- options = {...options, timeZone};
141
+ if (!options?.timeZone) {
142
+ if (globalTimeZone) {
143
+ options = {...options, timeZone: globalTimeZone};
144
+ } else {
145
+ onError(
146
+ new IntlError(
147
+ IntlErrorCode.ENVIRONMENT_FALLBACK,
148
+ process.env.NODE_ENV !== 'production'
149
+ ? `The \`timeZone\` parameter wasn't provided and there is no global default configured. Consider adding a global default to avoid markup mismatches caused by environment differences. Learn more: https://next-intl-docs.vercel.app/docs/configuration#time-zone`
150
+ : undefined
151
+ )
152
+ );
153
+ }
126
154
  }
127
155
 
128
156
  return new Intl.DateTimeFormat(locale, options).format(value);
@@ -142,30 +170,53 @@ export default function createFormatter({
142
170
  );
143
171
  }
144
172
 
173
+ function getGlobalNow() {
174
+ if (globalNow) {
175
+ return globalNow;
176
+ } else {
177
+ onError(
178
+ new IntlError(
179
+ IntlErrorCode.ENVIRONMENT_FALLBACK,
180
+ process.env.NODE_ENV !== 'production'
181
+ ? `The \`now\` parameter wasn't provided and there is no global default configured. Consider adding a global default to avoid markup mismatches caused by environment differences. Learn more: https://next-intl-docs.vercel.app/docs/configuration#now`
182
+ : undefined
183
+ )
184
+ );
185
+ return new Date();
186
+ }
187
+ }
188
+
189
+ function extractNowDate(
190
+ nowOrOptions?: RelativeTimeFormatOptions['now'] | RelativeTimeFormatOptions
191
+ ) {
192
+ if (nowOrOptions instanceof Date || typeof nowOrOptions === 'number') {
193
+ return new Date(nowOrOptions);
194
+ }
195
+ if (nowOrOptions?.now !== undefined) {
196
+ return new Date(nowOrOptions.now);
197
+ }
198
+ return getGlobalNow();
199
+ }
200
+
145
201
  function relativeTime(
146
202
  /** The date time that needs to be formatted. */
147
203
  date: number | Date,
148
204
  /** The reference point in time to which `date` will be formatted in relation to. */
149
- now?: number | Date
205
+ nowOrOptions?: RelativeTimeFormatOptions['now'] | RelativeTimeFormatOptions
150
206
  ) {
151
207
  try {
152
- if (!now) {
153
- if (globalNow) {
154
- now = globalNow;
155
- } else {
156
- throw new Error(
157
- process.env.NODE_ENV !== 'production'
158
- ? `The \`now\` parameter wasn't provided and there was no global fallback configured on the provider.`
159
- : undefined
160
- );
161
- }
162
- }
208
+ const dateDate = new Date(date);
209
+ const nowDate = extractNowDate(nowOrOptions);
210
+ const seconds = (dateDate.getTime() - nowDate.getTime()) / 1000;
163
211
 
164
- const dateDate = date instanceof Date ? date : new Date(date);
165
- const nowDate = now instanceof Date ? now : new Date(now);
212
+ const unit =
213
+ typeof nowOrOptions === 'number' ||
214
+ nowOrOptions instanceof Date ||
215
+ nowOrOptions?.unit === undefined
216
+ ? resolveRelativeTimeUnit(seconds)
217
+ : nowOrOptions.unit;
166
218
 
167
- const seconds = (dateDate.getTime() - nowDate.getTime()) / 1000;
168
- const {unit, value} = getRelativeTimeFormatConfig(seconds);
219
+ const value = calculateRelativeTimeValue(seconds, unit);
169
220
 
170
221
  return new Intl.RelativeTimeFormat(locale, {
171
222
  numeric: 'auto'