New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

use-intl

Package Overview
Dependencies
Maintainers
1
Versions
276
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-intl - npm Package Compare versions

Comparing version 2.7.1 to 2.7.2-alpha.1

dist/_virtual/use-intl.esm.js

2

dist/IntlProvider.d.ts
import { ReactNode } from 'react';
import AbstractIntlMessages from './AbstractIntlMessages';
import Formats from './Formats';
import IntlError from './IntlError';
import { RichTranslationValues } from './TranslationValues';
import { IntlError } from '.';
declare type Props = {

@@ -7,0 +7,0 @@ /** All messages that will be available in your components. */

@@ -1,712 +0,8 @@

import React, { createContext, useEffect, useContext, useRef, useMemo, isValidElement, cloneElement, useState } from 'react';
import { IntlMessageFormat } from 'intl-messageformat';
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
_setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var IntlContext = /*#__PURE__*/createContext(undefined);
var IntlErrorCode;
(function (IntlErrorCode) {
IntlErrorCode["MISSING_MESSAGE"] = "MISSING_MESSAGE";
IntlErrorCode["MISSING_FORMAT"] = "MISSING_FORMAT";
IntlErrorCode["INSUFFICIENT_PATH"] = "INSUFFICIENT_PATH";
IntlErrorCode["INVALID_MESSAGE"] = "INVALID_MESSAGE";
IntlErrorCode["INVALID_KEY"] = "INVALID_KEY";
IntlErrorCode["FORMATTING_ERROR"] = "FORMATTING_ERROR";
})(IntlErrorCode || (IntlErrorCode = {}));
var IntlError = /*#__PURE__*/function (_Error) {
_inheritsLoose(IntlError, _Error);
function IntlError(code, originalMessage) {
var _this;
var message = code;
if (originalMessage) {
message += ': ' + originalMessage;
}
_this = _Error.call(this, message) || this;
_this.code = void 0;
_this.originalMessage = void 0;
_this.code = code;
if (originalMessage) {
_this.originalMessage = originalMessage;
}
return _this;
}
return IntlError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
function validateMessagesSegment(messages, invalidKeyLabels, parentPath) {
Object.entries(messages).forEach(function (_ref) {
var key = _ref[0],
messageOrMessages = _ref[1];
if (key.includes('.')) {
var keyLabel = key;
if (parentPath) keyLabel += " (at " + parentPath + ")";
invalidKeyLabels.push(keyLabel);
}
if (messageOrMessages != null && typeof messageOrMessages === 'object') {
validateMessagesSegment(messageOrMessages, invalidKeyLabels, [parentPath, key].filter(function (part) {
return part != null;
}).join('.'));
}
});
}
function validateMessages(messages, onError) {
var invalidKeyLabels = [];
validateMessagesSegment(messages, invalidKeyLabels);
if (invalidKeyLabels.length > 0) {
onError(new IntlError(IntlErrorCode.INVALID_KEY, "Namespace keys can not contain the character \".\" as this is used to express nesting. Please remove it or replace it with another character.\n\nInvalid " + (invalidKeyLabels.length === 1 ? 'key' : 'keys') + ": " + invalidKeyLabels.join(', ')));
}
}
var _excluded = ["children", "onError", "getMessageFallback", "messages"];
function defaultGetMessageFallback(_ref) {
var key = _ref.key,
namespace = _ref.namespace;
return [namespace, key].filter(function (part) {
return part != null;
}).join('.');
}
function defaultOnError(error) {
console.error(error);
}
function IntlProvider(_ref2) {
var children = _ref2.children,
_ref2$onError = _ref2.onError,
onError = _ref2$onError === void 0 ? defaultOnError : _ref2$onError,
_ref2$getMessageFallb = _ref2.getMessageFallback,
getMessageFallback = _ref2$getMessageFallb === void 0 ? defaultGetMessageFallback : _ref2$getMessageFallb,
messages = _ref2.messages,
contextValues = _objectWithoutPropertiesLoose(_ref2, _excluded);
if (process.env.NODE_ENV !== "production") {
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(function () {
if (messages) {
validateMessages(messages, onError);
}
}, [messages, onError]);
}
return React.createElement(IntlContext.Provider, {
value: _extends({}, contextValues, {
messages: messages,
onError: onError,
getMessageFallback: getMessageFallback
})
}, children);
}
function useIntlContext() {
var context = useContext(IntlContext);
if (!context) {
throw new Error(process.env.NODE_ENV !== "production" ? 'No intl context found. Have you configured the provider?' : undefined);
}
return context;
}
function setTimeZoneInFormats(formats, timeZone) {
if (!formats) return formats; // The only way to set a time zone with `intl-messageformat` is to merge it into the formats
// https://github.com/formatjs/formatjs/blob/8256c5271505cf2606e48e3c97ecdd16ede4f1b5/packages/intl/src/message.ts#L15
return Object.keys(formats).reduce(function (acc, key) {
acc[key] = _extends({
timeZone: timeZone
}, formats[key]);
return acc;
}, {});
}
/**
* `intl-messageformat` uses separate keys for `date` and `time`, but there's
* only one native API: `Intl.DateTimeFormat`. Additionally you might want to
* include both a time and a date in a value, therefore the separation doesn't
* seem so useful. We offer a single `dateTime` namespace instead, but we have
* to convert the format before `intl-messageformat` can be used.
*/
function convertFormatsToIntlMessageFormat(formats, timeZone) {
var formatsWithTimeZone = timeZone ? _extends({}, formats, {
dateTime: setTimeZoneInFormats(formats.dateTime, timeZone)
}) : formats;
return _extends({}, formatsWithTimeZone, {
date: formatsWithTimeZone == null ? void 0 : formatsWithTimeZone.dateTime,
time: formatsWithTimeZone == null ? void 0 : formatsWithTimeZone.dateTime
});
}
function resolvePath(messages, idPath, namespace) {
if (!messages) {
throw new Error(process.env.NODE_ENV !== "production" ? "No messages available at `" + namespace + "`." : undefined);
}
var message = messages;
idPath.split('.').forEach(function (part) {
var next = message[part];
if (part == null || next == null) {
throw new Error(process.env.NODE_ENV !== "production" ? "Could not resolve `" + idPath + "` in " + (namespace ? "`" + namespace + "`" : 'messages') + "." : undefined);
}
message = next;
});
return message;
}
function prepareTranslationValues(values) {
if (Object.keys(values).length === 0) return undefined; // Workaround for https://github.com/formatjs/formatjs/issues/1467
var transformedValues = {};
Object.keys(values).forEach(function (key) {
var index = 0;
var value = values[key];
var transformed;
if (typeof value === 'function') {
transformed = function transformed(children) {
var result = value(children);
return isValidElement(result) ? cloneElement(result, {
key: key + index++
}) : result;
};
} else {
transformed = value;
}
transformedValues[key] = transformed;
});
return transformedValues;
}
function useTranslationsImpl(allMessages, namespace, namespacePrefix) {
var _useIntlContext = useIntlContext(),
defaultTranslationValues = _useIntlContext.defaultTranslationValues,
globalFormats = _useIntlContext.formats,
getMessageFallback = _useIntlContext.getMessageFallback,
locale = _useIntlContext.locale,
onError = _useIntlContext.onError,
timeZone = _useIntlContext.timeZone; // The `namespacePrefix` is part of the type system.
// See the comment in the hook invocation.
allMessages = allMessages[namespacePrefix];
namespace = namespace === namespacePrefix ? undefined : namespace.slice((namespacePrefix + '.').length);
var cachedFormatsByLocaleRef = useRef({});
var messagesOrError = useMemo(function () {
try {
if (!allMessages) {
throw new Error(process.env.NODE_ENV !== "production" ? "No messages were configured on the provider." : undefined);
}
var retrievedMessages = namespace ? resolvePath(allMessages, namespace) : allMessages;
if (!retrievedMessages) {
throw new Error(process.env.NODE_ENV !== "production" ? "No messages for namespace `" + namespace + "` found." : undefined);
}
return retrievedMessages;
} catch (error) {
var intlError = new IntlError(IntlErrorCode.MISSING_MESSAGE, error.message);
onError(intlError);
return intlError;
}
}, [allMessages, namespace, onError]);
var translate = useMemo(function () {
function getFallbackFromErrorAndNotify(key, code, message) {
var error = new IntlError(code, message);
onError(error);
return getMessageFallback({
error: error,
key: key,
namespace: namespace
});
}
function translateBaseFn(
/** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
key,
/** Key value pairs for values to interpolate into the message. */
values,
/** Provide custom formats for numbers, dates and times. */
formats) {
var _cachedFormatsByLocal;
var cachedFormatsByLocale = cachedFormatsByLocaleRef.current;
if (messagesOrError instanceof IntlError) {
// We have already warned about this during render
return getMessageFallback({
error: messagesOrError,
key: key,
namespace: namespace
});
}
var messages = messagesOrError;
var cacheKey = [namespace, key].filter(function (part) {
return part != null;
}).join('.');
var messageFormat;
if ((_cachedFormatsByLocal = cachedFormatsByLocale[locale]) != null && _cachedFormatsByLocal[cacheKey]) {
messageFormat = cachedFormatsByLocale[locale][cacheKey];
} else {
var message;
try {
message = resolvePath(messages, key, namespace);
} catch (error) {
return getFallbackFromErrorAndNotify(key, IntlErrorCode.MISSING_MESSAGE, error.message);
}
if (typeof message === 'object') {
return getFallbackFromErrorAndNotify(key, IntlErrorCode.INSUFFICIENT_PATH, process.env.NODE_ENV !== "production" ? "Insufficient path specified for `" + key + "` in `" + (namespace ? "`" + namespace + "`" : 'messages') + "`." : undefined);
}
try {
messageFormat = new IntlMessageFormat(message, locale, convertFormatsToIntlMessageFormat(_extends({}, globalFormats, formats), timeZone));
} catch (error) {
return getFallbackFromErrorAndNotify(key, IntlErrorCode.INVALID_MESSAGE, error.message);
}
if (!cachedFormatsByLocale[locale]) {
cachedFormatsByLocale[locale] = {};
}
cachedFormatsByLocale[locale][cacheKey] = messageFormat;
}
try {
var formattedMessage = messageFormat.format( // @ts-ignore `intl-messageformat` expects a different format
// for rich text elements since a recent minor update. This
// needs to be evaluated in detail, possibly also in regards
// to be able to format to parts.
prepareTranslationValues(_extends({}, defaultTranslationValues, values)));
if (formattedMessage == null) {
throw new Error(process.env.NODE_ENV !== "production" ? "Unable to format `" + key + "` in " + (namespace ? "namespace `" + namespace + "`" : 'messages') : undefined);
} // Limit the function signature to return strings or React elements
return isValidElement(formattedMessage) || // Arrays of React elements
Array.isArray(formattedMessage) || typeof formattedMessage === 'string' ? formattedMessage : String(formattedMessage);
} catch (error) {
return getFallbackFromErrorAndNotify(key, IntlErrorCode.FORMATTING_ERROR, error.message);
}
}
function translateFn(
/** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
key,
/** Key value pairs for values to interpolate into the message. */
values,
/** Provide custom formats for numbers, dates and times. */
formats) {
var message = translateBaseFn(key, values, formats);
if (typeof message !== 'string') {
return getFallbackFromErrorAndNotify(key, IntlErrorCode.INVALID_MESSAGE, process.env.NODE_ENV !== "production" ? "The message `" + key + "` in " + (namespace ? "namespace `" + namespace + "`" : 'messages') + " didn't resolve to a string. If you want to format rich text, use `t.rich` instead." : undefined);
}
return message;
}
translateFn.rich = translateBaseFn;
translateFn.raw = function (
/** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
key) {
if (messagesOrError instanceof IntlError) {
// We have already warned about this during render
return getMessageFallback({
error: messagesOrError,
key: key,
namespace: namespace
});
}
var messages = messagesOrError;
try {
return resolvePath(messages, key, namespace);
} catch (error) {
return getFallbackFromErrorAndNotify(key, IntlErrorCode.MISSING_MESSAGE, error.message);
}
};
return translateFn;
}, [onError, getMessageFallback, namespace, messagesOrError, locale, globalFormats, timeZone, defaultTranslationValues]);
return translate;
}
/**
* Translates messages from the given namespace by using the ICU syntax.
* See https://formatjs.io/docs/core-concepts/icu-syntax.
*
* If no namespace is provided, all available messages are returned.
* The namespace can also indicate nesting by using a dot
* (e.g. `namespace.Component`).
*/
function useTranslations(namespace) {
var context = useIntlContext();
var messages = context.messages;
if (!messages) {
var intlError = new IntlError(IntlErrorCode.MISSING_MESSAGE, process.env.NODE_ENV !== "production" ? "No messages were configured on the provider." : undefined);
context.onError(intlError);
throw intlError;
} // We have to wrap the actual hook so the type inference for the optional
// namespace works correctly. See https://stackoverflow.com/a/71529575/343045
// The prefix ("!"") is arbitrary, but we have to use some.
return useTranslationsImpl({
'!': messages
}, // @ts-ignore
namespace ? "!." + namespace : '!', '!');
}
var MINUTE = 60;
var HOUR = MINUTE * 60;
var DAY = HOUR * 24;
var WEEK = DAY * 7;
var MONTH = DAY * (365 / 12); // Approximation
var YEAR = DAY * 365;
function getRelativeTimeFormatConfig(seconds) {
var absValue = Math.abs(seconds);
var value, unit; // We have to round the resulting values, as `Intl.RelativeTimeFormat`
// will include fractions like '2.1 hours ago'.
if (absValue < MINUTE) {
unit = 'second';
value = Math.round(seconds);
} else if (absValue < HOUR) {
unit = 'minute';
value = Math.round(seconds / MINUTE);
} else if (absValue < DAY) {
unit = 'hour';
value = Math.round(seconds / HOUR);
} else if (absValue < WEEK) {
unit = 'day';
value = Math.round(seconds / DAY);
} else if (absValue < MONTH) {
unit = 'week';
value = Math.round(seconds / WEEK);
} else if (absValue < YEAR) {
unit = 'month';
value = Math.round(seconds / MONTH);
} else {
unit = 'year';
value = Math.round(seconds / YEAR);
}
return {
value: value,
unit: unit
};
}
function useIntl() {
var _useIntlContext = useIntlContext(),
formats = _useIntlContext.formats,
locale = _useIntlContext.locale,
globalNow = _useIntlContext.now,
onError = _useIntlContext.onError,
timeZone = _useIntlContext.timeZone;
function resolveFormatOrOptions(typeFormats, formatOrOptions) {
var options;
if (typeof formatOrOptions === 'string') {
var formatName = formatOrOptions;
options = typeFormats == null ? void 0 : typeFormats[formatName];
if (!options) {
var error = new IntlError(IntlErrorCode.MISSING_FORMAT, process.env.NODE_ENV !== "production" ? "Format `" + formatName + "` is not available. You can configure it on the provider or provide custom options." : undefined);
onError(error);
throw error;
}
} else {
options = formatOrOptions;
}
return options;
}
function getFormattedValue(value, formatOrOptions, typeFormats, formatter) {
var options;
try {
options = resolveFormatOrOptions(typeFormats, formatOrOptions);
} catch (error) {
return String(value);
}
try {
return formatter(options);
} catch (error) {
onError(new IntlError(IntlErrorCode.FORMATTING_ERROR, error.message));
return String(value);
}
}
function formatDateTime(
/** If a number is supplied, this is interpreted as a UTC timestamp. */
value,
/** If a time zone is supplied, the `value` is converted to that time zone.
* Otherwise the user time zone will be used. */
formatOrOptions) {
return getFormattedValue(value, formatOrOptions, formats == null ? void 0 : formats.dateTime, function (options) {
var _options;
if (timeZone && !((_options = options) != null && _options.timeZone)) {
options = _extends({}, options, {
timeZone: timeZone
});
}
return new Intl.DateTimeFormat(locale, options).format(value);
});
}
function formatNumber(value, formatOrOptions) {
return getFormattedValue(value, formatOrOptions, formats == null ? void 0 : formats.number, function (options) {
return new Intl.NumberFormat(locale, options).format(value);
});
}
function formatRelativeTime(
/** The date time that needs to be formatted. */
date,
/** The reference point in time to which `date` will be formatted in relation to. */
now) {
try {
if (!now) {
if (globalNow) {
now = globalNow;
} else {
throw new Error(process.env.NODE_ENV !== "production" ? "The `now` parameter wasn't provided to `formatRelativeTime` and there was no global fallback configured on the provider." : undefined);
}
}
var dateDate = date instanceof Date ? date : new Date(date);
var nowDate = now instanceof Date ? now : new Date(now);
var seconds = (dateDate.getTime() - nowDate.getTime()) / 1000;
var _getRelativeTimeForma = getRelativeTimeFormatConfig(seconds),
unit = _getRelativeTimeForma.unit,
value = _getRelativeTimeForma.value;
return new Intl.RelativeTimeFormat(locale, {
numeric: 'auto'
}).format(value, unit);
} catch (error) {
onError(new IntlError(IntlErrorCode.FORMATTING_ERROR, error.message));
return String(date);
}
}
return {
formatDateTime: formatDateTime,
formatNumber: formatNumber,
formatRelativeTime: formatRelativeTime
};
}
function useLocale() {
return useIntlContext().locale;
}
function getNow() {
return new Date();
}
/**
* Reading the current date via `new Date()` in components should be avoided, as
* it causes components to be impure and can lead to flaky tests. Instead, this
* hook can be used.
*
* By default, it returns the time when the component mounts. If `updateInterval`
* is specified, the value will be updated based on the interval.
*
* You can however also return a static value from this hook, if you
* configure the `now` parameter on the context provider. Note however,
* that if `updateInterval` is configured in this case, the component
* will initialize with the global value, but will afterwards update
* continuously based on the interval.
*
* For unit tests, this can be mocked to a constant value. For end-to-end
* testing, an environment parameter can be passed to the `now` parameter
* of the provider to mock this to a static value.
*/
function useNow(options) {
var updateInterval = options == null ? void 0 : options.updateInterval;
var _useIntlContext = useIntlContext(),
globalNow = _useIntlContext.now;
var _useState = useState(globalNow || getNow()),
now = _useState[0],
setNow = _useState[1];
useEffect(function () {
if (!updateInterval) return;
var intervalId = setInterval(function () {
setNow(getNow());
}, updateInterval);
return function () {
clearInterval(intervalId);
};
}, [globalNow, updateInterval]);
return now;
}
function useTimeZone() {
return useIntlContext().timeZone;
}
export { IntlError, IntlErrorCode, IntlProvider, useIntl, useLocale, useNow, useTimeZone, useTranslations };
export { default as IntlProvider } from './use-intl.esm3.js';
export { default as useTranslations } from './use-intl.esm4.js';
export { default as useIntl } from './use-intl.esm2.js';
export { default as useLocale } from './use-intl.esm7.js';
export { default as useNow } from './use-intl.esm5.js';
export { default as useTimeZone } from './use-intl.esm8.js';
export { default as IntlError, IntlErrorCode } from './use-intl.esm6.js';
//# sourceMappingURL=use-intl.esm.js.map
{
"name": "use-intl",
"version": "2.7.1",
"version": "2.7.2-alpha.1",
"sideEffects": false,

@@ -62,3 +62,3 @@ "author": "Jan Amann <jan@amann.me>",

},
"gitHead": "6c4aa2b59a2345811cfbb5603f1a368fe73352ed"
"gitHead": "25a01ee749abb7106df1699be1ae71d0493a45e4"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc