Blame view

bower_components/l20n/dist/bundle/node/l20n.js 40.9 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
  'use strict';
  
  var string_prototype_startswith = require('string.prototype.startswith');
  var string_prototype_endswith = require('string.prototype.endswith');
  var fs = require('fs');
  
  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(url) {
    return new Promise(function(resolve, reject) {
      fs.readFile(url, function(err, data) {
        if (err) {
          reject(new L10nError(err.message));
        } else {
          resolve(data.toString());
        }
      });
    });
  }
  
c5169e0e   Renato De Donato   a new hope
28
29
  function fetchResource$1(res, lang) {
    const url = res.replace('{locale}', lang.code);
0e9aeacd   root   localization l20n
30
31
32
33
    return res.endsWith('.json') ?
      load(url).then(JSON.parse) : load(url);
  }
  
c5169e0e   Renato De Donato   a new hope
34
  const MAX_PLACEABLES$1 = 100;
0e9aeacd   root   localization l20n
35
  
c5169e0e   Renato De Donato   a new hope
36
37
38
39
40
41
42
  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
43
  
c5169e0e   Renato De Donato   a new hope
44
45
      return this.getResource();
    },
0e9aeacd   root   localization l20n
46
  
c5169e0e   Renato De Donato   a new hope
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    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
63
  
c5169e0e   Renato De Donato   a new hope
64
65
66
67
        if (this._index < this._length) {
          this.getWS();
        }
      }
0e9aeacd   root   localization l20n
68
  
c5169e0e   Renato De Donato   a new hope
69
70
      return this.entries;
    },
0e9aeacd   root   localization l20n
71
  
c5169e0e   Renato De Donato   a new hope
72
73
74
75
76
77
78
79
80
81
    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
82
  
c5169e0e   Renato De Donato   a new hope
83
84
      if (this._source.startsWith('/*', this._index)) {
        return this.getComment();
0e9aeacd   root   localization l20n
85
      }
0e9aeacd   root   localization l20n
86
  
c5169e0e   Renato De Donato   a new hope
87
88
      throw this.error('Invalid entry');
    },
0e9aeacd   root   localization l20n
89
  
c5169e0e   Renato De Donato   a new hope
90
91
92
93
    getEntity: function(id, index) {
      if (!this.getRequiredWS()) {
        throw this.error('Expected white space');
      }
0e9aeacd   root   localization l20n
94
  
c5169e0e   Renato De Donato   a new hope
95
96
97
      const ch = this._source[this._index];
      const value = this.getValue(ch, index === undefined);
      let attrs;
0e9aeacd   root   localization l20n
98
  
c5169e0e   Renato De Donato   a new hope
99
100
101
102
103
104
105
106
107
108
109
110
111
112
      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
113
  
c5169e0e   Renato De Donato   a new hope
114
115
      // skip '>'
      ++this._index;
0e9aeacd   root   localization l20n
116
  
c5169e0e   Renato De Donato   a new hope
117
118
119
120
121
122
123
124
125
126
127
128
129
      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
130
  
c5169e0e   Renato De Donato   a new hope
131
132
133
134
135
136
137
138
    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
139
  
c5169e0e   Renato De Donato   a new hope
140
141
      if (!optional) {
        throw this.error('Unknown value type');
0e9aeacd   root   localization l20n
142
      }
0e9aeacd   root   localization l20n
143
  
c5169e0e   Renato De Donato   a new hope
144
145
      return;
    },
0e9aeacd   root   localization l20n
146
  
c5169e0e   Renato De Donato   a new hope
147
148
149
150
151
    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
152
      }
c5169e0e   Renato De Donato   a new hope
153
    },
0e9aeacd   root   localization l20n
154
  
c5169e0e   Renato De Donato   a new hope
155
156
157
158
159
160
161
162
163
    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
164
  
c5169e0e   Renato De Donato   a new hope
165
166
167
    getIdentifier: function() {
      const start = this._index;
      let cc = this._source.charCodeAt(this._index);
a1a3bc73   Luigi Serra   graphs updates
168
  
c5169e0e   Renato De Donato   a new hope
169
170
171
172
173
174
      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
175
      }
c5169e0e   Renato De Donato   a new hope
176
177
178
179
180
181
  
      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
182
      }
c5169e0e   Renato De Donato   a new hope
183
184
185
186
187
188
189
190
191
192
193
194
195
  
      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
196
      }
c5169e0e   Renato De Donato   a new hope
197
198
199
200
      this._index++;
      return String.fromCharCode(
        parseInt(this._source.slice(this._index - 4, this._index), 16));
    },
0e9aeacd   root   localization l20n
201
  
