forked from mashpie/i18n-node
/
i18n.js
314 lines (269 loc) · 7.57 KB
/
i18n.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/**
* @author Created by Marcus Spiegel <marcus.spiegel@gmail.com> on 2011-03-25.
* @link https://github.com/mashpie/i18n-node
* @license http://creativecommons.org/licenses/by-sa/3.0/
*
* @version 0.3.5
*/
// dependencies
var vsprintf = require('sprintf').vsprintf,
fs = require('fs'),
url = require('url'),
path = require('path'),
locales = {},
defaultLocale = 'en',
updateFiles = true,
cookiename = null,
debug = false,
verbose = false,
extension = '.js',
directory = './locales';
// public exports
var i18n = exports;
i18n.version = '0.3.5';
i18n.configure = function (opt) {
// you may register helpers in global scope, up to you
if (typeof opt.register === 'object') {
opt.register.__ = i18n.__;
opt.register.__n = i18n.__n;
opt.register.getLocale = i18n.getLocale;
}
// sets a custom cookie name to parse locale settings from
if (typeof opt.cookie === 'string') {
cookiename = opt.cookie;
}
// where to store json files
if (typeof opt.directory === 'string') {
directory = opt.directory;
} else {
directory = './locales';
}
// write new locale information to disk
if (typeof opt.updateFiles === 'boolean') {
updateFiles = opt.updateFiles
}
// where to store json files
if (typeof opt.extension === 'string') {
extension = opt.extension;
}
// enabled some debug output
if (opt.debug) {
debug = opt.debug;
}
// implicitly read all locales
if (typeof opt.locales === 'object') {
opt.locales.forEach(function (l) {
read(l);
});
}
};
i18n.init = function (request, response, next) {
if (typeof request === 'object') {
guessLanguage(request);
}
if (typeof next === 'function') {
next();
}
};
i18n.__ = function () {
var locale;
if (this && this.scope) {
locale = this.scope.locale;
}
var msg = translate(locale, arguments[0]);
if (arguments.length > 1) {
msg = vsprintf(msg, Array.prototype.slice.call(arguments, 1));
}
return msg;
};
i18n.__n = function () {
var locale;
if (this && this.scope) {
locale = this.scope.locale;
}
var zero = arguments[0];
var singular = arguments[1];
var plural = arguments[2];
var count = arguments[3];
var msg = translate(locale, singular, plural, zero);
if (parseInt(count, 10) > 1) {
msg = vsprintf(msg.other, [count]);
} else if(parseInt(count, 10) === 1){
msg = vsprintf(msg.one, [count]);
} else {
msg = vsprintf(msg.zero, [count]);
}
if (arguments.length > 4) {
msg = vsprintf(msg, Array.prototype.slice.call(arguments, 4));
}
return msg;
};
// either gets called like
// setLocale('en') or like
// setLocale(req, 'en')
i18n.setLocale = function (arg1, arg2) {
var request = undefined,
target_locale = arg1;
if (arg2 && locales[arg2]) {
request = arg1;
target_locale = arg2;
}
if (locales[target_locale]) {
if (request === undefined) {
defaultLocale = target_locale;
}
else {
request.locale = target_locale;
}
}
return i18n.getLocale(request);
};
i18n.getLocale = function (request) {
if (request === undefined) {
return defaultLocale;
}
return request.locale;
};
i18n.overrideLocaleFromQuery = function (req) {
if (req == null) {
return;
}
var urlObj = url.parse(req.url, true);
if (urlObj.query.locale) {
if (debug) console.log("Overriding locale from query: " + urlObj.query.locale);
i18n.setLocale(req, urlObj.query.locale.toLowerCase());
}
};
// ===================
// = private methods =
// ===================
// guess language setting based on http headers
function guessLanguage(request) {
if (typeof request === 'object') {
var language_header = request.headers['accept-language'],
languages = [],
regions = [];
request.languages = [defaultLocale];
request.regions = [defaultLocale];
request.language = defaultLocale;
request.region = defaultLocale;
if (language_header) {
language_header.split(',').forEach(function (l) {
var header = l.split(';', 1)[0];
var lr = header.split('-', 2);
if (lr[0]) {
languages.push(lr[0].toLowerCase());
}
if (lr[1]) {
regions.push(lr[1].toLowerCase());
}
});
if (languages.length > 0) {
request.languages = languages;
request.language = languages[0];
}
if (regions.length > 0) {
request.regions = regions;
request.region = regions[0];
}
}
// setting the language by cookie
if (cookiename && request.cookies[cookiename]) {
request.language = request.cookies[cookiename];
}
i18n.setLocale(request, request.language);
}
}
// read locale file, translate a msg and write to fs if new
function translate(locale, singular, plural, zero) {
if (locale === undefined) {
if (debug) console.warn("WARN: No locale found - check the context of the call to $__. Using " + defaultLocale + " (set by request) as current locale");
locale = defaultLocale;
}
if (!locales[locale]) {
read(locale);
}
if(zero) {
if(!locales[locale][zero]) {
locales[locale][zero] = {
'zero': zero,
'one': singular,
'other': plural
};
write(locale);
}
return locales[locale][zero];
} else if (plural) {
if (!locales[locale][singular]) {
locales[locale][singular] = {
'one': singular,
'other': plural
};
write(locale);
}
return locales[locale][plural];
}
if (!locales[locale][singular]) {
locales[locale][singular] = singular;
write(locale);
}
return locales[locale][singular];
}
// try reading a file
function read(locale) {
var localeFile = {};
var file = locate(locale);
try {
if (verbose) console.log('read ' + file + ' for locale: ' + locale);
localeFile = fs.readFileSync(file);
try {
// parsing filecontents to locales[locale]
locales[locale] = JSON.parse(localeFile);
} catch (e) {
console.error('unable to parse locales from file (maybe ' + file + ' is empty or invalid json?): ', e);
}
} catch (e) {
// unable to read, so intialize that file
// locales[locale] are already set in memory, so no extra read required
// or locales[locale] are empty, which initializes an empty locale.json file
if (verbose) console.log('initializing ' + file);
write(locale);
}
}
// try writing a file in a created directory
function write(locale) {
// don't write new locale information to disk if updateFiles isn't true
if(!updateFiles) {
return;
}
// creating directory if necessary
try {
var stats = fs.lstatSync(directory);
} catch (e) {
if (debug) console.log('creating locales dir in: ' + directory);
fs.mkdirSync(directory, 0755);
}
// first time init has an empty file
if (!locales[locale]) {
locales[locale] = {};
}
// writing to tmp and rename on success
try {
var target = locate(locale),
tmp = target + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(locales[locale], null, "\t"), "utf8");
var Stats = fs.statSync(tmp);
if (Stats.isFile()) {
fs.renameSync(tmp, target);
} else {
console.error('unable to write locales to file (either ' + tmp + ' or ' + target + ' are not writeable?): ', e);
}
} catch (e) {
console.error('unexpected error writing files (either ' + tmp + ' or ' + target + ' are not writeable?): ', e);
}
}
// basic normalization of filepath
function locate(locale) {
var ext = extension || '.js';
return path.normalize(directory + '/' + locale + ext);
}