forked from jeresig/i18n-node-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi18n.js
359 lines (276 loc) · 7.64 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
* @author John Resig <[email protected]>
* @author Originally by Marcus Spiegel <[email protected]>
* @link https://github.com/jeresig/i18n-node
* @license http://opensource.org/licenses/MIT
*
* @version 0.4.6
*/
// dependencies
var vsprintf = require("sprintf").vsprintf,
fs = require("fs"),
path = require("path");
var i18n = module.exports = function(opt) {
var self = this;
// Put into dev or production mode
this.devMode = process.env.NODE_ENV !== "production";
// Copy over options
for (var prop in opt) {
this[prop] = opt[prop];
}
// you may register helpers in global scope, up to you
if (typeof this.register === "object") {
i18n.resMethods.forEach(function(method) {
self.register[method] = self[method].bind(self);
});
}
// implicitly read all locales
// if it's an array of locale names, read in the data
if (opt.locales && opt.locales.forEach) {
this.locales = {};
opt.locales.forEach(function(locale) {
self.readFile(locale);
});
this.defaultLocale = opt.locales[0];
}
// Set the locale to the default locale
this.setLocale(this.defaultLocale);
// Check the defaultLocale
if (!this.locales[this.defaultLocale]) {
console.error("Not a valid default locale.");
}
if (this.request) {
if (this.subdomain) {
this.setLocaleFromSubdomain(this.request);
}
if (this.query !== false) {
this.setLocaleFromQuery(this.request);
}
this.prefLocale = this.preferredLocale();
}
};
i18n.version = "0.4.6";
i18n.localeCache = {};
i18n.resMethods = ["__", "__n", "getLocale", "isPreferredLocale"];
i18n.expressBind = function(app, opt) {
if (!app) {
return;
}
app.use(function(req, res, next) {
opt.request = req;
req.i18n = new i18n(opt);
// Express 3
if (res.locals) {
i18n.registerMethods(res.locals, req)
}
next();
});
// Express 2
if (app.dynamicHelpers) {
app.dynamicHelpers(i18n.registerMethods({}));
}
};
i18n.registerMethods = function(helpers, req) {
i18n.resMethods.forEach(function(method) {
if (req) {
helpers[method] = req.i18n[method].bind(req.i18n);
} else {
helpers[method] = function(req) {
return req.i18n[method].bind(req.i18n);
};
}
});
return helpers;
};
i18n.prototype = {
defaultLocale: "en",
extension: ".js",
directory: "./locales",
cookieName: "lang",
__: function() {
var msg = this.translate(this.locale, arguments[0]);
if (arguments.length > 1) {
msg = vsprintf(msg, Array.prototype.slice.call(arguments, 1));
}
return msg;
},
__n: function(singular, plural, count) {
var msg = this.translate(this.locale, singular, plural);
msg = vsprintf(parseInt(count, 10) > 1 ? msg.other : msg.one, [count]);
if (arguments.length > 3) {
msg = vsprintf(msg, Array.prototype.slice.call(arguments, 3));
}
return msg;
},
setLocale: function(locale) {
if (!locale) return;
if (!this.locales[locale]) {
if (this.devMode) {
console.warn("Locale (" + locale + ") not found.");
}
locale = this.defaultLocale;
}
return (this.locale = locale);
},
getLocale: function() {
return this.locale;
},
isPreferredLocale: function() {
return !this.prefLocale ||
this.prefLocale === this.getLocale();
},
setLocaleFromQuery: function(req) {
req = req || this.request;
if (!req || !req.query || !req.query.lang) {
return;
}
var locale = req.query.lang.toLowerCase();
if (this.locales[locale]) {
if (this.devMode) {
console.log("Overriding locale from query: " + locale);
}
this.setLocale(locale);
}
},
setLocaleFromSubdomain: function(req) {
req = req || this.request;
if (!req || !req.headers || !req.headers.host) {
return;
}
if (/^([^.]+)/.test(req.headers.host) && this.locales[RegExp.$1]) {
if (this.devMode) {
console.log("Overriding locale from host: " + RegExp.$1);
}
this.setLocale(RegExp.$1);
}
},
setLocaleFromCookie: function(req) {
req = req || this.request;
if (!req || !req.cookies || !this.cookieName || !req.cookies[this.cookieName]) {
return;
}
var locale = req.cookies[this.cookieName].toLowerCase();
if (this.locales[locale]) {
if (this.devMode) {
console.log("Overriding locale from cookie: " + locale);
}
this.setLocale(locale);
}
},
preferredLocale: function(req) {
req = req || this.request;
if (!req || !req.headers) {
return;
}
var accept = req.headers["accept-language"] || "",
regExp = /(^|,\s*)([a-z-]+)/gi,
self = this,
prefLocale;
while ((match = regExp.exec(accept))){
var locale = match[2];
var parts = locale.split("-");
if (!prefLocale) {
if (self.locales[locale]) {
prefLocale = locale;
} else if (parts.length > 1 && self.locales[parts[0]]) {
prefLocale = parts[0];
}
}
}
return prefLocale || this.defaultLocale;
},
// read locale file, translate a msg and write to fs if new
translate: function(locale, singular, plural) {
if (!locale || !this.locales[locale]) {
if (this.devMode) {
console.warn("WARN: No locale found. Using the default (" +
this.defaultLocale + ") as current locale");
}
locale = this.defaultLocale;
this.initLocale(locale, {});
}
if (!this.locales[locale][singular]) {
this.locales[locale][singular] = plural ?
{ one: singular, other: plural } :
singular;
if (this.devMode) {
this.writeFile(locale);
}
}
return this.locales[locale][singular];
},
// try reading a file
readFile: function(locale) {
var file = this.locateFile(locale);
if (!this.devMode && i18n.localeCache[file]) {
this.initLocale(locale, i18n.localeCache[file]);
return;
}
try {
var localeFile = fs.readFileSync(file);
try {
// parsing filecontents to locales[locale]
this.initLocale(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
this.writeFile(locale);
}
},
// try writing a file in a created directory
writeFile: function(locale) {
// don't write new locale information to disk if we're not in dev mode
if (!this.devMode) {
// Initialize the locale if didn't exist already
this.initLocale(locale, {});
}
// creating directory if necessary
try {
fs.lstatSync(this.directory);
} catch (e) {
if (this.devMode) {
console.log('creating locales dir in: ' + this.directory);
}
fs.mkdirSync(this.directory, 0755);
}
// Initialize the locale if didn't exist already
this.initLocale(locale, {});
// writing to tmp and rename on success
try {
var target = this.locateFile(locale),
tmp = target + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(
this.locales[locale], null, "\t"), "utf8");
if (fs.statSync(tmp).isFile()) {
fs.renameSync(tmp, target);
} else {
console.error('unable to write locales to file (either ' + tmp +
' or ' + target + ' are not writeable?): ');
}
} catch (e) {
console.error('unexpected error writing files (either ' + tmp +
' or ' + target + ' are not writeable?): ', e);
}
},
// basic normalization of filepath
locateFile: function(locale) {
return path.normalize(this.directory + '/' + locale + this.extension);
},
initLocale: function(locale, data) {
if (!this.locales[locale]) {
this.locales[locale] = data;
// Only cache the files when we're not in dev mode
if (!this.devMode) {
var file = this.locateFile(locale);
if ( !i18n.localeCache[file] ) {
i18n.localeCache[file] = data;
}
}
}
}
};