c5169e0e   Renato De Donato   a new hope
202
203
204
205
    stringRe: /"|'|{{|\\/g,
    getString: function(opchar, opcharLen) {
      const body = [];
      let placeables = 0;
0e9aeacd   root   localization l20n
206
  
c5169e0e   Renato De Donato   a new hope
207
208
      this._index += opcharLen;
      const start = this._index;
0e9aeacd   root   localization l20n
209
  
c5169e0e   Renato De Donato   a new hope
210
211
      let bufStart = start;
      let buf = '';
0e9aeacd   root   localization l20n
212
  
c5169e0e   Renato De Donato   a new hope
213
214
215
      while (true) {
        this.stringRe.lastIndex = this._index;
        const match = this.stringRe.exec(this._source);
0e9aeacd   root   localization l20n
216
  
c5169e0e   Renato De Donato   a new hope
217
218
219
        if (!match) {
          throw this.error('Unclosed string literal');
        }
0e9aeacd   root   localization l20n
220
  
c5169e0e   Renato De Donato   a new hope
221
222
223
224
225
226
227
228
        if (match[0] === '"' || match[0] === '\'') {
          if (match[0] !== opchar) {
            this._index += opcharLen;
            continue;
          }
          this._index = match.index + opcharLen;
          break;
        }
0e9aeacd   root   localization l20n
229
  
c5169e0e   Renato De Donato   a new hope
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
        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
248
  
c5169e0e   Renato De Donato   a new hope
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
        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
266
      }
c5169e0e   Renato De Donato   a new hope
267
268
269
  
      if (body.length === 0) {
        return buf + this._source.slice(bufStart, this._index - opcharLen);
0e9aeacd   root   localization l20n
270
      }
c5169e0e   Renato De Donato   a new hope
271
272
273
  
      if (this._index - opcharLen > bufStart || buf.length > 0) {
        body.push(buf + this._source.slice(bufStart, this._index - opcharLen));
0e9aeacd   root   localization l20n
274
      }
c5169e0e   Renato De Donato   a new hope
275
276
  
      return body;
0e9aeacd   root   localization l20n
277
    },
c5169e0e   Renato De Donato   a new hope
278
279
280
281
282
283
284
285
286
287
288
289
290
  
    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 ">"');
        }
0e9aeacd   root   localization l20n
291
      }
c5169e0e   Renato De Donato   a new hope
292
      return attrs;
0e9aeacd   root   localization l20n
293
    },
c5169e0e   Renato De Donato   a new hope
294
295
296
297
298
299
300
301
302
  
    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
303
      }
c5169e0e   Renato De Donato   a new hope
304
305
306
      this.getWS();
      if (this._source[this._index] !== ':') {
        throw this.error('Expected ":"');
a1a3bc73   Luigi Serra   graphs updates
307
      }
c5169e0e   Renato De Donato   a new hope
308
309
310
311
312
313
      ++this._index;
      this.getWS();
      const value = this.getValue();
  
      if (key in attrs) {
        throw this.error('Duplicate attribute "' + key, 'duplicateerror');
a1a3bc73   Luigi Serra   graphs updates
314
      }
c5169e0e   Renato De Donato   a new hope
315
316
317
318
319
320
321
322
  
      if (!index && typeof value === 'string') {
        attrs[key] = value;
      } else {
        attrs[key] = {
          value,
          index
        };
a1a3bc73   Luigi Serra   graphs updates
323
      }
a1a3bc73   Luigi Serra   graphs updates
324
    },
c5169e0e   Renato De Donato   a new hope
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
  
    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 "}"');
        }
a1a3bc73   Luigi Serra   graphs updates
358
      }
c5169e0e   Renato De Donato   a new hope
359
360
361
  
      if (defKey) {
        items.__default = defKey;
a1a3bc73   Luigi Serra   graphs updates
362
      }
c5169e0e   Renato De Donato   a new hope
363
364
  
      return items;
a1a3bc73   Luigi Serra   graphs updates
365
    },
c5169e0e   Renato De Donato   a new hope
366
367
368
369
370
371
  
    getHashItem: function() {
      let defItem = false;
      if (this._source[this._index] === '*') {
        ++this._index;
        defItem = true;
a1a3bc73   Luigi Serra   graphs updates
372
      }
c5169e0e   Renato De Donato   a new hope
373
374
375
376
377
  
      const key = this.getIdentifier();
      this.getWS();
      if (this._source[this._index] !== ':') {
        throw this.error('Expected ":"');
a1a3bc73   Luigi Serra   graphs updates
378
      }
c5169e0e   Renato De Donato   a new hope
379
380
381
382
      ++this._index;
      this.getWS();
  
      return [key, this.getValue(), defItem];
a1a3bc73   Luigi Serra   graphs updates
383
    },
c5169e0e   Renato De Donato   a new hope
384
385
386
387
388
389
390
391
  
    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
392
      }
c5169e0e   Renato De Donato   a new hope
393
394
  
      this._index = end + 2;
a1a3bc73   Luigi Serra   graphs updates
395
    },
c5169e0e   Renato De Donato   a new hope
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
  
    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
411
      }
c5169e0e   Renato De Donato   a new hope
412
413
  
      return exp;
a1a3bc73   Luigi Serra   graphs updates
414
    },
c5169e0e   Renato De Donato   a new hope
415
416
417
418
419
420
421
422
423
424
425
426
427
428
  
    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
429
      }
c5169e0e   Renato De Donato   a new hope
430
431
432
433
434
435
436
  
      return {
        type: 'prop',
        expr: idref,
        prop: exp,
        cmpt: computed
      };
a1a3bc73   Luigi Serra   graphs updates
437
    },
c5169e0e   Renato De Donato   a new hope
438
439
440
441
442
443
444
445
446
  
    getCallExpression: function(callee) {
      this.getWS();
  
      return {
        type: 'call',
        expr: callee,
        args: this.getItemList(this.getExpression, ')')
      };
a1a3bc73   Luigi Serra   graphs updates
447
    },
