You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 7-8.RSVP
Socket
Socket
Sign inDemoInstall

@angular/compiler

Package Overview
Dependencies
Maintainers
1
Versions
822
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.2.1 to 2.3.0-beta.0

src/i18n/serializers/xmb.metadata.json

2

bundles/compiler-testing.umd.js
/**
* @license Angular v2.2.1
* @license Angular v2.3.0-beta.0
* (c) 2010-2016 Google, Inc. https://angular.io/

@@ -4,0 +4,0 @@ * License: MIT

{
"name": "@angular/compiler",
"version": "2.2.1",
"version": "2.3.0-beta.0",
"description": "Angular - the compiler library",

@@ -11,3 +11,3 @@ "main": "bundles/compiler.umd.js",

"peerDependencies": {
"@angular/core": "2.2.1"
"@angular/core": "2.3.0-beta.0"
},

@@ -14,0 +14,0 @@ "repository": {

@@ -9,3 +9,4 @@ /**

import * as i18n from './i18n_ast';
export declare function digestMessage(message: i18n.Message): string;
export declare function digest(message: i18n.Message): string;
export declare function decimalDigest(message: i18n.Message): string;
export declare function serializeNodes(nodes: i18n.Node[]): string[];

@@ -21,1 +22,11 @@ /**

export declare function sha1(str: string): string;
/**
* Compute the fingerprint of the given string
*
* The output is 64 bit number encoded as a decimal string
*
* based on:
* https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
*/
export declare function fingerprint(str: string): [number, number];
export declare function computeMsgId(msg: string, meaning: string): string;

