Blame view

bower_components/l20n/dist/bundle/gaia/l20n.js 65.5 KB
0e9aeacd   root   localization l20n
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
  (function () { 'use strict';
  
    function emit(listeners, ...args) {
      const type = args.shift();
  
      if (listeners['*']) {
        listeners['*'].slice().forEach(
          listener => listener.apply(this, args));
      }
  
      if (listeners[type]) {
        listeners[type].slice().forEach(
          listener => listener.apply(this, args));
      }
    }
  
    function addEventListener(listeners, type, listener) {
      if (!(type in listeners)) {
        listeners[type] = [];
      }
      listeners[type].push(listener);
    }
  
    function removeEventListener(listeners, type, listener) {
      const typeListeners = listeners[type];
      const pos = typeListeners.indexOf(listener);
      if (pos === -1) {
        return;
      }
  
      typeListeners.splice(pos, 1);
    }
  
    class Client {
      constructor(remote) {
        this.id = this;
        this.remote = remote;
  
        const listeners = {};
        this.on = (...args) => addEventListener(listeners, ...args);
        this.emit = (...args) => emit(listeners, ...args);
      }
  
      method(name, ...args) {
        return this.remote[name](...args);
      }
    }
  
    function broadcast(type, data) {
      Array.from(this.ctxs.keys()).forEach(
        client => client.emit(type, data));
    }
  
    function L10nError(message, id, lang) {
      this.name = 'L10nError';
      this.message = message;
      this.id = id;
      this.lang = lang;
    }
    L10nError.prototype = Object.create(Error.prototype);
    L10nError.prototype.constructor = L10nError;
  
    function load(type, url) {
      return new Promise(function(resolve, reject) {
        const xhr = new XMLHttpRequest();
  
        if (xhr.overrideMimeType) {
          xhr.overrideMimeType(type);
        }
  
        xhr.open('GET', url, true);
  
        if (type === 'application/json') {
          xhr.responseType = 'json';
        }
  
        xhr.addEventListener('load', function io_onload(e) {
          if (e.target.status === 200 || e.target.status === 0) {
            // Sinon.JS's FakeXHR doesn't have the response property
            resolve(e.target.response || e.target.responseText);
          } else {
            reject(new L10nError('Not found: ' + url));
          }
        });
        xhr.addEventListener('error', reject);
        xhr.addEventListener('timeout', reject);
  
        // the app: protocol throws on 404, see https://bugzil.la/827243
        try {
          xhr.send(null);
        } catch (e) {
          if (e.name === 'NS_ERROR_FILE_NOT_FOUND') {
            // the app: protocol throws on 404, see https://bugzil.la/827243
            reject(new L10nError('Not found: ' + url));
          } else {
            throw e;
          }
        }
      });
    }
  
    const io = {
      extra: function(code, ver, path, type) {
        return navigator.mozApps.getLocalizationResource(
          code, ver, path, type);
      },
      app: function(code, ver, path, type) {
        switch (type) {
          case 'text':
            return load('text/plain', path);
          case 'json':
            return load('application/json', path);
          default:
            throw new L10nError('Unknown file type: ' + type);
        }
      },
    };
  
c5169e0e   Renato De Donato   a new hope
119
120
    function fetchResource(ver, res, lang) {
      const url = res.replace('{locale}', lang.code);
0e9aeacd   root   localization l20n
121
      const type = res.endsWith('.json') ? 'json' : 'text';
c5169e0e   Renato De Donato   a new hope
122
      return io[lang.src](lang.code, ver, url, type);
0e9aeacd   root   localization l20n
123
124
    }
  
c5169e0e   Renato De Donato   a new hope
125
    const MAX_PLACEABLES$1 = 100;
0e9aeacd   root   localization l20n
126
  
c5169e0e   Renato De Donato   a new hope
127
128
129
130
131
132
133
    var L20nParser = {
      parse: function(emit, string) {
        this._source = string;
        this._index = 0;
        this._length = string.length;
        this.entries = Object.create(null);
        this.emit = emit;
0e9aeacd   root   localization l20n
134
  
c5169e0e   Renato De Donato   a new hope
135
136
        return this.getResource();
      },
0e9aeacd   root   localization l20n
137
  
c5169e0e   Renato De Donato   a new hope
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
      getResource: function() {
        this.getWS();
        while (this._index < this._length) {
          try {
            this.getEntry();
          } catch (e) {
            if (e instanceof L10nError) {
              // we want to recover, but we don't need it in entries
              this.getJunkEntry();
              if (!this.emit) {
                throw e;
              }
            } else {
              throw e;
            }
          }
0e9aeacd   root   localization l20n
154
  
c5169e0e   Renato De Donato   a new hope
155
156
157
158
          if (this._index < this._length) {
            this.getWS();
          }
        }
0e9aeacd   root   localization l20n
159
  
c5169e0e   Renato De Donato   a new hope
160
161
        return this.entries;
      },
0e9aeacd   root   localization l20n
162
  
c5169e0e   Renato De Donato   a new hope
163
164
165
166
167
168
169
170
171
172
      getEntry: function() {
        if (this._source[this._index] === '<') {
          ++this._index;
          const id = this.getIdentifier();
          if (this._source[this._index] === '[') {
            ++this._index;
            return this.getEntity(id, this.getItemList(this.getExpression, ']'));
          }
          return this.getEntity(id);
        }
0e9aeacd   root   localization l20n
173
  
c5169e0e   Renato De Donato   a new hope
174
175
        if (this._source.startsWith('/*', this._index)) {
          return this.getComment();
0e9aeacd   root   localization l20n
176
        }
0e9aeacd   root   localization l20n
177
  
c5169e0e   Renato De Donato   a new hope
178
179
        throw this.error('Invalid entry');
      },
0e9aeacd   root   localization l20n
180
  
c5169e0e   Renato De Donato   a new hope
181
182
183
184
      getEntity: function(id, index) {
        if (!this.getRequiredWS()) {
          throw this.error('Expected white space');
        }
0e9aeacd   root   localization l20n
185
  
c5169e0e   Renato De Donato   a new hope
186
187
188
        const ch = this._source[this._index];
        const value = this.getValue(ch, index === undefined);
        let attrs;
0e9aeacd   root   localization l20n
189
  
c5169e0e   Renato De Donato   a new hope
190
191
192
193
194
195
196
197
198
199
200
201
202
203
        if (value === undefined) {
          if (ch === '>') {
            throw this.error('Expected ">"');
          }
          attrs = this.getAttributes();
        } else {
          const ws1 = this.getRequiredWS();
          if (this._source[this._index] !== '>') {
            if (!ws1) {
              throw this.error('Expected ">"');
            }
            attrs = this.getAttributes();
          }
        }
0e9aeacd   root   localization l20n
204
  
c5169e0e   Renato De Donato   a new hope
205
206
        // skip '>'
        ++this._index;
0e9aeacd   root   localization l20n
207
  
c5169e0e   Renato De Donato   a new hope
208
209
210
211
212
213
214
215
216
217
218
219
220
        if (id in this.entries) {
          throw this.error('Duplicate entry ID "' + id, 'duplicateerror');
        }
        if (!attrs && !index && typeof value === 'string') {
          this.entries[id] = value;
        } else {
          this.entries[id] = {
            value,
            attrs,
            index
          };
        }
      },
0e9aeacd   root   localization l20n
221
  
c5169e0e   Renato De Donato   a new hope
222
223
224
225
226
227
228
229
      getValue: function(ch = this._source[this._index], optional = false) {
        switch (ch) {
          case '\'':
          case '"':
            return this.getString(ch, 1);
          case '{':
            return this.getHash();
        }
a1a3bc73   Luigi Serra   graphs updates
230
  
c5169e0e   Renato De Donato   a new hope
231
232
        if (!optional) {
          throw this.error('Unknown value type');
0e9aeacd   root   localization l20n
233
        }
0e9aeacd   root   localization l20n
234
  
c5169e0e   Renato De Donato   a new hope
235
236
        return;
      },
0e9aeacd   root   localization l20n
237
  
c5169e0e   Renato De Donato   a new hope
238
239
240
241
242
      getWS: function() {
        let cc = this._source.charCodeAt(this._index);
        // space, \n, \t, \r
        while (cc === 32 || cc === 10 || cc === 9 || cc === 13) {
          cc = this._source.charCodeAt(++this._index);
0e9aeacd   root   localization l20n
243
        }
c5169e0e   Renato De Donato   a new hope
244
      },
0e9aeacd   root   localization l20n
245
  
c5169e0e   Renato De Donato   a new hope
246
247
248
249
250
251
252
253
254
      getRequiredWS: function() {
        const pos = this._index;
        let cc = this._source.charCodeAt(pos);
        // space, \n, \t, \r
        while (cc === 32 || cc === 10 || cc === 9 || cc === 13) {
          cc = this._source.charCodeAt(++this._index);
        }
        return this._index !== pos;
      },
0e9aeacd   root   localization l20n
255
  
c5169e0e   Renato De Donato   a new hope
256
257
258
      getIdentifier: function() {
        const start = this._index;
        let cc = this._source.charCodeAt(this._index);
a1a3bc73   Luigi Serra   graphs updates
259
  
c5169e0e   Renato De Donato   a new hope
260
261
262
263
264
265
        if ((cc >= 97 && cc <= 122) || // a-z
            (cc >= 65 && cc <= 90) ||  // A-Z
            cc === 95) {               // _
          cc = this._source.charCodeAt(++this._index);
        } else {
          throw this.error('Identifier has to start with [a-zA-Z_]');
0e9aeacd   root   localization l20n
266
        }
c5169e0e   Renato De Donato   a new hope
267
268
269
270
271
272
  
        while ((cc >= 97 && cc <= 122) || // a-z
               (cc >= 65 && cc <= 90) ||  // A-Z
               (cc >= 48 && cc <= 57) ||  // 0-9
               cc === 95) {               // _
          cc = this._source.charCodeAt(++this._index);
a1a3bc73   Luigi Serra   graphs updates
273
        }
c5169e0e   Renato De Donato   a new hope
274
275
276
277
278
279
280
281
282
283
284
285
286
  
        return this._source.slice(start, this._index);
      },
  
      getUnicodeChar: function() {
        for (let i = 0; i < 4; i++) {
          let cc = this._source.charCodeAt(++this._index);
          if ((cc > 96 && cc < 103) || // a-f
              (cc > 64 && cc < 71) ||  // A-F
              (cc > 47 && cc < 58)) {  // 0-9
            continue;
          }
          throw this.error('Illegal unicode escape sequence');
a1a3bc73   Luigi Serra   graphs updates
287
        }
c5169e0e   Renato De Donato   a new hope
288
289
290
291
        this._index++;
        return String.fromCharCode(
          parseInt(this._source.slice(this._index - 4, this._index), 16));
      },
0e9aeacd   root   localization l20n
292
  
c5169e0e   Renato De Donato   a new hope
293
294
295
296
      stringRe: /"|'|{{|\\/g,
      getString: function(opchar, opcharLen) {
        const body = [];
        let placeables = 0;
0e9aeacd   root   localization l20n
297
  
c5169e0e   Renato De Donato   a new hope
298
299
        this._index += opcharLen;
        const start = this._index;
0e9aeacd   root   localization l20n
300
  
c5169e0e   Renato De Donato   a new hope
301
302
        let bufStart = start;
        let buf = '';
0e9aeacd   root   localization l20n
303
  
c5169e0e   Renato De Donato   a new hope
304
305
306
        while (true) {
          this.stringRe.lastIndex = this._index;
          const match = this.stringRe.exec(this._source);
0e9aeacd   root   localization l20n
307
  
c5169e0e   Renato De Donato   a new hope
308
309
310
          if (!match) {
            throw this.error('Unclosed string literal');
          }
0e9aeacd   root   localization l20n
311
  
c5169e0e   Renato De Donato   a new hope
312
313
314
315
316
317
318
319
          if (match[0] === '"' || match[0] === '\'') {
            if (match[0] !== opchar) {
              this._index += opcharLen;
              continue;
            }
            this._index = match.index + opcharLen;
            break;
          }
0e9aeacd   root   localization l20n
320
  
c5169e0e   Renato De Donato   a new hope
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
          if (match[0] === '{{') {
            if (placeables > MAX_PLACEABLES$1 - 1) {
              throw this.error('Too many placeables, maximum allowed is ' +
                  MAX_PLACEABLES$1);
            }
            placeables++;
            if (match.index > bufStart || buf.length > 0) {
              body.push(buf + this._source.slice(bufStart, match.index));
              buf = '';
            }
            this._index = match.index + 2;
            this.getWS();
            body.push(this.getExpression());
            this.getWS();
            this._index += 2;
            bufStart = this._index;
            continue;
          }
0e9aeacd   root   localization l20n
339
  
c5169e0e   Renato De Donato   a new hope
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
          if (match[0] === '\\') {
            this._index = match.index + 1;
            const ch2 = this._source[this._index];
            if (ch2 === 'u') {
              buf += this._source.slice(bufStart, match.index) +
                this.getUnicodeChar();
            } else if (ch2 === opchar || ch2 === '\\') {
              buf += this._source.slice(bufStart, match.index) + ch2;
              this._index++;
            } else if (this._source.startsWith('{{', this._index)) {
              buf += this._source.slice(bufStart, match.index) + '{{';
              this._index += 2;
            } else {
              throw this.error('Illegal escape sequence');
            }
            bufStart = this._index;
          }
0e9aeacd   root   localization l20n
357
        }
c5169e0e   Renato De Donato   a new hope
358
359
360
  
        if (body.length === 0) {
          return buf + this._source.slice(bufStart, this._index - opcharLen);
0e9aeacd   root   localization l20n
361
        }
c5169e0e   Renato De Donato   a new hope
362
363
364
  
        if (this._index - opcharLen > bufStart || buf.length > 0) {
          body.push(buf + this._source.slice(bufStart, this._index - opcharLen));
0e9aeacd   root   localization l20n
365
        }
c5169e0e   Renato De Donato   a new hope
366
367
  
        return body;
0e9aeacd   root   localization l20n
368
      },
c5169e0e   Renato De Donato   a new hope
369
370
371
372
373
374
375
376
377
378
379
380
381
  
      getAttributes: function() {
        const attrs = Object.create(null);
  
        while (true) {
          this.getAttribute(attrs);
          const ws1 = this.getRequiredWS();
          const ch = this._source.charAt(this._index);
          if (ch === '>') {
            break;
          } else if (!ws1) {
            throw this.error('Expected ">"');
          }
a1a3bc73   Luigi Serra   graphs updates
382
        }
c5169e0e   Renato De Donato   a new hope
383
        return attrs;
0e9aeacd   root   localization l20n
384
      },
c5169e0e   Renato De Donato   a new hope
385
386
387
388
389
390
391
392
393
  
      getAttribute: function(attrs) {
        const key = this.getIdentifier();
        let index;
  
        if (this._source[this._index]=== '[') {
          ++this._index;
          this.getWS();
          index = this.getItemList(this.getExpression, ']');
0e9aeacd   root   localization l20n
394
        }
c5169e0e   Renato De Donato   a new hope
395
396
397
        this.getWS();
        if (this._source[this._index] !== ':') {
          throw this.error('Expected ":"');
0e9aeacd   root   localization l20n
398
        }
c5169e0e   Renato De Donato   a new hope
399
400
401
402
403
404
        ++this._index;
        this.getWS();
        const value = this.getValue();
  
        if (key in attrs) {
          throw this.error('Duplicate attribute "' + key, 'duplicateerror');
0e9aeacd   root   localization l20n
405
        }
c5169e0e   Renato De Donato   a new hope
406
407
408
409
410
411
412
413
  
        if (!index && typeof value === 'string') {
          attrs[key] = value;
        } else {
          attrs[key] = {
            value,
            index
          };
a1a3bc73   Luigi Serra   graphs updates
414
        }
0e9aeacd   root   localization l20n
415
      },
c5169e0e   Renato De Donato   a new hope
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
  
      getHash: function() {
        const items = Object.create(null);
  
        ++this._index;
        this.getWS();
  
        let defKey;
  
        while (true) {
          const [key, value, def] = this.getHashItem();
          items[key] = value;
  
          if (def) {
            if (defKey) {
              throw this.error('Default item redefinition forbidden');
            }
            defKey = key;
          }
          this.getWS();
  
          const comma = this._source[this._index] === ',';
          if (comma) {
            ++this._index;
            this.getWS();
          }
          if (this._source[this._index] === '}') {
            ++this._index;
            break;
          }
          if (!comma) {
            throw this.error('Expected "}"');
          }
0e9aeacd   root   localization l20n
449
        }
c5169e0e   Renato De Donato   a new hope
450
451
452
  
        if (defKey) {
          items.__default = defKey;
0e9aeacd   root   localization l20n
453
        }
c5169e0e   Renato De Donato   a new hope
454
455
  
        return items;
0e9aeacd   root   localization l20n
456
      },
c5169e0e   Renato De Donato   a new hope
457
458
459
460
461
462
  
      getHashItem: function() {
        let defItem = false;
        if (this._source[this._index] === '*') {
          ++this._index;
          defItem = true;
0e9aeacd   root   localization l20n
463
        }
c5169e0e   Renato De Donato   a new hope
464
465
466
467
468
  
        const key = this.getIdentifier();
        this.getWS();
        if (this._source[this._index] !== ':') {
          throw this.error('Expected ":"');
0e9aeacd   root   localization l20n
469
        }
c5169e0e   Renato De Donato   a new hope
470
471
472
473
        ++this._index;
        this.getWS();
  
        return [key, this.getValue(), defItem];
a1a3bc73   Luigi Serra   graphs updates
474
      },
c5169e0e   Renato De Donato   a new hope
475
476
477
478
479
480
481
482
  
      getComment: function() {
        this._index += 2;
        const start = this._index;
        const end = this._source.indexOf('*/', start);
  
        if (end === -1) {
          throw this.error('Comment without a closing tag');
a1a3bc73   Luigi Serra   graphs updates
483
        }
c5169e0e   Renato De Donato   a new hope
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
  
        this._index = end + 2;
      },
  
      getExpression: function () {
        let exp = this.getPrimaryExpression();
  
        while (true) {
          let ch = this._source[this._index];
          if (ch === '.' || ch === '[') {
            ++this._index;
            exp = this.getPropertyExpression(exp, ch === '[');
          } else if (ch === '(') {
            ++this._index;
            exp = this.getCallExpression(exp);
          } else {
            break;
          }
a1a3bc73   Luigi Serra   graphs updates
502
        }
c5169e0e   Renato De Donato   a new hope
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
  
        return exp;
      },
  
      getPropertyExpression: function(idref, computed) {
        let exp;
  
        if (computed) {
          this.getWS();
          exp = this.getExpression();
          this.getWS();
          if (this._source[this._index] !== ']') {
            throw this.error('Expected "]"');
          }
          ++this._index;
        } else {
          exp = this.getIdentifier();
a1a3bc73   Luigi Serra   graphs updates
520
        }
c5169e0e   Renato De Donato   a new hope
521
522
523
524
525
526
527
  
        return {
          type: 'prop',
          expr: idref,
          prop: exp,
          cmpt: computed
        };
a1a3bc73   Luigi Serra   graphs updates
528
      },
c5169e0e   Renato De Donato   a new hope
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
  
      getCallExpression: function(callee) {
        this.getWS();
  
        return {
          type: 'call',
          expr: callee,
          args: this.getItemList(this.getExpression, ')')
        };
      },
  
      getPrimaryExpression: function() {
        const ch = this._source[this._index];
  
        switch (ch) {
          case '$':
            ++this._index;
            return {
              type: 'var',
              name: this.getIdentifier()
            };
          case '@':
            ++this._index;
            return {
              type: 'glob',
              name: this.getIdentifier()
            };
          default:
            return {
              type: 'id',
              name: this.getIdentifier()
            };
0e9aeacd   root   localization l20n
561
        }
c5169e0e   Renato De Donato   a new hope
562
563
564
565
566
567
568
569
570
571
572
      },
  
      getItemList: function(callback, closeChar) {
        const items = [];
        let closed = false;
  
        this.getWS();
  
        if (this._source[this._index] === closeChar) {
          ++this._index;
          closed = true;
0e9aeacd   root   localization l20n
573
        }
c5169e0e   Renato De Donato   a new hope
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
  
        while (!closed) {
          items.push(callback.call(this));
          this.getWS();
          let ch = this._source.charAt(this._index);
          switch (ch) {
            case ',':
              ++this._index;
              this.getWS();
              break;
            case closeChar:
              ++this._index;
              closed = true;
              break;
            default:
              throw this.error('Expected "," or "' + closeChar + '"');
          }
a1a3bc73   Luigi Serra   graphs updates
591
        }
c5169e0e   Renato De Donato   a new hope
592
593
  
        return items;
0e9aeacd   root   localization l20n
594
      },
c5169e0e   Renato De Donato   a new hope
595
596
597
598
599
600
601
602
603
  
  
      getJunkEntry: function() {
        const pos = this._index;
        let nextEntity = this._source.indexOf('<', pos);
        let nextComment = this._source.indexOf('/*', pos);
  
        if (nextEntity === -1) {
          nextEntity = this._length;
0e9aeacd   root   localization l20n
604
        }
c5169e0e   Renato De Donato   a new hope
605
606
        if (nextComment === -1) {
          nextComment = this._length;
a1a3bc73   Luigi Serra   graphs updates
607
        }
c5169e0e   Renato De Donato   a new hope
608
609
610
611
  
        let nextEntry = Math.min(nextEntity, nextComment);
  
        this._index = nextEntry;
0e9aeacd   root   localization l20n
612
      },
c5169e0e   Renato De Donato   a new hope
613
614
615
616
617
618
619
620
621
622
623
624
625
  
      error: function(message, type = 'parsererror') {
        const pos = this._index;
  
        let start = this._source.lastIndexOf('<', pos - 1);
        const lastClose = this._source.lastIndexOf('>', pos - 1);
        start = lastClose > start ? lastClose + 1 : start;
        const context = this._source.slice(start, pos + 10);
  
        const msg = message + ' at pos ' + pos + ': `' + context + '`';
        const err = new L10nError(msg);
        if (this.emit) {
          this.emit(type, err);
0e9aeacd   root   localization l20n
626
        }
c5169e0e   Renato De Donato   a new hope
627
        return err;
0e9aeacd   root   localization l20n
628
      },
c5169e0e   Renato De Donato   a new hope
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
    };
  
    var MAX_PLACEABLES = 100;
  
    var PropertiesParser = {
      patterns: null,
      entryIds: null,
      emit: null,
  
      init: function() {
        this.patterns = {
          comment: /^\s*#|^\s*$/,
          entity: /^([^=\s]+)\s*=\s*(.*)$/,
          multiline: /[^\\]\\$/,
          index: /\{\[\s*(\w+)(?:\(([^\)]*)\))?\s*\]\}/i,
          unicode: /\\u([0-9a-fA-F]{1,4})/g,
          entries: /[^\r\n]+/g,
          controlChars: /\\([\\\n\r\t\b\f\{\}\"\'])/g,
          placeables: /\{\{\s*([^\s]*?)\s*\}\}/,
        };
      },
  
      parse: function(emit, source) {
        if (!this.patterns) {
          this.init();
a1a3bc73   Luigi Serra   graphs updates
654
        }
c5169e0e   Renato De Donato   a new hope
655
656
657
658
659
660
661
        this.emit = emit;
  
        var entries = {};
  
        var lines = source.match(this.patterns.entries);
        if (!lines) {
          return entries;
0e9aeacd   root   localization l20n
662
        }
c5169e0e   Renato De Donato   a new hope
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
        for (var i = 0; i < lines.length; i++) {
          var line = lines[i];
  
          if (this.patterns.comment.test(line)) {
            continue;
          }
  
          while (this.patterns.multiline.test(line) && i < lines.length) {
            line = line.slice(0, -1) + lines[++i].trim();
          }
  
          var entityMatch = line.match(this.patterns.entity);
          if (entityMatch) {
            try {
              this.parseEntity(entityMatch[1], entityMatch[2], entries);
            } catch (e) {
              if (!this.emit) {
                throw e;
              }
            }
          }
a1a3bc73   Luigi Serra   graphs updates
684
        }
c5169e0e   Renato De Donato   a new hope
685
        return entries;
0e9aeacd   root   localization l20n
686
      },
c5169e0e   Renato De Donato   a new hope
687
688
689
690
691
692
693
694
695
696
697
  
      parseEntity: function(id, value, entries) {
        var name, key;
  
        var pos = id.indexOf('[');
        if (pos !== -1) {
          name = id.substr(0, pos);
          key = id.substring(pos + 1, id.length - 1);
        } else {
          name = id;
          key = null;
0e9aeacd   root   localization l20n
698
        }
c5169e0e   Renato De Donato   a new hope
699
700
701
702
703
704
  
        var nameElements = name.split('.');
  
        if (nameElements.length > 2) {
          throw this.error('Error in ID: "' + name + '".' +
              ' Nested attributes are not supported.');
0e9aeacd   root   localization l20n
705
        }
c5169e0e   Renato De Donato   a new hope
706
707
708
709
710
711
712
713
714
715
716
  
        var attr;
        if (nameElements.length > 1) {
          name = nameElements[0];
          attr = nameElements[1];
  
          if (attr[0] === '$') {
            throw this.error('Attribute can\'t start with "$"');
          }
        } else {
          attr = null;
0e9aeacd   root   localization l20n
717
        }
c5169e0e   Renato De Donato   a new hope
718
719
  
        this.setEntityValue(name, attr, key, this.unescapeString(value), entries);
a1a3bc73   Luigi Serra   graphs updates
720
      },
c5169e0e   Renato De Donato   a new hope
721
722
723
724
725
726
727
728
729
730
731
732
733
  
      setEntityValue: function(id, attr, key, rawValue, entries) {
        var value = rawValue.indexOf('{{') > -1 ?
          this.parseString(rawValue) : rawValue;
  
        var isSimpleValue = typeof value === 'string';
        var root = entries;
  
        var isSimpleNode = typeof entries[id] === 'string';
  
        if (!entries[id] && (attr || key || !isSimpleValue)) {
          entries[id] = Object.create(null);
          isSimpleNode = false;
a1a3bc73   Luigi Serra   graphs updates
734
        }
c5169e0e   Renato De Donato   a new hope
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
  
        if (attr) {
          if (isSimpleNode) {
            const val = entries[id];
            entries[id] = Object.create(null);
            entries[id].value = val;
          }
          if (!entries[id].attrs) {
            entries[id].attrs = Object.create(null);
          }
          if (!entries[id].attrs && !isSimpleValue) {
            entries[id].attrs[attr] = Object.create(null);
          }
          root = entries[id].attrs;
          id = attr;
a1a3bc73   Luigi Serra   graphs updates
750
        }
c5169e0e   Renato De Donato   a new hope
751
752
753
754
755
756
757
758
759
760
761
762
  
        if (key) {
          isSimpleNode = false;
          if (typeof root[id] === 'string') {
            const val = root[id];
            root[id] = Object.create(null);
            root[id].index = this.parseIndex(val);
            root[id].value = Object.create(null);
          }
          root = root[id].value;
          id = key;
          isSimpleValue = true;
a1a3bc73   Luigi Serra   graphs updates
763
        }
c5169e0e   Renato De Donato   a new hope
764
765
766
767
768
769
770
771
772
773
774
  
        if (isSimpleValue && (!entries[id] || isSimpleNode)) {
          if (id in root) {
            throw this.error();
          }
          root[id] = value;
        } else {
          if (!root[id]) {
            root[id] = Object.create(null);
          }
          root[id].value = value;
a1a3bc73   Luigi Serra   graphs updates
775
        }
a1a3bc73   Luigi Serra   graphs updates
776
      },
c5169e0e   Renato De Donato   a new hope
777
778
779
780
781
782
783
784
785
786
787
  
      parseString: function(str) {
        var chunks = str.split(this.patterns.placeables);
        var complexStr = [];
  
        var len = chunks.length;
        var placeablesCount = (len - 1) / 2;
  
        if (placeablesCount >= MAX_PLACEABLES) {
          throw this.error('Too many placeables (' + placeablesCount +
                              ', max allowed is ' + MAX_PLACEABLES + ')');
0e9aeacd   root   localization l20n
788
        }
c5169e0e   Renato De Donato   a new hope
789
790
791
792
793
794
795
796
797
798
  
        for (var i = 0; i < chunks.length; i++) {
          if (chunks[i].length === 0) {
            continue;
          }
          if (i % 2 === 1) {
            complexStr.push({type: 'idOrVar', name: chunks[i]});
          } else {
            complexStr.push(chunks[i]);
          }
a1a3bc73   Luigi Serra   graphs updates
799
        }
c5169e0e   Renato De Donato   a new hope
800
        return complexStr;
a1a3bc73   Luigi Serra   graphs updates
801
      },
c5169e0e   Renato De Donato   a new hope
802
803
804
805
  
      unescapeString: function(str) {
        if (str.lastIndexOf('\\') !== -1) {
          str = str.replace(this.patterns.controlChars, '$1');
a1a3bc73   Luigi Serra   graphs updates
806
        }
c5169e0e   Renato De Donato   a new hope
807
808
809
        return str.replace(this.patterns.unicode, function(match, token) {
          return String.fromCodePoint(parseInt(token, 16));
        });
a1a3bc73   Luigi Serra   graphs updates
810
      },
c5169e0e   Renato De Donato   a new hope
811
812
813
814
815
  
      parseIndex: function(str) {
        var match = str.match(this.patterns.index);
        if (!match) {
          throw new L10nError('Malformed index');
a1a3bc73   Luigi Serra   graphs updates
816
        }
c5169e0e   Renato De Donato   a new hope
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
        if (match[2]) {
          return [{
            type: 'call',
            expr: {
              type: 'prop',
              expr: {
                type: 'glob',
                name: 'cldr'
              },
              prop: 'plural',
              cmpt: false
            }, args: [{
              type: 'idOrVar',
              name: match[2]
            }]
          }];
        } else {
          return [{type: 'idOrVar', name: match[1]}];
0e9aeacd   root   localization l20n
835
        }
c5169e0e   Renato De Donato   a new hope
836
837
838
839
840
841
      },
  
      error: function(msg, type = 'parsererror') {
        const err = new L10nError(msg);
        if (this.emit) {
          this.emit(type, err);
0e9aeacd   root   localization l20n
842
        }
c5169e0e   Renato De Donato   a new hope
843
        return err;
0e9aeacd   root   localization l20n
844
      }
a1a3bc73   Luigi Serra   graphs updates
845
    };
0e9aeacd   root   localization l20n
846
  
c5169e0e   Renato De Donato   a new hope
847
848
849
850
851
852
853
854
855
856
857
858
    const KNOWN_MACROS = ['plural'];
    const MAX_PLACEABLE_LENGTH = 2500;
  
    // Unicode bidi isolation characters
    const FSI = '\u2068';
    const PDI = '\u2069';
  
    const resolutionChain = new WeakSet();
  
    function format(ctx, lang, args, entity) {
      if (typeof entity === 'string') {
        return [{}, entity];
0e9aeacd   root   localization l20n
859
      }
c5169e0e   Renato De Donato   a new hope
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
  
      if (resolutionChain.has(entity)) {
        throw new L10nError('Cyclic reference detected');
      }
  
      resolutionChain.add(entity);
  
      let rv;
      // if format fails, we want the exception to bubble up and stop the whole
      // resolving process;  however, we still need to remove the entity from the
      // resolution chain
      try {
        rv = resolveValue(
          {}, ctx, lang, args, entity.value, entity.index);
      } finally {
        resolutionChain.delete(entity);
      }
      return rv;
0e9aeacd   root   localization l20n
878
879
    }
  
c5169e0e   Renato De Donato   a new hope
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
    function resolveIdentifier(ctx, lang, args, id) {
      if (KNOWN_MACROS.indexOf(id) > -1) {
        return [{}, ctx._getMacro(lang, id)];
      }
  
      if (args && args.hasOwnProperty(id)) {
        if (typeof args[id] === 'string' || (typeof args[id] === 'number' &&
            !isNaN(args[id]))) {
          return [{}, args[id]];
        } else {
          throw new L10nError('Arg must be a string or a number: ' + id);
        }
      }
  
      // XXX: special case for Node.js where still:
      // '__proto__' in Object.create(null) => true
      if (id === '__proto__') {
        throw new L10nError('Illegal id: ' + id);
a1a3bc73   Luigi Serra   graphs updates
898
      }
0e9aeacd   root   localization l20n
899
  
c5169e0e   Renato De Donato   a new hope
900
      const entity = ctx._getEntity(lang, id);
0e9aeacd   root   localization l20n
901
  
c5169e0e   Renato De Donato   a new hope
902
903
      if (entity) {
        return format(ctx, lang, args, entity);
a1a3bc73   Luigi Serra   graphs updates
904
905
      }
  
c5169e0e   Renato De Donato   a new hope
906
907
      throw new L10nError('Unknown reference: ' + id);
    }
a1a3bc73   Luigi Serra   graphs updates
908
  
c5169e0e   Renato De Donato   a new hope
909
910
    function subPlaceable(locals, ctx, lang, args, id) {
      let newLocals, value;
a1a3bc73   Luigi Serra   graphs updates
911
  
c5169e0e   Renato De Donato   a new hope
912
913
914
915
      try {
        [newLocals, value] = resolveIdentifier(ctx, lang, args, id);
      } catch (err) {
        return [{ error: err }, FSI + '{{ ' + id + ' }}' + PDI];
a1a3bc73   Luigi Serra   graphs updates
916
917
      }
  
c5169e0e   Renato De Donato   a new hope
918
919
920
      if (typeof value === 'number') {
        const formatter = ctx._getNumberFormatter(lang);
        return [newLocals, formatter.format(value)];
a1a3bc73   Luigi Serra   graphs updates
921
922
      }
  
c5169e0e   Renato De Donato   a new hope
923
924
925
926
927
928
      if (typeof value === 'string') {
        // prevent Billion Laughs attacks
        if (value.length >= MAX_PLACEABLE_LENGTH) {
          throw new L10nError('Too many characters in placeable (' +
                              value.length + ', max allowed is ' +
                              MAX_PLACEABLE_LENGTH + ')');
0e9aeacd   root   localization l20n
929
        }
c5169e0e   Renato De Donato   a new hope
930
        return [newLocals, FSI + value + PDI];
a1a3bc73   Luigi Serra   graphs updates
931
932
      }
  
c5169e0e   Renato De Donato   a new hope
933
934
      return [{}, FSI + '{{ ' + id + ' }}' + PDI];
    }
a1a3bc73   Luigi Serra   graphs updates
935
  
c5169e0e   Renato De Donato   a new hope
936
937
938
939
940
941
942
943
    function interpolate(locals, ctx, lang, args, arr) {
      return arr.reduce(function([localsSeq, valueSeq], cur) {
        if (typeof cur === 'string') {
          return [localsSeq, valueSeq + cur];
        } else {
          const [, value] = subPlaceable(locals, ctx, lang, args, cur.name);
          // wrap the substitution in bidi isolate characters
          return [localsSeq, valueSeq + value];
0e9aeacd   root   localization l20n
944
        }
c5169e0e   Renato De Donato   a new hope
945
946
      }, [locals, '']);
    }
a1a3bc73   Luigi Serra   graphs updates
947
  
c5169e0e   Renato De Donato   a new hope
948
949
950
951
952
953
954
955
956
957
    function resolveSelector(ctx, lang, args, expr, index) {
      //XXX: Dehardcode!!!
      let selectorName;
      if (index[0].type === 'call' && index[0].expr.type === 'prop' &&
          index[0].expr.expr.name === 'cldr') {
        selectorName = 'plural';
      } else {
        selectorName = index[0].name;
      }
      const selector = resolveIdentifier(ctx, lang, args, selectorName)[1];
a1a3bc73   Luigi Serra   graphs updates
958
  
c5169e0e   Renato De Donato   a new hope
959
960
961
962
      if (typeof selector !== 'function') {
        // selector is a simple reference to an entity or args
        return selector;
      }
a1a3bc73   Luigi Serra   graphs updates
963
  
c5169e0e   Renato De Donato   a new hope
964
965
      const argValue = index[0].args ?
        resolveIdentifier(ctx, lang, args, index[0].args[0].name)[1] : undefined;
a1a3bc73   Luigi Serra   graphs updates
966
  
c5169e0e   Renato De Donato   a new hope
967
968
969
970
971
972
973
974
975
976
      if (selectorName === 'plural') {
        // special cases for zero, one, two if they are defined on the hash
        if (argValue === 0 && 'zero' in expr) {
          return 'zero';
        }
        if (argValue === 1 && 'one' in expr) {
          return 'one';
        }
        if (argValue === 2 && 'two' in expr) {
          return 'two';
0e9aeacd   root   localization l20n
977
        }
a1a3bc73   Luigi Serra   graphs updates
978
979
      }
  
c5169e0e   Renato De Donato   a new hope
980
981
      return selector(argValue);
    }
a1a3bc73   Luigi Serra   graphs updates
982
  
c5169e0e   Renato De Donato   a new hope
983
984
985
    function resolveValue(locals, ctx, lang, args, expr, index) {
      if (!expr) {
        return [locals, expr];
a1a3bc73   Luigi Serra   graphs updates
986
987
      }
  
c5169e0e   Renato De Donato   a new hope
988
989
990
991
992
      if (typeof expr === 'string' ||
          typeof expr === 'boolean' ||
          typeof expr === 'number') {
        return [locals, expr];
      }
a1a3bc73   Luigi Serra   graphs updates
993
  
c5169e0e   Renato De Donato   a new hope
994
995
      if (Array.isArray(expr)) {
        return interpolate(locals, ctx, lang, args, expr);
a1a3bc73   Luigi Serra   graphs updates
996
997
      }
  
c5169e0e   Renato De Donato   a new hope
998
999
1000
1001
1002
1003
      // otherwise, it's a dict
      if (index) {
        // try to use the index in order to select the right dict member
        const selector = resolveSelector(ctx, lang, args, expr, index);
        if (selector in expr) {
          return resolveValue(locals, ctx, lang, args, expr[selector]);
0e9aeacd   root   localization l20n
1004
        }
a1a3bc73   Luigi Serra   graphs updates
1005
1006
      }
  
c5169e0e   Renato De Donato   a new hope
1007
1008
1009
1010
1011
      // if there was no index or no selector was found, try the default
      // XXX 'other' is an artifact from Gaia
      const defaultKey = expr.__default || 'other';
      if (defaultKey in expr) {
        return resolveValue(locals, ctx, lang, args, expr[defaultKey]);
a1a3bc73   Luigi Serra   graphs updates
1012
1013
      }
  
c5169e0e   Renato De Donato   a new hope
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
      throw new L10nError('Unresolvable value');
    }
  
    const locales2rules = {
      'af': 3,
      'ak': 4,
      'am': 4,
      'ar': 1,
      'asa': 3,
      'az': 0,
      'be': 11,
      'bem': 3,
      'bez': 3,
      'bg': 3,
      'bh': 4,
      'bm': 0,
      'bn': 3,
      'bo': 0,
      'br': 20,
      'brx': 3,
      'bs': 11,
      'ca': 3,
      'cgg': 3,
      'chr': 3,
      'cs': 12,
      'cy': 17,
      'da': 3,
      'de': 3,
      'dv': 3,
      'dz': 0,
      'ee': 3,
      'el': 3,
      'en': 3,
      'eo': 3,
      'es': 3,
      'et': 3,
      'eu': 3,
      'fa': 0,
      'ff': 5,
      'fi': 3,
      'fil': 4,
      'fo': 3,
      'fr': 5,
      'fur': 3,
      'fy': 3,
      'ga': 8,
      'gd': 24,
      'gl': 3,
      'gsw': 3,
      'gu': 3,
      'guw': 4,
      'gv': 23,
      'ha': 3,
      'haw': 3,
      'he': 2,
      'hi': 4,
      'hr': 11,
      'hu': 0,
      'id': 0,
      'ig': 0,
      'ii': 0,
      'is': 3,
      'it': 3,
      'iu': 7,
      'ja': 0,
      'jmc': 3,
      'jv': 0,
      'ka': 0,
      'kab': 5,
      'kaj': 3,
      'kcg': 3,
      'kde': 0,
      'kea': 0,
      'kk': 3,
      'kl': 3,
      'km': 0,
      'kn': 0,
      'ko': 0,
      'ksb': 3,
      'ksh': 21,
      'ku': 3,
      'kw': 7,
      'lag': 18,
      'lb': 3,
      'lg': 3,
      'ln': 4,
      'lo': 0,
      'lt': 10,
      'lv': 6,
      'mas': 3,
      'mg': 4,
      'mk': 16,
      'ml': 3,
      'mn': 3,
      'mo': 9,
      'mr': 3,
      'ms': 0,
      'mt': 15,
      'my': 0,
      'nah': 3,
      'naq': 7,
      'nb': 3,
      'nd': 3,
      'ne': 3,
      'nl': 3,
      'nn': 3,
      'no': 3,
      'nr': 3,
      'nso': 4,
      'ny': 3,
      'nyn': 3,
      'om': 3,
      'or': 3,
      'pa': 3,
      'pap': 3,
      'pl': 13,
      'ps': 3,
      'pt': 3,
      'rm': 3,
      'ro': 9,
      'rof': 3,
      'ru': 11,
      'rwk': 3,
      'sah': 0,
      'saq': 3,
      'se': 7,
      'seh': 3,
      'ses': 0,
      'sg': 0,
      'sh': 11,
      'shi': 19,
      'sk': 12,
      'sl': 14,
      'sma': 7,
      'smi': 7,
      'smj': 7,
      'smn': 7,
      'sms': 7,
      'sn': 3,
      'so': 3,
      'sq': 3,
      'sr': 11,
      'ss': 3,
      'ssy': 3,
      'st': 3,
      'sv': 3,
      'sw': 3,
      'syr': 3,
      'ta': 3,
      'te': 3,
      'teo': 3,
      'th': 0,
      'ti': 4,
      'tig': 3,
      'tk': 3,
      'tl': 4,
      'tn': 3,
      'to': 0,
      'tr': 0,
      'ts': 3,
      'tzm': 22,
      'uk': 11,
      'ur': 3,
      've': 3,
      'vi': 0,
      'vun': 3,
      'wa': 4,
      'wae': 3,
      'wo': 0,
      'xh': 3,
      'xog': 3,
      'yo': 0,
      'zh': 0,
      'zu': 3
    };
  
    // utility functions for plural rules methods
    function isIn(n, list) {
      return list.indexOf(n) !== -1;
a1a3bc73   Luigi Serra   graphs updates
1193
    }
c5169e0e   Renato De Donato   a new hope
1194
1195
    function isBetween(n, start, end) {
      return typeof n === typeof start && start <= n && n <= end;
a1a3bc73   Luigi Serra   graphs updates
1196
1197
    }
  
c5169e0e   Renato De Donato   a new hope
1198
1199
1200
1201
1202
    // list of all plural rules methods:
    // map an integer to the plural form name to use
    const pluralRules = {
      '0': function() {
        return 'other';
0e9aeacd   root   localization l20n
1203
      },
c5169e0e   Renato De Donato   a new hope
1204
1205
1206
      '1': function(n) {
        if ((isBetween((n % 100), 3, 10))) {
          return 'few';
0e9aeacd   root   localization l20n
1207
        }
c5169e0e   Renato De Donato   a new hope
1208
1209
        if (n === 0) {
          return 'zero';
0e9aeacd   root   localization l20n
1210
        }
c5169e0e   Renato De Donato   a new hope
1211
1212
        if ((isBetween((n % 100), 11, 99))) {
          return 'many';
0e9aeacd   root   localization l20n
1213
        }
c5169e0e   Renato De Donato   a new hope
1214
1215
        if (n === 2) {
          return 'two';
a1a3bc73   Luigi Serra   graphs updates
1216
        }
c5169e0e   Renato De Donato   a new hope
1217
1218
        if (n === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1219
        }
c5169e0e   Renato De Donato   a new hope
1220
        return 'other';
0e9aeacd   root   localization l20n
1221
      },
c5169e0e   Renato De Donato   a new hope
1222
1223
1224
      '2': function(n) {
        if (n !== 0 && (n % 10) === 0) {
          return 'many';
0e9aeacd   root   localization l20n
1225
        }
c5169e0e   Renato De Donato   a new hope
1226
1227
        if (n === 2) {
          return 'two';
0e9aeacd   root   localization l20n
1228
        }
c5169e0e   Renato De Donato   a new hope
1229
1230
        if (n === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1231
        }
c5169e0e   Renato De Donato   a new hope
1232
1233
1234
1235
1236
        return 'other';
      },
      '3': function(n) {
        if (n === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1237
        }
c5169e0e   Renato De Donato   a new hope
1238
        return 'other';
0e9aeacd   root   localization l20n
1239
      },
c5169e0e   Renato De Donato   a new hope
1240
1241
1242
      '4': function(n) {
        if ((isBetween(n, 0, 1))) {
          return 'one';
0e9aeacd   root   localization l20n
1243
        }
c5169e0e   Renato De Donato   a new hope
1244
1245
1246
1247
1248
        return 'other';
      },
      '5': function(n) {
        if ((isBetween(n, 0, 2)) && n !== 2) {
          return 'one';
0e9aeacd   root   localization l20n
1249
        }
c5169e0e   Renato De Donato   a new hope
1250
        return 'other';
0e9aeacd   root   localization l20n
1251
      },
c5169e0e   Renato De Donato   a new hope
1252
1253
1254
      '6': function(n) {
        if (n === 0) {
          return 'zero';
0e9aeacd   root   localization l20n
1255
        }
c5169e0e   Renato De Donato   a new hope
1256
1257
1258
1259
        if ((n % 10) === 1 && (n % 100) !== 11) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1260
      },
c5169e0e   Renato De Donato   a new hope
1261
1262
1263
      '7': function(n) {
        if (n === 2) {
          return 'two';
0e9aeacd   root   localization l20n
1264
        }
c5169e0e   Renato De Donato   a new hope
1265
1266
        if (n === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1267
        }
c5169e0e   Renato De Donato   a new hope
1268
        return 'other';
0e9aeacd   root   localization l20n
1269
      },
c5169e0e   Renato De Donato   a new hope
1270
1271
1272
      '8': function(n) {
        if ((isBetween(n, 3, 6))) {
          return 'few';
0e9aeacd   root   localization l20n
1273
        }
c5169e0e   Renato De Donato   a new hope
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
        if ((isBetween(n, 7, 10))) {
          return 'many';
        }
        if (n === 2) {
          return 'two';
        }
        if (n === 1) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1284
      },
c5169e0e   Renato De Donato   a new hope
1285
1286
1287
      '9': function(n) {
        if (n === 0 || n !== 1 && (isBetween((n % 100), 1, 19))) {
          return 'few';
0e9aeacd   root   localization l20n
1288
        }
c5169e0e   Renato De Donato   a new hope
1289
1290
1291
1292
        if (n === 1) {
          return 'one';
        }
        return 'other';
a1a3bc73   Luigi Serra   graphs updates
1293
      },
c5169e0e   Renato De Donato   a new hope
1294
1295
1296
      '10': function(n) {
        if ((isBetween((n % 10), 2, 9)) && !(isBetween((n % 100), 11, 19))) {
          return 'few';
0e9aeacd   root   localization l20n
1297
        }
c5169e0e   Renato De Donato   a new hope
1298
1299
        if ((n % 10) === 1 && !(isBetween((n % 100), 11, 19))) {
          return 'one';
0e9aeacd   root   localization l20n
1300
        }
c5169e0e   Renato De Donato   a new hope
1301
        return 'other';
0e9aeacd   root   localization l20n
1302
      },
c5169e0e   Renato De Donato   a new hope
1303
1304
1305
      '11': function(n) {
        if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) {
          return 'few';
0e9aeacd   root   localization l20n
1306
        }
c5169e0e   Renato De Donato   a new hope
1307
1308
1309
1310
        if ((n % 10) === 0 ||
            (isBetween((n % 10), 5, 9)) ||
            (isBetween((n % 100), 11, 14))) {
          return 'many';
0e9aeacd   root   localization l20n
1311
        }
c5169e0e   Renato De Donato   a new hope
1312
1313
        if ((n % 10) === 1 && (n % 100) !== 11) {
          return 'one';
a1a3bc73   Luigi Serra   graphs updates
1314
        }
c5169e0e   Renato De Donato   a new hope
1315
1316
1317
1318
1319
1320
1321
1322
        return 'other';
      },
      '12': function(n) {
        if ((isBetween(n, 2, 4))) {
          return 'few';
        }
        if (n === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1323
        }
c5169e0e   Renato De Donato   a new hope
1324
        return 'other';
0e9aeacd   root   localization l20n
1325
      },
c5169e0e   Renato De Donato   a new hope
1326
1327
1328
      '13': function(n) {
        if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) {
          return 'few';
0e9aeacd   root   localization l20n
1329
        }
c5169e0e   Renato De Donato   a new hope
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
        if (n !== 1 && (isBetween((n % 10), 0, 1)) ||
            (isBetween((n % 10), 5, 9)) ||
            (isBetween((n % 100), 12, 14))) {
          return 'many';
        }
        if (n === 1) {
          return 'one';
        }
        return 'other';
      },
      '14': function(n) {
        if ((isBetween((n % 100), 3, 4))) {
          return 'few';
        }
        if ((n % 100) === 2) {
          return 'two';
        }
        if ((n % 100) === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1349
        }
c5169e0e   Renato De Donato   a new hope
1350
        return 'other';
0e9aeacd   root   localization l20n
1351
      },
c5169e0e   Renato De Donato   a new hope
1352
1353
1354
1355
1356
1357
      '15': function(n) {
        if (n === 0 || (isBetween((n % 100), 2, 10))) {
          return 'few';
        }
        if ((isBetween((n % 100), 11, 19))) {
          return 'many';
0e9aeacd   root   localization l20n
1358
        }
c5169e0e   Renato De Donato   a new hope
1359
1360
1361
1362
        if (n === 1) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1363
      },
c5169e0e   Renato De Donato   a new hope
1364
1365
1366
      '16': function(n) {
        if ((n % 10) === 1 && n !== 11) {
          return 'one';
0e9aeacd   root   localization l20n
1367
        }
c5169e0e   Renato De Donato   a new hope
1368
        return 'other';
0e9aeacd   root   localization l20n
1369
      },
c5169e0e   Renato De Donato   a new hope
1370
1371
1372
      '17': function(n) {
        if (n === 3) {
          return 'few';
0e9aeacd   root   localization l20n
1373
        }
c5169e0e   Renato De Donato   a new hope
1374
1375
        if (n === 0) {
          return 'zero';
0e9aeacd   root   localization l20n
1376
        }
c5169e0e   Renato De Donato   a new hope
1377
1378
        if (n === 6) {
          return 'many';
0e9aeacd   root   localization l20n
1379
        }
c5169e0e   Renato De Donato   a new hope
1380
1381
        if (n === 2) {
          return 'two';
0e9aeacd   root   localization l20n
1382
        }
c5169e0e   Renato De Donato   a new hope
1383
1384
        if (n === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1385
        }
c5169e0e   Renato De Donato   a new hope
1386
1387
1388
1389
1390
        return 'other';
      },
      '18': function(n) {
        if (n === 0) {
          return 'zero';
0e9aeacd   root   localization l20n
1391
        }
c5169e0e   Renato De Donato   a new hope
1392
1393
1394
1395
        if ((isBetween(n, 0, 2)) && n !== 0 && n !== 2) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1396
      },
c5169e0e   Renato De Donato   a new hope
1397
1398
1399
      '19': function(n) {
        if ((isBetween(n, 2, 10))) {
          return 'few';
0e9aeacd   root   localization l20n
1400
        }
c5169e0e   Renato De Donato   a new hope
1401
1402
1403
1404
        if ((isBetween(n, 0, 1))) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1405
      },
c5169e0e   Renato De Donato   a new hope
1406
1407
1408
1409
1410
1411
1412
      '20': function(n) {
        if ((isBetween((n % 10), 3, 4) || ((n % 10) === 9)) && !(
            isBetween((n % 100), 10, 19) ||
            isBetween((n % 100), 70, 79) ||
            isBetween((n % 100), 90, 99)
            )) {
          return 'few';
0e9aeacd   root   localization l20n
1413
        }
c5169e0e   Renato De Donato   a new hope
1414
1415
        if ((n % 1000000) === 0 && n !== 0) {
          return 'many';
0e9aeacd   root   localization l20n
1416
        }
c5169e0e   Renato De Donato   a new hope
1417
1418
        if ((n % 10) === 2 && !isIn((n % 100), [12, 72, 92])) {
          return 'two';
0e9aeacd   root   localization l20n
1419
        }
c5169e0e   Renato De Donato   a new hope
1420
1421
        if ((n % 10) === 1 && !isIn((n % 100), [11, 71, 91])) {
          return 'one';
0e9aeacd   root   localization l20n
1422
        }
c5169e0e   Renato De Donato   a new hope
1423
        return 'other';
a1a3bc73   Luigi Serra   graphs updates
1424
      },
c5169e0e   Renato De Donato   a new hope
1425
1426
1427
1428
1429
1430
      '21': function(n) {
        if (n === 0) {
          return 'zero';
        }
        if (n === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1431
        }
c5169e0e   Renato De Donato   a new hope
1432
1433
1434
1435
1436
        return 'other';
      },
      '22': function(n) {
        if ((isBetween(n, 0, 1)) || (isBetween(n, 11, 99))) {
          return 'one';
a1a3bc73   Luigi Serra   graphs updates
1437
        }
c5169e0e   Renato De Donato   a new hope
1438
        return 'other';
a1a3bc73   Luigi Serra   graphs updates
1439
      },
c5169e0e   Renato De Donato   a new hope
1440
1441
1442
      '23': function(n) {
        if ((isBetween((n % 10), 1, 2)) || (n % 20) === 0) {
          return 'one';
0e9aeacd   root   localization l20n
1443
        }
c5169e0e   Renato De Donato   a new hope
1444
1445
1446
1447
1448
        return 'other';
      },
      '24': function(n) {
        if ((isBetween(n, 3, 10) || isBetween(n, 13, 19))) {
          return 'few';
a1a3bc73   Luigi Serra   graphs updates
1449
        }
c5169e0e   Renato De Donato   a new hope
1450
1451
1452
1453
1454
1455
1456
1457
1458
        if (isIn(n, [2, 12])) {
          return 'two';
        }
        if (isIn(n, [1, 11])) {
          return 'one';
        }
        return 'other';
      }
    };
0e9aeacd   root   localization l20n
1459
  
c5169e0e   Renato De Donato   a new hope
1460
1461
1462
1463
1464
1465
1466
1467
    function getPluralRule(code) {
      // return a function that gives the plural form name for a given integer
      const index = locales2rules[code.replace(/-.*$/, '')];
      if (!(index in pluralRules)) {
        return function() { return 'other'; };
      }
      return pluralRules[index];
    }
0e9aeacd   root   localization l20n
1468
  
c5169e0e   Renato De Donato   a new hope
1469
1470
1471
1472
1473
    class Context {
      constructor(env) {
        this._env = env;
        this._numberFormatters = null;
      }
0e9aeacd   root   localization l20n
1474
  
c5169e0e   Renato De Donato   a new hope
1475
1476
1477
1478
1479
1480
1481
1482
      _formatTuple(lang, args, entity, id, key) {
        try {
          return format(this, lang, args, entity);
        } catch (err) {
          err.id = key ? id + '::' + key : id;
          err.lang = lang;
          this._env.emit('resolveerror', err, this);
          return [{ error: err }, err.id];
0e9aeacd   root   localization l20n
1483
        }
c5169e0e   Renato De Donato   a new hope
1484
      }
0e9aeacd   root   localization l20n
1485
  
c5169e0e   Renato De Donato   a new hope
1486
1487
      _formatEntity(lang, args, entity, id) {
        const [, value] = this._formatTuple(lang, args, entity, id);
0e9aeacd   root   localization l20n
1488
  
c5169e0e   Renato De Donato   a new hope
1489
1490
1491
1492
        const formatted = {
          value,
          attrs: null,
        };
0e9aeacd   root   localization l20n
1493
  
c5169e0e   Renato De Donato   a new hope
1494
1495
1496
1497
1498
1499
1500
        if (entity.attrs) {
          formatted.attrs = Object.create(null);
          for (let key in entity.attrs) {
            /* jshint -W089 */
            const [, attrValue] = this._formatTuple(
              lang, args, entity.attrs[key], id, key);
            formatted.attrs[key] = attrValue;
0e9aeacd   root   localization l20n
1501
          }
a1a3bc73   Luigi Serra   graphs updates
1502
        }
0e9aeacd   root   localization l20n
1503
  
c5169e0e   Renato De Donato   a new hope
1504
1505
        return formatted;
      }
0e9aeacd   root   localization l20n
1506
  
c5169e0e   Renato De Donato   a new hope
1507
1508
1509
      _formatValue(lang, args, entity, id) {
        return this._formatTuple(lang, args, entity, id)[1];
      }
a1a3bc73   Luigi Serra   graphs updates
1510
  
c5169e0e   Renato De Donato   a new hope
1511
1512
1513
      fetch(langs) {
        if (langs.length === 0) {
          return Promise.resolve(langs);
0e9aeacd   root   localization l20n
1514
1515
        }
  
c5169e0e   Renato De Donato   a new hope
1516
        const resIds = Array.from(this._env._resLists.get(this));
0e9aeacd   root   localization l20n
1517
  
c5169e0e   Renato De Donato   a new hope
1518
1519
1520
1521
1522
        return Promise.all(
          resIds.map(
            this._env._getResource.bind(this._env, langs[0]))).then(
              () => langs);
      }
0e9aeacd   root   localization l20n
1523
  
c5169e0e   Renato De Donato   a new hope
1524
1525
      _resolve(langs, keys, formatter, prevResolved) {
        const lang = langs[0];
0e9aeacd   root   localization l20n
1526
  
c5169e0e   Renato De Donato   a new hope
1527
1528
        if (!lang) {
          return reportMissing.call(this, keys, formatter, prevResolved);
0e9aeacd   root   localization l20n
1529
        }
a1a3bc73   Luigi Serra   graphs updates
1530
  
c5169e0e   Renato De Donato   a new hope
1531
        let hasUnresolved = false;
a1a3bc73   Luigi Serra   graphs updates
1532
  
c5169e0e   Renato De Donato   a new hope
1533
1534
1535
1536
1537
1538
1539
        const resolved = keys.map((key, i) => {
          if (prevResolved && prevResolved[i] !== undefined) {
            return prevResolved[i];
          }
          const [id, args] = Array.isArray(key) ?
            key : [key, undefined];
          const entity = this._getEntity(lang, id);
0e9aeacd   root   localization l20n
1540
  
c5169e0e   Renato De Donato   a new hope
1541
1542
          if (entity) {
            return formatter.call(this, lang, args, entity, id);
a1a3bc73   Luigi Serra   graphs updates
1543
          }
c5169e0e   Renato De Donato   a new hope
1544
1545
1546
1547
1548
1549
1550
1551
1552
  
          this._env.emit('notfounderror',
            new L10nError('"' + id + '"' + ' not found in ' + lang.code,
              id, lang), this);
          hasUnresolved = true;
        });
  
        if (!hasUnresolved) {
          return resolved;
0e9aeacd   root   localization l20n
1553
        }
0e9aeacd   root   localization l20n
1554
  
c5169e0e   Renato De Donato   a new hope
1555
1556
1557
        return this.fetch(langs.slice(1)).then(
          nextLangs => this._resolve(nextLangs, keys, formatter, resolved));
      }
0e9aeacd   root   localization l20n
1558
  
c5169e0e   Renato De Donato   a new hope
1559
1560
1561
1562
      resolveEntities(langs, keys) {
        return this.fetch(langs).then(
          langs => this._resolve(langs, keys, this._formatEntity));
      }
0e9aeacd   root   localization l20n
1563
  
c5169e0e   Renato De Donato   a new hope
1564
1565
1566
1567
      resolveValues(langs, keys) {
        return this.fetch(langs).then(
          langs => this._resolve(langs, keys, this._formatValue));
      }
a1a3bc73   Luigi Serra   graphs updates
1568
  
c5169e0e   Renato De Donato   a new hope
1569
1570
1571
      _getEntity(lang, id) {
        const cache = this._env._resCache;
        const resIds = Array.from(this._env._resLists.get(this));
0e9aeacd   root   localization l20n
1572
  
c5169e0e   Renato De Donato   a new hope
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
        // Look for `id` in every resource in order.
        for (let i = 0, resId; resId = resIds[i]; i++) {
          const resource = cache.get(resId + lang.code + lang.src);
          if (resource instanceof L10nError) {
            continue;
          }
          if (id in resource) {
            return resource[id];
          }
        }
        return undefined;
      }
0e9aeacd   root   localization l20n
1585
  
c5169e0e   Renato De Donato   a new hope
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
      _getNumberFormatter(lang) {
        if (!this._numberFormatters) {
          this._numberFormatters = new Map();
        }
        if (!this._numberFormatters.has(lang)) {
          const formatter = Intl.NumberFormat(lang, {
            useGrouping: false,
          });
          this._numberFormatters.set(lang, formatter);
          return formatter;
        }
        return this._numberFormatters.get(lang);
      }
a1a3bc73   Luigi Serra   graphs updates
1599
  
c5169e0e   Renato De Donato   a new hope
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
      // XXX in the future macros will be stored in localization resources together 
      // with regular entities and this method will not be needed anymore
      _getMacro(lang, id) {
        switch(id) {
          case 'plural':
            return getPluralRule(lang.code);
          default:
            return undefined;
        }
      }
a1a3bc73   Luigi Serra   graphs updates
1610
  
c5169e0e   Renato De Donato   a new hope
1611
    }
a1a3bc73   Luigi Serra   graphs updates
1612
  
c5169e0e   Renato De Donato   a new hope
1613
1614
1615
1616
1617
1618
    function reportMissing(keys, formatter, resolved) {
      const missingIds = new Set();
  
      keys.forEach((key, i) => {
        if (resolved && resolved[i] !== undefined) {
          return;
a1a3bc73   Luigi Serra   graphs updates
1619
        }
c5169e0e   Renato De Donato   a new hope
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
        const id = Array.isArray(key) ? key[0] : key;
        missingIds.add(id);
        resolved[i] = formatter === this._formatValue ?
          id : {value: id, attrs: null};
      });
  
      this._env.emit('notfounderror', new L10nError(
        '"' + Array.from(missingIds).join(', ') + '"' +
        ' not found in any language', missingIds), this);
  
      return resolved;
    }
0e9aeacd   root   localization l20n
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
  
    // Walk an entry node searching for content leaves
    function walkEntry(entry, fn) {
      if (typeof entry === 'string') {
        return fn(entry);
      }
  
      const newEntry = Object.create(null);
  
      if (entry.value) {
        newEntry.value = walkValue(entry.value, fn);
      }
  
      if (entry.index) {
        newEntry.index = entry.index;
      }
  
      if (entry.attrs) {
        newEntry.attrs = Object.create(null);
        for (let key in entry.attrs) {
          newEntry.attrs[key] = walkEntry(entry.attrs[key], fn);
        }
      }
  
      return newEntry;
    }
  
    function walkValue(value, fn) {
      if (typeof value === 'string') {
        return fn(value);
      }
  
      // skip expressions in placeables
      if (value.type) {
        return value;
      }
  
      const newValue = Array.isArray(value) ? [] : Object.create(null);
      const keys = Object.keys(value);
  
      for (let i = 0, key; (key = keys[i]); i++) {
        newValue[key] = walkValue(value[key], fn);
      }
  
      return newValue;
    }
  
    /* Pseudolocalizations
     *
     * pseudo is a dict of strategies to be used to modify the English
     * context in order to create pseudolocalizations.  These can be used by
     * developers to test the localizability of their code without having to
     * actually speak a foreign language.
     *
     * Currently, the following pseudolocales are supported:
     *
     *   fr-x-psaccent - Ȧȧƈƈḗḗƞŧḗḗḓ Ḗḗƞɠŀīīşħ
     *
     *     In Accented English all English letters are replaced by accented
     *     Unicode counterparts which don't impair the readability of the content.
     *     This allows developers to quickly test if any given string is being
     *     correctly displayed in its 'translated' form.  Additionally, simple
     *     heuristics are used to make certain words longer to better simulate the
     *     experience of international users.
     *
     *   ar-x-psbidi - ɥsıʅƃuƎ ıpıԐ
     *
     *     Bidi English is a fake RTL locale.  All words are surrounded by
     *     Unicode formatting marks forcing the RTL directionality of characters.
     *     In addition, to make the reversed text easier to read, individual
     *     letters are flipped.
     *
     *     Note: The name above is hardcoded to be RTL in case code editors have
     *     trouble with the RLO and PDF Unicode marks.  In reality, it should be
     *     surrounded by those marks as well.
     *
     * See https://bugzil.la/900182 for more information.
     *
     */
  
    function createGetter(id, name) {
      let _pseudo = null;
  
      return function getPseudo() {
        if (_pseudo) {
          return _pseudo;
        }
  
        const reAlphas = /[a-zA-Z]/g;
        const reVowels = /[aeiouAEIOU]/g;
        const reWords = /[^\W0-9_]+/g;
        // strftime tokens (%a, %Eb), template {vars}, HTML entities (&#x202a;)
        // and HTML tags.
        const reExcluded = /(%[EO]?\w|\{\s*.+?\s*\}|&[#\w]+;|<\s*.+?\s*>)/;
  
        const charMaps = {
          'fr-x-psaccent':
            'ȦƁƇḒḖƑƓĦĪĴĶĿḾȠǾƤɊŘŞŦŬṼẆẊẎẐ[\\]^_`ȧƀƈḓḗƒɠħīĵķŀḿƞǿƥɋřşŧŭṽẇẋẏẑ',
          'ar-x-psbidi':
            // XXX Use pɟפ˥ʎ as replacements for ᗡℲ⅁⅂⅄. https://bugzil.la/1007340
            '∀ԐↃpƎɟפHIſӼ˥WNOԀÒᴚS⊥∩ɅMXʎZ[\\]ᵥ_,ɐqɔpǝɟƃɥıɾʞʅɯuodbɹsʇnʌʍxʎz',
        };
  
        const mods = {
          'fr-x-psaccent': val =>
            val.replace(reVowels, match => match + match.toLowerCase()),
  
          // Surround each word with Unicode formatting codes, RLO and PDF:
          //   U+202E:   RIGHT-TO-LEFT OVERRIDE (RLO)
          //   U+202C:   POP DIRECTIONAL FORMATTING (PDF)
          // See http://www.w3.org/International/questions/qa-bidi-controls
          'ar-x-psbidi': val =>
            val.replace(reWords, match => '\u202e' + match + '\u202c'),
        };
  
        // Replace each Latin letter with a Unicode character from map
        const replaceChars =
          (map, val) => val.replace(
            reAlphas, match => map.charAt(match.charCodeAt(0) - 65));
  
        const transform =
          val => replaceChars(charMaps[id], mods[id](val));
  
        // apply fn to translatable parts of val
        const apply = (fn, val) => {
          if (!val) {
            return val;
          }
  
          const parts = val.split(reExcluded);
          const modified = parts.map(function(part) {
            if (reExcluded.test(part)) {
              return part;
            }
            return fn(part);
          });
          return modified.join('');
        };
  
        return _pseudo = {
          name: transform(name),
          process: str => apply(transform, str)
        };
      };
    }
  
    const pseudo = Object.defineProperties(Object.create(null), {
      'fr-x-psaccent': {
        enumerable: true,
        get: createGetter('fr-x-psaccent', 'Runtime Accented')
      },
      'ar-x-psbidi': {
        enumerable: true,
        get: createGetter('ar-x-psbidi', 'Runtime Bidi')
      }
    });
  
c5169e0e   Renato De Donato   a new hope
1789
1790
1791
1792
1793
    const parsers = {
      properties: PropertiesParser,
      l20n: L20nParser,
    };
  
0e9aeacd   root   localization l20n
1794
    class Env {
c5169e0e   Renato De Donato   a new hope
1795
1796
      constructor(defaultLang, fetchResource) {
        this.defaultLang = defaultLang;
0e9aeacd   root   localization l20n
1797
1798
        this.fetchResource = fetchResource;
  
c5169e0e   Renato De Donato   a new hope
1799
1800
        this._resLists = new Map();
        this._resCache = new Map();
0e9aeacd   root   localization l20n
1801
1802
1803
1804
1805
1806
1807
  
        const listeners = {};
        this.emit = emit.bind(this, listeners);
        this.addEventListener = addEventListener.bind(this, listeners);
        this.removeEventListener = removeEventListener.bind(this, listeners);
      }
  
c5169e0e   Renato De Donato   a new hope
1808
1809
1810
      createContext(resIds) {
        const ctx = new Context(this);
        this._resLists.set(ctx, new Set(resIds));
0e9aeacd   root   localization l20n
1811
1812
1813
1814
        return ctx;
      }
  
      destroyContext(ctx) {
c5169e0e   Renato De Donato   a new hope
1815
1816
        const lists = this._resLists;
        const resList = lists.get(ctx);
0e9aeacd   root   localization l20n
1817
  
c5169e0e   Renato De Donato   a new hope
1818
1819
1820
        lists.delete(ctx);
        resList.forEach(
          resId => deleteIfOrphan(this._resCache, lists, resId));
0e9aeacd   root   localization l20n
1821
1822
1823
      }
  
      _parse(syntax, lang, data) {
c5169e0e   Renato De Donato   a new hope
1824
        const parser = parsers[syntax];
0e9aeacd   root   localization l20n
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
        if (!parser) {
          return data;
        }
  
        const emit = (type, err) => this.emit(type, amendError(lang, err));
        return parser.parse.call(parser, emit, data);
      }
  
      _create(lang, entries) {
        if (lang.src !== 'pseudo') {
          return entries;
        }
  
        const pseudoentries = Object.create(null);
        for (let key in entries) {
          pseudoentries[key] = walkEntry(
            entries[key], pseudo[lang.code].process);
        }
        return pseudoentries;
      }
  
      _getResource(lang, res) {
c5169e0e   Renato De Donato   a new hope
1847
        const cache = this._resCache;
0e9aeacd   root   localization l20n
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
        const id = res + lang.code + lang.src;
  
        if (cache.has(id)) {
          return cache.get(id);
        }
  
        const syntax = res.substr(res.lastIndexOf('.') + 1);
  
        const saveEntries = data => {
          const entries = this._parse(syntax, lang, data);
          cache.set(id, this._create(lang, entries));
        };
  
        const recover = err => {
          err.lang = lang;
          this.emit('fetcherror', err);
          cache.set(id, err);
        };
  
        const langToFetch = lang.src === 'pseudo' ?
c5169e0e   Renato De Donato   a new hope
1868
          { code: this.defaultLang, src: 'app' } :
0e9aeacd   root   localization l20n
1869
1870
          lang;
  
c5169e0e   Renato De Donato   a new hope
1871
1872
        const resource = this.fetchResource(res, langToFetch).then(
          saveEntries, recover);
0e9aeacd   root   localization l20n
1873
1874
1875
1876
1877
1878
1879
  
        cache.set(id, resource);
  
        return resource;
      }
    }
  
c5169e0e   Renato De Donato   a new hope
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
    function deleteIfOrphan(cache, lists, resId) {
      const isNeeded = Array.from(lists).some(
        ([ctx, resIds]) => resIds.has(resId));
  
      if (!isNeeded) {
        cache.forEach((val, key) =>
          key.startsWith(resId) ? cache.delete(key) : null);
      }
    }
  
0e9aeacd   root   localization l20n
1890
1891
1892
1893
1894
    function amendError(lang, err) {
      err.lang = lang;
      return err;
    }
  
c5169e0e   Renato De Donato   a new hope
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
    // Polyfill NodeList.prototype[Symbol.iterator] for Chrome.
    // See https://code.google.com/p/chromium/issues/detail?id=401699
    if (typeof NodeList === 'function' && !NodeList.prototype[Symbol.iterator]) {
      NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
    }
  
    // A document.ready shim
    // https://github.com/whatwg/html/issues/127
    function documentReady() {
      if (document.readyState !== 'loading') {
        return Promise.resolve();
      }
  
      return new Promise(resolve => {
        document.addEventListener('readystatechange', function onrsc() {
          document.removeEventListener('readystatechange', onrsc);
          resolve();
        });
      });
    }
  
    // Intl.Locale
    function getDirection(code) {
      const tag = code.split('-')[0];
      return ['ar', 'he', 'fa', 'ps', 'ur'].indexOf(tag) >= 0 ?
        'rtl' : 'ltr';
    }
  
0e9aeacd   root   localization l20n
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
    function prioritizeLocales(def, availableLangs, requested) {
      let supportedLocale;
      // Find the first locale in the requested list that is supported.
      for (let i = 0; i < requested.length; i++) {
        const locale = requested[i];
        if (availableLangs.indexOf(locale) !== -1) {
          supportedLocale = locale;
          break;
        }
      }
      if (!supportedLocale ||
          supportedLocale === def) {
        return [def];
      }
  
      return [supportedLocale, def];
    }
  
c5169e0e   Renato De Donato   a new hope
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
    function getMeta(head) {
      let availableLangs = Object.create(null);
      let defaultLang = null;
      let appVersion = null;
  
      // XXX take last found instead of first?
      const metas = head.querySelectorAll(
        'meta[name="availableLanguages"],' +
        'meta[name="defaultLanguage"],' +
        'meta[name="appVersion"]');
      for (let meta of metas) {
        const name = meta.getAttribute('name');
        const content = meta.getAttribute('content').trim();
        switch (name) {
          case 'availableLanguages':
            availableLangs = getLangRevisionMap(
              availableLangs, content);
            break;
          case 'defaultLanguage':
            const [lang, rev] = getLangRevisionTuple(content);
            defaultLang = lang;
            if (!(lang in availableLangs)) {
              availableLangs[lang] = rev;
            }
            break;
          case 'appVersion':
            appVersion = content;
        }
      }
  
      return {
        defaultLang,
        availableLangs,
        appVersion
      };
    }
  
    function getLangRevisionMap(seq, str) {
      return str.split(',').reduce((seq, cur) => {
        const [lang, rev] = getLangRevisionTuple(cur);
        seq[lang] = rev;
        return seq;
      }, seq);
    }
  
    function getLangRevisionTuple(str) {
      const [lang, rev]  = str.trim().split(':');
      // if revision is missing, use NaN
      return [lang, parseInt(rev)];
    }
  
0e9aeacd   root   localization l20n
1992
    function negotiateLanguages(
c5169e0e   Renato De Donato   a new hope
1993
      fn, appVersion, defaultLang, availableLangs, additionalLangs, prevLangs,
0e9aeacd   root   localization l20n
1994
1995
      requestedLangs) {
  
c5169e0e   Renato De Donato   a new hope
1996
1997
      const allAvailableLangs = Object.keys(availableLangs).concat(
        additionalLangs || []).concat(Object.keys(pseudo));
0e9aeacd   root   localization l20n
1998
1999
2000
2001
2002
2003
      const newLangs = prioritizeLocales(
        defaultLang, allAvailableLangs, requestedLangs);
  
      const langs = newLangs.map(code => ({
        code: code,
        src: getLangSource(appVersion, availableLangs, additionalLangs, code),
0e9aeacd   root   localization l20n
2004
2005
      }));
  
c5169e0e   Renato De Donato   a new hope
2006
2007
2008
2009
2010
      if (!arrEqual(prevLangs, newLangs)) {
        fn(langs);
      }
  
      return langs;
0e9aeacd   root   localization l20n
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
    }
  
    function arrEqual(arr1, arr2) {
      return arr1.length === arr2.length &&
        arr1.every((elem, i) => elem === arr2[i]);
    }
  
    function getMatchingLangpack(appVersion, langpacks) {
      for (let i = 0, langpack; (langpack = langpacks[i]); i++) {
        if (langpack.target === appVersion) {
          return langpack;
        }
      }
      return null;
    }
  
    function getLangSource(appVersion, availableLangs, additionalLangs, code) {
      if (additionalLangs && additionalLangs[code]) {
        const lp = getMatchingLangpack(appVersion, additionalLangs[code]);
        if (lp &&
            (!(code in availableLangs) ||
             parseInt(lp.revision) > availableLangs[code])) {
          return 'extra';
        }
      }
  
      if ((code in pseudo) && !(code in availableLangs)) {
        return 'pseudo';
      }
  
      return 'app';
    }
  
    class Remote {
c5169e0e   Renato De Donato   a new hope
2045
2046
      constructor(fetchResource, broadcast, requestedLangs) {
        this.fetchResource = fetchResource;
0e9aeacd   root   localization l20n
2047
        this.broadcast = broadcast;
0e9aeacd   root   localization l20n
2048
        this.ctxs = new Map();
c5169e0e   Renato De Donato   a new hope
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
        this.interactive = documentReady().then(
          () => this.init(requestedLangs));
      }
  
      init(requestedLangs) {
        const meta = getMeta(document.head);
        this.defaultLanguage = meta.defaultLang;
        this.availableLanguages = meta.availableLangs;
        this.appVersion = meta.appVersion;
  
        this.env = new Env(
          this.defaultLanguage,
          (...args) => this.fetchResource(this.appVersion, ...args));
  
        return this.requestLanguages(requestedLangs);
0e9aeacd   root   localization l20n
2064
2065
      }
  
c5169e0e   Renato De Donato   a new hope
2066
2067
2068
2069
2070
      registerView(view, resources) {
        return this.interactive.then(() => {
          this.ctxs.set(view, this.env.createContext(resources));
          return true;
        });
0e9aeacd   root   localization l20n
2071
2072
2073
      }
  
      unregisterView(view) {
c5169e0e   Renato De Donato   a new hope
2074
        return this.ctxs.delete(view);
0e9aeacd   root   localization l20n
2075
2076
      }
  
c5169e0e   Renato De Donato   a new hope
2077
2078
      resolveEntities(view, langs, keys) {
        return this.ctxs.get(view).resolveEntities(langs, keys);
0e9aeacd   root   localization l20n
2079
2080
2081
      }
  
      formatValues(view, keys) {
c5169e0e   Renato De Donato   a new hope
2082
2083
        return this.languages.then(
          langs => this.ctxs.get(view).resolveValues(langs, keys));
0e9aeacd   root   localization l20n
2084
2085
      }
  
c5169e0e   Renato De Donato   a new hope
2086
2087
      resolvedLanguages() {
        return this.languages;
0e9aeacd   root   localization l20n
2088
2089
2090
      }
  
      requestLanguages(requestedLangs) {
c5169e0e   Renato De Donato   a new hope
2091
2092
        return changeLanguages.call(
          this, getAdditionalLanguages(), requestedLangs);
0e9aeacd   root   localization l20n
2093
2094
2095
2096
2097
2098
2099
2100
2101
      }
  
      getName(code) {
        return pseudo[code].name;
      }
  
      processString(code, str) {
        return pseudo[code].process(str);
      }
0e9aeacd   root   localization l20n
2102
  
c5169e0e   Renato De Donato   a new hope
2103
2104
2105
      handleEvent(evt) {
        return changeLanguages.call(
          this, evt.detail || getAdditionalLanguages(), navigator.languages);
0e9aeacd   root   localization l20n
2106
      }
a1a3bc73   Luigi Serra   graphs updates
2107
    }
0e9aeacd   root   localization l20n
2108
  
c5169e0e   Renato De Donato   a new hope
2109
2110
2111
2112
    function getAdditionalLanguages() {
      if (navigator.mozApps && navigator.mozApps.getAdditionalLanguages) {
        return navigator.mozApps.getAdditionalLanguages().catch(
          () => []);
a1a3bc73   Luigi Serra   graphs updates
2113
      }
c5169e0e   Renato De Donato   a new hope
2114
2115
  
      return Promise.resolve([]);
0e9aeacd   root   localization l20n
2116
2117
    }
  
c5169e0e   Renato De Donato   a new hope
2118
2119
2120
2121
2122
2123
2124
2125
    function changeLanguages(additionalLangs, requestedLangs) {
      const prevLangs = this.languages || [];
      return this.languages = Promise.all([
        additionalLangs, prevLangs]).then(
          ([additionalLangs, prevLangs]) => negotiateLanguages(
            this.broadcast.bind(this, 'translateDocument'),
            this.appVersion, this.defaultLanguage, this.availableLanguages,
            additionalLangs, prevLangs, requestedLangs));
0e9aeacd   root   localization l20n
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
    }
  
    // match the opening angle bracket (<) in HTML tags, and HTML entities like
    // &amp;, &#0038;, &#x0026;.
    const reOverlay = /<|&#?\w+;/;
  
    const allowed = {
      elements: [
        'a', 'em', 'strong', 'small', 's', 'cite', 'q', 'dfn', 'abbr', 'data',
        'time', 'code', 'var', 'samp', 'kbd', 'sub', 'sup', 'i', 'b', 'u',
        'mark', 'ruby', 'rt', 'rp', 'bdi', 'bdo', 'span', 'br', 'wbr'
      ],
      attributes: {
        global: [ 'title', 'aria-label', 'aria-valuetext', 'aria-moz-hint' ],
        a: [ 'download' ],
        area: [ 'download', 'alt' ],
        // value is special-cased in isAttrAllowed
        input: [ 'alt', 'placeholder' ],
        menuitem: [ 'label' ],
        menu: [ 'label' ],
        optgroup: [ 'label' ],
        option: [ 'label' ],
        track: [ 'label' ],
        img: [ 'alt' ],
        textarea: [ 'placeholder' ],
        th: [ 'abbr']
      }
    };
  
    function overlayElement(element, translation) {
      const value = translation.value;
  
      if (typeof value === 'string') {
        if (!reOverlay.test(value)) {
          element.textContent = value;
        } else {
          // start with an inert template element and move its children into
          // `element` but such that `element`'s own children are not replaced
          const tmpl = element.ownerDocument.createElement('template');
          tmpl.innerHTML = value;
          // overlay the node with the DocumentFragment
          overlay(element, tmpl.content);
        }
      }
  
      for (let key in translation.attrs) {
        const attrName = camelCaseToDashed(key);
        if (isAttrAllowed({ name: attrName }, element)) {
          element.setAttribute(attrName, translation.attrs[key]);
        }
      }
    }
  
    // The goal of overlay is to move the children of `translationElement`
    // into `sourceElement` such that `sourceElement`'s own children are not
    // replaced, but onle have their text nodes and their attributes modified.
    //
    // We want to make it possible for localizers to apply text-level semantics to
    // the translations and make use of HTML entities. At the same time, we
    // don't trust translations so we need to filter unsafe elements and
    // attribtues out and we don't want to break the Web by replacing elements to
    // which third-party code might have created references (e.g. two-way
    // bindings in MVC frameworks).
    function overlay(sourceElement, translationElement) {
      const result = translationElement.ownerDocument.createDocumentFragment();
      let k, attr;
  
      // take one node from translationElement at a time and check it against
      // the allowed list or try to match it with a corresponding element
      // in the source
      let childElement;
      while ((childElement = translationElement.childNodes[0])) {
        translationElement.removeChild(childElement);
  
        if (childElement.nodeType === childElement.TEXT_NODE) {
          result.appendChild(childElement);
          continue;
        }
  
        const index = getIndexOfType(childElement);
        const sourceChild = getNthElementOfType(sourceElement, childElement, index);
        if (sourceChild) {
          // there is a corresponding element in the source, let's use it
          overlay(sourceChild, childElement);
          result.appendChild(sourceChild);
          continue;
        }
  
        if (isElementAllowed(childElement)) {
          const sanitizedChild = childElement.ownerDocument.createElement(
            childElement.nodeName);
          overlay(sanitizedChild, childElement);
          result.appendChild(sanitizedChild);
          continue;
        }
  
        // otherwise just take this child's textContent
        result.appendChild(
          translationElement.ownerDocument.createTextNode(
            childElement.textContent));
      }
  
      // clear `sourceElement` and append `result` which by this time contains
      // `sourceElement`'s original children, overlayed with translation
      sourceElement.textContent = '';
      sourceElement.appendChild(result);
  
      // if we're overlaying a nested element, translate the allowed
      // attributes; top-level attributes are handled in `translateElement`
      // XXX attributes previously set here for another language should be
      // cleared if a new language doesn't use them; https://bugzil.la/922577
      if (translationElement.attributes) {
        for (k = 0, attr; (attr = translationElement.attributes[k]); k++) {
          if (isAttrAllowed(attr, sourceElement)) {
            sourceElement.setAttribute(attr.name, attr.value);
          }
        }
      }
    }
  
    // XXX the allowed list should be amendable; https://bugzil.la/922573
    function isElementAllowed(element) {
      return allowed.elements.indexOf(element.tagName.toLowerCase()) !== -1;
    }
  
    function isAttrAllowed(attr, element) {
      const attrName = attr.name.toLowerCase();
      const tagName = element.tagName.toLowerCase();
      // is it a globally safe attribute?
      if (allowed.attributes.global.indexOf(attrName) !== -1) {
        return true;
      }
      // are there no allowed attributes for this element?
      if (!allowed.attributes[tagName]) {
        return false;
      }
      // is it allowed on this element?
      // XXX the allowed list should be amendable; https://bugzil.la/922573
      if (allowed.attributes[tagName].indexOf(attrName) !== -1) {
        return true;
      }
      // special case for value on inputs with type button, reset, submit
      if (tagName === 'input' && attrName === 'value') {
        const type = element.type.toLowerCase();
        if (type === 'submit' || type === 'button' || type === 'reset') {
          return true;
        }
      }
      return false;
    }
  
    // Get n-th immediate child of context that is of the same type as element.
    // XXX Use querySelector(':scope > ELEMENT:nth-of-type(index)'), when:
    // 1) :scope is widely supported in more browsers and 2) it works with
    // DocumentFragments.
    function getNthElementOfType(context, element, index) {
      /* jshint boss:true */
      let nthOfType = 0;
      for (let i = 0, child; child = context.children[i]; i++) {
        if (child.nodeType === child.ELEMENT_NODE &&
            child.tagName === element.tagName) {
          if (nthOfType === index) {
            return child;
          }
          nthOfType++;
        }
      }
      return null;
    }
  
    // Get the index of the element among siblings of the same type.
    function getIndexOfType(element) {
      let index = 0;
      let child;
      while ((child = element.previousElementSibling)) {
        if (child.tagName === element.tagName) {
          index++;
        }
      }
      return index;
    }
  
    function camelCaseToDashed(string) {
      // XXX workaround for https://bugzil.la/1141934
      if (string === 'ariaValueText') {
        return 'aria-valuetext';
      }
  
      return string
        .replace(/[A-Z]/g, function (match) {
          return '-' + match.toLowerCase();
        })
        .replace(/^-/, '');
    }
  
    const reHtml = /[&<>]/g;
    const htmlEntities = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
    };
  
c5169e0e   Renato De Donato   a new hope
2328
2329
2330
2331
2332
2333
    function getResourceLinks(head) {
      return Array.prototype.map.call(
        head.querySelectorAll('link[rel="localization"]'),
        el => el.getAttribute('href'));
    }
  
0e9aeacd   root   localization l20n
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
    function setAttributes(element, id, args) {
      element.setAttribute('data-l10n-id', id);
      if (args) {
        element.setAttribute('data-l10n-args', JSON.stringify(args));
      }
    }
  
    function getAttributes(element) {
      return {
        id: element.getAttribute('data-l10n-id'),
        args: JSON.parse(element.getAttribute('data-l10n-args'))
      };
    }
  
    function getTranslatables(element) {
      const nodes = Array.from(element.querySelectorAll('[data-l10n-id]'));
  
      if (typeof element.hasAttribute === 'function' &&
          element.hasAttribute('data-l10n-id')) {
        nodes.push(element);
      }
  
      return nodes;
    }
  
c5169e0e   Renato De Donato   a new hope
2359
    function translateMutations(view, langs, mutations) {
0e9aeacd   root   localization l20n
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
      const targets = new Set();
  
      for (let mutation of mutations) {
        switch (mutation.type) {
          case 'attributes':
            targets.add(mutation.target);
            break;
          case 'childList':
            for (let addedNode of mutation.addedNodes) {
              if (addedNode.nodeType === addedNode.ELEMENT_NODE) {
                if (addedNode.childElementCount) {
                  getTranslatables(addedNode).forEach(targets.add.bind(targets));
                } else {
                  if (addedNode.hasAttribute('data-l10n-id')) {
                    targets.add(addedNode);
                  }
                }
              }
            }
            break;
        }
      }
  
      if (targets.size === 0) {
        return;
      }
  
c5169e0e   Renato De Donato   a new hope
2387
      translateElements(view, langs, Array.from(targets));
0e9aeacd   root   localization l20n
2388
2389
    }
  
c5169e0e   Renato De Donato   a new hope
2390
2391
    function translateFragment(view, langs, frag) {
      return translateElements(view, langs, getTranslatables(frag));
0e9aeacd   root   localization l20n
2392
2393
    }
  
c5169e0e   Renato De Donato   a new hope
2394
    function getElementsTranslation(view, langs, elems) {
0e9aeacd   root   localization l20n
2395
2396
2397
2398
2399
2400
2401
2402
2403
      const keys = elems.map(elem => {
        const id = elem.getAttribute('data-l10n-id');
        const args = elem.getAttribute('data-l10n-args');
        return args ? [
          id,
          JSON.parse(args.replace(reHtml, match => htmlEntities[match]))
        ] : id;
      });
  
c5169e0e   Renato De Donato   a new hope
2404
      return view._resolveEntities(langs, keys);
0e9aeacd   root   localization l20n
2405
2406
    }
  
c5169e0e   Renato De Donato   a new hope
2407
2408
    function translateElements(view, langs, elements) {
      return getElementsTranslation(view, langs, elements).then(
0e9aeacd   root   localization l20n
2409
2410
2411
2412
        translations => applyTranslations(view, elements, translations));
    }
  
    function applyTranslations(view, elems, translations) {
c5169e0e   Renato De Donato   a new hope
2413
      view._disconnect();
0e9aeacd   root   localization l20n
2414
2415
2416
      for (let i = 0; i < elems.length; i++) {
        overlayElement(elems[i], translations[i]);
      }
c5169e0e   Renato De Donato   a new hope
2417
      view._observe();
a1a3bc73   Luigi Serra   graphs updates
2418
2419
    }
  
c5169e0e   Renato De Donato   a new hope
2420
2421
2422
2423
2424
2425
2426
    const observerConfig = {
      attributes: true,
      characterData: false,
      childList: true,
      subtree: true,
      attributeFilter: ['data-l10n-id', 'data-l10n-args']
    };
a1a3bc73   Luigi Serra   graphs updates
2427
  
c5169e0e   Renato De Donato   a new hope
2428
    const readiness = new WeakMap();
0e9aeacd   root   localization l20n
2429
2430
2431
  
    class View {
      constructor(client, doc) {
c5169e0e   Renato De Donato   a new hope
2432
        this._doc = doc;
0e9aeacd   root   localization l20n
2433
2434
2435
2436
2437
        this.pseudo = {
          'fr-x-psaccent': createPseudo(this, 'fr-x-psaccent'),
          'ar-x-psbidi': createPseudo(this, 'ar-x-psbidi')
        };
  
c5169e0e   Renato De Donato   a new hope
2438
2439
        this._interactive = documentReady().then(
          () => init(this, client));
0e9aeacd   root   localization l20n
2440
  
c5169e0e   Renato De Donato   a new hope
2441
2442
2443
        const observer = new MutationObserver(onMutations.bind(this));
        this._observe = () => observer.observe(doc, observerConfig);
        this._disconnect = () => observer.disconnect();
0e9aeacd   root   localization l20n
2444
  
c5169e0e   Renato De Donato   a new hope
2445
2446
2447
2448
2449
        const translateView = langs => translateDocument(this, langs);
        client.on('translateDocument', translateView);
        this.ready = this._interactive.then(
          client => client.method('resolvedLanguages')).then(
          translateView);
a1a3bc73   Luigi Serra   graphs updates
2450
2451
      }
  
c5169e0e   Renato De Donato   a new hope
2452
2453
2454
      requestLanguages(langs, global) {
        return this._interactive.then(
          client => client.method('requestLanguages', langs, global));
0e9aeacd   root   localization l20n
2455
2456
      }
  
c5169e0e   Renato De Donato   a new hope
2457
      _resolveEntities(langs, keys) {
0e9aeacd   root   localization l20n
2458
        return this._interactive.then(
c5169e0e   Renato De Donato   a new hope
2459
          client => client.method('resolveEntities', client.id, langs, keys));
0e9aeacd   root   localization l20n
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
      }
  
      formatValue(id, args) {
        return this._interactive.then(
          client => client.method('formatValues', client.id, [[id, args]])).then(
          values => values[0]);
      }
  
      formatValues(...keys) {
        return this._interactive.then(
          client => client.method('formatValues', client.id, keys));
      }
  
      translateFragment(frag) {
c5169e0e   Renato De Donato   a new hope
2474
2475
2476
        return this._interactive.then(
          client => client.method('resolvedLanguages')).then(
          langs => translateFragment(this, langs, frag));
0e9aeacd   root   localization l20n
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
      }
    }
  
    View.prototype.setAttributes = setAttributes;
    View.prototype.getAttributes = getAttributes;
  
    function createPseudo(view, code) {
      return {
        getName: () => view._interactive.then(
          client => client.method('getName', code)),
        processString: str => view._interactive.then(
          client => client.method('processString', code, str)),
      };
    }
  
    function init(view, client) {
c5169e0e   Renato De Donato   a new hope
2493
2494
2495
2496
      view._observe();
      return client.method(
        'registerView', client.id, getResourceLinks(view._doc.head)).then(
          () => client);
0e9aeacd   root   localization l20n
2497
2498
    }
  
c5169e0e   Renato De Donato   a new hope
2499
2500
2501
2502
    function onMutations(mutations) {
      return this._interactive.then(
        client => client.method('resolvedLanguages')).then(
        langs => translateMutations(this, langs, mutations));
0e9aeacd   root   localization l20n
2503
2504
    }
  
c5169e0e   Renato De Donato   a new hope
2505
2506
    function translateDocument(view, langs) {
      const html = view._doc.documentElement;
0e9aeacd   root   localization l20n
2507
  
c5169e0e   Renato De Donato   a new hope
2508
2509
      if (readiness.has(html)) {
        return translateFragment(view, langs, html).then(
0e9aeacd   root   localization l20n
2510
2511
2512
2513
2514
2515
2516
          () => setAllAndEmit(html, langs));
      }
  
      const translated =
        // has the document been already pre-translated?
        langs[0].code === html.getAttribute('lang') ?
          Promise.resolve() :
c5169e0e   Renato De Donato   a new hope
2517
          translateFragment(view, langs, html).then(
0e9aeacd   root   localization l20n
2518
2519
2520
2521
            () => setLangDir(html, langs));
  
      return translated.then(() => {
        setLangs(html, langs);
c5169e0e   Renato De Donato   a new hope
2522
        readiness.set(html, true);
0e9aeacd   root   localization l20n
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
      });
    }
  
    function setLangs(html, langs) {
      const codes = langs.map(lang => lang.code);
      html.setAttribute('langs', codes.join(' '));
    }
  
    function setLangDir(html, langs) {
      const code = langs[0].code;
      html.setAttribute('lang', code);
      html.setAttribute('dir', getDirection(code));
    }
  
    function setAllAndEmit(html, langs) {
      setLangDir(html, langs);
      setLangs(html, langs);
      html.parentNode.dispatchEvent(new CustomEvent('DOMRetranslated', {
        bubbles: false,
        cancelable: false,
      }));
    }
  
c5169e0e   Renato De Donato   a new hope
2546
2547
2548
    const remote = new Remote(fetchResource, broadcast, navigator.languages);
    window.addEventListener('languagechange', remote);
    document.addEventListener('additionallanguageschange', remote);
0e9aeacd   root   localization l20n
2549
  
c5169e0e   Renato De Donato   a new hope
2550
2551
    document.l10n = new View(
      new Client(remote), document);
0e9aeacd   root   localization l20n
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
  
    //Bug 1204660 - Temporary proxy for shared code. Will be removed once
    //              l10n.js migration is completed.
    navigator.mozL10n = {
      setAttributes: document.l10n.setAttributes,
      getAttributes: document.l10n.getAttributes,
      formatValue: (...args) => document.l10n.formatValue(...args),
      translateFragment: (...args) => document.l10n.translateFragment(...args),
      once: cb => document.l10n.ready.then(cb),
      ready: cb => document.l10n.ready.then(() => {
        document.addEventListener('DOMRetranslated', cb);
        cb();
      }),
    };
  
  })();