c5169e0e   Renato De Donato   a new hope
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
  
    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()
          };
a1a3bc73   Luigi Serra   graphs updates
470
      }
a1a3bc73   Luigi Serra   graphs updates
471
    },
c5169e0e   Renato De Donato   a new hope
472
473
474
475
476
477
478
479
480
481
  
    getItemList: function(callback, closeChar) {
      const items = [];
      let closed = false;
  
      this.getWS();
  
      if (this._source[this._index] === closeChar) {
        ++this._index;
        closed = true;
a1a3bc73   Luigi Serra   graphs updates
482
      }
c5169e0e   Renato De Donato   a new hope
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
  
      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
500
      }
c5169e0e   Renato De Donato   a new hope
501
502
  
      return items;
a1a3bc73   Luigi Serra   graphs updates
503
    },
c5169e0e   Renato De Donato   a new hope
504
505
506
507
508
509
510
511
512
  
  
    getJunkEntry: function() {
      const pos = this._index;
      let nextEntity = this._source.indexOf('<', pos);
      let nextComment = this._source.indexOf('/*', pos);
  
      if (nextEntity === -1) {
        nextEntity = this._length;
a1a3bc73   Luigi Serra   graphs updates
513
      }
c5169e0e   Renato De Donato   a new hope
514
515
      if (nextComment === -1) {
        nextComment = this._length;
a1a3bc73   Luigi Serra   graphs updates
516
      }
c5169e0e   Renato De Donato   a new hope
517
518
519
520
  
      let nextEntry = Math.min(nextEntity, nextComment);
  
      this._index = nextEntry;
a1a3bc73   Luigi Serra   graphs updates
521
    },
c5169e0e   Renato De Donato   a new hope
522
523
524
525
526
527
528
529
530
531
532
533
534
  
    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);
a1a3bc73   Luigi Serra   graphs updates
535
      }
c5169e0e   Renato De Donato   a new hope
536
      return err;
a1a3bc73   Luigi Serra   graphs updates
537
    },
c5169e0e   Renato De Donato   a new hope
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
  };
  
  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*\}\}/,
      };
a1a3bc73   Luigi Serra   graphs updates
558
    },
c5169e0e   Renato De Donato   a new hope
559
560
561
562
  
    parse: function(emit, source) {
      if (!this.patterns) {
        this.init();
a1a3bc73   Luigi Serra   graphs updates
563
      }
c5169e0e   Renato De Donato   a new hope
564
565
566
567
568
569
570
      this.emit = emit;
  
      var entries = {};
  
      var lines = source.match(this.patterns.entries);
      if (!lines) {
        return entries;
a1a3bc73   Luigi Serra   graphs updates
571
      }
c5169e0e   Renato De Donato   a new hope
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
      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;
            }
          }
        }
      }
      return entries;
a1a3bc73   Luigi Serra   graphs updates
595
    },
c5169e0e   Renato De Donato   a new hope
596
597
598
599
600
601
602
603
604
605
606
  
    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;
a1a3bc73   Luigi Serra   graphs updates
607
      }
c5169e0e   Renato De Donato   a new hope
608
609
610
611
612
613
  
      var nameElements = name.split('.');
  
      if (nameElements.length > 2) {
        throw this.error('Error in ID: "' + name + '".' +
            ' Nested attributes are not supported.');
a1a3bc73   Luigi Serra   graphs updates
614
      }
c5169e0e   Renato De Donato   a new hope
615
616
617
618
619
620
621
622
623
624
625
626
627
628
  
      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;
      }
  
      this.setEntityValue(name, attr, key, this.unescapeString(value), entries);
a1a3bc73   Luigi Serra   graphs updates
629
    },
c5169e0e   Renato De Donato   a new hope
630
631
632
633
634
635
636
637
638
639
640
641
642
  
    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
643
      }
c5169e0e   Renato De Donato   a new hope
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
  
      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
659
      }
c5169e0e   Renato De Donato   a new hope
660
661
662
663
664
665
666
667
668
669
670
671
  
      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
672
      }
c5169e0e   Renato De Donato   a new hope
673
674
675
676
677
678
679
680
681
682
683
  
      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
684
      }
a1a3bc73   Luigi Serra   graphs updates
685
    },
c5169e0e   Renato De Donato   a new hope
686
687
688
689
690
691
692
693
694
695
696
  
    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 + ')');
a1a3bc73   Luigi Serra   graphs updates
697
      }
c5169e0e   Renato De Donato   a new hope
698
699
700
701
702
703
704
705
706
707
  
      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
708
      }
c5169e0e   Renato De Donato   a new hope
709
      return complexStr;
a1a3bc73   Luigi Serra   graphs updates
710
    },
c5169e0e   Renato De Donato   a new hope
711
712
713
714
  
    unescapeString: function(str) {
      if (str.lastIndexOf('\\') !== -1) {
        str = str.replace(this.patterns.controlChars, '$1');
a1a3bc73   Luigi Serra   graphs updates
715
      }
c5169e0e   Renato De Donato   a new hope
716
717
718
      return str.replace(this.patterns.unicode, function(match, token) {
        return String.fromCodePoint(parseInt(token, 16));
      });
a1a3bc73   Luigi Serra   graphs updates
719
    },