@@ -8,5 +8,15 @@ /**

*/
export function digestMessage(message) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
export function digest(message) {
return sha1(serializeNodes(message.nodes).join('') + ("[" + message.meaning + "]"));
}
export function decimalDigest(message) {
var visitor = new _SerializerIgnoreIcuExpVisitor();
var parts = message.nodes.map(function (a) { return a.visit(visitor, null); });
return computeMsgId(parts.join(''), message.meaning);
}
/**

@@ -39,3 +49,3 @@ * Serialize the i18n ast to something xml-like in order to generate an UID.

_SerializerVisitor.prototype.visitPlaceholder = function (ph, context) {
return "<ph name=\"" + ph.name + "\">" + ph.value + "</ph>";
return ph.value ? "<ph name=\"" + ph.name + "\">" + ph.value + "</ph>" : "<ph name=\"" + ph.name + "\"/>";
};

@@ -52,2 +62,22 @@ _SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {

/**
* Serialize the i18n ast to something xml-like in order to generate an UID.
*
* Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
*
* @internal
*/
var _SerializerIgnoreIcuExpVisitor = (function (_super) {
__extends(_SerializerIgnoreIcuExpVisitor, _super);
function _SerializerIgnoreIcuExpVisitor() {
_super.apply(this, arguments);
}
_SerializerIgnoreIcuExpVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var strCases = Object.keys(icu.cases).map(function (k) { return (k + " {" + icu.cases[k].visit(_this) + "}"); });
// Do not take the expression into account
return "{" + icu.type + ", " + strCases.join(', ') + "}";
};
return _SerializerIgnoreIcuExpVisitor;
}(_SerializerVisitor));
/**
* Compute the SHA1 of the given string

@@ -62,3 +92,3 @@ *

var utf8 = utf8Encode(str);
var words32 = stringToWords32(utf8);
var words32 = stringToWords32(utf8, Endian.Big);
var len = utf8.length * 8;

@@ -84,11 +114,100 @@ var w = new Array(80);

}
var sha1 = words32ToString([a, b, c, d, e]);
var hex = '';
for (var i = 0; i < sha1.length; i++) {
var b_1 = sha1.charCodeAt(i);
hex += (b_1 >>> 4 & 0x0f).toString(16) + (b_1 & 0x0f).toString(16);
}
return hex.toLowerCase();
return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
var _d, _e;
}
function fk(index, b, c, d) {
if (index < 20) {
return [(b & c) | (~b & d), 0x5a827999];
}
if (index < 40) {
return [b ^ c ^ d, 0x6ed9eba1];
}
if (index < 60) {
return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
}
return [b ^ c ^ d, 0xca62c1d6];
}
/**
* Compute the fingerprint of the given string
*
* The output is 64 bit number encoded as a decimal string
*
* based on:
* https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
*/
export function fingerprint(str) {
var utf8 = utf8Encode(str);
var _a = [hash32(utf8, 0), hash32(utf8, 102072)], hi = _a[0], lo = _a[1];
if (hi == 0 && (lo == 0 || lo == 1)) {
hi = hi ^ 0x130f9bef;
lo = lo ^ -0x6b5f56d8;
}
return [hi, lo];
}
export function computeMsgId(msg, meaning) {
var _a = fingerprint(msg), hi = _a[0], lo = _a[1];
if (meaning) {
var _b = fingerprint(meaning), him = _b[0], lom = _b[1];
_c = add64(rol64([hi, lo], 1), [him, lom]), hi = _c[0], lo = _c[1];
}
return byteStringToDecString(words32ToByteString([hi & 0x7fffffff, lo]));
var _c;
}
function hash32(str, c) {
var _a = [0x9e3779b9, 0x9e3779b9], a = _a[0], b = _a[1];
var i;
var len = str.length;
for (i = 0; i + 12 <= len; i += 12) {
a = add32(a, wordAt(str, i, Endian.Little));
b = add32(b, wordAt(str, i + 4, Endian.Little));
c = add32(c, wordAt(str, i + 8, Endian.Little));
_b = mix([a, b, c]), a = _b[0], b = _b[1], c = _b[2];
}
a = add32(a, wordAt(str, i, Endian.Little));
b = add32(b, wordAt(str, i + 4, Endian.Little));
// the first byte of c is reserved for the length
c = add32(c, len);
c = add32(c, wordAt(str, i + 8, Endian.Little) << 8);
return mix([a, b, c])[2];
var _b;
}
// clang-format off
function mix(_a) {
var a = _a[0], b = _a[1], c = _a[2];
a = sub32(a, b);
a = sub32(a, c);
a ^= c >>> 13;
b = sub32(b, c);
b = sub32(b, a);
b ^= a << 8;
c = sub32(c, a);
c = sub32(c, b);
c ^= b >>> 13;
a = sub32(a, b);
a = sub32(a, c);
a ^= c >>> 12;
b = sub32(b, c);
b = sub32(b, a);
b ^= a << 16;
c = sub32(c, a);
c = sub32(c, b);
c ^= b >>> 5;
a = sub32(a, b);
a = sub32(a, c);
a ^= c >>> 3;
b = sub32(b, c);
b = sub32(b, a);
b ^= a << 10;
c = sub32(c, a);
c = sub32(c, b);
c ^= b >>> 15;
return [a, b, c];
}
// clang-format on
// Utils
var Endian;
(function (Endian) {
Endian[Endian["Little"] = 0] = "Little";
Endian[Endian["Big"] = 1] = "Big";
})(Endian || (Endian = {}));
function utf8Encode(str) {

@@ -119,5 +238,4 @@ var encoded = '';

var high = str.charCodeAt(index);
var low;
if (high >= 0xd800 && high <= 0xdfff && str.length > index + 1) {
low = str.charCodeAt(index + 1);
var low = byteAt(str, index + 1);
if (low >= 0xdc00 && low <= 0xdfff) {

@@ -129,39 +247,112 @@ return (high - 0xd800) * 0x400 + low - 0xdc00 + 0x10000;

}
function stringToWords32(str) {
var words32 = Array(str.length >>> 2);
function add32(a, b) {
return add32to64(a, b)[1];
}
function add32to64(a, b) {
var low = (a & 0xffff) + (b & 0xffff);
var high = (a >>> 16) + (b >>> 16) + (low >>> 16);
return [high >>> 16, (high << 16) | (low & 0xffff)];
}
function add64(_a, _b) {
var ah = _a[0], al = _a[1];
var bh = _b[0], bl = _b[1];
var _c = add32to64(al, bl), carry = _c[0], l = _c[1];
var h = add32(add32(ah, bh), carry);
return [h, l];
}
function sub32(a, b) {
var low = (a & 0xffff) - (b & 0xffff);
var high = (a >> 16) - (b >> 16) + (low >> 16);
return (high << 16) | (low & 0xffff);
}
// Rotate a 32b number left `count` position
function rol32(a, count) {
return (a << count) | (a >>> (32 - count));
}
// Rotate a 64b number left `count` position
function rol64(_a, count) {
var hi = _a[0], lo = _a[1];
var h = (hi << count) | (lo >>> (32 - count));
var l = (lo << count) | (hi >>> (32 - count));
return [h, l];
}
function stringToWords32(str, endian) {
var words32 = Array((str.length + 3) >>> 2);
for (var i = 0; i < words32.length; i++) {
words32[i] = 0;
words32[i] = wordAt(str, i * 4, endian);
}
for (var i = 0; i < str.length; i++) {
words32[i >>> 2] |= (str.charCodeAt(i) & 0xff) << 8 * (3 - i & 0x3);
}
return words32;
}
function words32ToString(words32) {
function byteAt(str, index) {
return index >= str.length ? 0 : str.charCodeAt(index) & 0xff;
}
function wordAt(str, index, endian) {
var word = 0;
if (endian === Endian.Big) {
for (var i = 0; i < 4; i++) {
word += byteAt(str, index + i) << (24 - 8 * i);
}
}
else {
for (var i = 0; i < 4; i++) {
word += byteAt(str, index + i) << 8 * i;
}
}
return word;
}
function words32ToByteString(words32) {
return words32.reduce(function (str, word) { return str + word32ToByteString(word); }, '');
}
function word32ToByteString(word) {
var str = '';
for (var i = 0; i < words32.length * 4; i++) {
str += String.fromCharCode((words32[i >>> 2] >>> 8 * (3 - i & 0x3)) & 0xff);
for (var i = 0; i < 4; i++) {
str += String.fromCharCode((word >>> 8 * (3 - i)) & 0xff);
}
return str;
}
function fk(index, b, c, d) {
if (index < 20) {
return [(b & c) | (~b & d), 0x5a827999];
function byteStringToHexString(str) {
var hex = '';
for (var i = 0; i < str.length; i++) {
var b = byteAt(str, i);
hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
}
if (index < 40) {
return [b ^ c ^ d, 0x6ed9eba1];
return hex.toLowerCase();
}
// based on http://www.danvk.org/hex2dec.html (JS can not handle more than 56b)
function byteStringToDecString(str) {
var decimal = '';
var toThePower = '1';
for (var i = str.length - 1; i >= 0; i--) {
decimal = addBigInt(decimal, numberTimesBigInt(byteAt(str, i), toThePower));
toThePower = numberTimesBigInt(256, toThePower);
}
if (index < 60) {
return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
return decimal.split('').reverse().join('');
}
// x and y decimal, lowest significant digit first
function addBigInt(x, y) {
var sum = '';
var len = Math.max(x.length, y.length);
for (var i = 0, carry = 0; i < len || carry; i++) {
var tmpSum = carry + +(x[i] || 0) + +(y[i] || 0);
if (tmpSum >= 10) {
carry = 1;
sum += tmpSum - 10;
}
else {
carry = 0;
sum += tmpSum;
}
}
return [b ^ c ^ d, 0xca62c1d6];
return sum;
}
function add32(a, b) {
var low = (a & 0xffff) + (b & 0xffff);
var high = (a >> 16) + (b >> 16) + (low >> 16);
return (high << 16) | (low & 0xffff);
function numberTimesBigInt(num, b) {
var product = '';
var bToThePower = b;
for (; num !== 0; num = num >>> 1) {
if (num & 1)
product = addBigInt(product, bToThePower);
bToThePower = addBigInt(bToThePower, bToThePower);
}
return product;
}
function rol32(a, count) {
return (a << count) | (a >>> (32 - count));
}
//# sourceMappingURL=digest.js.map

@@ -1,1 +0,1 @@

{"__symbolic":"module","version":1,"metadata":{"digestMessage":{"__symbolic":"function","parameters":["message"],"value":{"__symbolic":"call","expression":{"__symbolic":"reference","name":"sha1"},"arguments":[{"__symbolic":"binop","operator":"+","left":{"__symbolic":"call","expression":{"__symbolic":"select","expression":{"__symbolic":"call","expression":{"__symbolic":"reference","name":"serializeNodes"},"arguments":[{"__symbolic":"select","expression":{"__symbolic":"reference","name":"message"},"member":"nodes"}]},"member":"join"},"arguments":[""]},"right":{"__symbolic":"error","message":"Expression form not supported","line":11,"character":55}}]}},"serializeNodes":{"__symbolic":"function","parameters":["nodes"],"value":{"__symbolic":"error","message":"Function call not supported","line":52,"character":19}}}}
{"__symbolic":"module","version":1,"metadata":{"digest":{"__symbolic":"function","parameters":["message"],"value":{"__symbolic":"call","expression":{"__symbolic":"reference","name":"sha1"},"arguments":[{"__symbolic":"binop","operator":"+","left":{"__symbolic":"call","expression":{"__symbolic":"select","expression":{"__symbolic":"call","expression":{"__symbolic":"reference","name":"serializeNodes"},"arguments":[{"__symbolic":"select","expression":{"__symbolic":"reference","name":"message"},"member":"nodes"}]},"member":"join"},"arguments":[""]},"right":{"__symbolic":"error","message":"Expression form not supported","line":11,"character":55}}]}},"serializeNodes":{"__symbolic":"function","parameters":["nodes"],"value":{"__symbolic":"error","message":"Function call not supported","line":58,"character":19}}}}

@@ -10,3 +10,2 @@ /**

import { ParseTreeResult } from '../ml_parser/parser';
import { digestMessage } from './digest';
import * as i18n from './i18n_ast';

@@ -158,4 +157,4 @@ import { createI18nMessageFactory } from './i18n_parser';

var i18nAttr = _getI18nAttr(el);
var isImplicit = this._implicitTags.some(function (tag) { return el.name === tag; }) &&
!this._inIcu && !this._isInTranslatableSection;
var isImplicit = this._implicitTags.some(function (tag) { return el.name === tag; }) && !this._inIcu &&
!this._isInTranslatableSection;
var isTopLevelImplicit = !wasInImplicitNode && isImplicit;

@@ -277,8 +276,7 @@ this._inImplicitNode = this._inImplicitNode || isImplicit;

if (message && this._mode === _VisitorMode.Merge) {
var id = digestMessage(message);
var nodes = this._translations.get(id);
var nodes = this._translations.get(message);
if (nodes) {
return nodes;
}
this._reportError(el, "Translation unavailable for message id=\"" + id + "\"");
this._reportError(el, "Translation unavailable for message id=\"" + this._translations.digest(message) + "\"");
}

@@ -307,4 +305,3 @@ return [];

var message = _this._createI18nMessage([attr], meaning, '');
var id = digestMessage(message);
var nodes = _this._translations.get(id);
var nodes = _this._translations.get(message);
if (nodes) {

@@ -316,7 +313,7 @@ if (nodes[0] instanceof html.Text) {

else {
_this._reportError(el, "Unexpected translation for attribute \"" + attr.name + "\" (id=\"" + id + "\")");
_this._reportError(el, "Unexpected translation for attribute \"" + attr.name + "\" (id=\"" + _this._translations.digest(message) + "\")");
}
}
else {
_this._reportError(el, "Translation unavailable for attribute \"" + attr.name + "\" (id=\"" + id + "\")");
_this._reportError(el, "Translation unavailable for attribute \"" + attr.name + "\" (id=\"" + _this._translations.digest(message) + "\")");
}

@@ -323,0 +320,0 @@ }

@@ -12,6 +12,6 @@ /**

placeholders: {
[name: string]: string;
[phName: string]: string;
};
placeholderToMsgIds: {
[name: string]: string;
placeholderToMessage: {
[phName: string]: Message;
};

@@ -23,4 +23,3 @@ meaning: string;

* @param placeholders maps placeholder names to static content
* @param placeholderToMsgIds maps placeholder names to translatable message IDs (used for ICU
* messages)
* @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
* @param meaning

@@ -30,8 +29,9 @@ * @param description

constructor(nodes: Node[], placeholders: {
[name: string]: string;
}, placeholderToMsgIds: {
[name: string]: string;
[phName: string]: string;
}, placeholderToMessage: {
[phName: string]: Message;
}, meaning: string, description: string);
}
export interface Node {
sourceSpan: ParseSourceSpan;
visit(visitor: Visitor, context?: any): any;

@@ -58,2 +58,3 @@ }

sourceSpan: ParseSourceSpan;
expressionPlaceholder: string;
constructor(expression: string, type: string, cases: {

@@ -60,0 +61,0 @@ [k: string]: Node;

@@ -12,11 +12,10 @@ /**

* @param placeholders maps placeholder names to static content
* @param placeholderToMsgIds maps placeholder names to translatable message IDs (used for ICU
* messages)
* @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
* @param meaning
* @param description
*/
function Message(nodes, placeholders, placeholderToMsgIds, meaning, description) {
function Message(nodes, placeholders, placeholderToMessage, meaning, description) {
this.nodes = nodes;
this.placeholders = placeholders;
this.placeholderToMsgIds = placeholderToMsgIds;
this.placeholderToMessage = placeholderToMessage;
this.meaning = meaning;

@@ -35,2 +34,3 @@ this.description = description;

}());
// TODO(vicb): do we really need this node (vs an array) ?
export var Container = (function () {

@@ -69,3 +69,2 @@ function Container(children, sourceSpan) {

function Placeholder(value, name, sourceSpan) {
if (name === void 0) { name = ''; }
this.value = value;

@@ -80,3 +79,2 @@ this.name = name;

function IcuPlaceholder(value, name, sourceSpan) {
if (name === void 0) { name = ''; }
this.value = value;

@@ -83,0 +81,0 @@ this.name = name;

@@ -18,3 +18,3 @@ /**

parse(source: string, url: string, parseExpansionForms?: boolean, interpolationConfig?: InterpolationConfig): ParseTreeResult;
private _createSerializer(interpolationConfig);
private _createSerializer();
}

@@ -11,3 +11,2 @@ /**

import { mergeTranslations } from './extractor_merger';
import { MessageBundle } from './message_bundle';
import { Xliff } from './serializers/xliff';

@@ -35,12 +34,10 @@ import { Xmb } from './serializers/xmb';

// TODO(vicb): add support for implicit tags / attributes
var messageBundle = new MessageBundle(this._htmlParser, [], {});
var errors = messageBundle.updateFromTemplate(source, url, interpolationConfig);
if (errors && errors.length) {
return new ParseTreeResult(parseResult.rootNodes, parseResult.errors.concat(errors));
if (parseResult.errors.length) {
return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
}
var serializer = this._createSerializer(interpolationConfig);
var translationBundle = TranslationBundle.load(this._translations, url, messageBundle, serializer);
var serializer = this._createSerializer();
var translationBundle = TranslationBundle.load(this._translations, url, serializer);
return mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});
};
I18NHtmlParser.prototype._createSerializer = function (interpolationConfig) {
I18NHtmlParser.prototype._createSerializer = function () {
var format = (this._translationsFormat || 'xlf').toLowerCase();

@@ -51,7 +48,7 @@ switch (format) {

case 'xtb':
return new Xtb(this._htmlParser, interpolationConfig);
return new Xtb();
case 'xliff':
case 'xlf':
default:
return new Xliff(this._htmlParser, interpolationConfig);
return new Xliff();
}

@@ -58,0 +55,0 @@ };

@@ -12,3 +12,2 @@ /**

import { getHtmlTagDefinition } from '../ml_parser/html_tags';
import { digestMessage } from './digest';
import * as i18n from './i18n_ast';

@@ -36,5 +35,5 @@ import { PlaceholderRegistry } from './serializers/placeholder';

this._placeholderToContent = {};
this._placeholderToIds = {};
this._placeholderToMessage = {};
var i18nodes = html.visitAll(this, nodes, {});
return new i18n.Message(i18nodes, this._placeholderToContent, this._placeholderToIds, meaning, description);
return new i18n.Message(i18nodes, this._placeholderToContent, this._placeholderToMessage, meaning, description);
};

@@ -75,3 +74,8 @@ _I18nVisitor.prototype.visitElement = function (el, context) {

if (this._isIcu || this._icuDepth > 0) {
// If the message (vs a part of the message) is an ICU message returns it
// Returns an ICU node when:
// - the message (vs a part of the message) is an ICU message, or
// - the ICU message is nested.
var expPh = this._placeholderRegistry.getUniquePlaceholder("VAR_" + icu.type);
i18nIcu.expressionPlaceholder = expPh;
this._placeholderToContent[expPh] = icu.switchValue;
return i18nIcu;

@@ -86,3 +90,3 @@ }

var visitor = new _I18nVisitor(this._expressionParser, this._interpolationConfig);
this._placeholderToIds[phName] = digestMessage(visitor.toI18nMessage([icu], '', ''));
this._placeholderToMessage[phName] = visitor.toI18nMessage([icu], '', '');
return new i18n.IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);

@@ -89,0 +93,0 @@ };

@@ -20,3 +20,3 @@ /**

private _implicitAttrs;
private _messageMap;
private _messages;
constructor(_htmlParser: HtmlParser, _implicitTags: string[], _implicitAttrs: {

@@ -26,6 +26,4 @@ [k: string]: string[];

updateFromTemplate(html: string, url: string, interpolationConfig: InterpolationConfig): ParseError[];
getMessageMap(): {
[id: string]: Message;
};
getMessages(): Message[];
write(serializer: Serializer): string;
}

@@ -8,3 +8,2 @@ /**

*/
import { digestMessage } from './digest';
import { extractMessages } from './extractor_merger';

@@ -19,6 +18,5 @@ /**

this._implicitAttrs = _implicitAttrs;
this._messageMap = {};
this._messages = [];
}
MessageBundle.prototype.updateFromTemplate = function (html, url, interpolationConfig) {
var _this = this;
var htmlParserResult = this._htmlParser.parse(html, url, true, interpolationConfig);

@@ -32,8 +30,9 @@ if (htmlParserResult.errors.length) {

}
i18nParserResult.messages.forEach(function (message) { _this._messageMap[digestMessage(message)] = message; });
(_a = this._messages).push.apply(_a, i18nParserResult.messages);
var _a;
};
MessageBundle.prototype.getMessageMap = function () { return this._messageMap; };
MessageBundle.prototype.write = function (serializer) { return serializer.write(this._messageMap); };
MessageBundle.prototype.getMessages = function () { return this._messages; };
MessageBundle.prototype.write = function (serializer) { return serializer.write(this._messages); };
return MessageBundle;
}());
//# sourceMappingURL=message_bundle.js.map

@@ -41,4 +41,6 @@ /**

/**
* Creates unique names for placeholder with different content
* Creates unique names for placeholder with different content.
*
* Returns the same placeholder name when the content is identical.
*
* @internal

@@ -85,2 +87,5 @@ */

};
PlaceholderRegistry.prototype.getUniquePlaceholder = function (name) {
return this._generateUniqueName(name.toUpperCase());
};
// Generate a hash for a tag - does not take attribute order into account

@@ -95,13 +100,5 @@ PlaceholderRegistry.prototype._hashTag = function (tag, attrs, isVoid) {

PlaceholderRegistry.prototype._generateUniqueName = function (base) {
var name = base;
var next = this._placeHolderNameCounts[name];
if (!next) {
next = 1;
}
else {
name += "_" + next;
next++;
}
this._placeHolderNameCounts[base] = next;
return name;
var next = this._placeHolderNameCounts[base];
this._placeHolderNameCounts[base] = next ? next + 1 : 1;
return next ? base + "_" + next : base;
};

@@ -108,0 +105,0 @@ return PlaceholderRegistry;

@@ -8,22 +8,9 @@ /**

*/
import * as html from '../../ml_parser/ast';
import * as i18n from '../i18n_ast';
import { MessageBundle } from '../message_bundle';
export interface Serializer {
write(messageMap: {
[id: string]: i18n.Message;
}): string;
load(content: string, url: string, messageBundle: MessageBundle): {
[id: string]: html.Node[];
write(messages: i18n.Message[]): string;
load(content: string, url: string): {
[msgId: string]: i18n.Node[];
};
digest(message: i18n.Message): string;
}
export declare function extractPlaceholders(messageBundle: MessageBundle): {
[id: string]: {
[name: string]: string;
};
};
export declare function extractPlaceholderToIds(messageBundle: MessageBundle): {
[id: string]: {
[name: string]: string;
};
};

@@ -8,20 +8,2 @@ /**

*/
// Generate a map of placeholder to content indexed by message ids
export function extractPlaceholders(messageBundle) {
var messageMap = messageBundle.getMessageMap();
var placeholders = {};
Object.keys(messageMap).forEach(function (msgId) {
placeholders[msgId] = messageMap[msgId].placeholders;
});
return placeholders;
}
// Generate a map of placeholder to message ids indexed by message ids
export function extractPlaceholderToIds(messageBundle) {
var messageMap = messageBundle.getMessageMap();
var placeholderToIds = {};
Object.keys(messageMap).forEach(function (msgId) {
placeholderToIds[msgId] = messageMap[msgId].placeholderToMsgIds;
});
return placeholderToIds;
}
//# sourceMappingURL=serializer.js.map

@@ -1,24 +0,9 @@

/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ml from '../../ml_parser/ast';
import { HtmlParser } from '../../ml_parser/html_parser';
import { InterpolationConfig } from '../../ml_parser/interpolation_config';
import * as i18n from '../i18n_ast';
import { MessageBundle } from '../message_bundle';
import { Serializer } from './serializer';
export declare class Xliff implements Serializer {
private _htmlParser;
private _interpolationConfig;
constructor(_htmlParser: HtmlParser, _interpolationConfig: InterpolationConfig);
write(messageMap: {
[id: string]: i18n.Message;
}): string;
load(content: string, url: string, messageBundle: MessageBundle): {
[id: string]: ml.Node[];
write(messages: i18n.Message[]): string;
load(content: string, url: string): {
[msgId: string]: i18n.Node[];
};
digest(message: i18n.Message): string;
}

@@ -10,4 +10,5 @@ /**

import { XmlParser } from '../../ml_parser/xml_parser';
import { digest } from '../digest';
import * as i18n from '../i18n_ast';
import { I18nError } from '../parse_util';
import { extractPlaceholderToIds, extractPlaceholders } from './serializer';
import * as xml from './xml_helper';

@@ -25,11 +26,15 @@ var _VERSION = '1.2';

export var Xliff = (function () {
function Xliff(_htmlParser, _interpolationConfig) {
this._htmlParser = _htmlParser;
this._interpolationConfig = _interpolationConfig;
function Xliff() {
}
Xliff.prototype.write = function (messageMap) {
Xliff.prototype.write = function (messages) {
var _this = this;
var visitor = new _WriteVisitor();
var visited = {};
var transUnits = [];
Object.keys(messageMap).forEach(function (id) {
var message = messageMap[id];
messages.forEach(function (message) {
var id = _this.digest(message);
// deduplicate messages
if (visited[id])
return;
visited[id] = true;
var transUnit = new xml.Tag(_UNIT_TAG, { id: id, datatype: 'html' });

@@ -53,28 +58,20 @@ transUnit.children.push(new xml.CR(8), new xml.Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)), new xml.CR(8), new xml.Tag(_TARGET_TAG));

};
Xliff.prototype.load = function (content, url, messageBundle) {
var _this = this;
// Parse the xtb file into xml nodes
var result = new XmlParser().parse(content, url);
if (result.errors.length) {
throw new Error("xtb parse errors:\n" + result.errors.join('\n'));
}
// Replace the placeholders, messages are now string
var _a = new _LoadVisitor().parse(result.rootNodes, messageBundle), messages = _a.messages, errors = _a.errors;
Xliff.prototype.load = function (content, url) {
// xliff to xml nodes
var xliffParser = new XliffParser();
var _a = xliffParser.parse(content, url), mlNodesByMsgId = _a.mlNodesByMsgId, errors = _a.errors;
// xml nodes to i18n nodes
var i18nNodesByMsgId = {};
var converter = new XmlToI18n();
Object.keys(mlNodesByMsgId).forEach(function (msgId) {
var _a = converter.convert(mlNodesByMsgId[msgId]), i18nNodes = _a.i18nNodes, e = _a.errors;
errors.push.apply(errors, e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error("xtb parse errors:\n" + errors.join('\n'));
throw new Error("xliff parse errors:\n" + errors.join('\n'));
}
// Convert the string messages to html ast
// TODO(vicb): map error message back to the original message in xtb
var messageMap = {};
var parseErrors = [];
Object.keys(messages).forEach(function (id) {
var res = _this._htmlParser.parse(messages[id], url, true, _this._interpolationConfig);
parseErrors.push.apply(parseErrors, res.errors);
messageMap[id] = res.rootNodes;
});
if (parseErrors.length) {
throw new Error("xtb parse errors:\n" + parseErrors.join('\n'));
}
return messageMap;
return i18nNodesByMsgId;
};
Xliff.prototype.digest = function (message) { return digest(message); };
return Xliff;

@@ -130,60 +127,40 @@ }());

// TODO(vicb): add error management (structure)
// TODO(vicb): factorize (xtb) ?
var _LoadVisitor = (function () {
function _LoadVisitor() {
// Extract messages as xml nodes from the xliff file
var XliffParser = (function () {
function XliffParser() {
}
_LoadVisitor.prototype.parse = function (nodes, messageBundle) {
var _this = this;
this._messageNodes = [];
this._translatedMessages = {};
this._msgId = '';
this._target = [];
this._errors = [];
// Find all messages
ml.visitAll(this, nodes, null);
var messageMap = messageBundle.getMessageMap();
var placeholders = extractPlaceholders(messageBundle);
var placeholderToIds = extractPlaceholderToIds(messageBundle);
this._messageNodes
.filter(function (message) {
// Remove any messages that is not present in the source message bundle.
return messageMap.hasOwnProperty(message[0]);
})
.sort(function (a, b) {
// Because there could be no ICU placeholders inside an ICU message,
// we do not need to take into account the `placeholderToMsgIds` of the referenced
// messages, those would always be empty
// TODO(vicb): overkill - create 2 buckets and [...woDeps, ...wDeps].process()
if (Object.keys(messageMap[a[0]].placeholderToMsgIds).length == 0) {
return -1;
}
if (Object.keys(messageMap[b[0]].placeholderToMsgIds).length == 0) {
return 1;
}
return 0;
})
.forEach(function (message) {
var id = message[0];
_this._placeholders = placeholders[id] || {};
_this._placeholderToIds = placeholderToIds[id] || {};
// TODO(vicb): make sure there is no `_TRANSLATIONS_TAG` nor `_TRANSLATION_TAG`
_this._translatedMessages[id] = ml.visitAll(_this, message[1]).join('');
});
return { messages: this._translatedMessages, errors: this._errors };
XliffParser.prototype.parse = function (xliff, url) {
this._unitMlNodes = [];
this._mlNodesByMsgId = {};
var xml = new XmlParser().parse(xliff, url, false);
this._errors = xml.errors;
ml.visitAll(this, xml.rootNodes, null);
return {
mlNodesByMsgId: this._mlNodesByMsgId,
errors: this._errors,
};
};
_LoadVisitor.prototype.visitElement = function (element, context) {
XliffParser.prototype.visitElement = function (element, context) {
switch (element.name) {
case _UNIT_TAG:
this._target = null;
var msgId = element.attrs.find(function (attr) { return attr.name === 'id'; });
if (!msgId) {
this._unitMlNodes = null;
var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
if (!idAttr) {
this._addError(element, "<" + _UNIT_TAG + "> misses the \"id\" attribute");
}
else {
this._msgId = msgId.value;
var id = idAttr.value;
if (this._mlNodesByMsgId.hasOwnProperty(id)) {
this._addError(element, "Duplicated translations for msg " + id);
}
else {
ml.visitAll(this, element.children, null);
if (this._unitMlNodes) {
this._mlNodesByMsgId[id] = this._unitMlNodes;
}
else {
this._addError(element, "Message " + id + " misses a translation");
}
}
}
ml.visitAll(this, element.children, null);
if (this._msgId !== null) {
this._messageNodes.push([this._msgId, this._target]);
}
break;

@@ -194,42 +171,52 @@ case _SOURCE_TAG:

case _TARGET_TAG:
this._target = element.children;
this._unitMlNodes = element.children;
break;
case _PLACEHOLDER_TAG:
var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
if (!idAttr) {
this._addError(element, "<" + _PLACEHOLDER_TAG + "> misses the \"id\" attribute");
}
else {
var id = idAttr.value;
if (this._placeholders.hasOwnProperty(id)) {
return this._placeholders[id];
}
if (this._placeholderToIds.hasOwnProperty(id) &&
this._translatedMessages.hasOwnProperty(this._placeholderToIds[id])) {
return this._translatedMessages[this._placeholderToIds[id]];
}
// TODO(vicb): better error message for when
// !this._translatedMessages.hasOwnProperty(this._placeholderToIds[id])
this._addError(element, "The placeholder \"" + id + "\" does not exists in the source message");
}
break;
default:
// TODO(vicb): assert file structure, xliff version
// For now only recurse on unhandled nodes
ml.visitAll(this, element.children, null);
}
};
_LoadVisitor.prototype.visitAttribute = function (attribute, context) {
throw new Error('unreachable code');
XliffParser.prototype.visitAttribute = function (attribute, context) { };
XliffParser.prototype.visitText = function (text, context) { };
XliffParser.prototype.visitComment = function (comment, context) { };
XliffParser.prototype.visitExpansion = function (expansion, context) { };
XliffParser.prototype.visitExpansionCase = function (expansionCase, context) { };
XliffParser.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
_LoadVisitor.prototype.visitText = function (text, context) { return text.value; };
_LoadVisitor.prototype.visitComment = function (comment, context) { return ''; };
_LoadVisitor.prototype.visitExpansion = function (expansion, context) {
throw new Error('unreachable code');
return XliffParser;
}());
// Convert ml nodes (xliff syntax) to i18n nodes
var XmlToI18n = (function () {
function XmlToI18n() {
}
XmlToI18n.prototype.convert = function (nodes) {
this._errors = [];
return {
i18nNodes: ml.visitAll(this, nodes),
errors: this._errors,
};
};
_LoadVisitor.prototype.visitExpansionCase = function (expansionCase, context) {
throw new Error('unreachable code');
XmlToI18n.prototype.visitText = function (text, context) { return new i18n.Text(text.value, text.sourceSpan); };
XmlToI18n.prototype.visitElement = function (el, context) {
if (el.name === _PLACEHOLDER_TAG) {
var nameAttr = el.attrs.find(function (attr) { return attr.name === 'id'; });
if (nameAttr) {
return new i18n.Placeholder('', nameAttr.value, el.sourceSpan);
}
this._addError(el, "<" + _PLACEHOLDER_TAG + "> misses the \"id\" attribute");
}
else {
this._addError(el, "Unexpected tag");
}
};
_LoadVisitor.prototype._addError = function (node, message) {
XmlToI18n.prototype.visitExpansion = function (icu, context) { };
XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) { };
XmlToI18n.prototype.visitComment = function (comment, context) { };
XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
XmlToI18n.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return _LoadVisitor;
return XmlToI18n;
}());

@@ -236,0 +223,0 @@ function getCtypeForTag(tag) {

@@ -1,19 +0,10 @@

/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as html from '../../ml_parser/ast';
import * as i18n from '../i18n_ast';
import { MessageBundle } from '../message_bundle';
import { Serializer } from './serializer';
export declare class Xmb implements Serializer {
write(messageMap: {
[k: string]: i18n.Message;
}): string;
load(content: string, url: string, messageBundle: MessageBundle): {
[id: string]: html.Node[];
write(messages: i18n.Message[]): string;
load(content: string, url: string): {
[msgId: string]: i18n.Node[];
};
digest(message: i18n.Message): string;
}
export declare function digest(message: i18n.Message): string;

@@ -8,2 +8,3 @@ /**

*/
import { decimalDigest } from '../digest';
import * as xml from './xml_helper';

@@ -18,7 +19,13 @@ var _MESSAGES_TAG = 'messagebundle';

}
Xmb.prototype.write = function (messageMap) {
Xmb.prototype.write = function (messages) {
var _this = this;
var visitor = new _Visitor();
var visited = {};
var rootNode = new xml.Tag(_MESSAGES_TAG);
Object.keys(messageMap).forEach(function (id) {
var message = messageMap[id];
messages.forEach(function (message) {
var id = _this.digest(message);
// deduplicate messages
if (visited[id])
return;
visited[id] = true;
var attrs = { id: id };

@@ -43,5 +50,6 @@ if (message.description) {

};
Xmb.prototype.load = function (content, url, messageBundle) {
Xmb.prototype.load = function (content, url) {
throw new Error('Unsupported');
};
Xmb.prototype.digest = function (message) { return digest(message); };
return Xmb;

@@ -61,3 +69,3 @@ }());

var _this = this;
var nodes = [new xml.Text("{" + icu.expression + ", " + icu.type + ", ")];
var nodes = [new xml.Text("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
Object.keys(icu.cases).forEach(function (c) {

@@ -93,2 +101,5 @@ nodes.push.apply(nodes, [new xml.Text(c + " {")].concat(icu.cases[c].visit(_this), [new xml.Text("} ")]));

}());
export function digest(message) {
return decimalDigest(message);
}
//# sourceMappingURL=xmb.js.map

@@ -1,24 +0,9 @@

/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ml from '../../ml_parser/ast';
import { HtmlParser } from '../../ml_parser/html_parser';
import { InterpolationConfig } from '../../ml_parser/interpolation_config';
import * as i18n from '../i18n_ast';
import { MessageBundle } from '../message_bundle';
import { Serializer } from './serializer';
export declare class Xtb implements Serializer {
private _htmlParser;
private _interpolationConfig;
constructor(_htmlParser: HtmlParser, _interpolationConfig: InterpolationConfig);
write(messageMap: {
[id: string]: i18n.Message;
}): string;
load(content: string, url: string, messageBundle: MessageBundle): {
[id: string]: ml.Node[];
write(messages: i18n.Message[]): string;
load(content: string, url: string): {
[msgId: string]: i18n.Node[];
};
digest(message: i18n.Message): string;
}

@@ -10,4 +10,5 @@ /**

import { XmlParser } from '../../ml_parser/xml_parser';
import * as i18n from '../i18n_ast';
import { I18nError } from '../parse_util';
import { extractPlaceholderToIds, extractPlaceholders } from './serializer';
import { digest } from './xmb';
var _TRANSLATIONS_TAG = 'translationbundle';

@@ -17,78 +18,41 @@ var _TRANSLATION_TAG = 'translation';

export var Xtb = (function () {
function Xtb(_htmlParser, _interpolationConfig) {
this._htmlParser = _htmlParser;
this._interpolationConfig = _interpolationConfig;
function Xtb() {
}
Xtb.prototype.write = function (messageMap) { throw new Error('Unsupported'); };
Xtb.prototype.load = function (content, url, messageBundle) {
var _this = this;
// Parse the xtb file into xml nodes
var result = new XmlParser().parse(content, url);
if (result.errors.length) {
throw new Error("xtb parse errors:\n" + result.errors.join('\n'));
}
// Replace the placeholders, messages are now string
var _a = new _Visitor().parse(result.rootNodes, messageBundle), messages = _a.messages, errors = _a.errors;
Xtb.prototype.write = function (messages) { throw new Error('Unsupported'); };
Xtb.prototype.load = function (content, url) {
// xtb to xml nodes
var xtbParser = new XtbParser();
var _a = xtbParser.parse(content, url), mlNodesByMsgId = _a.mlNodesByMsgId, errors = _a.errors;
// xml nodes to i18n nodes
var i18nNodesByMsgId = {};
var converter = new XmlToI18n();
Object.keys(mlNodesByMsgId).forEach(function (msgId) {
var _a = converter.convert(mlNodesByMsgId[msgId]), i18nNodes = _a.i18nNodes, e = _a.errors;
errors.push.apply(errors, e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error("xtb parse errors:\n" + errors.join('\n'));
}
// Convert the string messages to html ast
// TODO(vicb): map error message back to the original message in xtb
var messageMap = {};
var parseErrors = [];
Object.keys(messages).forEach(function (id) {
var res = _this._htmlParser.parse(messages[id], url, true, _this._interpolationConfig);
parseErrors.push.apply(parseErrors, res.errors);
messageMap[id] = res.rootNodes;
});
if (parseErrors.length) {
throw new Error("xtb parse errors:\n" + parseErrors.join('\n'));
}
return messageMap;
return i18nNodesByMsgId;
};
Xtb.prototype.digest = function (message) { return digest(message); };
return Xtb;
}());
var _Visitor = (function () {
function _Visitor() {
// Extract messages as xml nodes from the xtb file
var XtbParser = (function () {
function XtbParser() {
}
_Visitor.prototype.parse = function (nodes, messageBundle) {
var _this = this;
this._messageNodes = [];
this._translatedMessages = {};
XtbParser.prototype.parse = function (xtb, url) {
this._bundleDepth = 0;
this._translationDepth = 0;
this._errors = [];
// Find all messages
ml.visitAll(this, nodes, null);
var messageMap = messageBundle.getMessageMap();
var placeholders = extractPlaceholders(messageBundle);
var placeholderToIds = extractPlaceholderToIds(messageBundle);
this._messageNodes
.filter(function (message) {
// Remove any messages that is not present in the source message bundle.
return messageMap.hasOwnProperty(message[0]);
})
.sort(function (a, b) {
// Because there could be no ICU placeholders inside an ICU message,
// we do not need to take into account the `placeholderToMsgIds` of the referenced
// messages, those would always be empty
// TODO(vicb): overkill - create 2 buckets and [...woDeps, ...wDeps].process()
if (Object.keys(messageMap[a[0]].placeholderToMsgIds).length == 0) {
return -1;
}
if (Object.keys(messageMap[b[0]].placeholderToMsgIds).length == 0) {
return 1;
}
return 0;
})
.forEach(function (message) {
var id = message[0];
_this._placeholders = placeholders[id] || {};
_this._placeholderToIds = placeholderToIds[id] || {};
// TODO(vicb): make sure there is no `_TRANSLATIONS_TAG` nor `_TRANSLATION_TAG`
_this._translatedMessages[id] = ml.visitAll(_this, message[1]).join('');
});
return { messages: this._translatedMessages, errors: this._errors };
this._mlNodesByMsgId = {};
var xml = new XmlParser().parse(xtb, url, true);
this._errors = xml.errors;
ml.visitAll(this, xml.rootNodes);
return {
mlNodesByMsgId: this._mlNodesByMsgId,
errors: this._errors,
};
};
_Visitor.prototype.visitElement = function (element, context) {
XtbParser.prototype.visitElement = function (element, context) {
switch (element.name) {

@@ -104,6 +68,2 @@ case _TRANSLATIONS_TAG:

case _TRANSLATION_TAG:
this._translationDepth++;
if (this._translationDepth > 1) {
this._addError(element, "<" + _TRANSLATION_TAG + "> elements can not be nested");
}
var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });

@@ -114,27 +74,9 @@ if (!idAttr) {

else {
// ICU placeholders are reference to other messages.
// The referenced message might not have been decoded yet.
// We need to have all messages available to make sure deps are decoded first.
// TODO(vicb): report an error on duplicate id
this._messageNodes.push([idAttr.value, element.children]);
}
this._translationDepth--;
break;
case _PLACEHOLDER_TAG:
var nameAttr = element.attrs.find(function (attr) { return attr.name === 'name'; });
if (!nameAttr) {
this._addError(element, "<" + _PLACEHOLDER_TAG + "> misses the \"name\" attribute");
}
else {
var name_1 = nameAttr.value;
if (this._placeholders.hasOwnProperty(name_1)) {
return this._placeholders[name_1];
var id = idAttr.value;
if (this._mlNodesByMsgId.hasOwnProperty(id)) {
this._addError(element, "Duplicated translations for msg " + id);
}
if (this._placeholderToIds.hasOwnProperty(name_1) &&
this._translatedMessages.hasOwnProperty(this._placeholderToIds[name_1])) {
return this._translatedMessages[this._placeholderToIds[name_1]];
else {
this._mlNodesByMsgId[id] = element.children;
}
// TODO(vicb): better error message for when
// !this._translatedMessages.hasOwnProperty(this._placeholderToIds[name])
this._addError(element, "The placeholder \"" + name_1 + "\" does not exists in the source message");
}

@@ -146,20 +88,56 @@ break;

};
_Visitor.prototype.visitAttribute = function (attribute, context) {
throw new Error('unreachable code');
XtbParser.prototype.visitAttribute = function (attribute, context) { };
XtbParser.prototype.visitText = function (text, context) { };
XtbParser.prototype.visitComment = function (comment, context) { };
XtbParser.prototype.visitExpansion = function (expansion, context) { };
XtbParser.prototype.visitExpansionCase = function (expansionCase, context) { };
XtbParser.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
_Visitor.prototype.visitText = function (text, context) { return text.value; };
_Visitor.prototype.visitComment = function (comment, context) { return ''; };
_Visitor.prototype.visitExpansion = function (expansion, context) {
var _this = this;
var strCases = expansion.cases.map(function (c) { return c.visit(_this, null); });
return "{" + expansion.switchValue + ", " + expansion.type + ", strCases.join(' ')}";
return XtbParser;
}());
// Convert ml nodes (xtb syntax) to i18n nodes
var XmlToI18n = (function () {
function XmlToI18n() {
}
XmlToI18n.prototype.convert = function (nodes) {
this._errors = [];
return {
i18nNodes: ml.visitAll(this, nodes),
errors: this._errors,
};
};
_Visitor.prototype.visitExpansionCase = function (expansionCase, context) {
return expansionCase.value + " {" + ml.visitAll(this, expansionCase.expression, null) + "}";
XmlToI18n.prototype.visitText = function (text, context) { return new i18n.Text(text.value, text.sourceSpan); };
XmlToI18n.prototype.visitExpansion = function (icu, context) {
var caseMap = {};
ml.visitAll(this, icu.cases).forEach(function (c) {
caseMap[c.value] = new i18n.Container(c.nodes, icu.sourceSpan);
});
return new i18n.Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
};
_Visitor.prototype._addError = function (node, message) {
XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
return {
value: icuCase.value,
nodes: ml.visitAll(this, icuCase.expression),
};
};
XmlToI18n.prototype.visitElement = function (el, context) {
if (el.name === _PLACEHOLDER_TAG) {
var nameAttr = el.attrs.find(function (attr) { return attr.name === 'name'; });
if (nameAttr) {
return new i18n.Placeholder('', nameAttr.value, el.sourceSpan);
}
this._addError(el, "<" + _PLACEHOLDER_TAG + "> misses the \"name\" attribute");
}
else {
this._addError(el, "Unexpected tag");
}
};
XmlToI18n.prototype.visitComment = function (comment, context) { };
XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
XmlToI18n.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return _Visitor;
return XmlToI18n;
}());
//# sourceMappingURL=xtb.js.map

@@ -9,3 +9,3 @@ /**

import * as html from '../ml_parser/ast';
import { MessageBundle } from './message_bundle';
import * as i18n from './i18n_ast';
import { Serializer } from './serializers/serializer';

@@ -16,9 +16,11 @@ /**

export declare class TranslationBundle {
private _messageMap;
constructor(_messageMap?: {
[id: string]: html.Node[];
});
static load(content: string, url: string, messageBundle: MessageBundle, serializer: Serializer): TranslationBundle;
get(id: string): html.Node[];
has(id: string): boolean;
private _i18nNodesByMsgId;
digest: (m: i18n.Message) => string;
private _i18nToHtml;
constructor(_i18nNodesByMsgId: {
[msgId: string]: i18n.Node[];
}, digest: (m: i18n.Message) => string);
static load(content: string, url: string, serializer: Serializer): TranslationBundle;
get(srcMsg: i18n.Message): html.Node[];
has(srcMsg: i18n.Message): boolean;
}

@@ -8,2 +8,4 @@ /**

*/
import { HtmlParser } from '../ml_parser/html_parser';
import { I18nError } from './parse_util';
/**

@@ -13,13 +15,91 @@ * A container for translated messages

export var TranslationBundle = (function () {
function TranslationBundle(_messageMap) {
if (_messageMap === void 0) { _messageMap = {}; }
this._messageMap = _messageMap;
function TranslationBundle(_i18nNodesByMsgId, digest) {
if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
this._i18nNodesByMsgId = _i18nNodesByMsgId;
this.digest = digest;
this._i18nToHtml = new I18nToHtmlVisitor(_i18nNodesByMsgId, digest);
}
TranslationBundle.load = function (content, url, messageBundle, serializer) {
return new TranslationBundle(serializer.load(content, url, messageBundle));
TranslationBundle.load = function (content, url, serializer) {
var i18nNodesByMsgId = serializer.load(content, url);
var digestFn = function (m) { return serializer.digest(m); };
return new TranslationBundle(i18nNodesByMsgId, digestFn);
};
TranslationBundle.prototype.get = function (id) { return this._messageMap[id]; };
TranslationBundle.prototype.has = function (id) { return id in this._messageMap; };
TranslationBundle.prototype.get = function (srcMsg) {
var html = this._i18nToHtml.convert(srcMsg);
if (html.errors.length) {
throw new Error(html.errors.join('\n'));
}
return html.nodes;
};
TranslationBundle.prototype.has = function (srcMsg) { return this.digest(srcMsg) in this._i18nNodesByMsgId; };
return TranslationBundle;
}());
var I18nToHtmlVisitor = (function () {
function I18nToHtmlVisitor(_i18nNodesByMsgId, _digest) {
if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
this._i18nNodesByMsgId = _i18nNodesByMsgId;
this._digest = _digest;
this._srcMsgStack = [];
this._errors = [];
}
I18nToHtmlVisitor.prototype.convert = function (srcMsg) {
this._srcMsgStack.length = 0;
this._errors.length = 0;
// i18n to text
var text = this._convertToText(srcMsg);
// text to html
var url = srcMsg.nodes[0].sourceSpan.start.file.url;
var html = new HtmlParser().parse(text, url, true);
return {
nodes: html.rootNodes,
errors: this._errors.concat(html.errors),
};
};
I18nToHtmlVisitor.prototype.visitText = function (text, context) { return text.value; };
I18nToHtmlVisitor.prototype.visitContainer = function (container, context) {
var _this = this;
return container.children.map(function (n) { return n.visit(_this); }).join('');
};
I18nToHtmlVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var cases = Object.keys(icu.cases).map(function (k) { return (k + " {" + icu.cases[k].visit(_this) + "}"); });
// TODO(vicb): Once all format switch to using expression placeholders
// we should throw when the placeholder is not in the source message
var exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
this._srcMsg.placeholders[icu.expression] :
icu.expression;
return "{" + exp + ", " + icu.type + ", " + cases.join(' ') + "}";
};
I18nToHtmlVisitor.prototype.visitPlaceholder = function (ph, context) {
var phName = ph.name;
if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
return this._srcMsg.placeholders[phName];
}
if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
}
this._addError(ph, "Unknown placeholder");
return '';
};
I18nToHtmlVisitor.prototype.visitTagPlaceholder = function (ph, context) { throw 'unreachable code'; };
I18nToHtmlVisitor.prototype.visitIcuPlaceholder = function (ph, context) { throw 'unreachable code'; };
I18nToHtmlVisitor.prototype._convertToText = function (srcMsg) {
var _this = this;
var digest = this._digest(srcMsg);
if (this._i18nNodesByMsgId.hasOwnProperty(digest)) {
this._srcMsgStack.push(this._srcMsg);
this._srcMsg = srcMsg;
var nodes = this._i18nNodesByMsgId[digest];
var text = nodes.map(function (node) { return node.visit(_this); }).join('');
this._srcMsg = this._srcMsgStack.pop();
return text;
}
this._addError(srcMsg.nodes[0], "Missing translation for message " + digest);
return '';
};
I18nToHtmlVisitor.prototype._addError = function (el, msg) {
this._errors.push(new I18nError(el.sourceSpan, msg));
};
return I18nToHtmlVisitor;
}());
//# sourceMappingURL=translation_bundle.js.map

@@ -8,3 +8,3 @@ /**

*/
import { isBlank, isPrimitive, isStrictStringMap } from './facade/lang';
import { isPrimitive, isStrictStringMap } from './facade/lang';
export var MODULE_SUFFIX = '';

@@ -53,3 +53,3 @@ var CAMEL_CASE_REGEXP = /([A-Z])/g;

}
if (isBlank(value) || isPrimitive(value)) {
if (value == null || isPrimitive(value)) {
return visitor.visitPrimitive(value, context);

@@ -56,0 +56,0 @@ }

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc