Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
The i18n-js npm package is a lightweight internationalization library for JavaScript. It allows developers to easily manage translations and localization in their applications. The package supports features like translation lookup, interpolation, pluralization, and more.
Translation Lookup
This feature allows you to look up translations based on the current locale. You can define translations for different languages and switch between them easily.
const I18n = require('i18n-js');
I18n.translations = {
en: { greeting: 'Hello' },
fr: { greeting: 'Bonjour' }
};
I18n.locale = 'en';
console.log(I18n.t('greeting')); // Output: 'Hello'
I18n.locale = 'fr';
console.log(I18n.t('greeting')); // Output: 'Bonjour'
Interpolation
Interpolation allows you to insert dynamic values into your translations. This is useful for personalizing messages or including variable data in your translations.
const I18n = require('i18n-js');
I18n.translations = {
en: { greeting: 'Hello, %{name}' }
};
I18n.locale = 'en';
console.log(I18n.t('greeting', { name: 'John' })); // Output: 'Hello, John'
Pluralization
Pluralization allows you to handle different translations based on the count of items. This is useful for correctly displaying singular and plural forms of words.
const I18n = require('i18n-js');
I18n.translations = {
en: { messages: { one: 'You have 1 message', other: 'You have %{count} messages' } }
};
I18n.locale = 'en';
console.log(I18n.t('messages', { count: 1 })); // Output: 'You have 1 message'
console.log(I18n.t('messages', { count: 5 })); // Output: 'You have 5 messages'
react-i18next is a powerful internationalization framework for React applications. It is built on top of i18next and provides seamless integration with React components. Compared to i18n-js, react-i18next offers more advanced features and better support for React-specific use cases.
Polyglot is a simple internationalization library for JavaScript. It provides basic translation and interpolation features. While it is less feature-rich compared to i18n-js, it is lightweight and easy to use for smaller projects.
i18next is a comprehensive internationalization framework for JavaScript. It supports a wide range of features including translation, interpolation, pluralization, and more. i18next is more feature-rich and flexible compared to i18n-js, making it suitable for larger and more complex projects.
It's a small library to provide the Rails I18n translations on the JavaScript.
Features:
The master
branch (including this README) is for latest 3.0.0
instead of 2.x
.
Add the gem to your Gemfile.
gem "i18n-js"
If you're using the asset pipeline,
then you must add the following line to your app/assets/javascripts/application.js
.
//
// This is optional (in case you have `I18n is not defined` error)
// If you want to put this line, you must put it BEFORE `i18n/translations`
//= require i18n
// Some people even need to add the extension to make it work, see https://github.com/fnando/i18n-js/issues/283
//= require i18n.js
//
// This is a must
//= require i18n/translations
First, put this in your application.html
(layout file).
Then get the JS files following the instructions below.
<%# This is just an example, you can put `i18n.js` and `translations.js` anywhere you like %>
<%# Unlike the Asset Pipeline example, you need to require both **in order** %>
<%= javascript_include_tag "i18n" %>
<%= javascript_include_tag "translations" %>
There are two ways to get translations.js
.
translations.js
file can be automatically generated by the I18n::JS::Middleware
.
Just add config.middleware.use I18n::JS::Middleware
to your config/application.rb
file.config/environments/development.rb
file
and run rake i18n:js:export
before deploying.
This will export all translation files, including the custom scopes
you may have defined on config/i18n-js.yml
.
If I18n.available_locales
is set (e.g. in your Rails config/application.rb
file)
then only the specified locales will be exported.
Current version of i18n.js
will also be exported to avoid version mismatching by downloading.Exported translation files generated by I18n::JS::Middleware
or rake i18n:js:export
can be customized with config file config/i18n-js.yml
(use rails generate i18n:js:config
to create it).
You can even get more files generated to different folders and with different translations to best suit your needs.
The config file also affects developers using Asset Pipeline to require translations.
Except the option file
, since all translations are required by adding //= require i18n/translations
.
Examples:
translations:
- file: 'public/javascripts/path-to-your-messages-file.js'
only: '*.date.formats'
- file: 'public/javascripts/path-to-your-second-file.js'
only: ['*.activerecord', '*.admin.*.title']
If only
is omitted all the translations will be saved. Also, make sure you add that initial *
; it specifies that all languages will be exported. If you want to export only one language, you can do something like this:
translations:
- file: 'public/javascripts/en.js'
only: 'en.*'
- file: 'public/javascripts/pt-BR.js'
only: 'pt-BR.*'
Optionally, you can auto generate a translation file per available locale if you specify the %{locale}
placeholder.
translations:
- file: "public/javascripts/i18n/%{locale}.js"
only: '*'
- file: "public/javascripts/frontend/i18n/%{locale}.js"
only: ['*.frontend', '*.users.*']
You can also include ERB in your config file.
translations:
<% Widgets.each do |widget| %>
- file: <%= "'#{widget.file}'" %>
only: <%= "'#{widget.only}'" %>
<% end %>
You are able to exclude certain phrases or whole groups of phrases by
specifying the YAML key(s) in the except
configuration option. The outputted
JS translations file (exported or generated by the middleware) will omit any
keys listed in except
configuration param:
translations:
- except: ['*.active_admin', '*.ransack', '*.activerecord.errors']
I18n::JS.config_file_path
Expected Type: String
Default: config/i18n-js.yml
Behaviour: Try to read the config file from that location
I18n::JS.export_i18n_js_dir_path
Expected Type: String
Default: public/javascripts
Behaviour:
String
: considered as a relative path for a folder to Rails.root
and export i18n.js
to that folder for rake i18n:js:export
String
(nil
, false
, :none
, etc): Disable i18n.js
exportingI18n::JS.sort_translation_keys
Expected Type: Boolean
Default: true
Behaviour:
You may also set export_i18n_js
and sort_translation_keys
in your config file, e.g.:
export_i18n_js: false
# OR
export_i18n_js: "my/path"
sort_translation_keys: false
translations:
- ...
To find more examples on how to use the configuration file please refer to the tests.
If you specify the fallbacks
option, you will be able to fill missing translations with those inside fallback locale(s).
Default value is true
.
Examples:
fallbacks: true
translations:
- file: "public/javascripts/i18n/%{locale}.js"
only: '*'
This will enable merging fallbacks into each file. (set to false
to disable).
If you use I18n
with fallbacks, the fallbacks defined there will be used.
Otherwise I18n.default_locale
will be used.
fallbacks: :de
translations:
- file: "public/javascripts/i18n/%{locale}.js"
only: '*'
Here, the specified locale :de
will be used as fallback for all locales.
fallbacks:
fr: ["de", "en"]
de: "en"
translations:
- file: "public/javascripts/i18n/%{locale}.js"
only: '*'
Fallbacks defined will be used, if not defined (e.g. :pl
) I18n.fallbacks
or I18n.default_locale
will be used.
fallbacks: :default_locale
translations:
- file: "public/javascripts/i18n/%{locale}.js"
only: '*'
Setting the option to :default_locale
will enforce the fallback to use the I18n.default_locale
, ignoring I18n.fallbacks
.
Examples:
fallbacks: false
translations:
- file: "public/javascripts/i18n/%{locale}.js"
only: '*'
You must disable this feature by setting the option to false
.
To find more examples on how to use the configuration file please refer to the tests.
Setting the namespace
option will change the namespace of the output Javascript file to something other than I18n
.
This can be useful in no-conflict scenarios. Example:
translations:
- file: "public/javascripts/i18n/translations.js"
namespace: "MyNamespace"
will create:
MyNamespace.translations || (MyNamespace.translations = {});
MyNamespace.translations["en"] = { ... }
Set the pretty_print
option if you would like whitespace and indentation in your output file (default: false)
translations:
- file: "public/javascripts/i18n/translations.js"
pretty_print: true
By default, the output file Javascript will call the I18n.extend
method to ensure that newly loaded locale
files are deep-merged with any locale data already in memory. To disable this either globally or per-file,
set the js_extend
option to false
js_extend: false # this will disable Javascript I18n.extend globally
translations:
- file: "public/javascripts/i18n/translations.js"
js_extend: false # this will disable Javascript I18n.extend for this file
Just add the i18n.js
file to your page. You'll have to build the translations object
by hand or using your favorite programming language. More info below.
Add the following line to your package.json dependencies
where version is the version you want
"i18n-js": "{version_constraint}"
// Or if you want unreleased version
// npm install requires it to be the gzipped tarball, see [npm install](https://www.npmjs.org/doc/cli/npm-install.html)
"i18n-js": "https://github.com/fnando/i18n-js/archive/{tag_name_or_branch_name_or_commit_sha}.tar.gz"
Run npm install then use via
var i18n = require("i18n-js");
You don't need to set up a thing. The default settings will work just okay. But if you want to split translations into several files or specify specific contexts, you can follow the rest of this setting up section.
Set your locale is easy as
I18n.defaultLocale = "pt-BR";
I18n.locale = "pt-BR";
I18n.currentLocale();
// pt-BR
NOTE: You can now apply your configuration before I18n is loaded like this:
I18n = {} // You must define this object in top namespace, which should be `window`
I18n.defaultLocale = "pt-BR";
I18n.locale = "pt-BR";
// Load I18n from `i18n.js`, `application.js` or whatever
I18n.currentLocale();
// pt-BR
In practice, you'll have something like the following in your application.html.erb
:
<script type="text/javascript">
I18n.defaultLocale = "<%= I18n.default_locale %>";
I18n.locale = "<%= I18n.locale %>";
</script>
You can use translate your messages:
I18n.t("some.scoped.translation");
// or translate with explicit setting of locale
I18n.t("some.scoped.translation", {locale: "fr"});
You can also interpolate values:
I18n.t("hello", {name: "John Doe"});
You can set default values for missing scopes:
// simple translation
I18n.t("some.missing.scope", {defaultValue: "A default message"});
// with interpolation
I18n.t("noun", {defaultValue: "I'm a {{noun}}", noun: "Mac"});
You can also provide a list of default fallbacks for missing scopes:
// As a scope
I18n.t("some.missing.scope", {defaults: [{scope: "some.existing.scope"}]});
// As a simple translation
I18n.t("some.missing.scope", {defaults: [{message: "Some message"}]});
Default values must be provided as an array of hashs where the key is the
type of translation desired, a scope
or a message
. The translation returned
will be either the first scope recognized, or the first message defined.
The translation will fallback to the defaultValue
translation if no scope
in defaults
matches and if no default of type message
is found.
Translation fallback can be enabled by enabling the I18n.fallbacks
option:
<script type="text/javascript">
I18n.fallbacks = true;
</script>
By default missing translations will first be looked for in less
specific versions of the requested locale and if that fails by taking
them from your I18n.defaultLocale
.
// if I18n.defaultLocale = "en" and translation doesn't exist
// for I18n.locale = "de-DE" this key will be taken from "de" locale scope
// or, if that also doesn't exist, from "en" locale scope
I18n.t("some.missing.scope");
Custom fallback rules can also be specified for a particular language. There are three different ways of doing it so:
I18n.locales.no = ["nb", "en"];
I18n.locales.no = "nb";
I18n.locales.no = function(locale){ return ["nb"]; };
By default a missing translation will be displayed as
[missing "name of scope" translation]
While you are developing or if you do not want to provide a translation in the default language you can set
I18n.missingBehaviour='guess';
this will take the last section of your scope and guess the intended value. Camel case becomes lower cased text and underscores are replaced with space
questionnaire.whatIsYourFavorite_ChristmasPresent
becomes "what is your favorite Christmas present"
In order to still detect untranslated strings, you can i18n.missingTranslationPrefix to something like:
I18n.missingTranslationPrefix = 'EE: ';
And result will be:
"EE: what is your favorite Christmas present"
This will help you doing automated tests against your localisation assets.
Some people prefer returning null
for missing translation:
I18n.missingTranslation = function () { return undefined; };
Pluralization is possible as well and by default provides English rules:
I18n.t("inbox.counting", {count: 10}); // You have 10 messages
The sample above expects the following translation:
en:
inbox:
counting:
one: You have 1 new message
other: You have {{count}} new messages
zero: You have no messages
NOTE: Rails I18n recognizes the zero
option.
If you need special rules just define them for your language, for example Russian, just add a new pluralizer:
I18n.pluralization["ru"] = function (count) {
var key = count % 10 == 1 && count % 100 != 11 ? "one" : [2, 3, 4].indexOf(count % 10) >= 0 && [12, 13, 14].indexOf(count % 100) < 0 ? "few" : count % 10 == 0 || [5, 6, 7, 8, 9].indexOf(count % 10) >= 0 || [11, 12, 13, 14].indexOf(count % 100) >= 0 ? "many" : "other";
return [key];
};
You can find all rules on http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html.
If you're using the same scope over and over again, you may use the scope
option.
var options = {scope: "activerecord.attributes.user"};
I18n.t("name", options);
I18n.t("email", options);
I18n.t("username", options);
You can also provide an array as scope.
// use the greetings.hello scope
I18n.t(["greetings", "hello"]);
Similar to Rails helpers, you have localized number and currency formatting.
I18n.l("currency", 1990.99);
// $1,990.99
I18n.l("number", 1990.99);
// 1,990.99
I18n.l("percentage", 123.45);
// 123.450%
To have more control over number formatting, you can use the
I18n.toNumber
, I18n.toPercentage
, I18n.toCurrency
and I18n.toHumanSize
functions.
I18n.toNumber(1000); // 1,000.000
I18n.toCurrency(1000); // $1,000.00
I18n.toPercentage(100); // 100.000%
The toNumber
and toPercentage
functions accept the following options:
precision
: defaults to 3
separator
: defaults to .
delimiter
: defaults to ,
strip_insignificant_zeros
: defaults to false
See some number formatting examples:
I18n.toNumber(1000, {precision: 0}); // 1,000
I18n.toNumber(1000, {delimiter: ".", separator: ","}); // 1.000,000
I18n.toNumber(1000, {delimiter: ".", precision: 0}); // 1.000
The toCurrency
function accepts the following options:
precision
: sets the level of precisionseparator
: sets the separator between the unitsdelimiter
: sets the thousands delimiterformat
: sets the format of the output stringunit
: sets the denomination of the currencystrip_insignificant_zeros
: defaults to false
sign_first
: defaults to true
You can provide only the options you want to override:
I18n.toCurrency(1000, {precision: 0}); // $1,000
The toHumanSize
function accepts the following options:
precision
: defaults to 1
separator
: defaults to .
delimiter
: defaults to ""
strip_insignificant_zeros
: defaults to false
format
: defaults to %n%u
I18n.toHumanSize(1234); // 1KB
I18n.toHumanSize(1234 * 1024); // 1MB
// accepted formats
I18n.l("date.formats.short", "2009-09-18"); // yyyy-mm-dd
I18n.l("time.formats.short", "2009-09-18 23:12:43"); // yyyy-mm-dd hh:mm:ss
I18n.l("time.formats.short", "2009-11-09T18:10:34"); // JSON format with local Timezone (part of ISO-8601)
I18n.l("time.formats.short", "2009-11-09T18:10:34Z"); // JSON format in UTC (part of ISO-8601)
I18n.l("date.formats.short", 1251862029000); // Epoch time
I18n.l("date.formats.short", "09/18/2009"); // mm/dd/yyyy
I18n.l("date.formats.short", (new Date())); // Date object
You can also add placeholders to the date format:
I18n.translations["en"] = {
date: {
formats: {
ordinal_day: "%B %{day}"
}
}
}
I18n.l("date.formats.ordinal_day", "2009-09-18", { day: '18th' }); // Sep 18th
If you prefer, you can use the I18n.strftime
function to format dates.
var date = new Date();
I18n.strftime(date, "%d/%m/%Y");
The accepted formats are:
%a - The abbreviated weekday name (Sun)
%A - The full weekday name (Sunday)
%b - The abbreviated month name (Jan)
%B - The full month name (January)
%d - Day of the month (01..31)
%-d - Day of the month (1..31)
%H - Hour of the day, 24-hour clock (00..23)
%-H - Hour of the day, 24-hour clock (0..23)
%I - Hour of the day, 12-hour clock (01..12)
%-I - Hour of the day, 12-hour clock (1..12)
%m - Month of the year (01..12)
%-m - Month of the year (1..12)
%M - Minute of the hour (00..59)
%-M - Minute of the hour (0..59)
%p - Meridian indicator (AM or PM)
%S - Second of the minute (00..60)
%-S - Second of the minute (0..60)
%w - Day of the week (Sunday is 0, 0..6)
%y - Year without a century (00..99)
%-y - Year without a century (0..99)
%Y - Year with century
%z - Timezone offset (+0545)
Check out spec/*.spec.js
files for more examples!
Sometimes you might want to display translation with formatted number, like adding thousand delimiters to displayed number
You can do this:
{
"en": {
"point": {
"one": "1 Point",
"other": "{{formatted_number}} Points",
"zero": "0 Points"
}
}
}
var point_in_number = 1000;
I18n.t('point', { count: point_in_number, formatted_number: I18n.toNumber(point_in_number) });
Output should be 1,000 points
This method is useful for very large apps where a single contained translations.js file is not desirable. Examples would be a global translations file and a more specific route translation file.
config/i18n-js.yml
to have multiple files and try to minimize any overlap.sort_translation_keys: true
fallbacks: false
translations:
+ file: "app/assets/javascript/nls/welcome.js"
only:
+ '*.welcome.*'
+ file: "app/assets/javascript/nls/albums.js"
only:
+ '*.albums.*'
+ file: "app/assets/javascript/nls/global.js"
only:
+ '*'
# Exempt any routes specific translations from being
# included in the global translation file
except:
+ '*.welcome.*'
+ '*.albums.*'
When rake i18n:js:export
is executed it will create 3 translations files that can be loaded via the javascript_include_tag
javascript_include_tag
to your layout and to any route specific files that will require it. # views/layouts/application.html.erb
<%= javascript_include_tag(
"i18n"
"nls/global"
) %>
and in the route specific
# views/welcome/index.html.erb
<%= javascript_include_tag(
"nls/welcome"
) %>
config/application.rb
config.assets.precompile += %w(
i18n
nls/*
)
To use this with require.js we are only going to change a few things from above.
config/i18n-js.yml
we need to add a better location for the i18n to be exported. You want to use this location so that it can be properly precompiled by r.js.export_i18n_js: "app/assets/javascript/nls"
config/require.yml
we need to add a map, shim all the translations, and include them into the appropriate modules# In your maps add (if you do not have this you will need to add it)
map:
'*':
i18n: 'nls/i18n'
# In your shims
shims:
nls/welcome:
deps:
+ i18n
nls/global:
deps:
+ i18n
# Finally in your modules
modules:
+ name: 'application'
include:
+ i18n
+ 'nls/global'
+ name: 'welcome'
exclude:
+ application
include:
+ 'nls/welcome'
rake assets:precompile
is executed it will optimize the translations into the correct modules so they are loaded with their assigned module, and loading them with requirejs is as simple as requiring any other shim.define(['welcome/other_asset','nls/welcome'], function (otherAsset){
// ...
});
# lib/tasks/i18n.rake
Rake::Task[:'i18n:js:export'].prerequisites.clear
task :'i18n:js:export' => :'i18n:js:before_export'
task :'requirejs:precompile:external' => :'i18n:js:export'
namespace :i18n do
namespace :js do
task :before_export => :'assets:environment' do
I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{yml,rb}')]
I18n.backend.load_translations
end
end
end
The JavaScript library is language agnostic; so you can use it with PHP, Python, [your favorite language here].
The only requirement is that you need to set the translations
attribute like following:
I18n.translations = {};
I18n.translations["en"] = {
message: "Some special message for you"
}
I18n.translations["pt-BR"] = {
message: "Uma mensagem especial para você"
}
Due to the design of sprockets
:
depend_on
only takes file paths, not directory pathspreprocessors
are only run when the fingerprint of any asset file, including .erb
files, is changedThis means that new locale files will not be detected, and so they will not trigger a i18n-js refresh. There are a few approaches to work around this:
$ rake assets:clobber
# Or, with older versions of Rails:
$ rake tmp:cache:clear
These commands will remove all fingerprinted assets, and you will have to recompile them with
$ rake assets:precompile
or similar commands. If you are precompiling assets on the target machine(s), cached pages may be broken by this, so they will need to be refreshed.
You can change something in a different locale file.
Finally, you can change config.assets.version
.
Note: See issue #213 for more details and discussion of this issue.
The "rails engine" declaration will try to detect existence of "sprockets" before adding the initailizer If sprockets is loaded after this gem, the preprocessor for making JS translations file cache to depend on content of locale files will not be hooked. So ensure sprockets is loaded before this gem like moving entry of sprockets in Gemfile or adding "require" statements for sprockets somewhere.
Note: See issue #404 for more details and discussion of this issue.
Once you've made your great commits:
Please respect the indentation rules and code style. And use 2 spaces, not tabs. And don't touch the versioning thing.
You can run I18n tests using Node.js or your browser.
To use Node.js, install the jasmine-node
library:
$ npm install jasmine-node
Then execute the following command from the lib's root directory:
$ npm test
To run using your browser, just open the spec/js/specs.html
file.
You can run both Ruby and JavaScript specs with rake spec
.
(The MIT License)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
A small library to provide I18n on JavaScript.
The npm package i18n-js receives a total of 294,122 weekly downloads. As such, i18n-js popularity was classified as popular.
We found that i18n-js demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.