c5169e0e   Renato De Donato   a new hope
720
721
722
723
724
  
    parseIndex: function(str) {
      var match = str.match(this.patterns.index);
      if (!match) {
        throw new L10nError('Malformed index');
a1a3bc73   Luigi Serra   graphs updates
725
      }
c5169e0e   Renato De Donato   a new hope
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
      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]}];
a1a3bc73   Luigi Serra   graphs updates
744
      }
c5169e0e   Renato De Donato   a new hope
745
746
747
748
749
750
    },
  
    error: function(msg, type = 'parsererror') {
      const err = new L10nError(msg);
      if (this.emit) {
        this.emit(type, err);
a1a3bc73   Luigi Serra   graphs updates
751
      }
c5169e0e   Renato De Donato   a new hope
752
      return err;
a1a3bc73   Luigi Serra   graphs updates
753
754
755
    }
  };
  
c5169e0e   Renato De Donato   a new hope
756
757
758
759
760
761
762
763
764
765
766
767
  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];
a1a3bc73   Luigi Serra   graphs updates
768
    }
a1a3bc73   Luigi Serra   graphs updates
769
  
c5169e0e   Renato De Donato   a new hope
770
771
    if (resolutionChain.has(entity)) {
      throw new L10nError('Cyclic reference detected');
a1a3bc73   Luigi Serra   graphs updates
772
    }
a1a3bc73   Luigi Serra   graphs updates
773
  
c5169e0e   Renato De Donato   a new hope
774
775
776
777
778
779
780
781
782
783
784
    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);
a1a3bc73   Luigi Serra   graphs updates
785
    }
c5169e0e   Renato De Donato   a new hope
786
787
    return rv;
  }
a1a3bc73   Luigi Serra   graphs updates
788
  
c5169e0e   Renato De Donato   a new hope
789
790
791
792
793
794
795
796
797
798
799
  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);
a1a3bc73   Luigi Serra   graphs updates
800
801
802
      }
    }
  
c5169e0e   Renato De Donato   a new hope
803
804
805
806
807
    // 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
808
  
c5169e0e   Renato De Donato   a new hope
809
    const entity = ctx._getEntity(lang, id);
a1a3bc73   Luigi Serra   graphs updates
810
  
c5169e0e   Renato De Donato   a new hope
811
812
813
814
815
816
817
818
819
    if (entity) {
      return format(ctx, lang, args, entity);
    }
  
    throw new L10nError('Unknown reference: ' + id);
  }
  
  function subPlaceable(locals, ctx, lang, args, id) {
    let newLocals, value;
a1a3bc73   Luigi Serra   graphs updates
820
  
c5169e0e   Renato De Donato   a new hope
821
822
823
824
    try {
      [newLocals, value] = resolveIdentifier(ctx, lang, args, id);
    } catch (err) {
      return [{ error: err }, FSI + '{{ ' + id + ' }}' + PDI];
a1a3bc73   Luigi Serra   graphs updates
825
826
    }
  
c5169e0e   Renato De Donato   a new hope
827
828
829
    if (typeof value === 'number') {
      const formatter = ctx._getNumberFormatter(lang);
      return [newLocals, formatter.format(value)];
a1a3bc73   Luigi Serra   graphs updates
830
831
    }
  
c5169e0e   Renato De Donato   a new hope
832
833
834
835
836
837
    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
838
      }
c5169e0e   Renato De Donato   a new hope
839
      return [newLocals, FSI + value + PDI];
a1a3bc73   Luigi Serra   graphs updates
840
841
    }
  
c5169e0e   Renato De Donato   a new hope
842
843
    return [{}, FSI + '{{ ' + id + ' }}' + PDI];
  }
a1a3bc73   Luigi Serra   graphs updates
844
  
c5169e0e   Renato De Donato   a new hope
845
846
847
848
849
850
851
852
  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
853
      }
c5169e0e   Renato De Donato   a new hope
854
855
    }, [locals, '']);
  }
a1a3bc73   Luigi Serra   graphs updates
856
  
c5169e0e   Renato De Donato   a new hope
857
858
859
860
861
862
863
864
865
866
  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
867
  
c5169e0e   Renato De Donato   a new hope
868
869
870
871
    if (typeof selector !== 'function') {
      // selector is a simple reference to an entity or args
      return selector;
    }
a1a3bc73   Luigi Serra   graphs updates
872
  
c5169e0e   Renato De Donato   a new hope
873
874
    const argValue = index[0].args ?
      resolveIdentifier(ctx, lang, args, index[0].args[0].name)[1] : undefined;
a1a3bc73   Luigi Serra   graphs updates
875
  
c5169e0e   Renato De Donato   a new hope
876
877
878
879
880
881
882
883
884
885
    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
886
      }
a1a3bc73   Luigi Serra   graphs updates
887
888
    }
  
c5169e0e   Renato De Donato   a new hope
889
890
    return selector(argValue);
  }
a1a3bc73   Luigi Serra   graphs updates
891
  
c5169e0e   Renato De Donato   a new hope
892
893
894
  function resolveValue(locals, ctx, lang, args, expr, index) {
    if (!expr) {
      return [locals, expr];
a1a3bc73   Luigi Serra   graphs updates
895
896
    }
  
c5169e0e   Renato De Donato   a new hope
897
898
899
900
901
    if (typeof expr === 'string' ||
        typeof expr === 'boolean' ||
        typeof expr === 'number') {
      return [locals, expr];
    }
a1a3bc73   Luigi Serra   graphs updates
902
  
c5169e0e   Renato De Donato   a new hope
903
904
    if (Array.isArray(expr)) {
      return interpolate(locals, ctx, lang, args, expr);
a1a3bc73   Luigi Serra   graphs updates
905
906
    }
  
c5169e0e   Renato De Donato   a new hope
907
908
909
910
911
912
    // 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
913
      }
a1a3bc73   Luigi Serra   graphs updates
914
915
    }
  
c5169e0e   Renato De Donato   a new hope
916
917
918
919
920
    // 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
921
922
    }
  
c5169e0e   Renato De Donato   a new hope
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
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
    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
1102
  }
c5169e0e   Renato De Donato   a new hope
1103
1104
  function isBetween(n, start, end) {
    return typeof n === typeof start && start <= n && n <= end;
a1a3bc73   Luigi Serra   graphs updates
1105
1106
  }
  
c5169e0e   Renato De Donato   a new hope
1107
1108
1109
1110
1111
  // 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
1112
    },
c5169e0e   Renato De Donato   a new hope
1113
1114
1115
    '1': function(n) {
      if ((isBetween((n % 100), 3, 10))) {
        return 'few';
0e9aeacd   root   localization l20n
1116
      }
c5169e0e   Renato De Donato   a new hope
1117
1118
      if (n === 0) {
        return 'zero';
0e9aeacd   root   localization l20n
1119
      }
c5169e0e   Renato De Donato   a new hope
1120
1121
      if ((isBetween((n % 100), 11, 99))) {
        return 'many';
0e9aeacd   root   localization l20n
1122
      }
c5169e0e   Renato De Donato   a new hope
1123
1124
      if (n === 2) {
        return 'two';
0e9aeacd   root   localization l20n
1125
      }
c5169e0e   Renato De Donato   a new hope
1126
1127
      if (n === 1) {
        return 'one';
0e9aeacd   root   localization l20n
1128
      }
c5169e0e   Renato De Donato   a new hope
1129
      return 'other';
0e9aeacd   root   localization l20n
1130
    },
c5169e0e   Renato De Donato   a new hope
1131
1132
1133
    '2': function(n) {
      if (n !== 0 && (n % 10) === 0) {
        return 'many';
0e9aeacd   root   localization l20n
1134
      }
c5169e0e   Renato De Donato   a new hope
1135
1136
      if (n === 2) {
        return 'two';
0e9aeacd   root   localization l20n
1137
      }
c5169e0e   Renato De Donato   a new hope
1138
1139
      if (n === 1) {
        return 'one';
0e9aeacd   root   localization l20n
1140
      }
c5169e0e   Renato De Donato   a new hope
1141
      return 'other';
0e9aeacd   root   localization l20n
1142
    },
c5169e0e   Renato De Donato   a new hope
1143
1144
1145
    '3': function(n) {
      if (n === 1) {
        return 'one';
0e9aeacd   root   localization l20n
1146
      }
c5169e0e   Renato De Donato   a new hope
1147
      return 'other';
0e9aeacd   root   localization l20n
1148
    },
c5169e0e   Renato De Donato   a new hope
1149
1150
1151
    '4': function(n) {
      if ((isBetween(n, 0, 1))) {
        return 'one';
0e9aeacd   root   localization l20n
1152
      }
c5169e0e   Renato De Donato   a new hope
1153
      return 'other';
a1a3bc73   Luigi Serra   graphs updates
1154
    },
c5169e0e   Renato De Donato   a new hope
1155
1156
1157
    '5': function(n) {
      if ((isBetween(n, 0, 2)) && n !== 2) {
        return 'one';
0e9aeacd   root   localization l20n
1158
      }
c5169e0e   Renato De Donato   a new hope
1159
1160
1161
1162
1163
1164
1165
1166
      return 'other';
    },
    '6': function(n) {
      if (n === 0) {
        return 'zero';
      }
      if ((n % 10) === 1 && (n % 100) !== 11) {
        return 'one';
0e9aeacd   root   localization l20n
1167
      }
c5169e0e   Renato De Donato   a new hope
1168
      return 'other';
0e9aeacd   root   localization l20n
1169
    },
c5169e0e   Renato De Donato   a new hope
1170
1171
1172
    '7': function(n) {
      if (n === 2) {
        return 'two';
0e9aeacd   root   localization l20n
1173
      }
c5169e0e   Renato De Donato   a new hope
1174
1175
1176
1177
      if (n === 1) {
        return 'one';
      }
      return 'other';
0e9aeacd   root   localization l20n
1178
    },
c5169e0e   Renato De Donato   a new hope
1179
1180
1181
    '8': function(n) {
      if ((isBetween(n, 3, 6))) {
        return 'few';
0e9aeacd   root   localization l20n
1182
      }
c5169e0e   Renato De Donato   a new hope
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
      if ((isBetween(n, 7, 10))) {
        return 'many';
      }
      if (n === 2) {
        return 'two';
      }
      if (n === 1) {
        return 'one';
      }
      return 'other';
a1a3bc73   Luigi Serra   graphs updates
1193
    },
c5169e0e   Renato De Donato   a new hope
1194
1195
1196
    '9': function(n) {
      if (n === 0 || n !== 1 && (isBetween((n % 100), 1, 19))) {
        return 'few';
0e9aeacd   root   localization l20n
1197
      }
c5169e0e   Renato De Donato   a new hope
1198
1199
      if (n === 1) {
        return 'one';
0e9aeacd   root   localization l20n
1200
      }
c5169e0e   Renato De Donato   a new hope
1201
      return 'other';
a1a3bc73   Luigi Serra   graphs updates
1202
    },
c5169e0e   Renato De Donato   a new hope
1203
1204
1205
    '10': function(n) {
      if ((isBetween((n % 10), 2, 9)) && !(isBetween((n % 100), 11, 19))) {
        return 'few';
0e9aeacd   root   localization l20n
1206
      }
c5169e0e   Renato De Donato   a new hope
1207
1208
      if ((n % 10) === 1 && !(isBetween((n % 100), 11, 19))) {
        return 'one';
0e9aeacd   root   localization l20n
1209
      }
c5169e0e   Renato De Donato   a new hope
1210
1211
1212
1213
1214
      return 'other';
    },
    '11': function(n) {
      if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) {
        return 'few';
0e9aeacd   root   localization l20n
1215
      }
c5169e0e   Renato De Donato   a new hope
1216
1217
1218
1219
      if ((n % 10) === 0 ||
          (isBetween((n % 10), 5, 9)) ||
          (isBetween((n % 100), 11, 14))) {
        return 'many';
0e9aeacd   root   localization l20n
1220
      }
c5169e0e   Renato De Donato   a new hope
1221
1222
1223
1224
      if ((n % 10) === 1 && (n % 100) !== 11) {
        return 'one';
      }
      return 'other';
0e9aeacd   root   localization l20n
1225
    },
c5169e0e   Renato De Donato   a new hope
1226
1227
1228
    '12': function(n) {
      if ((isBetween(n, 2, 4))) {
        return 'few';
0e9aeacd   root   localization l20n
1229
      }
c5169e0e   Renato De Donato   a new hope
1230
1231
      if (n === 1) {
        return 'one';
0e9aeacd   root   localization l20n
1232
      }
c5169e0e   Renato De Donato   a new hope
1233
      return 'other';
0e9aeacd   root   localization l20n
1234
    },
c5169e0e   Renato De Donato   a new hope
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
    '13': function(n) {
      if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) {
        return 'few';
      }
      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';
0e9aeacd   root   localization l20n
1246
      }
c5169e0e   Renato De Donato   a new hope
1247
      return 'other';
a1a3bc73   Luigi Serra   graphs updates
1248
    },
c5169e0e   Renato De Donato   a new hope
1249
1250
1251
    '14': function(n) {
      if ((isBetween((n % 100), 3, 4))) {
        return 'few';
0e9aeacd   root   localization l20n
1252
      }
c5169e0e   Renato De Donato   a new hope
1253
1254
1255
1256
1257
1258
1259
      if ((n % 100) === 2) {
        return 'two';
      }
      if ((n % 100) === 1) {
        return 'one';
      }
      return 'other';
a1a3bc73   Luigi Serra   graphs updates
1260
    },
c5169e0e   Renato De Donato   a new hope
1261
1262
1263
1264
1265
1266
    '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
1267
      }
c5169e0e   Renato De Donato   a new hope
1268
1269
      if (n === 1) {
        return 'one';
0e9aeacd   root   localization l20n
1270
      }
c5169e0e   Renato De Donato   a new hope
1271
      return 'other';
0e9aeacd   root   localization l20n
1272
    },
c5169e0e   Renato De Donato   a new hope
1273
1274
1275
    '16': function(n) {
      if ((n % 10) === 1 && n !== 11) {
        return 'one';
0e9aeacd   root   localization l20n
1276
      }
c5169e0e   Renato De Donato   a new hope
1277
      return 'other';
0e9aeacd   root   localization l20n
1278
    },
c5169e0e   Renato De Donato   a new hope
1279
1280
1281
    '17': function(n) {
      if (n === 3) {
        return 'few';
0e9aeacd   root   localization l20n
1282
      }
c5169e0e   Renato De Donato   a new hope
1283
1284
      if (n === 0) {
        return 'zero';
a1a3bc73   Luigi Serra   graphs updates
1285
      }
c5169e0e   Renato De Donato   a new hope
1286
1287
      if (n === 6) {
        return 'many';
a1a3bc73   Luigi Serra   graphs updates
1288
      }
c5169e0e   Renato De Donato   a new hope
1289
1290
1291
1292
1293
1294
1295
      if (n === 2) {
        return 'two';
      }
      if (n === 1) {
        return 'one';
      }
      return 'other';
0e9aeacd   root   localization l20n
1296
    },
c5169e0e   Renato De Donato   a new hope
1297
1298
1299
    '18': function(n) {
      if (n === 0) {
        return 'zero';
0e9aeacd   root   localization l20n
1300
      }
c5169e0e   Renato De Donato   a new hope
1301
1302
1303
1304
      if ((isBetween(n, 0, 2)) && n !== 0 && n !== 2) {
        return 'one';
      }
      return 'other';
0e9aeacd   root   localization l20n
1305
    },
c5169e0e   Renato De Donato   a new hope
1306
1307
1308
    '19': function(n) {
      if ((isBetween(n, 2, 10))) {
        return 'few';
0e9aeacd   root   localization l20n
1309
      }
c5169e0e   Renato De Donato   a new hope
1310
1311
      if ((isBetween(n, 0, 1))) {
        return 'one';
0e9aeacd   root   localization l20n
1312
      }
c5169e0e   Renato De Donato   a new hope
1313
1314
1315
1316
1317
1318
1319
1320
1321
      return 'other';
    },
    '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
1322
      }
c5169e0e   Renato De Donato   a new hope
1323
1324
1325
1326
1327
1328
1329
1330
      if ((n % 1000000) === 0 && n !== 0) {
        return 'many';
      }
      if ((n % 10) === 2 && !isIn((n % 100), [12, 72, 92])) {
        return 'two';
      }
      if ((n % 10) === 1 && !isIn((n % 100), [11, 71, 91])) {
        return 'one';
a1a3bc73   Luigi Serra   graphs updates
1331
      }
c5169e0e   Renato De Donato   a new hope
1332
      return 'other';
a1a3bc73   Luigi Serra   graphs updates
1333
    },
c5169e0e   Renato De Donato   a new hope
1334
1335
1336
    '21': function(n) {
      if (n === 0) {
        return 'zero';
0e9aeacd   root   localization l20n
1337
      }
c5169e0e   Renato De Donato   a new hope
1338
1339
      if (n === 1) {
        return 'one';
a1a3bc73   Luigi Serra   graphs updates
1340
      }
c5169e0e   Renato De Donato   a new hope
1341
      return 'other';
a1a3bc73   Luigi Serra   graphs updates
1342
    },
c5169e0e   Renato De Donato   a new hope
1343
1344
1345
    '22': function(n) {
      if ((isBetween(n, 0, 1)) || (isBetween(n, 11, 99))) {
        return 'one';
0e9aeacd   root   localization l20n
1346
      }
c5169e0e   Renato De Donato   a new hope
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
      return 'other';
    },
    '23': function(n) {
      if ((isBetween((n % 10), 1, 2)) || (n % 20) === 0) {
        return 'one';
      }
      return 'other';
    },
    '24': function(n) {
      if ((isBetween(n, 3, 10) || isBetween(n, 13, 19))) {
        return 'few';
      }
      if (isIn(n, [2, 12])) {
        return 'two';
a1a3bc73   Luigi Serra   graphs updates
1361
      }
c5169e0e   Renato De Donato   a new hope
1362
1363
1364
1365
1366
1367
      if (isIn(n, [1, 11])) {
        return 'one';
      }
      return 'other';
    }
  };
0e9aeacd   root   localization l20n
1368
  
c5169e0e   Renato De Donato   a new hope
1369
1370
1371
1372
1373
1374
1375
1376
  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
1377
  
c5169e0e   Renato De Donato   a new hope
1378
1379
1380
1381
1382
  class Context {
    constructor(env) {
      this._env = env;
      this._numberFormatters = null;
    }
0e9aeacd   root   localization l20n
1383
  
c5169e0e   Renato De Donato   a new hope
1384
1385
1386
1387
1388
1389
1390
1391
    _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
1392
      }
c5169e0e   Renato De Donato   a new hope
1393
    }
0e9aeacd   root   localization l20n
1394
  
c5169e0e   Renato De Donato   a new hope
1395
1396
    _formatEntity(lang, args, entity, id) {
      const [, value] = this._formatTuple(lang, args, entity, id);
0e9aeacd   root   localization l20n
1397
  
c5169e0e   Renato De Donato   a new hope
1398
1399
1400
1401
      const formatted = {
        value,
        attrs: null,
      };
0e9aeacd   root   localization l20n
1402
  
c5169e0e   Renato De Donato   a new hope
1403
1404
1405
1406
1407
1408
1409
      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
1410
        }
a1a3bc73   Luigi Serra   graphs updates
1411
      }
0e9aeacd   root   localization l20n
1412
  
c5169e0e   Renato De Donato   a new hope
1413
1414
      return formatted;
    }
0e9aeacd   root   localization l20n
1415
  
c5169e0e   Renato De Donato   a new hope
1416
1417
1418
    _formatValue(lang, args, entity, id) {
      return this._formatTuple(lang, args, entity, id)[1];
    }
a1a3bc73   Luigi Serra   graphs updates
1419
  
c5169e0e   Renato De Donato   a new hope
1420
1421
1422
    fetch(langs) {
      if (langs.length === 0) {
        return Promise.resolve(langs);
0e9aeacd   root   localization l20n
1423
1424
      }
  
c5169e0e   Renato De Donato   a new hope
1425
      const resIds = Array.from(this._env._resLists.get(this));
0e9aeacd   root   localization l20n
1426
  
c5169e0e   Renato De Donato   a new hope
1427
1428
1429
1430
1431
      return Promise.all(
        resIds.map(
          this._env._getResource.bind(this._env, langs[0]))).then(
            () => langs);
    }
0e9aeacd   root   localization l20n
1432
  
c5169e0e   Renato De Donato   a new hope
1433
1434
    _resolve(langs, keys, formatter, prevResolved) {
      const lang = langs[0];
0e9aeacd   root   localization l20n
1435
  
c5169e0e   Renato De Donato   a new hope
1436
1437
      if (!lang) {
        return reportMissing.call(this, keys, formatter, prevResolved);
0e9aeacd   root   localization l20n
1438
      }
a1a3bc73   Luigi Serra   graphs updates
1439
  
c5169e0e   Renato De Donato   a new hope
1440
      let hasUnresolved = false;
a1a3bc73   Luigi Serra   graphs updates
1441
  
c5169e0e   Renato De Donato   a new hope
1442
1443
1444
1445
1446
1447
1448
      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
1449
  
c5169e0e   Renato De Donato   a new hope
1450
1451
        if (entity) {
          return formatter.call(this, lang, args, entity, id);
a1a3bc73   Luigi Serra   graphs updates
1452
        }
c5169e0e   Renato De Donato   a new hope
1453
1454
1455
1456
1457
1458
1459
1460
1461
  
        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
1462
      }
0e9aeacd   root   localization l20n
1463
  
c5169e0e   Renato De Donato   a new hope
1464
1465
1466
      return this.fetch(langs.slice(1)).then(
        nextLangs => this._resolve(nextLangs, keys, formatter, resolved));
    }
0e9aeacd   root   localization l20n
1467
  
c5169e0e   Renato De Donato   a new hope
1468
1469
1470
1471
    resolveEntities(langs, keys) {
      return this.fetch(langs).then(
        langs => this._resolve(langs, keys, this._formatEntity));
    }
0e9aeacd   root   localization l20n
1472
  
c5169e0e   Renato De Donato   a new hope
1473
1474
1475
1476
    resolveValues(langs, keys) {
      return this.fetch(langs).then(
        langs => this._resolve(langs, keys, this._formatValue));
    }
a1a3bc73   Luigi Serra   graphs updates
1477
  
c5169e0e   Renato De Donato   a new hope
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
    _getEntity(lang, id) {
      const cache = this._env._resCache;
      const resIds = Array.from(this._env._resLists.get(this));
  
      // 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];
        }
0e9aeacd   root   localization l20n
1491
      }
c5169e0e   Renato De Donato   a new hope
1492
1493
      return undefined;
    }
0e9aeacd   root   localization l20n
1494
  
c5169e0e   Renato De Donato   a new hope
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
    _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);
    }
0e9aeacd   root   localization l20n
1508
  
c5169e0e   Renato De Donato   a new hope
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
    // 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
1519
  
c5169e0e   Renato De Donato   a new hope
1520
  }
a1a3bc73   Luigi Serra   graphs updates
1521
  
c5169e0e   Renato De Donato   a new hope
1522
1523
  function reportMissing(keys, formatter, resolved) {
    const missingIds = new Set();
a1a3bc73   Luigi Serra   graphs updates
1524
  
c5169e0e   Renato De Donato   a new hope
1525
1526
1527
    keys.forEach((key, i) => {
      if (resolved && resolved[i] !== undefined) {
        return;
a1a3bc73   Luigi Serra   graphs updates
1528
      }
c5169e0e   Renato De Donato   a new hope
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
      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
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
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
  
  // 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')
    }
  });
  
  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);
  }
  
c5169e0e   Renato De Donato   a new hope
1729
1730
1731
1732
1733
  const parsers = {
    properties: PropertiesParser,
    l20n: L20nParser,
  };
  
0e9aeacd   root   localization l20n
1734
  class Env$1 {
c5169e0e   Renato De Donato   a new hope
1735
1736
    constructor(defaultLang, fetchResource) {
      this.defaultLang = defaultLang;
0e9aeacd   root   localization l20n
1737
1738
      this.fetchResource = fetchResource;
  
c5169e0e   Renato De Donato   a new hope
1739
1740
      this._resLists = new Map();
      this._resCache = new Map();
0e9aeacd   root   localization l20n
1741
1742
1743
1744
1745
1746
1747
  
      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
1748
1749
1750
    createContext(resIds) {
      const ctx = new Context(this);
      this._resLists.set(ctx, new Set(resIds));
0e9aeacd   root   localization l20n
1751
1752
1753
1754
      return ctx;
    }
  
    destroyContext(ctx) {
c5169e0e   Renato De Donato   a new hope
1755
1756
      const lists = this._resLists;
      const resList = lists.get(ctx);
0e9aeacd   root   localization l20n
1757
  
c5169e0e   Renato De Donato   a new hope
1758
1759
1760
      lists.delete(ctx);
      resList.forEach(
        resId => deleteIfOrphan(this._resCache, lists, resId));
0e9aeacd   root   localization l20n
1761
1762
1763
    }
  
    _parse(syntax, lang, data) {
c5169e0e   Renato De Donato   a new hope
1764
      const parser = parsers[syntax];
0e9aeacd   root   localization l20n
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
      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
1787
      const cache = this._resCache;
0e9aeacd   root   localization l20n
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
      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
1808
        { code: this.defaultLang, src: 'app' } :
0e9aeacd   root   localization l20n
1809
1810
        lang;
  
c5169e0e   Renato De Donato   a new hope
1811
1812
      const resource = this.fetchResource(res, langToFetch).then(
        saveEntries, recover);
0e9aeacd   root   localization l20n
1813
1814
1815
1816
1817
1818
1819
  
      cache.set(id, resource);
  
      return resource;
    }
  }
  
c5169e0e   Renato De Donato   a new hope
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
  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
1830
1831
1832
1833
1834
1835
1836
  function amendError(lang, err) {
    err.lang = lang;
    return err;
  }
  
  exports.fetchResource = fetchResource$1;
  exports.Env = Env$1;