_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/compiler/test/render3/view/i18n_spec.ts_11051_18628 | describe('serializeI18nMessageForLocalize', () => {
const serialize = (input: string) => {
const tree = parse(`<div i18n>${input}</div>`, {leadingTriviaChars: LEADING_TRIVIA_CHARS});
const root = tree.nodes[0] as t.Element;
return serializeI18nMessageForLocalize(root.i18n as i18n.Message);
};
it('should serialize plain text for `$localize()`', () => {
expect(serialize('Some text')).toEqual({
messageParts: [literal('Some text')],
placeHolders: [],
});
});
it('should serialize text with interpolation for `$localize()`', () => {
expect(serialize('Some text {{ valueA }} and {{ valueB + valueC }} done')).toEqual({
messageParts: [literal('Some text '), literal(' and '), literal(' done')],
placeHolders: [placeholder('INTERPOLATION'), placeholder('INTERPOLATION_1')],
});
});
it('should compute source-spans when serializing text with interpolation for `$localize()`', () => {
const {messageParts, placeHolders} = serialize(
'Some text {{ valueA }} and {{ valueB + valueC }} done',
);
expect(messageParts[0].text).toEqual('Some text ');
expect(messageParts[0].sourceSpan.toString()).toEqual('Some text ');
expect(messageParts[1].text).toEqual(' and ');
expect(messageParts[1].sourceSpan.toString()).toEqual(' and ');
expect(messageParts[2].text).toEqual(' done');
expect(messageParts[2].sourceSpan.toString()).toEqual(' done');
expect(placeHolders[0].text).toEqual('INTERPOLATION');
expect(placeHolders[0].sourceSpan.toString()).toEqual('{{ valueA }}');
expect(placeHolders[1].text).toEqual('INTERPOLATION_1');
expect(placeHolders[1].sourceSpan.toString()).toEqual('{{ valueB + valueC }}');
});
it('should serialize text with interpolation at start for `$localize()`', () => {
expect(serialize('{{ valueA }} and {{ valueB + valueC }} done')).toEqual({
messageParts: [literal(''), literal(' and '), literal(' done')],
placeHolders: [placeholder('INTERPOLATION'), placeholder('INTERPOLATION_1')],
});
});
it('should serialize text with interpolation at end for `$localize()`', () => {
expect(serialize('Some text {{ valueA }} and {{ valueB + valueC }}')).toEqual({
messageParts: [literal('Some text '), literal(' and '), literal('')],
placeHolders: [placeholder('INTERPOLATION'), placeholder('INTERPOLATION_1')],
});
});
it('should serialize only interpolation for `$localize()`', () => {
expect(serialize('{{ valueB + valueC }}')).toEqual({
messageParts: [literal(''), literal('')],
placeHolders: [placeholder('INTERPOLATION')],
});
});
it('should serialize interpolation with named placeholder for `$localize()`', () => {
expect(serialize('{{ valueB + valueC // i18n(ph="PLACEHOLDER NAME") }}')).toEqual({
messageParts: [literal(''), literal('')],
placeHolders: [placeholder('PLACEHOLDER_NAME')],
});
});
it('should serialize content with HTML tags for `$localize()`', () => {
expect(serialize('A <span>B<div>C</div></span> D')).toEqual({
messageParts: [literal('A '), literal('B'), literal('C'), literal(''), literal(' D')],
placeHolders: [
placeholder('START_TAG_SPAN'),
placeholder('START_TAG_DIV'),
placeholder('CLOSE_TAG_DIV'),
placeholder('CLOSE_TAG_SPAN'),
],
});
});
it('should compute source-spans when serializing content with HTML tags for `$localize()`', () => {
const {messageParts, placeHolders} = serialize('A <span>B<div>C</div></span> D');
expect(messageParts[0].text).toEqual('A ');
expect(messageParts[0].sourceSpan.toString()).toEqual('A ');
expect(messageParts[1].text).toEqual('B');
expect(messageParts[1].sourceSpan.toString()).toEqual('B');
expect(messageParts[2].text).toEqual('C');
expect(messageParts[2].sourceSpan.toString()).toEqual('C');
expect(messageParts[3].text).toEqual('');
expect(messageParts[3].sourceSpan.toString()).toEqual('');
expect(messageParts[4].text).toEqual(' D');
expect(messageParts[4].sourceSpan.toString()).toEqual(' D');
expect(placeHolders[0].text).toEqual('START_TAG_SPAN');
expect(placeHolders[0].sourceSpan.toString()).toEqual('<span>');
expect(placeHolders[1].text).toEqual('START_TAG_DIV');
expect(placeHolders[1].sourceSpan.toString()).toEqual('<div>');
expect(placeHolders[2].text).toEqual('CLOSE_TAG_DIV');
expect(placeHolders[2].sourceSpan.toString()).toEqual('</div>');
expect(placeHolders[3].text).toEqual('CLOSE_TAG_SPAN');
expect(placeHolders[3].sourceSpan.toString()).toEqual('</span>');
});
it('should create the correct source-spans when there are two placeholders next to each other', () => {
const {messageParts, placeHolders} = serialize('<b>{{value}}</b>');
expect(messageParts[0].text).toEqual('');
expect(humanizeSourceSpan(messageParts[0].sourceSpan)).toEqual('"" (10-10)');
expect(messageParts[1].text).toEqual('');
expect(humanizeSourceSpan(messageParts[1].sourceSpan)).toEqual('"" (13-13)');
expect(messageParts[2].text).toEqual('');
expect(humanizeSourceSpan(messageParts[2].sourceSpan)).toEqual('"" (22-22)');
expect(messageParts[3].text).toEqual('');
expect(humanizeSourceSpan(messageParts[3].sourceSpan)).toEqual('"" (26-26)');
expect(placeHolders[0].text).toEqual('START_BOLD_TEXT');
expect(humanizeSourceSpan(placeHolders[0].sourceSpan)).toEqual('"<b>" (10-13)');
expect(placeHolders[1].text).toEqual('INTERPOLATION');
expect(humanizeSourceSpan(placeHolders[1].sourceSpan)).toEqual('"{{value}}" (13-22)');
expect(placeHolders[2].text).toEqual('CLOSE_BOLD_TEXT');
expect(humanizeSourceSpan(placeHolders[2].sourceSpan)).toEqual('"</b>" (22-26)');
});
it('should create the correct placeholder source-spans when there is skipped leading whitespace', () => {
const {messageParts, placeHolders} = serialize('<b> {{value}}</b>');
expect(messageParts[0].text).toEqual('');
expect(humanizeSourceSpan(messageParts[0].sourceSpan)).toEqual('"" (10-10)');
expect(messageParts[1].text).toEqual(' ');
expect(humanizeSourceSpan(messageParts[1].sourceSpan)).toEqual('" " (13-16)');
expect(messageParts[2].text).toEqual('');
expect(humanizeSourceSpan(messageParts[2].sourceSpan)).toEqual('"" (25-25)');
expect(messageParts[3].text).toEqual('');
expect(humanizeSourceSpan(messageParts[3].sourceSpan)).toEqual('"" (29-29)');
expect(placeHolders[0].text).toEqual('START_BOLD_TEXT');
expect(humanizeSourceSpan(placeHolders[0].sourceSpan)).toEqual('"<b>" (10-13)');
expect(placeHolders[1].text).toEqual('INTERPOLATION');
expect(humanizeSourceSpan(placeHolders[1].sourceSpan)).toEqual('"{{value}}" (16-25)');
expect(placeHolders[2].text).toEqual('CLOSE_BOLD_TEXT');
expect(humanizeSourceSpan(placeHolders[2].sourceSpan)).toEqual('"</b>" (25-29)');
});
it('should serialize simple ICU for `$localize()`', () => {
expect(serialize('{age, plural, 10 {ten} other {other}}')).toEqual({
messageParts: [literal('{VAR_PLURAL, plural, 10 {ten} other {other}}')],
placeHolders: [],
});
});
it('should serialize nested ICUs for `$localize()`', () => {
expect(
serialize('{age, plural, 10 {ten {size, select, 1 {one} 2 {two} other {2+}}} other {other}}'),
).toEqual({
messageParts: [
literal(
'{VAR_PLURAL, plural, 10 {ten {VAR_SELECT, select, 1 {one} 2 {two} other {2+}}} other {other}}',
),
],
placeHolders: [],
});
}); | {
"end_byte": 18628,
"start_byte": 11051,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/i18n_spec.ts"
} |
angular/packages/compiler/test/render3/view/i18n_spec.ts_18632_22198 | it('should serialize ICU with embedded HTML for `$localize()`', () => {
expect(serialize('{age, plural, 10 {<b>ten</b>} other {<div class="A">other</div>}}')).toEqual({
messageParts: [
literal(
'{VAR_PLURAL, plural, 10 {{START_BOLD_TEXT}ten{CLOSE_BOLD_TEXT}} other {{START_TAG_DIV}other{CLOSE_TAG_DIV}}}',
),
],
placeHolders: [],
});
});
it('should serialize ICU with embedded interpolation for `$localize()`', () => {
expect(serialize('{age, plural, 10 {<b>ten</b>} other {{{age}} years old}}')).toEqual({
messageParts: [
literal(
'{VAR_PLURAL, plural, 10 {{START_BOLD_TEXT}ten{CLOSE_BOLD_TEXT}} other {{INTERPOLATION} years old}}',
),
],
placeHolders: [],
});
});
it('should serialize ICU with nested HTML containing further ICUs for `$localize()`', () => {
const icu = placeholder('ICU');
icu.associatedMessage = jasmine.any(i18n.Message) as unknown as i18n.Message;
expect(
serialize(
'{gender, select, male {male} female {female} other {other}}<div>{gender, select, male {male} female {female} other {other}}</div>',
),
).toEqual({
messageParts: [literal(''), literal(''), literal(''), literal(''), literal('')],
placeHolders: [icu, placeholder('START_TAG_DIV'), icu, placeholder('CLOSE_TAG_DIV')],
});
});
it('should serialize nested ICUs with embedded interpolation for `$localize()`', () => {
expect(
serialize(
'{age, plural, 10 {ten {size, select, 1 {{{ varOne }}} 2 {{{ varTwo }}} other {2+}}} other {other}}',
),
).toEqual({
messageParts: [
literal(
'{VAR_PLURAL, plural, 10 {ten {VAR_SELECT, select, 1 {{INTERPOLATION}} 2 {{INTERPOLATION_1}} other {2+}}} other {other}}',
),
],
placeHolders: [],
});
});
});
describe('serializeIcuNode', () => {
const serialize = (input: string) => {
const tree = parse(`<div i18n>${input}</div>`);
const rooti18n = (tree.nodes[0] as t.Element).i18n as i18n.Message;
return serializeIcuNode(rooti18n.nodes[0] as i18n.Icu);
};
it('should serialize a simple ICU', () => {
expect(serialize('{age, plural, 10 {ten} other {other}}')).toEqual(
'{VAR_PLURAL, plural, 10 {ten} other {other}}',
);
});
it('should serialize a nested ICU', () => {
expect(
serialize('{age, plural, 10 {ten {size, select, 1 {one} 2 {two} other {2+}}} other {other}}'),
).toEqual(
'{VAR_PLURAL, plural, 10 {ten {VAR_SELECT, select, 1 {one} 2 {two} other {2+}}} other {other}}',
);
});
it('should serialize ICU with nested HTML', () => {
expect(serialize('{age, plural, 10 {<b>ten</b>} other {<div class="A">other</div>}}')).toEqual(
'{VAR_PLURAL, plural, 10 {{START_BOLD_TEXT}ten{CLOSE_BOLD_TEXT}} other {{START_TAG_DIV}other{CLOSE_TAG_DIV}}}',
);
});
it('should serialize an ICU with embedded interpolations', () => {
expect(serialize('{age, select, 10 {ten} other {{{age}} years old}}')).toEqual(
'{VAR_SELECT, select, 10 {ten} other {{INTERPOLATION} years old}}',
);
});
});
function literal(text: string, span: any = jasmine.any(ParseSourceSpan)): o.LiteralPiece {
return new o.LiteralPiece(text, span);
}
function placeholder(name: string, span: any = jasmine.any(ParseSourceSpan)): o.PlaceholderPiece {
return new o.PlaceholderPiece(name, span);
}
function humanizeSourceSpan(span: ParseSourceSpan): string {
return `"${span.toString()}" (${span.start.offset}-${span.end.offset})`;
} | {
"end_byte": 22198,
"start_byte": 18632,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/i18n_spec.ts"
} |
angular/packages/compiler/test/render3/view/parse_template_options_spec.ts_0_2139 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ParseSourceSpan} from '../../../src/parse_util';
import {Comment} from '../../../src/render3/r3_ast';
import {parseTemplate} from '../../../src/render3/view/template';
describe('collectCommentNodes', () => {
it('should include an array of HTML comment nodes on the returned R3 AST', () => {
const html = `
<!-- eslint-disable-next-line -->
<div *ngFor="let item of items">
{{item.name}}
</div>
<div>
<p>
<!-- some nested comment -->
<span>Text</span>
</p>
</div>
`;
const templateNoCommentsOption = parseTemplate(html, '', {});
expect(templateNoCommentsOption.commentNodes).toBeUndefined();
const templateCommentsOptionDisabled = parseTemplate(html, '', {collectCommentNodes: false});
expect(templateCommentsOptionDisabled.commentNodes).toBeUndefined();
const templateCommentsOptionEnabled = parseTemplate(html, '', {collectCommentNodes: true});
expect(templateCommentsOptionEnabled.commentNodes!.length).toEqual(2);
expect(templateCommentsOptionEnabled.commentNodes![0]).toBeInstanceOf(Comment);
expect(templateCommentsOptionEnabled.commentNodes![0].value).toEqual(
'eslint-disable-next-line',
);
expect(templateCommentsOptionEnabled.commentNodes![0].sourceSpan).toBeInstanceOf(
ParseSourceSpan,
);
expect(templateCommentsOptionEnabled.commentNodes![0].sourceSpan.toString()).toEqual(
'<!-- eslint-disable-next-line -->',
);
expect(templateCommentsOptionEnabled.commentNodes![1]).toBeInstanceOf(Comment);
expect(templateCommentsOptionEnabled.commentNodes![1].value).toEqual('some nested comment');
expect(templateCommentsOptionEnabled.commentNodes![1].sourceSpan).toBeInstanceOf(
ParseSourceSpan,
);
expect(templateCommentsOptionEnabled.commentNodes![1].sourceSpan.toString()).toEqual(
'<!-- some nested comment -->',
);
});
});
| {
"end_byte": 2139,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/parse_template_options_spec.ts"
} |
angular/packages/compiler/test/render3/view/util.ts_0_6745 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as e from '../../../src/expression_parser/ast';
import {Lexer} from '../../../src/expression_parser/lexer';
import {Parser} from '../../../src/expression_parser/parser';
import * as html from '../../../src/ml_parser/ast';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../../../src/ml_parser/defaults';
import {HtmlParser} from '../../../src/ml_parser/html_parser';
import {WhitespaceVisitor, visitAllWithSiblings} from '../../../src/ml_parser/html_whitespaces';
import {ParseTreeResult} from '../../../src/ml_parser/parser';
import * as a from '../../../src/render3/r3_ast';
import {htmlAstToRender3Ast, Render3ParseResult} from '../../../src/render3/r3_template_transform';
import {I18nMetaVisitor} from '../../../src/render3/view/i18n/meta';
import {LEADING_TRIVIA_CHARS} from '../../../src/render3/view/template';
import {ElementSchemaRegistry} from '../../../src/schema/element_schema_registry';
import {BindingParser} from '../../../src/template_parser/binding_parser';
class MockSchemaRegistry implements ElementSchemaRegistry {
constructor(
public existingProperties: {[key: string]: boolean},
public attrPropMapping: {[key: string]: string},
public existingElements: {[key: string]: boolean},
public invalidProperties: Array<string>,
public invalidAttributes: Array<string>,
) {}
hasProperty(tagName: string, property: string, schemas: any[]): boolean {
const value = this.existingProperties[property];
return value === void 0 ? true : value;
}
hasElement(tagName: string, schemaMetas: any[]): boolean {
const value = this.existingElements[tagName.toLowerCase()];
return value === void 0 ? true : value;
}
allKnownElementNames(): string[] {
return Object.keys(this.existingElements);
}
securityContext(selector: string, property: string, isAttribute: boolean): any {
return 0;
}
getMappedPropName(attrName: string): string {
return this.attrPropMapping[attrName] || attrName;
}
getDefaultComponentElementName(): string {
return 'ng-component';
}
validateProperty(name: string): {error: boolean; msg?: string} {
if (this.invalidProperties.indexOf(name) > -1) {
return {error: true, msg: `Binding to property '${name}' is disallowed for security reasons`};
} else {
return {error: false};
}
}
validateAttribute(name: string): {error: boolean; msg?: string} {
if (this.invalidAttributes.indexOf(name) > -1) {
return {
error: true,
msg: `Binding to attribute '${name}' is disallowed for security reasons`,
};
} else {
return {error: false};
}
}
normalizeAnimationStyleProperty(propName: string): string {
return propName;
}
normalizeAnimationStyleValue(
camelCaseProp: string,
userProvidedProp: string,
val: string | number,
): {error: string; value: string} {
return {error: null!, value: val.toString()};
}
}
export function findExpression(tmpl: a.Node[], expr: string): e.AST | null {
const res = tmpl.reduce(
(found, node) => {
if (found !== null) {
return found;
} else {
return findExpressionInNode(node, expr);
}
},
null as e.AST | null,
);
if (res instanceof e.ASTWithSource) {
return res.ast;
}
return res;
}
function findExpressionInNode(node: a.Node, expr: string): e.AST | null {
if (node instanceof a.Element || node instanceof a.Template) {
return findExpression([...node.inputs, ...node.outputs, ...node.children], expr);
} else if (node instanceof a.BoundAttribute || node instanceof a.BoundText) {
const ts = toStringExpression(node.value);
return toStringExpression(node.value) === expr ? node.value : null;
} else if (node instanceof a.BoundEvent) {
return toStringExpression(node.handler) === expr ? node.handler : null;
} else {
return null;
}
}
export function toStringExpression(expr: e.AST): string {
while (expr instanceof e.ASTWithSource) {
expr = expr.ast;
}
if (expr instanceof e.PropertyRead) {
if (expr.receiver instanceof e.ImplicitReceiver) {
return expr.name;
} else {
return `${toStringExpression(expr.receiver)}.${expr.name}`;
}
} else if (expr instanceof e.ImplicitReceiver) {
return '';
} else if (expr instanceof e.Interpolation) {
let str = '{{';
for (let i = 0; i < expr.expressions.length; i++) {
str += expr.strings[i] + toStringExpression(expr.expressions[i]);
}
str += expr.strings[expr.strings.length - 1] + '}}';
return str;
} else {
throw new Error(`Unsupported type: ${(expr as any).constructor.name}`);
}
}
// Parse an html string to IVY specific info
export function parseR3(
input: string,
options: {
preserveWhitespaces?: boolean;
leadingTriviaChars?: string[];
ignoreError?: boolean;
} = {},
): Render3ParseResult {
const htmlParser = new HtmlParser();
const parseResult = htmlParser.parse(input, 'path:://to/template', {
tokenizeExpansionForms: true,
leadingTriviaChars: options.leadingTriviaChars ?? LEADING_TRIVIA_CHARS,
});
if (parseResult.errors.length > 0 && !options.ignoreError) {
const msg = parseResult.errors.map((e) => e.toString()).join('\n');
throw new Error(msg);
}
let htmlNodes = processI18nMeta(parseResult).rootNodes;
if (!options.preserveWhitespaces) {
htmlNodes = visitAllWithSiblings(
new WhitespaceVisitor(true /* preserveSignificantWhitespace */),
htmlNodes,
);
}
const expressionParser = new Parser(new Lexer());
const schemaRegistry = new MockSchemaRegistry(
{'invalidProp': false},
{'mappedAttr': 'mappedProp'},
{'unknown': false, 'un-known': false},
['onEvent'],
['onEvent'],
);
const bindingParser = new BindingParser(
expressionParser,
DEFAULT_INTERPOLATION_CONFIG,
schemaRegistry,
[],
);
const r3Result = htmlAstToRender3Ast(htmlNodes, bindingParser, {collectCommentNodes: false});
if (r3Result.errors.length > 0 && !options.ignoreError) {
const msg = r3Result.errors.map((e) => e.toString()).join('\n');
throw new Error(msg);
}
return r3Result;
}
export function processI18nMeta(
htmlAstWithErrors: ParseTreeResult,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
): ParseTreeResult {
return new ParseTreeResult(
html.visitAll(
new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ false),
htmlAstWithErrors.rootNodes,
),
htmlAstWithErrors.errors,
);
}
| {
"end_byte": 6745,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/util.ts"
} |
angular/packages/compiler/test/expression_parser/parser_spec.ts_0_776 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {
AbsoluteSourceSpan,
ASTWithSource,
BindingPipe,
Call,
EmptyExpr,
Interpolation,
LiteralMap,
ParserError,
PropertyRead,
TemplateBinding,
VariableBinding,
} from '@angular/compiler/src/expression_parser/ast';
import {Lexer} from '@angular/compiler/src/expression_parser/lexer';
import {Parser, SplitInterpolation} from '@angular/compiler/src/expression_parser/parser';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {unparse, unparseWithSpan} from './utils/unparser';
import {validate} from './utils/validator'; | {
"end_byte": 776,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/parser_spec.ts"
} |
angular/packages/compiler/test/expression_parser/parser_spec.ts_778_8325 | describe('parser', () => {
describe('parseAction', () => {
it('should parse numbers', () => {
checkAction('1');
});
it('should parse strings', () => {
checkAction("'1'", '"1"');
checkAction('"1"');
});
it('should parse null', () => {
checkAction('null');
});
it('should parse undefined', () => {
checkAction('undefined');
});
it('should parse unary - and + expressions', () => {
checkAction('-1', '-1');
checkAction('+1', '+1');
checkAction(`-'1'`, `-"1"`);
checkAction(`+'1'`, `+"1"`);
});
it('should parse unary ! expressions', () => {
checkAction('!true');
checkAction('!!true');
checkAction('!!!true');
});
it('should parse postfix ! expression', () => {
checkAction('true!');
checkAction('a!.b');
checkAction('a!!!!.b');
checkAction('a!()');
checkAction('a.b!()');
});
it('should parse multiplicative expressions', () => {
checkAction('3*4/2%5', '3 * 4 / 2 % 5');
});
it('should parse additive expressions', () => {
checkAction('3 + 6 - 2');
});
it('should parse relational expressions', () => {
checkAction('2 < 3');
checkAction('2 > 3');
checkAction('2 <= 2');
checkAction('2 >= 2');
});
it('should parse equality expressions', () => {
checkAction('2 == 3');
checkAction('2 != 3');
});
it('should parse strict equality expressions', () => {
checkAction('2 === 3');
checkAction('2 !== 3');
});
it('should parse expressions', () => {
checkAction('true && true');
checkAction('true || false');
checkAction('null ?? 0');
checkAction('null ?? undefined ?? 0');
});
it('should parse typeof expression', () => {
checkAction(`typeof {} === "object"`);
checkAction('(!(typeof {} === "number"))', '!typeof {} === "number"');
});
it('should parse grouped expressions', () => {
checkAction('(1 + 2) * 3', '1 + 2 * 3');
});
it('should ignore comments in expressions', () => {
checkAction('a //comment', 'a');
});
it('should retain // in string literals', () => {
checkAction(`"http://www.google.com"`, `"http://www.google.com"`);
});
it('should parse an empty string', () => {
checkAction('');
});
describe('literals', () => {
it('should parse array', () => {
checkAction('[1][0]');
checkAction('[[1]][0][0]');
checkAction('[]');
checkAction('[].length');
checkAction('[1, 2].length');
checkAction('[1, 2,]', '[1, 2]');
});
it('should parse map', () => {
checkAction('{}');
checkAction('{a: 1, "b": 2}[2]');
checkAction('{}["a"]');
checkAction('{a: 1, b: 2,}', '{a: 1, b: 2}');
});
it('should only allow identifier, string, or keyword as map key', () => {
expectActionError('{(:0}', 'expected identifier, keyword, or string');
expectActionError('{1234:0}', 'expected identifier, keyword, or string');
expectActionError('{#myField:0}', 'expected identifier, keyword or string');
});
it('should parse property shorthand declarations', () => {
checkAction('{a, b, c}', '{a: a, b: b, c: c}');
checkAction('{a: 1, b}', '{a: 1, b: b}');
checkAction('{a, b: 1}', '{a: a, b: 1}');
checkAction('{a: 1, b, c: 2}', '{a: 1, b: b, c: 2}');
});
it('should not allow property shorthand declaration on quoted properties', () => {
expectActionError('{"a-b"}', 'expected : at column 7');
});
it('should not infer invalid identifiers as shorthand property declarations', () => {
expectActionError('{a.b}', 'expected } at column 3');
expectActionError('{a["b"]}', 'expected } at column 3');
expectActionError('{1234}', ' expected identifier, keyword, or string at column 2');
});
});
describe('member access', () => {
it('should parse field access', () => {
checkAction('a');
checkAction('this.a', 'a');
checkAction('a.a');
});
it('should error for private identifiers with implicit receiver', () => {
checkActionWithError(
'#privateField',
'',
'Private identifiers are not supported. Unexpected private identifier: #privateField at column 1',
);
});
it('should only allow identifier or keyword as member names', () => {
checkActionWithError('x.', 'x.', 'identifier or keyword');
checkActionWithError('x.(', 'x.', 'identifier or keyword');
checkActionWithError('x. 1234', 'x.', 'identifier or keyword');
checkActionWithError('x."foo"', 'x.', 'identifier or keyword');
checkActionWithError(
'x.#privateField',
'x.',
'Private identifiers are not supported. Unexpected private identifier: #privateField, expected identifier or keyword',
);
});
it('should parse safe field access', () => {
checkAction('a?.a');
checkAction('a.a?.a');
});
it('should parse incomplete safe field accesses', () => {
checkActionWithError('a?.a.', 'a?.a.', 'identifier or keyword');
checkActionWithError('a.a?.a.', 'a.a?.a.', 'identifier or keyword');
checkActionWithError('a.a?.a?. 1234', 'a.a?.a?.', 'identifier or keyword');
});
});
describe('property write', () => {
it('should parse property writes', () => {
checkAction('a.a = 1 + 2');
checkAction('this.a.a = 1 + 2', 'a.a = 1 + 2');
checkAction('a.a.a = 1 + 2');
});
describe('malformed property writes', () => {
it('should recover on empty rvalues', () => {
checkActionWithError('a.a = ', 'a.a = ', 'Unexpected end of expression');
});
it('should recover on incomplete rvalues', () => {
checkActionWithError('a.a = 1 + ', 'a.a = 1 + ', 'Unexpected end of expression');
});
it('should recover on missing properties', () => {
checkActionWithError(
'a. = 1',
'a. = 1',
'Expected identifier for property access at column 2',
);
});
it('should error on writes after a property write', () => {
const ast = parseAction('a.a = 1 = 2');
expect(unparse(ast)).toEqual('a.a = 1');
validate(ast);
expect(ast.errors.length).toBe(1);
expect(ast.errors[0].message).toContain("Unexpected token '='");
});
});
});
describe('calls', () => {
it('should parse calls', () => {
checkAction('fn()');
checkAction('add(1, 2)');
checkAction('a.add(1, 2)');
checkAction('fn().add(1, 2)');
checkAction('fn()(1, 2)');
});
it('should parse an EmptyExpr with a correct span for a trailing empty argument', () => {
const ast = parseAction('fn(1, )').ast as Call;
expect(ast.args[1]).toBeInstanceOf(EmptyExpr);
const sourceSpan = (ast.args[1] as EmptyExpr).sourceSpan;
expect([sourceSpan.start, sourceSpan.end]).toEqual([5, 6]);
});
it('should parse safe calls', () => {
checkAction('fn?.()');
checkAction('add?.(1, 2)');
checkAction('a.add?.(1, 2)');
checkAction('a?.add?.(1, 2)');
checkAction('fn?.().add?.(1, 2)');
checkAction('fn?.()?.(1, 2)');
});
}); | {
"end_byte": 8325,
"start_byte": 778,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/parser_spec.ts"
} |
angular/packages/compiler/test/expression_parser/parser_spec.ts_8331_13654 | describe('keyed read', () => {
it('should parse keyed reads', () => {
checkBinding('a["a"]');
checkBinding('this.a["a"]', 'a["a"]');
checkBinding('a.a["a"]');
});
it('should parse safe keyed reads', () => {
checkBinding('a?.["a"]');
checkBinding('this.a?.["a"]', 'a?.["a"]');
checkBinding('a.a?.["a"]');
checkBinding('a.a?.["a" | foo]', 'a.a?.[("a" | foo)]');
});
describe('malformed keyed reads', () => {
it('should recover on missing keys', () => {
checkActionWithError('a[]', 'a[]', 'Key access cannot be empty');
});
it('should recover on incomplete expression keys', () => {
checkActionWithError('a[1 + ]', 'a[1 + ]', 'Unexpected token ]');
});
it('should recover on unterminated keys', () => {
checkActionWithError(
'a[1 + 2',
'a[1 + 2]',
'Missing expected ] at the end of the expression',
);
});
it('should recover on incomplete and unterminated keys', () => {
checkActionWithError(
'a[1 + ',
'a[1 + ]',
'Missing expected ] at the end of the expression',
);
});
});
});
describe('keyed write', () => {
it('should parse keyed writes', () => {
checkAction('a["a"] = 1 + 2');
checkAction('this.a["a"] = 1 + 2', 'a["a"] = 1 + 2');
checkAction('a.a["a"] = 1 + 2');
});
it('should report on safe keyed writes', () => {
expectActionError('a?.["a"] = 123', 'cannot be used in the assignment');
});
describe('malformed keyed writes', () => {
it('should recover on empty rvalues', () => {
checkActionWithError('a["a"] = ', 'a["a"] = ', 'Unexpected end of expression');
});
it('should recover on incomplete rvalues', () => {
checkActionWithError('a["a"] = 1 + ', 'a["a"] = 1 + ', 'Unexpected end of expression');
});
it('should recover on missing keys', () => {
checkActionWithError('a[] = 1', 'a[] = 1', 'Key access cannot be empty');
});
it('should recover on incomplete expression keys', () => {
checkActionWithError('a[1 + ] = 1', 'a[1 + ] = 1', 'Unexpected token ]');
});
it('should recover on unterminated keys', () => {
checkActionWithError('a[1 + 2 = 1', 'a[1 + 2] = 1', 'Missing expected ]');
});
it('should recover on incomplete and unterminated keys', () => {
const ast = parseAction('a[1 + = 1');
expect(unparse(ast)).toEqual('a[1 + ] = 1');
validate(ast);
const errors = ast.errors.map((e) => e.message);
expect(errors.length).toBe(2);
expect(errors[0]).toContain('Unexpected token =');
expect(errors[1]).toContain('Missing expected ]');
});
it('should error on writes after a keyed write', () => {
const ast = parseAction('a[1] = 1 = 2');
expect(unparse(ast)).toEqual('a[1] = 1');
validate(ast);
expect(ast.errors.length).toBe(1);
expect(ast.errors[0].message).toContain("Unexpected token '='");
});
it('should recover on parenthesized empty rvalues', () => {
const ast = parseAction('(a[1] = b) = c = d');
expect(unparse(ast)).toEqual('a[1] = b');
validate(ast);
expect(ast.errors.length).toBe(1);
expect(ast.errors[0].message).toContain("Unexpected token '='");
});
});
});
describe('conditional', () => {
it('should parse ternary/conditional expressions', () => {
checkAction('7 == 3 + 4 ? 10 : 20');
checkAction('false ? 10 : 20');
});
it('should report incorrect ternary operator syntax', () => {
expectActionError('true?1', 'Conditional expression true?1 requires all 3 expressions');
});
});
describe('assignment', () => {
it('should support field assignments', () => {
checkAction('a = 12');
checkAction('a.a.a = 123');
checkAction('a = 123; b = 234;');
});
it('should report on safe field assignments', () => {
expectActionError('a?.a = 123', 'cannot be used in the assignment');
});
it('should support array updates', () => {
checkAction('a[0] = 200');
});
});
it('should error when using pipes', () => {
expectActionError('x|blah', 'Cannot have a pipe');
});
it('should store the source in the result', () => {
expect(parseAction('someExpr', 'someExpr'));
});
it('should store the passed-in location', () => {
expect(parseAction('someExpr', 'location').location).toBe('location');
});
it('should report when encountering interpolation', () => {
expectActionError('{{a()}}', 'Got interpolation ({{}}) where expression was expected');
});
it('should not report interpolation inside a string', () => {
expect(parseAction(`"{{a()}}"`).errors).toEqual([]);
expect(parseAction(`'{{a()}}'`).errors).toEqual([]);
expect(parseAction(`"{{a('\\"')}}"`).errors).toEqual([]);
expect(parseAction(`'{{a("\\'")}}'`).errors).toEqual([]);
});
}); | {
"end_byte": 13654,
"start_byte": 8331,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/parser_spec.ts"
} |
angular/packages/compiler/test/expression_parser/parser_spec.ts_13658_17477 | describe('parse spans', () => {
it('should record property read span', () => {
const ast = parseAction('foo');
expect(unparseWithSpan(ast)).toContain(['foo', 'foo']);
expect(unparseWithSpan(ast)).toContain(['foo', '[nameSpan] foo']);
});
it('should record accessed property read span', () => {
const ast = parseAction('foo.bar');
expect(unparseWithSpan(ast)).toContain(['foo.bar', 'foo.bar']);
expect(unparseWithSpan(ast)).toContain(['foo.bar', '[nameSpan] bar']);
});
it('should record safe property read span', () => {
const ast = parseAction('foo?.bar');
expect(unparseWithSpan(ast)).toContain(['foo?.bar', 'foo?.bar']);
expect(unparseWithSpan(ast)).toContain(['foo?.bar', '[nameSpan] bar']);
});
it('should record call span', () => {
const ast = parseAction('foo()');
expect(unparseWithSpan(ast)).toContain(['foo()', 'foo()']);
expect(unparseWithSpan(ast)).toContain(['foo()', '[argumentSpan] ']);
expect(unparseWithSpan(ast)).toContain(['foo', '[nameSpan] foo']);
});
it('should record call argument span', () => {
const ast = parseAction('foo(1 + 2)');
expect(unparseWithSpan(ast)).toContain(['foo(1 + 2)', '[argumentSpan] 1 + 2']);
});
it('should record accessed call span', () => {
const ast = parseAction('foo.bar()');
expect(unparseWithSpan(ast)).toContain(['foo.bar()', 'foo.bar()']);
expect(unparseWithSpan(ast)).toContain(['foo.bar', '[nameSpan] bar']);
});
it('should record property write span', () => {
const ast = parseAction('a = b');
expect(unparseWithSpan(ast)).toContain(['a = b', 'a = b']);
expect(unparseWithSpan(ast)).toContain(['a = b', '[nameSpan] a']);
});
it('should record accessed property write span', () => {
const ast = parseAction('a.b = c');
expect(unparseWithSpan(ast)).toContain(['a.b = c', 'a.b = c']);
expect(unparseWithSpan(ast)).toContain(['a.b = c', '[nameSpan] b']);
});
it('should include parenthesis in spans', () => {
// When a LHS expression is parenthesized, the parenthesis on the left used to be
// excluded from the span. This test verifies that the parenthesis are properly included
// in the span for both LHS and RHS expressions.
// https://github.com/angular/angular/issues/40721
expectSpan('(foo) && (bar)');
expectSpan('(foo) || (bar)');
expectSpan('(foo) == (bar)');
expectSpan('(foo) === (bar)');
expectSpan('(foo) != (bar)');
expectSpan('(foo) !== (bar)');
expectSpan('(foo) > (bar)');
expectSpan('(foo) >= (bar)');
expectSpan('(foo) < (bar)');
expectSpan('(foo) <= (bar)');
expectSpan('(foo) + (bar)');
expectSpan('(foo) - (bar)');
expectSpan('(foo) * (bar)');
expectSpan('(foo) / (bar)');
expectSpan('(foo) % (bar)');
expectSpan('(foo) | pipe');
expectSpan('(foo)()');
expectSpan('(foo).bar');
expectSpan('(foo)?.bar');
expectSpan('(foo).bar = (baz)');
expectSpan('(foo | pipe) == false');
expectSpan('(((foo) && bar) || baz) === true');
function expectSpan(input: string) {
expect(unparseWithSpan(parseBinding(input))).toContain([jasmine.any(String), input]);
}
});
});
describe('general error handling', () => {
it('should report an unexpected token', () => {
expectActionError('[1,2] trac', "Unexpected token 'trac'");
});
it('should report reasonable error for unconsumed tokens', () => {
expectActionError(')', 'Unexpected token ) at column 1 in [)]');
});
it('should report a missing expected token', () => {
expectActionError('a(b', 'Missing expected ) at the end of the expression [a(b]');
});
}); | {
"end_byte": 17477,
"start_byte": 13658,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/parser_spec.ts"
} |
angular/packages/compiler/test/expression_parser/parser_spec.ts_17481_22291 | describe('parseBinding', () => {
describe('pipes', () => {
it('should parse pipes', () => {
checkBinding('a(b | c)', 'a((b | c))');
checkBinding('a.b(c.d(e) | f)', 'a.b((c.d(e) | f))');
checkBinding('[1, 2, 3] | a', '([1, 2, 3] | a)');
checkBinding('{a: 1, "b": 2} | c', '({a: 1, "b": 2} | c)');
checkBinding('a[b] | c', '(a[b] | c)');
checkBinding('a?.b | c', '(a?.b | c)');
checkBinding('true | a', '(true | a)');
checkBinding('a | b:c | d', '((a | b:c) | d)');
checkBinding('a | b:(c | d)', '(a | b:(c | d))');
});
describe('should parse incomplete pipes', () => {
const cases: Array<[string, string, string, string]> = [
[
'should parse missing pipe names: end',
'a | b | ',
'((a | b) | )',
'Unexpected end of input, expected identifier or keyword',
],
[
'should parse missing pipe names: middle',
'a | | b',
'((a | ) | b)',
'Unexpected token |, expected identifier or keyword',
],
[
'should parse missing pipe names: start',
' | a | b',
'(( | a) | b)',
'Unexpected token |',
],
[
'should parse missing pipe args: end',
'a | b | c: ',
'((a | b) | c:)',
'Unexpected end of expression',
],
[
'should parse missing pipe args: middle',
'a | b: | c',
'((a | b:) | c)',
'Unexpected token |',
],
[
'should parse incomplete pipe args',
'a | b: (a | ) + | c',
'((a | b:(a | ) + ) | c)',
'Unexpected token |',
],
];
for (const [name, input, output, err] of cases) {
it(name, () => {
checkBinding(input, output);
expectBindingError(input, err);
});
}
it('should parse an incomplete pipe with a source span that includes trailing whitespace', () => {
const bindingText = 'foo | ';
const binding = parseBinding(bindingText).ast as BindingPipe;
// The sourceSpan should include all characters of the input.
expect(rawSpan(binding.sourceSpan)).toEqual([0, bindingText.length]);
// The nameSpan should be positioned at the end of the input.
expect(rawSpan(binding.nameSpan)).toEqual([bindingText.length, bindingText.length]);
});
});
it('should only allow identifier or keyword as formatter names', () => {
expectBindingError('"Foo"|(', 'identifier or keyword');
expectBindingError('"Foo"|1234', 'identifier or keyword');
expectBindingError('"Foo"|"uppercase"', 'identifier or keyword');
expectBindingError('"Foo"|#privateIdentifier"', 'identifier or keyword');
});
it('should not crash when prefix part is not tokenizable', () => {
checkBinding('"a:b"', '"a:b"');
});
});
it('should store the source in the result', () => {
expect(parseBinding('someExpr').source).toBe('someExpr');
});
it('should store the passed-in location', () => {
expect(parseBinding('someExpr', 'location').location).toBe('location');
});
it('should report chain expressions', () => {
expectError(parseBinding('1;2'), 'contain chained expression');
});
it('should report assignment', () => {
expectError(parseBinding('a=2'), 'contain assignments');
});
it('should report when encountering interpolation', () => {
expectBindingError('{{a.b}}', 'Got interpolation ({{}}) where expression was expected');
});
it('should not report interpolation inside a string', () => {
expect(parseBinding(`"{{exp}}"`).errors).toEqual([]);
expect(parseBinding(`'{{exp}}'`).errors).toEqual([]);
expect(parseBinding(`'{{\\"}}'`).errors).toEqual([]);
expect(parseBinding(`'{{\\'}}'`).errors).toEqual([]);
});
it('should parse conditional expression', () => {
checkBinding('a < b ? a : b');
});
it('should ignore comments in bindings', () => {
checkBinding('a //comment', 'a');
});
it('should retain // in string literals', () => {
checkBinding(`"http://www.google.com"`, `"http://www.google.com"`);
});
it('should expose object shorthand information in AST', () => {
const parser = new Parser(new Lexer());
const ast = parser.parseBinding('{bla}', '', 0);
expect(ast.ast instanceof LiteralMap).toBe(true);
expect((ast.ast as LiteralMap).keys.length).toBe(1);
expect((ast.ast as LiteralMap).keys[0].isShorthandInitialized).toBe(true);
});
}); | {
"end_byte": 22291,
"start_byte": 17481,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/parser_spec.ts"
} |
angular/packages/compiler/test/expression_parser/parser_spec.ts_22295_29479 | describe('parseTemplateBindings', () => {
function humanize(bindings: TemplateBinding[]): Array<[string, string | null, boolean]> {
return bindings.map((binding) => {
const key = binding.key.source;
const value = binding.value ? binding.value.source : null;
const keyIsVar = binding instanceof VariableBinding;
return [key, value, keyIsVar];
});
}
function humanizeSpans(
bindings: TemplateBinding[],
attr: string,
): Array<[string, string, string | null]> {
return bindings.map((binding) => {
const {sourceSpan, key, value} = binding;
const sourceStr = attr.substring(sourceSpan.start, sourceSpan.end);
const keyStr = attr.substring(key.span.start, key.span.end);
let valueStr = null;
if (value) {
const {start, end} = value instanceof ASTWithSource ? value.ast.sourceSpan : value.span;
valueStr = attr.substring(start, end);
}
return [sourceStr, keyStr, valueStr];
});
}
it('should parse key and value', () => {
const cases: Array<[string, string, string | null, boolean, string, string, string | null]> =
[
// expression, key, value, VariableBinding, source span, key span, value span
['*a=""', 'a', null, false, 'a="', 'a', null],
['*a="b"', 'a', 'b', false, 'a="b', 'a', 'b'],
['*a-b="c"', 'a-b', 'c', false, 'a-b="c', 'a-b', 'c'],
['*a="1+1"', 'a', '1+1', false, 'a="1+1', 'a', '1+1'],
];
for (const [attr, key, value, keyIsVar, sourceSpan, keySpan, valueSpan] of cases) {
const bindings = parseTemplateBindings(attr);
expect(humanize(bindings)).toEqual([[key, value, keyIsVar]]);
expect(humanizeSpans(bindings, attr)).toEqual([[sourceSpan, keySpan, valueSpan]]);
}
});
it('should variable declared via let', () => {
const bindings = parseTemplateBindings('*a="let b"');
expect(humanize(bindings)).toEqual([
// key, value, VariableBinding
['a', null, false],
['b', null, true],
]);
});
it('should allow multiple pairs', () => {
const bindings = parseTemplateBindings('*a="1 b 2"');
expect(humanize(bindings)).toEqual([
// key, value, VariableBinding
['a', '1', false],
['aB', '2', false],
]);
});
it('should allow space and colon as separators', () => {
const bindings = parseTemplateBindings('*a="1,b 2"');
expect(humanize(bindings)).toEqual([
// key, value, VariableBinding
['a', '1', false],
['aB', '2', false],
]);
});
it('should store the templateUrl', () => {
const bindings = parseTemplateBindings('*a="1,b 2"', '/foo/bar.html');
expect(humanize(bindings)).toEqual([
// key, value, VariableBinding
['a', '1', false],
['aB', '2', false],
]);
expect((bindings[0].value as ASTWithSource).location).toEqual('/foo/bar.html');
});
it('should support common usage of ngIf', () => {
const bindings = parseTemplateBindings('*ngIf="cond | pipe as foo, let x; ngIf as y"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['ngIf', 'cond | pipe', false],
['foo', 'ngIf', true],
['x', null, true],
['y', 'ngIf', true],
]);
});
it('should support common usage of ngFor', () => {
let bindings: TemplateBinding[];
bindings = parseTemplateBindings('*ngFor="let person of people"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['ngFor', null, false],
['person', null, true],
['ngForOf', 'people', false],
]);
bindings = parseTemplateBindings(
'*ngFor="let item; of items | slice:0:1 as collection, trackBy: func; index as i"',
);
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['ngFor', null, false],
['item', null, true],
['ngForOf', 'items | slice:0:1', false],
['collection', 'ngForOf', true],
['ngForTrackBy', 'func', false],
['i', 'index', true],
]);
bindings = parseTemplateBindings(
'*ngFor="let item, of: [1,2,3] | pipe as items; let i=index, count as len"',
);
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['ngFor', null, false],
['item', null, true],
['ngForOf', '[1,2,3] | pipe', false],
['items', 'ngForOf', true],
['i', 'index', true],
['len', 'count', true],
]);
});
it('should parse pipes', () => {
const bindings = parseTemplateBindings('*key="value|pipe "');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['key', 'value|pipe', false],
]);
const {value} = bindings[0];
expect(value).toBeInstanceOf(ASTWithSource);
expect((value as ASTWithSource).ast).toBeInstanceOf(BindingPipe);
});
describe('"let" binding', () => {
it('should support single declaration', () => {
const bindings = parseTemplateBindings('*key="let i"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['key', null, false],
['i', null, true],
]);
});
it('should support multiple declarations', () => {
const bindings = parseTemplateBindings('*key="let a; let b"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['key', null, false],
['a', null, true],
['b', null, true],
]);
});
it('should support empty string assignment', () => {
const bindings = parseTemplateBindings(`*key="let a=''; let b='';"`);
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['key', null, false],
['a', '', true],
['b', '', true],
]);
});
it('should support key and value names with dash', () => {
const bindings = parseTemplateBindings('*key="let i-a = j-a,"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['key', null, false],
['i-a', 'j-a', true],
]);
});
it('should support declarations with or without value assignment', () => {
const bindings = parseTemplateBindings('*key="let item; let i = k"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['key', null, false],
['item', null, true],
['i', 'k', true],
]);
});
it('should support declaration before an expression', () => {
const bindings = parseTemplateBindings('*directive="let item in expr; let a = b"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['directive', null, false],
['item', null, true],
['directiveIn', 'expr', false],
['a', 'b', true],
]);
});
}); | {
"end_byte": 29479,
"start_byte": 22295,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/parser_spec.ts"
} |
angular/packages/compiler/test/expression_parser/parser_spec.ts_29485_33927 | describe('"as" binding', () => {
it('should support single declaration', () => {
const bindings = parseTemplateBindings('*ngIf="exp as local"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['ngIf', 'exp', false],
['local', 'ngIf', true],
]);
});
it('should support declaration after an expression', () => {
const bindings = parseTemplateBindings('*ngFor="let item of items as iter; index as i"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['ngFor', null, false],
['item', null, true],
['ngForOf', 'items', false],
['iter', 'ngForOf', true],
['i', 'index', true],
]);
});
it('should support key and value names with dash', () => {
const bindings = parseTemplateBindings('*key="foo, k-b as l-b;"');
expect(humanize(bindings)).toEqual([
// [ key, value, VariableBinding ]
['key', 'foo', false],
['l-b', 'k-b', true],
]);
});
});
describe('source, key, value spans', () => {
it('should map empty expression', () => {
const attr = '*ngIf=""';
const bindings = parseTemplateBindings(attr);
expect(humanizeSpans(bindings, attr)).toEqual([
// source span, key span, value span
['ngIf="', 'ngIf', null],
]);
});
it('should map variable declaration via "let"', () => {
const attr = '*key="let i"';
const bindings = parseTemplateBindings(attr);
expect(humanizeSpans(bindings, attr)).toEqual([
// source span, key span, value span
['key="', 'key', null], // source span stretches till next binding
['let i', 'i', null],
]);
});
it('shoud map multiple variable declarations via "let"', () => {
const attr = '*key="let item; let i=index; let e=even;"';
const bindings = parseTemplateBindings(attr);
expect(humanizeSpans(bindings, attr)).toEqual([
// source span, key span, value span
['key="', 'key', null],
['let item; ', 'item', null],
['let i=index; ', 'i', 'index'],
['let e=even;', 'e', 'even'],
]);
});
it('shoud map expression with pipe', () => {
const attr = '*ngIf="cond | pipe as foo, let x; ngIf as y"';
const bindings = parseTemplateBindings(attr);
expect(humanizeSpans(bindings, attr)).toEqual([
// source span, key span, value span
['ngIf="cond | pipe ', 'ngIf', 'cond | pipe'],
['ngIf="cond | pipe as foo, ', 'foo', 'ngIf'],
['let x; ', 'x', null],
['ngIf as y', 'y', 'ngIf'],
]);
});
it('should report unexpected token when encountering interpolation', () => {
const attr = '*ngIf="name && {{name}}"';
expectParseTemplateBindingsError(
attr,
'Parser Error: Unexpected token {, expected identifier, keyword, or string at column 10 in [name && {{name}}] in foo.html',
);
});
it('should map variable declaration via "as"', () => {
const attr =
'*ngFor="let item; of items | slice:0:1 as collection, trackBy: func; index as i"';
const bindings = parseTemplateBindings(attr);
expect(humanizeSpans(bindings, attr)).toEqual([
// source span, key span, value span
['ngFor="', 'ngFor', null],
['let item; ', 'item', null],
['of items | slice:0:1 ', 'of', 'items | slice:0:1'],
['of items | slice:0:1 as collection, ', 'collection', 'of'],
['trackBy: func; ', 'trackBy', 'func'],
['index as i', 'i', 'index'],
]);
});
it('should map literal array', () => {
const attr = '*ngFor="let item, of: [1,2,3] | pipe as items; let i=index, count as len, "';
const bindings = parseTemplateBindings(attr);
expect(humanizeSpans(bindings, attr)).toEqual([
// source span, key span, value span
['ngFor="', 'ngFor', null],
['let item, ', 'item', null],
['of: [1,2,3] | pipe ', 'of', '[1,2,3] | pipe'],
['of: [1,2,3] | pipe as items; ', 'items', 'of'],
['let i=index, ', 'i', 'index'],
['count as len,', 'len', 'count'],
]);
});
});
}); | {
"end_byte": 33927,
"start_byte": 29485,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/parser_spec.ts"
} |
angular/packages/compiler/test/expression_parser/parser_spec.ts_33931_38930 | describe('parseInterpolation', () => {
it('should return null if no interpolation', () => {
expect(parseInterpolation('nothing')).toBe(null);
});
it('should not parse malformed interpolations as strings', () => {
const ast = parseInterpolation('{{a}} {{example}<!--->}')!.ast as Interpolation;
expect(ast.strings).toEqual(['', ' {{example}<!--->}']);
expect(ast.expressions.length).toEqual(1);
expect((ast.expressions[0] as PropertyRead).name).toEqual('a');
});
it('should parse no prefix/suffix interpolation', () => {
const ast = parseInterpolation('{{a}}')!.ast as Interpolation;
expect(ast.strings).toEqual(['', '']);
expect(ast.expressions.length).toEqual(1);
expect((ast.expressions[0] as PropertyRead).name).toEqual('a');
});
it('should parse interpolation inside quotes', () => {
const ast = parseInterpolation('"{{a}}"')!.ast as Interpolation;
expect(ast.strings).toEqual(['"', '"']);
expect(ast.expressions.length).toEqual(1);
expect((ast.expressions[0] as PropertyRead).name).toEqual('a');
});
it('should parse interpolation with interpolation characters inside quotes', () => {
checkInterpolation('{{"{{a}}"}}', '{{ "{{a}}" }}');
checkInterpolation('{{"{{"}}', '{{ "{{" }}');
checkInterpolation('{{"}}"}}', '{{ "}}" }}');
checkInterpolation('{{"{"}}', '{{ "{" }}');
checkInterpolation('{{"}"}}', '{{ "}" }}');
});
it('should parse interpolation with escaped quotes', () => {
checkInterpolation(`{{'It\\'s just Angular'}}`, `{{ "It's just Angular" }}`);
checkInterpolation(`{{'It\\'s {{ just Angular'}}`, `{{ "It's {{ just Angular" }}`);
checkInterpolation(`{{'It\\'s }} just Angular'}}`, `{{ "It's }} just Angular" }}`);
});
it('should parse interpolation with escaped backslashes', () => {
checkInterpolation(`{{foo.split('\\\\')}}`, `{{ foo.split("\\") }}`);
checkInterpolation(`{{foo.split('\\\\\\\\')}}`, `{{ foo.split("\\\\") }}`);
checkInterpolation(`{{foo.split('\\\\\\\\\\\\')}}`, `{{ foo.split("\\\\\\") }}`);
});
it('should not parse interpolation with mismatching quotes', () => {
expect(parseInterpolation(`{{ "{{a}}' }}`)).toBeNull();
});
it('should parse prefix/suffix with multiple interpolation', () => {
const originalExp = 'before {{ a }} middle {{ b }} after';
const ast = parseInterpolation(originalExp)!.ast;
expect(unparse(ast)).toEqual(originalExp);
validate(ast);
});
it('should report empty interpolation expressions', () => {
expectError(
parseInterpolation('{{}}')!,
'Blank expressions are not allowed in interpolated strings',
);
expectError(
parseInterpolation('foo {{ }}')!,
'Parser Error: Blank expressions are not allowed in interpolated strings',
);
});
it('should produce an empty expression ast for empty interpolations', () => {
const parsed = parseInterpolation('{{}}')!.ast as Interpolation;
expect(parsed.expressions.length).toBe(1);
expect(parsed.expressions[0]).toBeInstanceOf(EmptyExpr);
});
it('should parse conditional expression', () => {
checkInterpolation('{{ a < b ? a : b }}');
});
it('should parse expression with newline characters', () => {
checkInterpolation(`{{ 'foo' +\n 'bar' +\r 'baz' }}`, `{{ "foo" + "bar" + "baz" }}`);
});
it('should support custom interpolation', () => {
const parser = new Parser(new Lexer());
const ast = parser.parseInterpolation('{% a %}', '', 0, null, {start: '{%', end: '%}'})!
.ast as any;
expect(ast.strings).toEqual(['', '']);
expect(ast.expressions.length).toEqual(1);
expect(ast.expressions[0].name).toEqual('a');
});
describe('comments', () => {
it('should ignore comments in interpolation expressions', () => {
checkInterpolation('{{a //comment}}', '{{ a }}');
});
it('should retain // in single quote strings', () => {
checkInterpolation(`{{ 'http://www.google.com' }}`, `{{ "http://www.google.com" }}`);
});
it('should retain // in double quote strings', () => {
checkInterpolation(`{{ "http://www.google.com" }}`, `{{ "http://www.google.com" }}`);
});
it('should ignore comments after string literals', () => {
checkInterpolation(`{{ "a//b" //comment }}`, `{{ "a//b" }}`);
});
it('should retain // in complex strings', () => {
checkInterpolation(
`{{"//a\'//b\`//c\`//d\'//e" //comment}}`,
`{{ "//a\'//b\`//c\`//d\'//e" }}`,
);
});
it('should retain // in nested, unterminated strings', () => {
checkInterpolation(`{{ "a\'b\`" //comment}}`, `{{ "a\'b\`" }}`);
});
it('should ignore quotes inside a comment', () => {
checkInterpolation(`"{{name // " }}"`, `"{{ name }}"`);
});
});
}); | {
"end_byte": 38930,
"start_byte": 33931,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/parser_spec.ts"
} |
angular/packages/compiler/test/expression_parser/parser_spec.ts_38934_47383 | describe('parseSimpleBinding', () => {
it('should parse a field access', () => {
const p = parseSimpleBinding('name');
expect(unparse(p)).toEqual('name');
validate(p);
});
it('should report when encountering pipes', () => {
expectError(
validate(parseSimpleBinding('a | somePipe')),
'Host binding expression cannot contain pipes',
);
});
it('should report when encountering interpolation', () => {
expectError(
validate(parseSimpleBinding('{{exp}}')),
'Got interpolation ({{}}) where expression was expected',
);
});
it('should not report interpolation inside a string', () => {
expect(parseSimpleBinding(`"{{exp}}"`).errors).toEqual([]);
expect(parseSimpleBinding(`'{{exp}}'`).errors).toEqual([]);
expect(parseSimpleBinding(`'{{\\"}}'`).errors).toEqual([]);
expect(parseSimpleBinding(`'{{\\'}}'`).errors).toEqual([]);
});
it('should report when encountering field write', () => {
expectError(validate(parseSimpleBinding('a = b')), 'Bindings cannot contain assignments');
});
it('should throw if a pipe is used inside a conditional', () => {
expectError(
validate(parseSimpleBinding('(hasId | myPipe) ? "my-id" : ""')),
'Host binding expression cannot contain pipes',
);
});
it('should throw if a pipe is used inside a call', () => {
expectError(
validate(parseSimpleBinding('getId(true, id | myPipe)')),
'Host binding expression cannot contain pipes',
);
});
it('should throw if a pipe is used inside a call to a property access', () => {
expectError(
validate(parseSimpleBinding('idService.getId(true, id | myPipe)')),
'Host binding expression cannot contain pipes',
);
});
it('should throw if a pipe is used inside a call to a safe property access', () => {
expectError(
validate(parseSimpleBinding('idService?.getId(true, id | myPipe)')),
'Host binding expression cannot contain pipes',
);
});
it('should throw if a pipe is used inside a property access', () => {
expectError(
validate(parseSimpleBinding('a[id | myPipe]')),
'Host binding expression cannot contain pipes',
);
});
it('should throw if a pipe is used inside a keyed read expression', () => {
expectError(
validate(parseSimpleBinding('a[id | myPipe].b')),
'Host binding expression cannot contain pipes',
);
});
it('should throw if a pipe is used inside a safe property read', () => {
expectError(
validate(parseSimpleBinding('(id | myPipe)?.id')),
'Host binding expression cannot contain pipes',
);
});
it('should throw if a pipe is used inside a non-null assertion', () => {
expectError(
validate(parseSimpleBinding('[id | myPipe]!')),
'Host binding expression cannot contain pipes',
);
});
it('should throw if a pipe is used inside a prefix not expression', () => {
expectError(
validate(parseSimpleBinding('!(id | myPipe)')),
'Host binding expression cannot contain pipes',
);
});
it('should throw if a pipe is used inside a binary expression', () => {
expectError(
validate(parseSimpleBinding('(id | myPipe) === true')),
'Host binding expression cannot contain pipes',
);
});
});
describe('wrapLiteralPrimitive', () => {
it('should wrap a literal primitive', () => {
expect(unparse(validate(createParser().wrapLiteralPrimitive('foo', '', 0)))).toEqual('"foo"');
});
});
describe('error recovery', () => {
function recover(text: string, expected?: string) {
const expr = validate(parseAction(text));
expect(unparse(expr)).toEqual(expected || text);
}
it('should be able to recover from an extra paren', () => recover('((a)))', 'a'));
it('should be able to recover from an extra bracket', () => recover('[[a]]]', '[[a]]'));
it('should be able to recover from a missing )', () => recover('(a;b', 'a; b;'));
it('should be able to recover from a missing ]', () => recover('[a,b', '[a, b]'));
it('should be able to recover from a missing selector', () => recover('a.'));
it('should be able to recover from a missing selector in a array literal', () =>
recover('[[a.], b, c]'));
});
describe('offsets', () => {
it('should retain the offsets of an interpolation', () => {
const interpolations = splitInterpolation('{{a}} {{b}} {{c}}')!;
expect(interpolations.offsets).toEqual([2, 9, 16]);
});
it('should retain the offsets into the expression AST of interpolations', () => {
const source = parseInterpolation('{{a}} {{b}} {{c}}')!;
const interpolation = source.ast as Interpolation;
expect(interpolation.expressions.map((e) => e.span.start)).toEqual([2, 9, 16]);
});
});
});
function createParser() {
return new Parser(new Lexer());
}
function parseAction(text: string, location: any = null, offset: number = 0): ASTWithSource {
return createParser().parseAction(text, location, offset);
}
function parseBinding(text: string, location: any = null, offset: number = 0): ASTWithSource {
return createParser().parseBinding(text, location, offset);
}
function parseTemplateBindings(attribute: string, templateUrl = 'foo.html'): TemplateBinding[] {
const result = _parseTemplateBindings(attribute, templateUrl);
expect(result.errors).toEqual([]);
expect(result.warnings).toEqual([]);
return result.templateBindings;
}
function expectParseTemplateBindingsError(attribute: string, error: string) {
const result = _parseTemplateBindings(attribute, 'foo.html');
expect(result.errors[0].message).toEqual(error);
}
function _parseTemplateBindings(attribute: string, templateUrl: string) {
const match = attribute.match(/^\*(.+)="(.*)"$/);
expect(match).toBeTruthy(`failed to extract key and value from ${attribute}`);
const [_, key, value] = match!;
const absKeyOffset = 1; // skip the * prefix
const absValueOffset = attribute.indexOf('=') + '="'.length;
const parser = createParser();
return parser.parseTemplateBindings(key, value, templateUrl, absKeyOffset, absValueOffset);
}
function parseInterpolation(
text: string,
location: any = null,
offset: number = 0,
): ASTWithSource | null {
return createParser().parseInterpolation(text, location, offset, null);
}
function splitInterpolation(text: string, location: any = null): SplitInterpolation | null {
return createParser().splitInterpolation(text, location, null);
}
function parseSimpleBinding(text: string, location: any = null, offset: number = 0): ASTWithSource {
return createParser().parseSimpleBinding(text, location, offset);
}
function checkInterpolation(exp: string, expected?: string) {
const ast = parseInterpolation(exp);
if (expected == null) expected = exp;
if (ast === null) {
throw Error(`Failed to parse expression "${exp}"`);
}
expect(unparse(ast)).toEqual(expected);
validate(ast);
}
function checkBinding(exp: string, expected?: string) {
const ast = parseBinding(exp);
if (expected == null) expected = exp;
expect(unparse(ast)).toEqual(expected);
validate(ast);
}
function checkAction(exp: string, expected?: string) {
const ast = parseAction(exp);
if (expected == null) expected = exp;
expect(unparse(ast)).toEqual(expected);
validate(ast);
}
function expectError(ast: {errors: ParserError[]}, message: string) {
for (const error of ast.errors) {
if (error.message.indexOf(message) >= 0) {
return;
}
}
const errMsgs = ast.errors.map((err) => err.message).join('\n');
throw Error(
`Expected an error containing "${message}" to be reported, but got the errors:\n` + errMsgs,
);
}
function expectActionError(text: string, message: string) {
expectError(validate(parseAction(text)), message);
}
function expectBindingError(text: string, message: string) {
expectError(validate(parseBinding(text)), message);
}
/**
* Check that a malformed action parses to a recovered AST while emitting an error.
*/
function checkActionWithError(text: string, expected: string, error: string) {
checkAction(text, expected);
expectActionError(text, error);
}
function rawSpan(span: AbsoluteSourceSpan): [number, number] {
return [span.start, span.end];
} | {
"end_byte": 47383,
"start_byte": 38934,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/parser_spec.ts"
} |
angular/packages/compiler/test/expression_parser/ast_spec.ts_0_1531 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {AST, Lexer, Parser, RecursiveAstVisitor} from '@angular/compiler';
import {Call, ImplicitReceiver, PropertyRead} from '@angular/compiler/src/compiler';
describe('RecursiveAstVisitor', () => {
it('should visit every node', () => {
const parser = new Parser(new Lexer());
const ast = parser.parseBinding('x.y()', '', 0 /* absoluteOffset */);
const visitor = new Visitor();
const path: AST[] = [];
visitor.visit(ast.ast, path);
// If the visitor method of RecursiveAstVisitor is implemented correctly,
// then we should have collected the full path from root to leaf.
expect(path.length).toBe(4);
const [call, yRead, xRead, implicitReceiver] = path;
expectType(call, Call);
expectType(yRead, PropertyRead);
expectType(xRead, PropertyRead);
expectType(implicitReceiver, ImplicitReceiver);
expect(xRead.name).toBe('x');
expect(yRead.name).toBe('y');
expect(call.args).toEqual([]);
});
});
class Visitor extends RecursiveAstVisitor {
override visit(node: AST, path: AST[]) {
path.push(node);
node.visit(this, path);
}
}
type Newable = new (...args: any) => any;
function expectType<T extends Newable>(val: any, t: T): asserts val is InstanceType<T> {
expect(val instanceof t).toBe(true, `expect ${val.constructor.name} to be ${t.name}`);
}
| {
"end_byte": 1531,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/ast_spec.ts"
} |
angular/packages/compiler/test/expression_parser/BUILD.bazel_0_641 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
ts_library(
name = "expression_parser_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/compiler/test/expression_parser/utils",
"//packages/platform-browser/testing",
],
)
jasmine_node_test(
name = "expression_parser",
bootstrap = ["//tools/testing:node"],
deps = [
":expression_parser_lib",
],
)
karma_web_test_suite(
name = "expression_parser_web",
deps = [
":expression_parser_lib",
],
)
| {
"end_byte": 641,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/BUILD.bazel"
} |
angular/packages/compiler/test/expression_parser/lexer_spec.ts_0_2205 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {Lexer, Token} from '@angular/compiler/src/expression_parser/lexer';
function lex(text: string): any[] {
return new Lexer().tokenize(text);
}
function expectToken(token: any, index: number, end: number) {
expect(token instanceof Token).toBe(true);
expect(token.index).toEqual(index);
expect(token.end).toEqual(end);
}
function expectCharacterToken(token: any, index: number, end: number, character: string) {
expect(character.length).toBe(1);
expectToken(token, index, end);
expect(token.isCharacter(character.charCodeAt(0))).toBe(true);
}
function expectOperatorToken(token: any, index: number, end: number, operator: string) {
expectToken(token, index, end);
expect(token.isOperator(operator)).toBe(true);
}
function expectNumberToken(token: any, index: number, end: number, n: number) {
expectToken(token, index, end);
expect(token.isNumber()).toBe(true);
expect(token.toNumber()).toEqual(n);
}
function expectStringToken(token: any, index: number, end: number, str: string) {
expectToken(token, index, end);
expect(token.isString()).toBe(true);
expect(token.toString()).toEqual(str);
}
function expectIdentifierToken(token: any, index: number, end: number, identifier: string) {
expectToken(token, index, end);
expect(token.isIdentifier()).toBe(true);
expect(token.toString()).toEqual(identifier);
}
function expectPrivateIdentifierToken(token: any, index: number, end: number, identifier: string) {
expectToken(token, index, end);
expect(token.isPrivateIdentifier()).toBe(true);
expect(token.toString()).toEqual(identifier);
}
function expectKeywordToken(token: any, index: number, end: number, keyword: string) {
expectToken(token, index, end);
expect(token.isKeyword()).toBe(true);
expect(token.toString()).toEqual(keyword);
}
function expectErrorToken(token: Token, index: any, end: number, message: string) {
expectToken(token, index, end);
expect(token.isError()).toBe(true);
expect(token.toString()).toEqual(message);
} | {
"end_byte": 2205,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/expression_parser/lexer_spec.ts_2207_8810 | describe('lexer', () => {
describe('token', () => {
it('should tokenize a simple identifier', () => {
const tokens: number[] = lex('j');
expect(tokens.length).toEqual(1);
expectIdentifierToken(tokens[0], 0, 1, 'j');
});
it('should tokenize "this"', () => {
const tokens: number[] = lex('this');
expect(tokens.length).toEqual(1);
expectKeywordToken(tokens[0], 0, 4, 'this');
});
it('should tokenize a dotted identifier', () => {
const tokens: number[] = lex('j.k');
expect(tokens.length).toEqual(3);
expectIdentifierToken(tokens[0], 0, 1, 'j');
expectCharacterToken(tokens[1], 1, 2, '.');
expectIdentifierToken(tokens[2], 2, 3, 'k');
});
it('should tokenize a private identifier', () => {
const tokens: number[] = lex('#a');
expect(tokens.length).toEqual(1);
expectPrivateIdentifierToken(tokens[0], 0, 2, '#a');
});
it('should tokenize a property access with private identifier', () => {
const tokens: number[] = lex('j.#k');
expect(tokens.length).toEqual(3);
expectIdentifierToken(tokens[0], 0, 1, 'j');
expectCharacterToken(tokens[1], 1, 2, '.');
expectPrivateIdentifierToken(tokens[2], 2, 4, '#k');
});
it(
'should throw an invalid character error when a hash character is discovered but ' +
'not indicating a private identifier',
() => {
expectErrorToken(
lex('#')[0],
0,
1,
`Lexer Error: Invalid character [#] at column 0 in expression [#]`,
);
expectErrorToken(
lex('#0')[0],
0,
1,
`Lexer Error: Invalid character [#] at column 0 in expression [#0]`,
);
},
);
it('should tokenize an operator', () => {
const tokens: number[] = lex('j-k');
expect(tokens.length).toEqual(3);
expectOperatorToken(tokens[1], 1, 2, '-');
});
it('should tokenize an indexed operator', () => {
const tokens: number[] = lex('j[k]');
expect(tokens.length).toEqual(4);
expectCharacterToken(tokens[1], 1, 2, '[');
expectCharacterToken(tokens[3], 3, 4, ']');
});
it('should tokenize a safe indexed operator', () => {
const tokens: number[] = lex('j?.[k]');
expect(tokens.length).toBe(5);
expectOperatorToken(tokens[1], 1, 3, '?.');
expectCharacterToken(tokens[2], 3, 4, '[');
expectCharacterToken(tokens[4], 5, 6, ']');
});
it('should tokenize numbers', () => {
const tokens: number[] = lex('88');
expect(tokens.length).toEqual(1);
expectNumberToken(tokens[0], 0, 2, 88);
});
it('should tokenize numbers within index ops', () => {
expectNumberToken(lex('a[22]')[2], 2, 4, 22);
});
it('should tokenize simple quoted strings', () => {
expectStringToken(lex('"a"')[0], 0, 3, 'a');
});
it('should tokenize quoted strings with escaped quotes', () => {
expectStringToken(lex('"a\\""')[0], 0, 5, 'a"');
});
it('should tokenize a string', () => {
const tokens: Token[] = lex('j-a.bc[22]+1.3|f:\'a\\\'c\':"d\\"e"');
expectIdentifierToken(tokens[0], 0, 1, 'j');
expectOperatorToken(tokens[1], 1, 2, '-');
expectIdentifierToken(tokens[2], 2, 3, 'a');
expectCharacterToken(tokens[3], 3, 4, '.');
expectIdentifierToken(tokens[4], 4, 6, 'bc');
expectCharacterToken(tokens[5], 6, 7, '[');
expectNumberToken(tokens[6], 7, 9, 22);
expectCharacterToken(tokens[7], 9, 10, ']');
expectOperatorToken(tokens[8], 10, 11, '+');
expectNumberToken(tokens[9], 11, 14, 1.3);
expectOperatorToken(tokens[10], 14, 15, '|');
expectIdentifierToken(tokens[11], 15, 16, 'f');
expectCharacterToken(tokens[12], 16, 17, ':');
expectStringToken(tokens[13], 17, 23, "a'c");
expectCharacterToken(tokens[14], 23, 24, ':');
expectStringToken(tokens[15], 24, 30, 'd"e');
});
it('should tokenize undefined', () => {
const tokens: Token[] = lex('undefined');
expectKeywordToken(tokens[0], 0, 9, 'undefined');
expect(tokens[0].isKeywordUndefined()).toBe(true);
});
it('should tokenize typeof', () => {
const tokens: Token[] = lex('typeof');
expectKeywordToken(tokens[0], 0, 6, 'typeof');
expect(tokens[0].isKeywordTypeof()).toBe(true);
});
it('should ignore whitespace', () => {
const tokens: Token[] = lex('a \t \n \r b');
expectIdentifierToken(tokens[0], 0, 1, 'a');
expectIdentifierToken(tokens[1], 8, 9, 'b');
});
it('should tokenize quoted string', () => {
const str = '[\'\\\'\', "\\""]';
const tokens: Token[] = lex(str);
expectStringToken(tokens[1], 1, 5, "'");
expectStringToken(tokens[3], 7, 11, '"');
});
it('should tokenize escaped quoted string', () => {
const str = '"\\"\\n\\f\\r\\t\\v\\u00A0"';
const tokens: Token[] = lex(str);
expect(tokens.length).toEqual(1);
expect(tokens[0].toString()).toEqual('"\n\f\r\t\v\u00A0');
});
it('should tokenize unicode', () => {
const tokens: Token[] = lex('"\\u00A0"');
expect(tokens.length).toEqual(1);
expect(tokens[0].toString()).toEqual('\u00a0');
});
it('should tokenize relation', () => {
const tokens: Token[] = lex('! == != < > <= >= === !==');
expectOperatorToken(tokens[0], 0, 1, '!');
expectOperatorToken(tokens[1], 2, 4, '==');
expectOperatorToken(tokens[2], 5, 7, '!=');
expectOperatorToken(tokens[3], 8, 9, '<');
expectOperatorToken(tokens[4], 10, 11, '>');
expectOperatorToken(tokens[5], 12, 14, '<=');
expectOperatorToken(tokens[6], 15, 17, '>=');
expectOperatorToken(tokens[7], 18, 21, '===');
expectOperatorToken(tokens[8], 22, 25, '!==');
});
it('should tokenize statements', () => {
const tokens: Token[] = lex('a;b;');
expectIdentifierToken(tokens[0], 0, 1, 'a');
expectCharacterToken(tokens[1], 1, 2, ';');
expectIdentifierToken(tokens[2], 2, 3, 'b');
expectCharacterToken(tokens[3], 3, 4, ';');
});
it('should tokenize function invocation', () => {
const tokens: Token[] = lex('a()');
expectIdentifierToken(tokens[0], 0, 1, 'a');
expectCharacterToken(tokens[1], 1, 2, '(');
expectCharacterToken(tokens[2], 2, 3, ')');
});
it('should tokenize simple method invocations', () => {
const tokens: Token[] = lex('a.method()');
expectIdentifierToken(tokens[2], 2, 8, 'method');
}); | {
"end_byte": 8810,
"start_byte": 2207,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/expression_parser/lexer_spec.ts_8816_13278 | it('should tokenize method invocation', () => {
const tokens: Token[] = lex('a.b.c (d) - e.f()');
expectIdentifierToken(tokens[0], 0, 1, 'a');
expectCharacterToken(tokens[1], 1, 2, '.');
expectIdentifierToken(tokens[2], 2, 3, 'b');
expectCharacterToken(tokens[3], 3, 4, '.');
expectIdentifierToken(tokens[4], 4, 5, 'c');
expectCharacterToken(tokens[5], 6, 7, '(');
expectIdentifierToken(tokens[6], 7, 8, 'd');
expectCharacterToken(tokens[7], 8, 9, ')');
expectOperatorToken(tokens[8], 10, 11, '-');
expectIdentifierToken(tokens[9], 12, 13, 'e');
expectCharacterToken(tokens[10], 13, 14, '.');
expectIdentifierToken(tokens[11], 14, 15, 'f');
expectCharacterToken(tokens[12], 15, 16, '(');
expectCharacterToken(tokens[13], 16, 17, ')');
});
it('should tokenize safe function invocation', () => {
const tokens: Token[] = lex('a?.()');
expectIdentifierToken(tokens[0], 0, 1, 'a');
expectOperatorToken(tokens[1], 1, 3, '?.');
expectCharacterToken(tokens[2], 3, 4, '(');
expectCharacterToken(tokens[3], 4, 5, ')');
});
it('should tokenize a safe method invocations', () => {
const tokens: Token[] = lex('a.method?.()');
expectIdentifierToken(tokens[0], 0, 1, 'a');
expectCharacterToken(tokens[1], 1, 2, '.');
expectIdentifierToken(tokens[2], 2, 8, 'method');
expectOperatorToken(tokens[3], 8, 10, '?.');
expectCharacterToken(tokens[4], 10, 11, '(');
expectCharacterToken(tokens[5], 11, 12, ')');
});
it('should tokenize number', () => {
expectNumberToken(lex('0.5')[0], 0, 3, 0.5);
});
it('should tokenize number with exponent', () => {
let tokens: Token[] = lex('0.5E-10');
expect(tokens.length).toEqual(1);
expectNumberToken(tokens[0], 0, 7, 0.5e-10);
tokens = lex('0.5E+10');
expectNumberToken(tokens[0], 0, 7, 0.5e10);
});
it('should return exception for invalid exponent', () => {
expectErrorToken(
lex('0.5E-')[0],
4,
5,
'Lexer Error: Invalid exponent at column 4 in expression [0.5E-]',
);
expectErrorToken(
lex('0.5E-A')[0],
4,
5,
'Lexer Error: Invalid exponent at column 4 in expression [0.5E-A]',
);
});
it('should tokenize number starting with a dot', () => {
expectNumberToken(lex('.5')[0], 0, 2, 0.5);
});
it('should throw error on invalid unicode', () => {
expectErrorToken(
lex("'\\u1''bla'")[0],
2,
2,
"Lexer Error: Invalid unicode escape [\\u1''b] at column 2 in expression ['\\u1''bla']",
);
});
it('should tokenize ?. as operator', () => {
expectOperatorToken(lex('?.')[0], 0, 2, '?.');
});
it('should tokenize ?? as operator', () => {
expectOperatorToken(lex('??')[0], 0, 2, '??');
});
it('should tokenize number with separator', () => {
expectNumberToken(lex('123_456')[0], 0, 7, 123_456);
expectNumberToken(lex('1_000_000_000')[0], 0, 13, 1_000_000_000);
expectNumberToken(lex('123_456.78')[0], 0, 10, 123_456.78);
expectNumberToken(lex('123_456_789.123_456_789')[0], 0, 23, 123_456_789.123_456_789);
expectNumberToken(lex('1_2_3_4')[0], 0, 7, 1_2_3_4);
expectNumberToken(lex('1_2_3_4.5_6_7_8')[0], 0, 15, 1_2_3_4.5_6_7_8);
});
it('should tokenize number starting with an underscore as an identifier', () => {
expectIdentifierToken(lex('_123')[0], 0, 4, '_123');
expectIdentifierToken(lex('_123_')[0], 0, 5, '_123_');
expectIdentifierToken(lex('_1_2_3_')[0], 0, 7, '_1_2_3_');
});
it('should throw error for invalid number separators', () => {
expectErrorToken(
lex('123_')[0],
3,
3,
'Lexer Error: Invalid numeric separator at column 3 in expression [123_]',
);
expectErrorToken(
lex('12__3')[0],
2,
2,
'Lexer Error: Invalid numeric separator at column 2 in expression [12__3]',
);
expectErrorToken(
lex('1_2_3_.456')[0],
5,
5,
'Lexer Error: Invalid numeric separator at column 5 in expression [1_2_3_.456]',
);
expectErrorToken(
lex('1_2_3._456')[0],
6,
6,
'Lexer Error: Invalid numeric separator at column 6 in expression [1_2_3._456]',
);
});
});
}); | {
"end_byte": 13278,
"start_byte": 8816,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/expression_parser/serializer_spec.ts_0_4376 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as expr from '../../src/expression_parser/ast';
import {Lexer} from '../../src/expression_parser/lexer';
import {Parser} from '../../src/expression_parser/parser';
import {serialize} from '../../src/expression_parser/serializer';
const parser = new Parser(new Lexer());
function parse(expression: string): expr.ASTWithSource {
return parser.parseBinding(expression, /* location */ '', /* absoluteOffset */ 0);
}
function parseAction(expression: string): expr.ASTWithSource {
return parser.parseAction(expression, /* location */ '', /* absoluteOffset */ 0);
}
describe('serializer', () => {
describe('serialize', () => {
it('serializes unary plus', () => {
expect(serialize(parse(' + 1234 '))).toBe('+1234');
});
it('serializes unary negative', () => {
expect(serialize(parse(' - 1234 '))).toBe('-1234');
});
it('serializes binary operations', () => {
expect(serialize(parse(' 1234 + 4321 '))).toBe('1234 + 4321');
});
it('serializes chains', () => {
expect(serialize(parseAction(' 1234; 4321 '))).toBe('1234; 4321');
});
it('serializes conditionals', () => {
expect(serialize(parse(' cond ? 1234 : 4321 '))).toBe('cond ? 1234 : 4321');
});
it('serializes `this`', () => {
expect(serialize(parse(' this '))).toBe('this');
});
it('serializes keyed reads', () => {
expect(serialize(parse(' foo [bar] '))).toBe('foo[bar]');
});
it('serializes keyed write', () => {
expect(serialize(parse(' foo [bar] = baz '))).toBe('foo[bar] = baz');
});
it('serializes array literals', () => {
expect(serialize(parse(' [ foo, bar, baz ] '))).toBe('[foo, bar, baz]');
});
it('serializes object literals', () => {
expect(serialize(parse(' { foo: bar, baz: test } '))).toBe('{foo: bar, baz: test}');
});
it('serializes primitives', () => {
expect(serialize(parse(` 'test' `))).toBe(`'test'`);
expect(serialize(parse(' "test" '))).toBe(`'test'`);
expect(serialize(parse(' true '))).toBe('true');
expect(serialize(parse(' false '))).toBe('false');
expect(serialize(parse(' 1234 '))).toBe('1234');
expect(serialize(parse(' null '))).toBe('null');
expect(serialize(parse(' undefined '))).toBe('undefined');
});
it('escapes string literals', () => {
expect(serialize(parse(` 'Hello, \\'World\\'...' `))).toBe(`'Hello, \\'World\\'...'`);
expect(serialize(parse(` 'Hello, \\"World\\"...' `))).toBe(`'Hello, "World"...'`);
});
it('serializes pipes', () => {
expect(serialize(parse(' foo | pipe '))).toBe('foo | pipe');
});
it('serializes not prefixes', () => {
expect(serialize(parse(' ! foo '))).toBe('!foo');
});
it('serializes non-null assertions', () => {
expect(serialize(parse(' foo ! '))).toBe('foo!');
});
it('serializes property reads', () => {
expect(serialize(parse(' foo . bar '))).toBe('foo.bar');
});
it('serializes property writes', () => {
expect(serialize(parseAction(' foo . bar = baz '))).toBe('foo.bar = baz');
});
it('serializes safe property reads', () => {
expect(serialize(parse(' foo ?. bar '))).toBe('foo?.bar');
});
it('serializes safe keyed reads', () => {
expect(serialize(parse(' foo ?. [ bar ] '))).toBe('foo?.[bar]');
});
it('serializes calls', () => {
expect(serialize(parse(' foo ( ) '))).toBe('foo()');
expect(serialize(parse(' foo ( bar ) '))).toBe('foo(bar)');
expect(serialize(parse(' foo ( bar , ) '))).toBe('foo(bar, )');
expect(serialize(parse(' foo ( bar , baz ) '))).toBe('foo(bar, baz)');
});
it('serializes safe calls', () => {
expect(serialize(parse(' foo ?. ( ) '))).toBe('foo?.()');
expect(serialize(parse(' foo ?. ( bar ) '))).toBe('foo?.(bar)');
expect(serialize(parse(' foo ?. ( bar , ) '))).toBe('foo?.(bar, )');
expect(serialize(parse(' foo ?. ( bar , baz ) '))).toBe('foo?.(bar, baz)');
});
});
});
| {
"end_byte": 4376,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/serializer_spec.ts"
} |
angular/packages/compiler/test/expression_parser/utils/unparser.ts_0_7188 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {
AST,
AstVisitor,
ASTWithSource,
Binary,
BindingPipe,
Call,
Chain,
Conditional,
ImplicitReceiver,
Interpolation,
KeyedRead,
KeyedWrite,
LiteralArray,
LiteralMap,
LiteralPrimitive,
NonNullAssert,
PrefixNot,
TypeofExpression,
PropertyRead,
PropertyWrite,
RecursiveAstVisitor,
SafeCall,
SafeKeyedRead,
SafePropertyRead,
ThisReceiver,
Unary,
} from '../../../src/expression_parser/ast';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../../../src/ml_parser/defaults';
class Unparser implements AstVisitor {
private static _quoteRegExp = /"/g;
// using non-null assertion because they're both re(set) by unparse()
private _expression!: string;
private _interpolationConfig!: InterpolationConfig;
unparse(ast: AST, interpolationConfig: InterpolationConfig) {
this._expression = '';
this._interpolationConfig = interpolationConfig;
this._visit(ast);
return this._expression;
}
visitPropertyRead(ast: PropertyRead, context: any) {
this._visit(ast.receiver);
this._expression += ast.receiver instanceof ImplicitReceiver ? `${ast.name}` : `.${ast.name}`;
}
visitPropertyWrite(ast: PropertyWrite, context: any) {
this._visit(ast.receiver);
this._expression +=
ast.receiver instanceof ImplicitReceiver ? `${ast.name} = ` : `.${ast.name} = `;
this._visit(ast.value);
}
visitUnary(ast: Unary, context: any) {
this._expression += ast.operator;
this._visit(ast.expr);
}
visitBinary(ast: Binary, context: any) {
this._visit(ast.left);
this._expression += ` ${ast.operation} `;
this._visit(ast.right);
}
visitChain(ast: Chain, context: any) {
const len = ast.expressions.length;
for (let i = 0; i < len; i++) {
this._visit(ast.expressions[i]);
this._expression += i == len - 1 ? ';' : '; ';
}
}
visitConditional(ast: Conditional, context: any) {
this._visit(ast.condition);
this._expression += ' ? ';
this._visit(ast.trueExp);
this._expression += ' : ';
this._visit(ast.falseExp);
}
visitPipe(ast: BindingPipe, context: any) {
this._expression += '(';
this._visit(ast.exp);
this._expression += ` | ${ast.name}`;
ast.args.forEach((arg) => {
this._expression += ':';
this._visit(arg);
});
this._expression += ')';
}
visitCall(ast: Call, context: any) {
this._visit(ast.receiver);
this._expression += '(';
let isFirst = true;
ast.args.forEach((arg) => {
if (!isFirst) this._expression += ', ';
isFirst = false;
this._visit(arg);
});
this._expression += ')';
}
visitSafeCall(ast: SafeCall, context: any) {
this._visit(ast.receiver);
this._expression += '?.(';
let isFirst = true;
ast.args.forEach((arg) => {
if (!isFirst) this._expression += ', ';
isFirst = false;
this._visit(arg);
});
this._expression += ')';
}
visitImplicitReceiver(ast: ImplicitReceiver, context: any) {}
visitThisReceiver(ast: ThisReceiver, context: any) {}
visitInterpolation(ast: Interpolation, context: any) {
for (let i = 0; i < ast.strings.length; i++) {
this._expression += ast.strings[i];
if (i < ast.expressions.length) {
this._expression += `${this._interpolationConfig.start} `;
this._visit(ast.expressions[i]);
this._expression += ` ${this._interpolationConfig.end}`;
}
}
}
visitKeyedRead(ast: KeyedRead, context: any) {
this._visit(ast.receiver);
this._expression += '[';
this._visit(ast.key);
this._expression += ']';
}
visitKeyedWrite(ast: KeyedWrite, context: any) {
this._visit(ast.receiver);
this._expression += '[';
this._visit(ast.key);
this._expression += '] = ';
this._visit(ast.value);
}
visitLiteralArray(ast: LiteralArray, context: any) {
this._expression += '[';
let isFirst = true;
ast.expressions.forEach((expression) => {
if (!isFirst) this._expression += ', ';
isFirst = false;
this._visit(expression);
});
this._expression += ']';
}
visitLiteralMap(ast: LiteralMap, context: any) {
this._expression += '{';
let isFirst = true;
for (let i = 0; i < ast.keys.length; i++) {
if (!isFirst) this._expression += ', ';
isFirst = false;
const key = ast.keys[i];
this._expression += key.quoted ? JSON.stringify(key.key) : key.key;
this._expression += ': ';
this._visit(ast.values[i]);
}
this._expression += '}';
}
visitLiteralPrimitive(ast: LiteralPrimitive, context: any) {
if (typeof ast.value === 'string') {
this._expression += `"${ast.value.replace(Unparser._quoteRegExp, '"')}"`;
} else {
this._expression += `${ast.value}`;
}
}
visitPrefixNot(ast: PrefixNot, context: any) {
this._expression += '!';
this._visit(ast.expression);
}
visitTypeofExpresion(ast: TypeofExpression, context: any) {
this._expression += 'typeof ';
this._visit(ast.expression);
}
visitNonNullAssert(ast: NonNullAssert, context: any) {
this._visit(ast.expression);
this._expression += '!';
}
visitSafePropertyRead(ast: SafePropertyRead, context: any) {
this._visit(ast.receiver);
this._expression += `?.${ast.name}`;
}
visitSafeKeyedRead(ast: SafeKeyedRead, context: any) {
this._visit(ast.receiver);
this._expression += '?.[';
this._visit(ast.key);
this._expression += ']';
}
private _visit(ast: AST) {
ast.visit(this);
}
}
const sharedUnparser = new Unparser();
export function unparse(
ast: AST,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
): string {
return sharedUnparser.unparse(ast, interpolationConfig);
}
// [unparsed AST, original source code of AST]
type UnparsedWithSpan = [string, string];
export function unparseWithSpan(
ast: ASTWithSource,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
): UnparsedWithSpan[] {
const unparsed: UnparsedWithSpan[] = [];
const source = ast.source!;
const recursiveSpanUnparser = new (class extends RecursiveAstVisitor {
private recordUnparsed(ast: any, spanKey: string, unparsedList: UnparsedWithSpan[]) {
const span = ast[spanKey];
const prefix = spanKey === 'span' ? '' : `[${spanKey}] `;
const src = source.substring(span.start, span.end);
unparsedList.push([unparse(ast, interpolationConfig), prefix + src]);
}
override visit(ast: AST, unparsedList: UnparsedWithSpan[]) {
this.recordUnparsed(ast, 'span', unparsedList);
if (ast.hasOwnProperty('nameSpan')) {
this.recordUnparsed(ast, 'nameSpan', unparsedList);
}
if (ast.hasOwnProperty('argumentSpan')) {
this.recordUnparsed(ast, 'argumentSpan', unparsedList);
}
ast.visit(this, unparsedList);
}
})();
recursiveSpanUnparser.visitAll([ast.ast], unparsed);
return unparsed;
}
| {
"end_byte": 7188,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/utils/unparser.ts"
} |
angular/packages/compiler/test/expression_parser/utils/BUILD.bazel_0_270 | load("//tools:defaults.bzl", "ts_library")
ts_library(
name = "utils",
testonly = True,
srcs = glob(
["*.ts"],
),
visibility = [
"//packages/compiler/test:__subpackages__",
],
deps = [
"//packages/compiler",
],
)
| {
"end_byte": 270,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/utils/BUILD.bazel"
} |
angular/packages/compiler/test/expression_parser/utils/validator.ts_0_4513 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {
AST,
Binary,
BindingPipe,
Call,
Chain,
Conditional,
ImplicitReceiver,
Interpolation,
KeyedRead,
KeyedWrite,
LiteralArray,
LiteralMap,
LiteralPrimitive,
ParseSpan,
PrefixNot,
TypeofExpression,
PropertyRead,
PropertyWrite,
RecursiveAstVisitor,
SafeCall,
SafeKeyedRead,
SafePropertyRead,
Unary,
} from '../../../src/expression_parser/ast';
import {unparse} from './unparser';
class ASTValidator extends RecursiveAstVisitor {
private parentSpan: ParseSpan | undefined;
override visit(ast: AST) {
this.parentSpan = undefined;
ast.visit(this);
}
validate(ast: AST, cb: () => void): void {
if (!inSpan(ast.span, this.parentSpan)) {
if (this.parentSpan) {
const parentSpan = this.parentSpan as ParseSpan;
throw Error(
`Invalid AST span [expected (${ast.span.start}, ${ast.span.end}) to be in (${
parentSpan.start
}, ${parentSpan.end}) for ${unparse(ast)}`,
);
} else {
throw Error(`Invalid root AST span for ${unparse(ast)}`);
}
}
const oldParent = this.parentSpan;
this.parentSpan = ast.span;
cb();
this.parentSpan = oldParent;
}
override visitUnary(ast: Unary, context: any): any {
this.validate(ast, () => super.visitUnary(ast, context));
}
override visitBinary(ast: Binary, context: any): any {
this.validate(ast, () => super.visitBinary(ast, context));
}
override visitChain(ast: Chain, context: any): any {
this.validate(ast, () => super.visitChain(ast, context));
}
override visitConditional(ast: Conditional, context: any): any {
this.validate(ast, () => super.visitConditional(ast, context));
}
override visitImplicitReceiver(ast: ImplicitReceiver, context: any): any {
this.validate(ast, () => super.visitImplicitReceiver(ast, context));
}
override visitInterpolation(ast: Interpolation, context: any): any {
this.validate(ast, () => super.visitInterpolation(ast, context));
}
override visitKeyedRead(ast: KeyedRead, context: any): any {
this.validate(ast, () => super.visitKeyedRead(ast, context));
}
override visitKeyedWrite(ast: KeyedWrite, context: any): any {
this.validate(ast, () => super.visitKeyedWrite(ast, context));
}
override visitLiteralArray(ast: LiteralArray, context: any): any {
this.validate(ast, () => super.visitLiteralArray(ast, context));
}
override visitLiteralMap(ast: LiteralMap, context: any): any {
this.validate(ast, () => super.visitLiteralMap(ast, context));
}
override visitLiteralPrimitive(ast: LiteralPrimitive, context: any): any {
this.validate(ast, () => super.visitLiteralPrimitive(ast, context));
}
override visitPipe(ast: BindingPipe, context: any): any {
this.validate(ast, () => super.visitPipe(ast, context));
}
override visitPrefixNot(ast: PrefixNot, context: any): any {
this.validate(ast, () => super.visitPrefixNot(ast, context));
}
override visitTypeofExpresion(ast: TypeofExpression, context: any): any {
this.validate(ast, () => super.visitTypeofExpresion(ast, context));
}
override visitPropertyRead(ast: PropertyRead, context: any): any {
this.validate(ast, () => super.visitPropertyRead(ast, context));
}
override visitPropertyWrite(ast: PropertyWrite, context: any): any {
this.validate(ast, () => super.visitPropertyWrite(ast, context));
}
override visitSafePropertyRead(ast: SafePropertyRead, context: any): any {
this.validate(ast, () => super.visitSafePropertyRead(ast, context));
}
override visitSafeKeyedRead(ast: SafeKeyedRead, context: any): any {
this.validate(ast, () => super.visitSafeKeyedRead(ast, context));
}
override visitCall(ast: Call, context: any): any {
this.validate(ast, () => super.visitCall(ast, context));
}
override visitSafeCall(ast: SafeCall, context: any): any {
this.validate(ast, () => super.visitSafeCall(ast, context));
}
}
function inSpan(span: ParseSpan, parentSpan: ParseSpan | undefined): parentSpan is ParseSpan {
return !parentSpan || (span.start >= parentSpan.start && span.end <= parentSpan.end);
}
const sharedValidator = new ASTValidator();
export function validate<T extends AST>(ast: T): T {
sharedValidator.visit(ast);
return ast;
}
| {
"end_byte": 4513,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/expression_parser/utils/validator.ts"
} |
angular/packages/compiler/test/i18n/i18n_ast_spec.ts_0_3513 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {createI18nMessageFactory} from '../../src/i18n/i18n_parser';
import {Node} from '../../src/ml_parser/ast';
import {DEFAULT_CONTAINER_BLOCKS, DEFAULT_INTERPOLATION_CONFIG} from '../../src/ml_parser/defaults';
import {HtmlParser} from '../../src/ml_parser/html_parser';
describe('Message', () => {
const messageFactory = createI18nMessageFactory(
DEFAULT_INTERPOLATION_CONFIG,
DEFAULT_CONTAINER_BLOCKS,
/* retainEmptyTokens */ false,
/* preserveExpressionWhitespace */ true,
);
describe('messageText()', () => {
it('should serialize simple text', () => {
const message = messageFactory(parseHtml('abc\ndef'), '', '', '');
expect(message.messageString).toEqual('abc\ndef');
});
it('should serialize text with interpolations', () => {
const message = messageFactory(parseHtml('abc {{ 123 }}{{ 456 }} def'), '', '', '');
expect(message.messageString).toEqual('abc {$INTERPOLATION}{$INTERPOLATION_1} def');
});
it('should serialize HTML elements', () => {
const message = messageFactory(
parseHtml('abc <span>foo</span><span>bar</span> def'),
'',
'',
'',
);
expect(message.messageString).toEqual(
'abc {$START_TAG_SPAN}foo{$CLOSE_TAG_SPAN}{$START_TAG_SPAN}bar{$CLOSE_TAG_SPAN} def',
);
});
it('should serialize ICU placeholders', () => {
const message = messageFactory(
parseHtml('abc {value, select, case1 {value1} case2 {value2} case3 {value3}} def'),
'',
'',
'',
);
expect(message.messageString).toEqual('abc {$ICU} def');
});
it('should serialize ICU expressions', () => {
const message = messageFactory(
parseHtml('{value, select, case1 {value1} case2 {value2} case3 {value3}}'),
'',
'',
'',
);
expect(message.messageString).toEqual(
'{VAR_SELECT, select, case1 {value1} case2 {value2} case3 {value3}}',
);
});
it('should serialize nested ICU expressions', () => {
const message = messageFactory(
parseHtml(`{gender, select,
male {male of age: {age, select, 10 {ten} 20 {twenty} 30 {thirty} other {other}}}
female {female}
other {other}
}`),
'',
'',
'',
);
expect(message.messageString).toEqual(
`{VAR_SELECT_1, select, male {male of age: {VAR_SELECT, select, 10 {ten} 20 {twenty} 30 {thirty} other {other}}} female {female} other {other}}`,
);
});
it('should serialize blocks', () => {
const message = messageFactory(
parseHtml('abc @if (foo) {foo} @else if (bar) {bar} @else {baz} def'),
'',
'',
'',
);
expect(message.messageString).toEqual(
'abc {$START_BLOCK_IF}foo{$CLOSE_BLOCK_IF} {$START_BLOCK_ELSE_IF}bar{$CLOSE_BLOCK_ELSE_IF} {$START_BLOCK_ELSE}baz{$CLOSE_BLOCK_ELSE} def',
);
});
});
});
export function parseHtml(html: string): Node[] {
const htmlParser = new HtmlParser();
const parseResult = htmlParser.parse(html, 'i18n_ast spec', {tokenizeExpansionForms: true});
if (parseResult.errors.length > 0) {
throw Error(`unexpected parse errors: ${parseResult.errors.join('\n')}`);
}
return parseResult.rootNodes;
}
| {
"end_byte": 3513,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/i18n_ast_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff_spec.ts_0_2041 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {Xliff} from '@angular/compiler/src/i18n/serializers/xliff';
import {waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {
configureCompiler,
createComponent,
HTML,
serializeTranslations,
validateHtml,
} from './integration_common';
// TODO(alxhub): figure out if this test is still relevant.
xdescribe('i18n XLIFF integration spec', () => {
describe('(with LF line endings)', () => {
beforeEach(waitForAsync(() =>
configureCompiler(XLIFF_TOMERGE + LF_LINE_ENDING_XLIFF_TOMERGE, 'xlf')));
it('should extract from templates', () => {
const serializer = new Xliff();
const serializedXliff = serializeTranslations(HTML, serializer);
XLIFF_EXTRACTED.forEach((x) => {
expect(serializedXliff).toContain(x);
});
expect(serializedXliff).toContain(LF_LINE_ENDING_XLIFF_EXTRACTED);
});
it('should translate templates', () => {
const {tb, cmp, el} = createComponent(HTML);
validateHtml(tb, cmp, el);
});
});
describe('(with CRLF line endings', () => {
beforeEach(waitForAsync(() =>
configureCompiler(XLIFF_TOMERGE + CRLF_LINE_ENDING_XLIFF_TOMERGE, 'xlf')));
it('should extract from templates (with CRLF line endings)', () => {
const serializer = new Xliff();
const serializedXliff = serializeTranslations(HTML.replace(/\n/g, '\r\n'), serializer);
XLIFF_EXTRACTED.forEach((x) => {
expect(serializedXliff).toContain(x);
});
expect(serializedXliff).toContain(CRLF_LINE_ENDING_XLIFF_EXTRACTED);
});
it('should translate templates (with CRLF line endings)', () => {
const {tb, cmp, el} = createComponent(HTML.replace(/\n/g, '\r\n'));
validateHtml(tb, cmp, el);
});
});
});
const XLIFF_TOMERGE = ` | {
"end_byte": 2041,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff_spec.ts_0_6126 |
<trans-unit id="3cb04208df1c2f62553ed48e75939cf7107f9dad" datatype="html">
<source>i18n attribute on tags</source>
<target>attributs i18n sur les balises</target>
</trans-unit>
<trans-unit id="52895b1221effb3f3585b689f049d2784d714952" datatype="html">
<source>nested</source>
<target>imbriqué</target>
</trans-unit>
<trans-unit id="88d5f22050a9df477ee5646153558b3a4862d47e" datatype="html">
<source>nested</source>
<target>imbriqué</target>
<note priority="1" from="meaning">different meaning</note>
</trans-unit>
<trans-unit id="34fec9cc62e28e8aa6ffb306fa8569ef0a8087fe" datatype="html">
<source><x id="START_ITALIC_TEXT" ctype="x-i" equiv-text="<i>"/>with placeholders<x id="CLOSE_ITALIC_TEXT" ctype="x-i" equiv-text="</i>"/></source>
<target><x id="START_ITALIC_TEXT" ctype="x-i"/>avec des espaces réservés<x id="CLOSE_ITALIC_TEXT" ctype="x-i"/></target>
</trans-unit>
<trans-unit id="651d7249d3a225037eb66f3433d98ad4a86f0a22" datatype="html">
<source><x id="START_TAG_DIV" ctype="x-div"/>with <x id="START_TAG_DIV" ctype="x-div"/>nested<x id="CLOSE_TAG_DIV" ctype="x-div"/> placeholders<x id="CLOSE_TAG_DIV" ctype="x-div"/></source>
<target><x id="START_TAG_DIV" ctype="x-div"/>with <x id="START_TAG_DIV" ctype="x-div"/>nested<x id="CLOSE_TAG_DIV" ctype="x-div"/> placeholders<x id="CLOSE_TAG_DIV" ctype="x-div"/></target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">11</context>
</context-group>
</trans-unit>
<trans-unit id="1fe4616cce80a57c7707bac1c97054aa8e244a67" datatype="html">
<source>on not translatable node</source>
<target>sur des balises non traductibles</target>
</trans-unit>
<trans-unit id="480aaeeea1570bc1dde6b8404e380dee11ed0759" datatype="html">
<source><b>bold</b></source>
<target><b>gras</b></target>
</trans-unit>
<trans-unit id="67162b5af5f15fd0eb6480c88688dafdf952b93a" datatype="html">
<source>on translatable node</source>
<target>sur des balises traductibles</target>
</trans-unit>
<trans-unit id="dc5536bb9e0e07291c185a0d306601a2ecd4813f" datatype="html">
<source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<x id="START_BOLD_TEXT" ctype="x-b" equiv-text="<b>"/>many<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="</b>"/>} }</source>
<target>{VAR_PLURAL, plural, =0 {zero} =1 {un} =2 {deux} other {<x id="START_BOLD_TEXT" ctype="x-b"/>beaucoup<x id="CLOSE_BOLD_TEXT" ctype="x-b"/>} }</target>
</trans-unit>
<trans-unit id="49feb201083cbd2c8bfc48a4ae11f105fb984876" datatype="html">
<source>
<x id="ICU" equiv-text="{sex, select, male {...} female {...}}"/>
</source>
<target><x id="ICU"/></target>
</trans-unit>
<trans-unit id="f3be30eb9a18f6e336cc3ca4dd66bbc3a35c5f97" datatype="html">
<source>{VAR_SELECT, select, other {other} male {m} female {f} }</source>
<target>{VAR_SELECT, select, other {autre} male {homme} female {femme}}</target>
</trans-unit>
<trans-unit id="cc16e9745fa0b95b2ebc2f18b47ed8e64fe5f0f9" datatype="html">
<source>
<x id="ICU" equiv-text="{sexB, select, m {...} f {...}}"/>
</source>
<target><x id="ICU"/></target>
</trans-unit>
<trans-unit id="4573f2edb0329d69afc2ab8c73c71e2f8b08f807" datatype="html">
<source>{VAR_SELECT, select, male {m} female {f} }</source>
<target>{VAR_SELECT, select, male {homme} female {femme} }</target>
</trans-unit>
<trans-unit id="d9879678f727b244bc7c7e20f22b63d98cb14890" datatype="html">
<source><x id="INTERPOLATION" equiv-text="{{ "count = " + count }}"/></source>
<target><x id="INTERPOLATION"/></target>
</trans-unit>
<trans-unit id="50dac33dc6fc0578884baac79d875785ed77c928" datatype="html">
<source>sex = <x id="INTERPOLATION" equiv-text="{{ sex }}"/></source>
<target>sexe = <x id="INTERPOLATION"/></target>
</trans-unit>
<trans-unit id="a46f833b1fe6ca49e8b97c18f4b7ea0b930c9383" datatype="html">
<source><x id="CUSTOM_NAME" equiv-text="{{ "custom name" //i18n(ph="CUSTOM_NAME") }}"/></source>
<target><x id="CUSTOM_NAME"/></target>
</trans-unit>
<trans-unit id="2ec983b4893bcd5b24af33bebe3ecba63868453c" datatype="html">
<source>in a translatable section</source>
<target>dans une section traductible</target>
</trans-unit>
<trans-unit id="7f6272480ea8e7ffab548da885ab8105ee2caa93" datatype="html">
<source>
<x id="START_HEADING_LEVEL1" ctype="x-h1" equiv-text="<h1>"/>Markers in html comments<x id="CLOSE_HEADING_LEVEL1" ctype="x-h1" equiv-text="</h1>"/>
<x id="START_TAG_DIV" ctype="x-div" equiv-text="<div>"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="</div>"/>
<x id="START_TAG_DIV_1" ctype="x-div" equiv-text="<div>"/><x id="ICU" equiv-text="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="</div>"/>
</source>
<target>
<x id="START_HEADING_LEVEL1" ctype="x-h1"/>Balises dans les commentaires html<x id="CLOSE_HEADING_LEVEL1" ctype="x-h1"/>
<x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/>
<x id="START_TAG_DIV_1" ctype="x-div"/><x id="ICU"/><x id="CLOSE_TAG_DIV" ctype="x-div"/>
</target>
</trans-unit>
<trans-unit id="93a30c67d4e6c9b37aecfe2ac0f2b5d366d7b520" datatype="html">
<source>it <x id="START_BOLD_TEXT" ctype="x-b" equiv-text="<b>"/>should<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="</b>"/> work</source>
<target>ca <x id="START_BOLD_TEXT" ctype="x-b"/>devrait<x id="CLOSE_BOLD_TEXT" ctype="x-b"/> marcher</target>
</trans-unit>
<trans-unit id="i18n16" datatype="html"> | {
"end_byte": 6126,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff_spec.ts_6127_10358 | 8" datatype="html">
<source>sex = <x id="INTERPOLATION" equiv-text="{{ sex }}"/></source>
<target>sexe = <x id="INTERPOLATION"/></target>
</trans-unit>
<trans-unit id="a46f833b1fe6ca49e8b97c18f4b7ea0b930c9383" datatype="html">
<source><x id="CUSTOM_NAME" equiv-text="{{ "custom name" //i18n(ph="CUSTOM_NAME") }}"/></source>
<target><x id="CUSTOM_NAME"/></target>
</trans-unit>
<trans-unit id="2ec983b4893bcd5b24af33bebe3ecba63868453c" datatype="html">
<source>in a translatable section</source>
<target>dans une section traductible</target>
</trans-unit>
<trans-unit id="7f6272480ea8e7ffab548da885ab8105ee2caa93" datatype="html">
<source>
<x id="START_HEADING_LEVEL1" ctype="x-h1" equiv-text="<h1>"/>Markers in html comments<x id="CLOSE_HEADING_LEVEL1" ctype="x-h1" equiv-text="</h1>"/>
<x id="START_TAG_DIV" ctype="x-div" equiv-text="<div>"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="</div>"/>
<x id="START_TAG_DIV_1" ctype="x-div" equiv-text="<div>"/><x id="ICU" equiv-text="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="</div>"/>
</source>
<target>
<x id="START_HEADING_LEVEL1" ctype="x-h1"/>Balises dans les commentaires html<x id="CLOSE_HEADING_LEVEL1" ctype="x-h1"/>
<x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/>
<x id="START_TAG_DIV_1" ctype="x-div"/><x id="ICU"/><x id="CLOSE_TAG_DIV" ctype="x-div"/>
</target>
</trans-unit>
<trans-unit id="93a30c67d4e6c9b37aecfe2ac0f2b5d366d7b520" datatype="html">
<source>it <x id="START_BOLD_TEXT" ctype="x-b" equiv-text="<b>"/>should<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="</b>"/> work</source>
<target>ca <x id="START_BOLD_TEXT" ctype="x-b"/>devrait<x id="CLOSE_BOLD_TEXT" ctype="x-b"/> marcher</target>
</trans-unit>
<trans-unit id="i18n16" datatype="html">
<source>with an explicit ID</source>
<target>avec un ID explicite</target>
</trans-unit>
<trans-unit id="i18n17" datatype="html">
<source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<x id="START_BOLD_TEXT" ctype="x-b" equiv-text="<b>"/>many<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="</b>"/>} }</source>
<target>{VAR_PLURAL, plural, =0 {zero} =1 {un} =2 {deux} other {<x id="START_BOLD_TEXT" ctype="x-b"/>beaucoup<x id="CLOSE_BOLD_TEXT" ctype="x-b"/>} }</target>
</trans-unit>
<trans-unit id="296ab5eab8d370822488c152586db3a5875ee1a2" datatype="html">
<source>foo<x id="START_LINK" ctype="x-a" equiv-text="<a>"/>bar<x id="CLOSE_LINK" ctype="x-a" equiv-text="</a>"/></source>
<target>FOO<x id="START_LINK" ctype="x-a"/>BAR<x id="CLOSE_LINK" ctype=" x-a"/></target>
</trans-unit>
<trans-unit id="2e013b311caa0916478941a985887e091d8288b6" datatype="html">
<source><x id="MAP NAME" equiv-text="{{ 'test' //i18n(ph="map name") }}"/></source>
<target><x id="MAP NAME"/></target>
</trans-unit>`;
const LF_LINE_ENDING_XLIFF_TOMERGE = ` <trans-unit id="2370d995bdcc1e7496baa32df20654aff65c2d10" datatype="html">
<source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <x id="INTERPOLATION" equiv-text="{{response.getItemsList().length}}"/> results} }</source>
<target>{VAR_PLURAL, plural, =0 {Pas de réponse} =1 {Une réponse} other {<x id="INTERPOLATION"/> réponses} }</target>
<note priority="1" from="description">desc</note>
</trans-unit>`;
const CRLF_LINE_ENDING_XLIFF_TOMERGE = ` <trans-unit id="73a09babbde7a003ece74b02acfd22057507717b" datatype="html">
<source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <x id="INTERPOLATION" equiv-text="{{response.getItemsList().length}}"/> results} }</source>
<target>{VAR_PLURAL, plural, =0 {Pas de réponse} =1 {Une réponse} other {<x id="INTERPOLATION"/> réponses} }</target>
<note priority="1" from="description">desc</note>
</trans-unit>`;
const XL | {
"end_byte": 10358,
"start_byte": 6127,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff_spec.ts_10360_17156 | F_EXTRACTED: string[] = [
` <trans-unit id="3cb04208df1c2f62553ed48e75939cf7107f9dad" datatype="html">
<source>i18n attribute on tags</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">3</context>
</context-group>
</trans-unit>`,
` <trans-unit id="52895b1221effb3f3585b689f049d2784d714952" datatype="html">
<source>nested</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">5</context>
</context-group>
</trans-unit>`,
` <trans-unit id="88d5f22050a9df477ee5646153558b3a4862d47e" datatype="html">
<source>nested</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">7</context>
</context-group>
<note priority="1" from="meaning">different meaning</note>
</trans-unit>`,
`<trans-unit id="34fec9cc62e28e8aa6ffb306fa8569ef0a8087fe" datatype="html">
<source><x id="START_ITALIC_TEXT" ctype="x-i" equiv-text="<i>"/>with placeholders<x id="CLOSE_ITALIC_TEXT" ctype="x-i" equiv-text="</i>"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">9</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">10</context>
</context-group>
</trans-unit>`,
` <trans-unit id="651d7249d3a225037eb66f3433d98ad4a86f0a22" datatype="html">
<source><x id="START_TAG_DIV" ctype="x-div" equiv-text="<div>"/>with <x id="START_TAG_DIV" ctype="x-div" equiv-text="<div>"/>nested<x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="</div>"/> placeholders<x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="</div>"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">11</context>
</context-group>
</trans-unit>`,
` <trans-unit id="1fe4616cce80a57c7707bac1c97054aa8e244a67" datatype="html">
<source>on not translatable node</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">14</context>
</context-group>
</trans-unit>`,
` <trans-unit id="480aaeeea1570bc1dde6b8404e380dee11ed0759" datatype="html">
<source><b>bold</b></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">14</context>
</context-group>
</trans-unit>`,
` <trans-unit id="67162b5af5f15fd0eb6480c88688dafdf952b93a" datatype="html">
<source>on translatable node</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">15</context>
</context-group>
</trans-unit>`,
` <trans-unit id="dc5536bb9e0e07291c185a0d306601a2ecd4813f" datatype="html">
<source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<x id="START_BOLD_TEXT" ctype="x-b" equiv-text="<b>"/>many<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="</b>"/>} }</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">20</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">37</context>
</context-group>
</trans-unit>`,
` <trans-unit id="49feb201083cbd2c8bfc48a4ae11f105fb984876" datatype="html">
<source>
<x id="ICU" equiv-text="{sex, select, male {...} female {...} other {...}}"/>
</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">22</context>
</context-group>
</trans-unit>`,
` <trans-unit id="f3be30eb9a18f6e336cc3ca4dd66bbc3a35c5f97" datatype="html">
<source>{VAR_SELECT, select, male {m} female {f} other {other} }</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">23</context>
</context-group>
</trans-unit>`,
` <trans-unit id="cc16e9745fa0b95b2ebc2f18b47ed8e64fe5f0f9" datatype="html">
<source>
<x id="ICU" equiv-text="{sexB, select, male {...} female {...}}"/>
</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">25</context>
</context-group>
</trans-unit>`,
` <trans-unit id="4573f2edb0329d69afc2ab8c73c71e2f8b08f807" datatype="html">
<source>{VAR_SELECT, select, male {m} female {f} }</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">26</context>
</context-group>
</trans-unit>`,
` <trans-unit id="d9879678f727b244bc7c7e20f22b63d98cb14890" datatype="html">
<source><x id="INTERPOLATION" equiv-text="{{ "count = " + count }}"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">29</context>
</context-group>
</trans-unit>`,
` <trans-unit id="50dac33dc6fc0578884baac79d875785ed77c928" datatype="html">
<source>sex = <x id="INTERPOLATION" equiv-text="{{ sex }}"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">30</context>
</context-group>
</trans-unit>`,
` <trans-unit id="a46f833b1fe6ca49e8b97c18f4b7ea0b930c9383" datatype="html">
<source><x id="CUSTOM_NAME" equiv-text="{{ "custom name" //i18n(ph="CUSTOM_NAME") }}"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">31</context>
</context-group>
</trans-unit>`,
` | {
"end_byte": 17156,
"start_byte": 10360,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff_spec.ts_17159_21758 | ans-unit id="2ec983b4893bcd5b24af33bebe3ecba63868453c" datatype="html">
<source>in a translatable section</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">36</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">54</context>
</context-group>
</trans-unit>`,
` <trans-unit id="7f6272480ea8e7ffab548da885ab8105ee2caa93" datatype="html">
<source>
<x id="START_HEADING_LEVEL1" ctype="x-h1" equiv-text="<h1>"/>Markers in html comments<x id="CLOSE_HEADING_LEVEL1" ctype="x-h1" equiv-text="</h1>"/>
<x id="START_TAG_DIV" ctype="x-div" equiv-text="<div>"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="</div>"/>
<x id="START_TAG_DIV_1" ctype="x-div" equiv-text="<div>"/><x id="ICU" equiv-text="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="</div>"/>
</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">34</context>
</context-group>
</trans-unit>`,
` <trans-unit id="93a30c67d4e6c9b37aecfe2ac0f2b5d366d7b520" datatype="html">
<source>it <x id="START_BOLD_TEXT" ctype="x-b" equiv-text="<b>"/>should<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="</b>"/> work</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">40</context>
</context-group>
</trans-unit>`,
` <trans-unit id="i18n16" datatype="html">
<source>with an explicit ID</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">42</context>
</context-group>
</trans-unit>`,
` <trans-unit id="i18n17" datatype="html">
<source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<x id="START_BOLD_TEXT" ctype="x-b" equiv-text="<b>"/>many<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="</b>"/>} }</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">43</context>
</context-group>
</trans-unit>`,
` <trans-unit id="296ab5eab8d370822488c152586db3a5875ee1a2" datatype="html">
<source>foo<x id="START_LINK" ctype="x-a" equiv-text="<a>"/>bar<x id="CLOSE_LINK" ctype="x-a" equiv-text="</a>"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">54</context>
</context-group>
</trans-unit>`,
` <trans-unit id="2e013b311caa0916478941a985887e091d8288b6" datatype="html">
<source><x id="MAP NAME" equiv-text="{{ 'test' //i18n(ph="map name") }}"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">56</context>
</context-group>
</trans-unit>`,
];
const LF_LINE_ENDING_XLIFF_EXTRACTED = ` <trans-unit id="2370d995bdcc1e7496baa32df20654aff65c2d10" datatype="html">
<source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <x id="INTERPOLATION" equiv-text="{{response.getItemsList().length}}"/> results} }</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">46</context>
</context-group>
<note priority="1" from="description">desc</note>
</trans-unit>`;
const CRLF_LINE_ENDING_XLIFF_EXTRACTED = ` <trans-unit id="73a09babbde7a003ece74b02acfd22057507717b" datatype="html">
<source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <x id="INTERPOLATION" equiv-text="{{response.getItemsList().length}}"/> results} }</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">46</context>
</context-group>
<note priority="1" from="description">desc</note>
</trans-unit>`;
| {
"end_byte": 21758,
"start_byte": 17159,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xmb_xtb_spec.ts_0_4925 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {Xmb} from '@angular/compiler/src/i18n/serializers/xmb';
import {waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {
configureCompiler,
createComponent,
HTML,
serializeTranslations,
validateHtml,
} from './integration_common';
// TODO(alxhub): figure out if this test is still relevant.
xdescribe('i18n XMB/XTB integration spec', () => {
describe('(with LF line endings)', () => {
beforeEach(waitForAsync(() => configureCompiler(XTB + LF_LINE_ENDING_XTB, 'xtb')));
it('should extract from templates', () => {
const serializer = new Xmb();
const serializedXmb = serializeTranslations(HTML, serializer);
XMB.forEach((x) => {
expect(serializedXmb).toContain(x);
});
expect(serializedXmb).toContain(LF_LINE_ENDING_XMB);
});
it('should translate templates', () => {
const {tb, cmp, el} = createComponent(HTML);
validateHtml(tb, cmp, el);
});
});
describe('(with CRLF line endings', () => {
beforeEach(waitForAsync(() => configureCompiler(XTB + CRLF_LINE_ENDING_XTB, 'xtb')));
it('should extract from templates (with CRLF line endings)', () => {
const serializer = new Xmb();
const serializedXmb = serializeTranslations(HTML.replace(/\n/g, '\r\n'), serializer);
XMB.forEach((x) => {
expect(serializedXmb).toContain(x);
});
expect(serializedXmb).toContain(CRLF_LINE_ENDING_XMB);
});
it('should translate templates (with CRLF line endings)', () => {
const {tb, cmp, el} = createComponent(HTML.replace(/\n/g, '\r\n'));
validateHtml(tb, cmp, el);
});
});
});
const XTB = `
<translationbundle>
<translation id="615790887472569365">attributs i18n sur les balises</translation>
<translation id="3707494640264351337">imbriqué</translation>
<translation id="5539162898278769904">imbriqué</translation>
<translation id="3780349238193953556"><ph name="START_ITALIC_TEXT"/>avec des espaces réservés<ph name="CLOSE_ITALIC_TEXT"/></translation>
<translation id="5415448997399451992"><ph name="START_TAG_DIV"><ex><div></ex></ph>avec <ph name="START_TAG_DIV"><ex><div></ex></ph>des espaces réservés<ph name="CLOSE_TAG_DIV"><ex></div></ex></ph> imbriqués<ph name="CLOSE_TAG_DIV"><ex></div></ex></ph></translation>
<translation id="5525133077318024839">sur des balises non traductibles</translation>
<translation id="2174788525135228764"><b>gras</b></translation>
<translation id="8670732454866344690">sur des balises traductibles</translation>
<translation id="4593805537723189714">{VAR_PLURAL, plural, =0 {zero} =1 {un} =2 {deux} other {<ph name="START_BOLD_TEXT"/>beaucoup<ph name="CLOSE_BOLD_TEXT"/>}}</translation>
<translation id="703464324060964421"><ph name="ICU"/></translation>
<translation id="5430374139308914421">{VAR_SELECT, select, male {homme} female {femme} other {autre}}</translation>
<translation id="1300564767229037107"><ph name="ICU"/></translation>
<translation id="2500580913783245106">{VAR_SELECT, select, male {homme} female {femme}}</translation>
<translation id="4851788426695310455"><ph name="INTERPOLATION"/></translation>
<translation id="9013357158046221374">sexe = <ph name="INTERPOLATION"/></translation>
<translation id="8324617391167353662"><ph name="CUSTOM_NAME"/></translation>
<translation id="7685649297917455806">dans une section traductible</translation>
<translation id="2329001734457059408">
<ph name="START_HEADING_LEVEL1"/>Balises dans les commentaires html<ph name="CLOSE_HEADING_LEVEL1"/>
<ph name="START_TAG_DIV"/><ph name="CLOSE_TAG_DIV"/>
<ph name="START_TAG_DIV_1"/><ph name="ICU"/><ph name="CLOSE_TAG_DIV"></ph>
</translation>
<translation id="1491627405349178954">ca <ph name="START_BOLD_TEXT"/>devrait<ph name="CLOSE_BOLD_TEXT"/> marcher</translation>
<translation id="i18n16">avec un ID explicite</translation>
<translation id="i18n17">{VAR_PLURAL, plural, =0 {zero} =1 {un} =2 {deux} other {<ph
name="START_BOLD_TEXT"><ex><b></ex></ph>beaucoup<ph name="CLOSE_BOLD_TEXT"><ex></b></ex></ph>} }</translation>
<translation id="4085484936881858615">{VAR_PLURAL, plural, =0 {Pas de réponse} =1 {Une réponse} other {<ph name="INTERPOLATION"><ex>INTERPOLATION</ex></ph> réponses} }</translation>
<translation id="4035252431381981115">FOO<ph name="START_LINK"><ex><a></ex></ph>BAR<ph name="CLOSE_LINK"><ex></a></ex></ph></translation>
<translation id="5339604010413301604"><ph name="MAP_NAME"><ex>MAP_NAME</ex></ph></translation>
</translationbundle>`;
const LF_LINE_ENDING_XTB = ``;
const CRLF_LINE_ENDING_XTB = ``;
const XM | {
"end_byte": 4925,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xmb_xtb_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xmb_xtb_spec.ts_4927_9537 | = [
`<msg id="615790887472569365"><source>file.ts:3</source>i18n attribute on tags</msg>`,
`<msg id="3707494640264351337"><source>file.ts:5</source>nested</msg>`,
`<msg id="5539162898278769904" meaning="different meaning"><source>file.ts:7</source>nested</msg>`,
`<msg id="3780349238193953556"><source>file.ts:9</source><source>file.ts:10</source><ph name="START_ITALIC_TEXT"><ex><i></ex><i></ph>with placeholders<ph name="CLOSE_ITALIC_TEXT"><ex></i></ex></i></ph></msg>`,
`<msg id="5415448997399451992"><source>file.ts:11</source><ph name="START_TAG_DIV"><ex><div></ex><div></ph>with <ph name="START_TAG_DIV"><ex><div></ex><div></ph>nested<ph name="CLOSE_TAG_DIV"><ex></div></ex></div></ph> placeholders<ph name="CLOSE_TAG_DIV"><ex></div></ex></div></ph></msg>`,
`<msg id="5525133077318024839"><source>file.ts:14</source>on not translatable node</msg>`,
`<msg id="2174788525135228764"><source>file.ts:14</source><b>bold</b></msg>`,
`<msg id="8670732454866344690"><source>file.ts:15</source>on translatable node</msg>`,
`<msg id="4593805537723189714"><source>file.ts:20</source><source>file.ts:37</source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<ph name="START_BOLD_TEXT"><ex><b></ex><b></ph>many<ph name="CLOSE_BOLD_TEXT"><ex></b></ex></b></ph>} }</msg>`,
`<msg id="703464324060964421"><source>file.ts:22,24</source>
<ph name="ICU"><ex>{sex, select, male {...} female {...} other {...}}</ex>{sex, select, male {...} female {...} other {...}}</ph>
</msg>`,
`<msg id="5430374139308914421"><source>file.ts:23</source>{VAR_SELECT, select, male {m} female {f} other {other} }</msg>`,
`<msg id="1300564767229037107"><source>file.ts:25,27</source>
<ph name="ICU"><ex>{sexB, select, male {...} female {...}}</ex>{sexB, select, male {...} female {...}}</ph>
</msg>`,
`<msg id="2500580913783245106"><source>file.ts:26</source>{VAR_SELECT, select, male {m} female {f} }</msg>`,
`<msg id="4851788426695310455"><source>file.ts:29</source><ph name="INTERPOLATION"><ex>{{ "count = " + count }}</ex>{{ "count = " + count }}</ph></msg>`,
`<msg id="9013357158046221374"><source>file.ts:30</source>sex = <ph name="INTERPOLATION"><ex>{{ sex }}</ex>{{ sex }}</ph></msg>`,
`<msg id="8324617391167353662"><source>file.ts:31</source><ph name="CUSTOM_NAME"><ex>{{ "custom name" //i18n(ph="CUSTOM_NAME") }}</ex>{{ "custom name" //i18n(ph="CUSTOM_NAME") }}</ph></msg>`,
`<msg id="7685649297917455806"><source>file.ts:36</source><source>file.ts:54</source>in a translatable section</msg>`,
`<msg id="2329001734457059408"><source>file.ts:34,38</source>
<ph name="START_HEADING_LEVEL1"><ex><h1></ex><h1></ph>Markers in html comments<ph name="CLOSE_HEADING_LEVEL1"><ex></h1></ex></h1></ph>
<ph name="START_TAG_DIV"><ex><div></ex><div></ph><ph name="CLOSE_TAG_DIV"><ex></div></ex></div></ph>
<ph name="START_TAG_DIV_1"><ex><div></ex><div></ph><ph name="ICU"><ex>{count, plural, =0 {...} =1 {...} =2 {...} other {...}}</ex>{count, plural, =0 {...} =1 {...} =2 {...} other {...}}</ph><ph name="CLOSE_TAG_DIV"><ex></div></ex></div></ph>
</msg>`,
`<msg id="1491627405349178954"><source>file.ts:40</source>it <ph name="START_BOLD_TEXT"><ex><b></ex><b></ph>should<ph name="CLOSE_BOLD_TEXT"><ex></b></ex></b></ph> work</msg>`,
`<msg id="i18n16"><source>file.ts:42</source>with an explicit ID</msg>`,
`<msg id="i18n17"><source>file.ts:43</source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<ph name="START_BOLD_TEXT"><ex><b></ex><b></ph>many<ph name="CLOSE_BOLD_TEXT"><ex></b></ex></b></ph>} }</msg>`,
`<msg id="4085484936881858615" desc="desc"><source>file.ts:46,52</source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <ph name="INTERPOLATION"><ex>{{response.getItemsList().length}}</ex>{{response.getItemsList().length}}</ph> results} }</msg>`,
`<msg id="4035252431381981115"><source>file.ts:54</source>foo<ph name="START_LINK"><ex><a></ex><a></ph>bar<ph name="CLOSE_LINK"><ex></a></ex></a></ph></msg>`,
`<msg id="5339604010413301604"><source>file.ts:56</source><ph name="MAP_NAME"><ex>{{ 'test' //i18n(ph="map name") }}</ex>{{ 'test' //i18n(ph="map name") }}</ph></msg>`,
];
const LF_LINE_ENDING_XMB = ``;
const CRLF_LINE_ENDING_XMB = ``;
| {
"end_byte": 9537,
"start_byte": 4927,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xmb_xtb_spec.ts"
} |
angular/packages/compiler/test/i18n/digest_spec.ts_0_4201 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {computeMsgId, digest, sha1} from '../../src/i18n/digest';
describe('digest', () => {
describe('digest', () => {
it("must return the ID if it's explicit", () => {
expect(
digest({
id: 'i',
legacyIds: [],
nodes: [],
placeholders: {},
placeholderToMessage: {},
meaning: '',
description: '',
sources: [],
customId: 'i',
messageString: '',
}),
).toEqual('i');
});
});
describe('sha1', () => {
it('should work on empty strings', () => {
expect(sha1('')).toEqual('da39a3ee5e6b4b0d3255bfef95601890afd80709');
});
it('should returns the sha1 of "hello world"', () => {
expect(sha1('abc')).toEqual('a9993e364706816aba3e25717850c26c9cd0d89d');
});
it('should returns the sha1 of unicode strings', () => {
expect(sha1('你好,世界')).toEqual('3becb03b015ed48050611c8d7afe4b88f70d5a20');
});
it('should support arbitrary string size', () => {
// node.js reference code:
//
// var crypto = require('crypto');
//
// function sha1(string) {
// var shasum = crypto.createHash('sha1');
// shasum.update(string, 'utf8');
// return shasum.digest('hex', 'utf8');
// }
//
// var prefix = `你好,世界`;
// var result = sha1(prefix);
// for (var size = prefix.length; size < 5000; size += 101) {
// result = prefix + sha1(result);
// while (result.length < size) {
// result += result;
// }
// result = result.slice(-size);
// }
//
// console.log(sha1(result));
const prefix = `你好,世界`;
let result = sha1(prefix);
for (let size = prefix.length; size < 5000; size += 101) {
result = prefix + sha1(result);
while (result.length < size) {
result += result;
}
result = result.slice(-size);
}
expect(sha1(result)).toEqual('24c2dae5c1ac6f604dbe670a60290d7ce6320b45');
});
});
describe('decimal fingerprint', () => {
it('should work on well known inputs w/o meaning', () => {
const fixtures: {[msg: string]: string} = {
' Spaced Out ': '3976450302996657536',
'Last Name': '4407559560004943843',
'First Name': '6028371114637047813',
'View': '2509141182388535183',
'START_BOLDNUMEND_BOLD of START_BOLDmillionsEND_BOLD': '29997634073898638',
"The customer's credit card was authorized for AMOUNT and passed all risk checks.":
'6836487644149622036',
'Hello world!': '3022994926184248873',
'Jalape\u00f1o': '8054366208386598941',
'The set of SET_NAME is {XXX, ...}.': '135956960462609535',
'NAME took a trip to DESTINATION.': '768490705511913603',
'by AUTHOR (YEAR)': '7036633296476174078',
'': '4416290763660062288',
};
Object.keys(fixtures).forEach((msg) => {
expect(computeMsgId(msg, '')).toEqual(fixtures[msg]);
});
});
it('should work on well known inputs with meaning', () => {
const fixtures: {[msg: string]: [string, string]} = {
'7790835225175622807': ['Last Name', 'Gmail UI'],
'1809086297585054940': ['First Name', 'Gmail UI'],
'3993998469942805487': ['View', 'Gmail UI'],
};
Object.keys(fixtures).forEach((id) => {
expect(computeMsgId(fixtures[id][0], fixtures[id][1])).toEqual(id);
});
});
it('should support arbitrary string size', () => {
const prefix = `你好,世界`;
let result = computeMsgId(prefix, '');
for (let size = prefix.length; size < 5000; size += 101) {
result = prefix + computeMsgId(result, '');
while (result.length < size) {
result += result;
}
result = result.slice(-size);
}
expect(computeMsgId(result, '')).toEqual('2122606631351252558');
});
});
});
| {
"end_byte": 4201,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/digest_spec.ts"
} |
angular/packages/compiler/test/i18n/i18n_parser_spec.ts_0_5859 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {digest, serializeNodes} from '@angular/compiler/src/i18n/digest';
import {extractMessages} from '@angular/compiler/src/i18n/extractor_merger';
import {Message} from '@angular/compiler/src/i18n/i18n_ast';
import {DEFAULT_INTERPOLATION_CONFIG} from '@angular/compiler/src/ml_parser/defaults';
import {HtmlParser} from '@angular/compiler/src/ml_parser/html_parser';
describe('I18nParser', () => {
describe('elements', () => {
it('should extract from elements', () => {
expect(_humanizeMessages('<div i18n="m|d">text</div>')).toEqual([[['text'], 'm', 'd', '']]);
});
it('should extract from nested elements', () => {
expect(_humanizeMessages('<div i18n="m|d">text<span><b>nested</b></span></div>')).toEqual([
[
[
'text',
'<ph tag name="START_TAG_SPAN"><ph tag name="START_BOLD_TEXT">nested</ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_TAG_SPAN">',
],
'm',
'd',
'',
],
]);
});
it('should not create a message for empty elements', () => {
expect(_humanizeMessages('<div i18n="m|d"></div>')).toEqual([]);
});
it('should not create a message for plain elements', () => {
expect(_humanizeMessages('<div></div>')).toEqual([]);
});
it('should support void elements', () => {
expect(_humanizeMessages('<div i18n="m|d"><p><br></p></div>')).toEqual([
[
[
'<ph tag name="START_PARAGRAPH"><ph tag name="LINE_BREAK"/></ph name="CLOSE_PARAGRAPH">',
],
'm',
'd',
'',
],
]);
});
it('should trim whitespace from custom ids (but not meanings)', () => {
expect(_humanizeMessages('<div i18n="\n m|d@@id\n ">text</div>')).toEqual([
[['text'], '\n m', 'd', 'id'],
]);
});
});
describe('attributes', () => {
it('should extract from attributes outside of translatable section', () => {
expect(_humanizeMessages('<div i18n-title="m|d" title="msg"></div>')).toEqual([
[['msg'], 'm', 'd', ''],
]);
});
it('should extract from attributes in translatable element', () => {
expect(
_humanizeMessages('<div i18n><p><b i18n-title="m|d" title="msg"></b></p></div>'),
).toEqual([
[
[
'<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">',
],
'',
'',
'',
],
[['msg'], 'm', 'd', ''],
]);
});
it('should extract from attributes in translatable block', () => {
expect(
_humanizeMessages('<!-- i18n --><p><b i18n-title="m|d" title="msg"></b></p><!-- /i18n -->'),
).toEqual([
[['msg'], 'm', 'd', ''],
[
[
'<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">',
],
'',
'',
'',
],
]);
});
it('should extract from attributes in translatable ICU', () => {
expect(
_humanizeMessages(
'<!-- i18n -->{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}<!-- /i18n -->',
),
).toEqual([
[['msg'], 'm', 'd', ''],
[
[
'{count, plural, =0 {[<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">]}}',
],
'',
'',
'',
],
]);
});
it('should extract from attributes in non translatable ICU', () => {
expect(
_humanizeMessages('{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}'),
).toEqual([[['msg'], 'm', 'd', '']]);
});
it('should not create a message for empty attributes', () => {
expect(_humanizeMessages('<div i18n-title="m|d" title></div>')).toEqual([]);
});
});
describe('interpolation', () => {
it('should replace interpolation with placeholder', () => {
expect(_humanizeMessages('<div i18n="m|d">before{{ exp }}after</div>')).toEqual([
[['[before, <ph name="INTERPOLATION"> exp </ph>, after]'], 'm', 'd', ''],
]);
});
it('should support named interpolation', () => {
expect(
_humanizeMessages('<div i18n="m|d">before{{ exp //i18n(ph="teSt") }}after</div>'),
).toEqual([
[['[before, <ph name="TEST"> exp //i18n(ph="teSt") </ph>, after]'], 'm', 'd', ''],
]);
expect(
_humanizeMessages("<div i18n='m|d'>before{{ exp //i18n(ph='teSt') }}after</div>"),
).toEqual([
[[`[before, <ph name="TEST"> exp //i18n(ph='teSt') </ph>, after]`], 'm', 'd', ''],
]);
});
});
describe('blocks', () => {
it('should extract from blocks', () => {
expect(
_humanizeMessages(`<!-- i18n: meaning1|desc1 -->message1<!-- /i18n -->
<!-- i18n: desc2 -->message2<!-- /i18n -->
<!-- i18n -->message3<!-- /i18n -->`),
).toEqual([
[['message1'], 'meaning1', 'desc1', ''],
[['message2'], '', 'desc2', ''],
[['message3'], '', '', ''],
]);
});
it('should extract all siblings', () => {
expect(_humanizeMessages(`<!-- i18n -->text<p>html<b>nested</b></p><!-- /i18n -->`)).toEqual([
[
[
'text',
'<ph tag name="START_PARAGRAPH">html, <ph tag name="START_BOLD_TEXT">nested</ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">',
],
'',
'',
'',
],
]);
});
}); | {
"end_byte": 5859,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/i18n_parser_spec.ts"
} |
angular/packages/compiler/test/i18n/i18n_parser_spec.ts_5863_12649 | describe('ICU messages', () => {
it('should extract as ICU when single child of an element', () => {
expect(_humanizeMessages('<div i18n="m|d">{count, plural, =0 {zero}}</div>')).toEqual([
[['{count, plural, =0 {[zero]}}'], 'm', 'd', ''],
]);
});
it('should extract as ICU + ph when not single child of an element', () => {
expect(_humanizeMessages('<div i18n="m|d">b{count, plural, =0 {zero}}a</div>')).toEqual([
[['b', '<ph icu name="ICU">{count, plural, =0 {[zero]}}</ph>', 'a'], 'm', 'd', ''],
[['{count, plural, =0 {[zero]}}'], '', '', ''],
]);
});
it('should extract as ICU + ph when wrapped in whitespace in an element', () => {
expect(_humanizeMessages('<div i18n="m|d"> {count, plural, =0 {zero}} </div>')).toEqual([
[[' ', '<ph icu name="ICU">{count, plural, =0 {[zero]}}</ph>', ' '], 'm', 'd', ''],
[['{count, plural, =0 {[zero]}}'], '', '', ''],
]);
});
it('should extract as ICU when single child of a block', () => {
expect(
_humanizeMessages('<!-- i18n:m|d -->{count, plural, =0 {zero}}<!-- /i18n -->'),
).toEqual([[['{count, plural, =0 {[zero]}}'], 'm', 'd', '']]);
});
it('should extract as ICU + ph when not single child of a block', () => {
expect(
_humanizeMessages('<!-- i18n:m|d -->b{count, plural, =0 {zero}}a<!-- /i18n -->'),
).toEqual([
[['{count, plural, =0 {[zero]}}'], '', '', ''],
[['b', '<ph icu name="ICU">{count, plural, =0 {[zero]}}</ph>', 'a'], 'm', 'd', ''],
]);
});
it('should not extract nested ICU messages', () => {
expect(
_humanizeMessages('<div i18n="m|d">b{count, plural, =0 {{sex, select, male {m}}}}a</div>'),
).toEqual([
[
['b', '<ph icu name="ICU">{count, plural, =0 {[{sex, select, male {[m]}}]}}</ph>', 'a'],
'm',
'd',
'',
],
[['{count, plural, =0 {[{sex, select, male {[m]}}]}}'], '', '', ''],
]);
});
it('should preserve whitespace when preserving significant whitespace', () => {
const html = '<div i18n="m|d">{count, plural, =0 {{{ foo }}}}</div>';
expect(
_humanizeMessages(
html,
/* implicitTags */ undefined,
/* implicitAttrs */ undefined,
/* preserveSignificantWhitespace */ true,
),
).toEqual([
[['{count, plural, =0 {[[<ph name="INTERPOLATION"> foo </ph>]]}}'], 'm', 'd', ''],
]);
});
it('should normalize whitespace when not preserving significant whitespace', () => {
const html = '<div i18n="m|d">{count, plural, =0 {{{ foo }}}}</div>';
expect(
_humanizeMessages(
html,
/* implicitTags */ undefined,
/* implicitAttrs */ undefined,
/* preserveSignificantWhitespace */ false,
),
).toEqual([
[['{count, plural, =0 {[[, <ph name="INTERPOLATION">foo</ph>, ]]}}'], 'm', 'd', ''],
]);
});
});
describe('implicit elements', () => {
it('should extract from implicit elements', () => {
expect(_humanizeMessages('<b>bold</b><i>italic</i>', ['b'])).toEqual([
[['bold'], '', '', ''],
]);
});
});
describe('implicit attributes', () => {
it('should extract implicit attributes', () => {
expect(
_humanizeMessages('<b title="bb">bold</b><i title="ii">italic</i>', [], {'b': ['title']}),
).toEqual([[['bb'], '', '', '']]);
});
});
describe('placeholders', () => {
it('should reuse the same placeholder name for tags', () => {
const html = '<div i18n="m|d"><p>one</p><p>two</p><p other>three</p></div>';
expect(_humanizeMessages(html)).toEqual([
[
[
'<ph tag name="START_PARAGRAPH">one</ph name="CLOSE_PARAGRAPH">',
'<ph tag name="START_PARAGRAPH">two</ph name="CLOSE_PARAGRAPH">',
'<ph tag name="START_PARAGRAPH_1">three</ph name="CLOSE_PARAGRAPH">',
],
'm',
'd',
'',
],
]);
expect(_humanizePlaceholders(html)).toEqual([
'START_PARAGRAPH=<p>, CLOSE_PARAGRAPH=</p>, START_PARAGRAPH_1=<p other>',
]);
});
it('should reuse the same placeholder name for interpolations', () => {
const html = '<div i18n="m|d">{{ a }}{{ a }}{{ b }}</div>';
expect(_humanizeMessages(html)).toEqual([
[
[
'[<ph name="INTERPOLATION"> a </ph>, <ph name="INTERPOLATION"> a </ph>, <ph name="INTERPOLATION_1"> b </ph>]',
],
'm',
'd',
'',
],
]);
expect(_humanizePlaceholders(html)).toEqual([
'INTERPOLATION={{ a }}, INTERPOLATION_1={{ b }}',
]);
});
it('should reuse the same placeholder name for icu messages', () => {
const html =
'<div i18n="m|d">{count, plural, =0 {0}}{count, plural, =0 {0}}{count, plural, =1 {1}}</div>';
expect(_humanizeMessages(html)).toEqual([
[
[
'<ph icu name="ICU">{count, plural, =0 {[0]}}</ph>',
'<ph icu name="ICU">{count, plural, =0 {[0]}}</ph>',
'<ph icu name="ICU_1">{count, plural, =1 {[1]}}</ph>',
],
'm',
'd',
'',
],
[['{count, plural, =0 {[0]}}'], '', '', ''],
[['{count, plural, =0 {[0]}}'], '', '', ''],
[['{count, plural, =1 {[1]}}'], '', '', ''],
]);
expect(_humanizePlaceholders(html)).toEqual([
'',
'VAR_PLURAL=count',
'VAR_PLURAL=count',
'VAR_PLURAL=count',
]);
expect(_humanizePlaceholdersToMessage(html)).toEqual([
'ICU=f0f76923009914f1b05f41042a5c7231b9496504, ICU_1=73693d1f78d0fc882f0bcbce4cb31a0aa1995cfe',
'',
'',
'',
]);
});
it('should preserve whitespace when preserving significant whitespace', () => {
const html = '<div i18n="m|d">hello {{ foo }}</div>';
expect(
_humanizeMessages(
html,
/* implicitTags */ undefined,
/* implicitAttrs */ undefined,
/* preserveSignificantWhitespace */ true,
),
).toEqual([[['[hello , <ph name="INTERPOLATION"> foo </ph>]'], 'm', 'd', '']]);
});
it('should normalize whitespace when not preserving significant whitespace', () => {
const html = '<div i18n="m|d">hello {{ foo }}</div>';
expect(
_humanizeMessages(
html,
/* implicitTags */ undefined,
/* implicitAttrs */ undefined,
/* preserveSignificantWhitespace */ false,
),
).toEqual([[['[hello , <ph name="INTERPOLATION">foo</ph>, ]'], 'm', 'd', '']]);
});
});
}); | {
"end_byte": 12649,
"start_byte": 5863,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/i18n_parser_spec.ts"
} |
angular/packages/compiler/test/i18n/i18n_parser_spec.ts_12651_14580 | export function _humanizeMessages(
html: string,
implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {},
preserveSignificantWhitespace = true,
): [string[], string, string, string][] {
return _extractMessages(html, implicitTags, implicitAttrs, preserveSignificantWhitespace).map(
(message) => [serializeNodes(message.nodes), message.meaning, message.description, message.id],
) as [string[], string, string, string][];
}
function _humanizePlaceholders(
html: string,
implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {},
preserveSignificantWhitespace = true,
): string[] {
return _extractMessages(html, implicitTags, implicitAttrs, preserveSignificantWhitespace).map(
(msg) =>
Object.keys(msg.placeholders)
.map((name) => `${name}=${msg.placeholders[name].text}`)
.join(', '),
);
}
function _humanizePlaceholdersToMessage(
html: string,
implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {},
preserveSignificantWhitespace = true,
): string[] {
return _extractMessages(html, implicitTags, implicitAttrs, preserveSignificantWhitespace).map(
(msg) =>
Object.keys(msg.placeholderToMessage)
.map((k) => `${k}=${digest(msg.placeholderToMessage[k])}`)
.join(', '),
);
}
export function _extractMessages(
html: string,
implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {},
preserveSignificantWhitespace = true,
): Message[] {
const htmlParser = new HtmlParser();
const parseResult = htmlParser.parse(html, 'extractor spec', {tokenizeExpansionForms: true});
if (parseResult.errors.length > 1) {
throw Error(`unexpected parse errors: ${parseResult.errors.join('\n')}`);
}
return extractMessages(
parseResult.rootNodes,
DEFAULT_INTERPOLATION_CONFIG,
implicitTags,
implicitAttrs,
preserveSignificantWhitespace,
).messages;
} | {
"end_byte": 14580,
"start_byte": 12651,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/i18n_parser_spec.ts"
} |
angular/packages/compiler/test/i18n/i18n_html_parser_spec.ts_0_1052 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {I18NHtmlParser} from '@angular/compiler/src/i18n/i18n_html_parser';
import {TranslationBundle} from '@angular/compiler/src/i18n/translation_bundle';
import {HtmlParser} from '@angular/compiler/src/ml_parser/html_parser';
describe('I18N html parser', () => {
// https://github.com/angular/angular/issues/14322
it('should parse the translations only once', () => {
const transBundle = new TranslationBundle({}, null, () => 'id');
spyOn(TranslationBundle, 'load').and.returnValue(transBundle);
const htmlParser = new HtmlParser();
const i18nHtmlParser = new I18NHtmlParser(htmlParser, 'translations');
expect(TranslationBundle.load).toHaveBeenCalledTimes(1);
i18nHtmlParser.parse('source', 'url');
i18nHtmlParser.parse('source', 'url');
expect(TranslationBundle.load).toHaveBeenCalledTimes(1);
});
});
| {
"end_byte": 1052,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/i18n_html_parser_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_common.ts_0_5024 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {NgLocalization} from '@angular/common';
import {Serializer} from '@angular/compiler/src/i18n';
import {MessageBundle} from '@angular/compiler/src/i18n/message_bundle';
import {DEFAULT_INTERPOLATION_CONFIG} from '@angular/compiler/src/ml_parser/defaults';
import {HtmlParser} from '@angular/compiler/src/ml_parser/html_parser';
import {ResourceLoader} from '@angular/compiler/src/resource_loader';
import {Component, DebugElement, TRANSLATIONS, TRANSLATIONS_FORMAT} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {stringifyElement} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
@Component({
selector: 'i18n-cmp',
template: '',
standalone: false,
})
export class I18nComponent {
count?: number;
sex?: string;
sexB?: string;
response: any = {getItemsList: (): any[] => []};
}
export class FrLocalization extends NgLocalization {
public static PROVIDE = {provide: NgLocalization, useClass: FrLocalization, deps: []};
override getPluralCategory(value: number): string {
switch (value) {
case 0:
case 1:
return 'one';
default:
return 'other';
}
}
}
export function validateHtml(
tb: ComponentFixture<I18nComponent>,
cmp: I18nComponent,
el: DebugElement,
) {
expectHtml(el, 'h1').toBe('<h1>attributs i18n sur les balises</h1>');
expectHtml(el, '#i18n-1').toBe('<div id="i18n-1"><p>imbriqué</p></div>');
expectHtml(el, '#i18n-2').toBe('<div id="i18n-2"><p>imbriqué</p></div>');
expectHtml(el, '#i18n-3').toBe('<div id="i18n-3"><p><i>avec des espaces réservés</i></p></div>');
expectHtml(el, '#i18n-3b').toBe(
'<div id="i18n-3b"><p><i class="preserved-on-placeholders">avec des espaces réservés</i></p></div>',
);
expectHtml(el, '#i18n-4').toBe(
'<p data-html="<b>gras</b>" id="i18n-4" title="sur des balises non traductibles"></p>',
);
expectHtml(el, '#i18n-5').toBe('<p id="i18n-5" title="sur des balises traductibles"></p>');
expectHtml(el, '#i18n-6').toBe('<p id="i18n-6" title=""></p>');
cmp.count = 0;
tb.detectChanges();
expect(el.query(By.css('#i18n-7')).nativeElement).toHaveText('zero');
expect(el.query(By.css('#i18n-14')).nativeElement).toHaveText('zero');
cmp.count = 1;
tb.detectChanges();
expect(el.query(By.css('#i18n-7')).nativeElement).toHaveText('un');
expect(el.query(By.css('#i18n-14')).nativeElement).toHaveText('un');
expect(el.query(By.css('#i18n-17')).nativeElement).toHaveText('un');
cmp.count = 2;
tb.detectChanges();
expect(el.query(By.css('#i18n-7')).nativeElement).toHaveText('deux');
expect(el.query(By.css('#i18n-14')).nativeElement).toHaveText('deux');
expect(el.query(By.css('#i18n-17')).nativeElement).toHaveText('deux');
cmp.count = 3;
tb.detectChanges();
expect(el.query(By.css('#i18n-7')).nativeElement).toHaveText('beaucoup');
expect(el.query(By.css('#i18n-14')).nativeElement).toHaveText('beaucoup');
expect(el.query(By.css('#i18n-17')).nativeElement).toHaveText('beaucoup');
cmp.sex = 'male';
cmp.sexB = 'female';
tb.detectChanges();
expect(el.query(By.css('#i18n-8')).nativeElement).toHaveText('homme');
expect(el.query(By.css('#i18n-8b')).nativeElement).toHaveText('femme');
cmp.sex = 'female';
tb.detectChanges();
expect(el.query(By.css('#i18n-8')).nativeElement).toHaveText('femme');
cmp.sex = '0';
tb.detectChanges();
expect(el.query(By.css('#i18n-8')).nativeElement).toHaveText('autre');
cmp.count = 123;
tb.detectChanges();
expectHtml(el, '#i18n-9').toEqual('<div id="i18n-9">count = 123</div>');
cmp.sex = 'f';
tb.detectChanges();
expectHtml(el, '#i18n-10').toEqual('<div id="i18n-10">sexe = f</div>');
expectHtml(el, '#i18n-11').toEqual('<div id="i18n-11">custom name</div>');
expectHtml(el, '#i18n-12').toEqual('<h1 id="i18n-12">Balises dans les commentaires html</h1>');
expectHtml(el, '#i18n-13').toBe('<div id="i18n-13" title="dans une section traductible"></div>');
expectHtml(el, '#i18n-15').toMatch(/ca <b>devrait<\/b> marcher/);
expectHtml(el, '#i18n-16').toMatch(/avec un ID explicite/);
expectHtml(el, '#i18n-17-5').toContain('Pas de réponse');
cmp.response.getItemsList = () => ['a'];
tb.detectChanges();
expectHtml(el, '#i18n-17-5').toContain('Une réponse');
cmp.response.getItemsList = () => ['a', 'b'];
tb.detectChanges();
expectHtml(el, '#i18n-17-5').toContain('2 réponses');
expectHtml(el, '#i18n-18').toEqual(
'<div id="i18n-18">FOO<a title="dans une section traductible">BAR</a></div>',
);
}
function expectHtml(el: DebugElement, cssSelector: string): any {
return expect(stringifyElement(el.query(By.css(cssSelector)).nativeElement));
}
export | {
"end_byte": 5024,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_common.ts"
} |
angular/packages/compiler/test/i18n/integration_common.ts_5026_8168 | nst HTML = `
<div>
<h1 i18n>i18n attribute on tags</h1>
<div id="i18n-1"><p i18n>nested</p></div>
<div id="i18n-2"><p i18n="different meaning|">nested</p></div>
<div id="i18n-3"><p i18n><i>with placeholders</i></p></div>
<div id="i18n-3b"><p i18n><i class="preserved-on-placeholders">with placeholders</i></p></div>
<div id="i18n-3c"><div i18n><div>with <div>nested</div> placeholders</div></div></div>
<div>
<p id="i18n-4" i18n-title title="on not translatable node" i18n-data-html data-html="<b>bold</b>"></p>
<p id="i18n-5" i18n i18n-title title="on translatable node"></p>
<p id="i18n-6" i18n-title title></p>
</div>
<!-- no ph below because the ICU node is the only child of the div, i.e. no text nodes -->
<div i18n id="i18n-7">{count, plural, =0 {zero} =1 {one} =2 {two} other {<b>many</b>}}</div>
<div i18n id="i18n-8">
{sex, select, male {m} female {f} other {other}}
</div>
<div i18n id="i18n-8b">
{sexB, select, male {m} female {f}}
</div>
<div i18n id="i18n-9">{{ "count = " + count }}</div>
<div i18n id="i18n-10">sex = {{ sex }}</div>
<div i18n id="i18n-11">{{ "custom name" //i18n(ph="CUSTOM_NAME") }}</div>
</div>
<!-- i18n -->
<h1 id="i18n-12" >Markers in html comments</h1>
<div id="i18n-13" i18n-title title="in a translatable section"></div>
<div id="i18n-14">{count, plural, =0 {zero} =1 {one} =2 {two} other {<b>many</b>}}</div>
<!-- /i18n -->
<div id="i18n-15"><ng-container i18n>it <b>should</b> work</ng-container></div>
<div id="i18n-16" i18n="@@i18n16">with an explicit ID</div>
<div id="i18n-17" i18n="@@i18n17">{count, plural, =0 {zero} =1 {one} =2 {two} other {<b>many</b>}}</div>
<!-- make sure that ICU messages are not treated as text nodes -->
<div id="i18n-17-5" i18n="desc">{
response.getItemsList().length,
plural,
=0 {Found no results}
=1 {Found one result}
other {Found {{response.getItemsList().length}} results}
}</div>
<div i18n id="i18n-18">foo<a i18n-title title="in a translatable section">bar</a></div>
<div id="i18n-19" i18n>{{ 'test' //i18n(ph="map name") }}</div>
`;
export async function configureCompiler(translationsToMerge: string, format: string) {
TestBed.configureCompiler({
providers: [
{provide: ResourceLoader, useValue: jasmine.createSpyObj('ResourceLoader', ['get'])},
FrLocalization.PROVIDE,
{provide: TRANSLATIONS, useValue: translationsToMerge},
{provide: TRANSLATIONS_FORMAT, useValue: format},
],
});
TestBed.configureTestingModule({declarations: [I18nComponent]});
}
export function createComponent(html: string) {
const tb: ComponentFixture<I18nComponent> = TestBed.overrideTemplate(
I18nComponent,
html,
).createComponent(I18nComponent);
return {tb, cmp: tb.componentInstance, el: tb.debugElement};
}
export function serializeTranslations(html: string, serializer: Serializer) {
const catalog = new MessageBundle(new HtmlParser(), [], {});
catalog.updateFromTemplate(html, 'file.ts', DEFAULT_INTERPOLATION_CONFIG);
return catalog.write(serializer);
}
| {
"end_byte": 8168,
"start_byte": 5026,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_common.ts"
} |
angular/packages/compiler/test/i18n/whitespace_sensitivity_spec.ts_0_555 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as i18n from '../../src/i18n/i18n_ast';
import {MessageBundle} from '../../src/i18n/message_bundle';
import {DEFAULT_INTERPOLATION_CONFIG} from '../../src/ml_parser/defaults';
import {HtmlParser} from '../../src/ml_parser/html_parser';
import {Xmb} from '../../src/i18n/serializers/xmb';
describe('i18nPreserveWhitespaceForLegacyExtraction', | {
"end_byte": 555,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/whitespace_sensitivity_spec.ts"
} |
angular/packages/compiler/test/i18n/whitespace_sensitivity_spec.ts_556_7245 | () => {
describe('ignores whitespace changes when disabled', () => {
it('from converting one-line messages to block messages', () => {
const initial = extractMessages(
`
<div i18n>Hello, World!</div>
<div i18n>Hello {{ abc }}</div>
<div i18n>Start {{ abc }} End</div>
<div i18n>{{ first }} middle {{ end }}</div>
<div i18n><a href="/foo">First Second</a></div>
<div i18n>Before <a href="/foo">First Second</a> After</div>
<div i18n><input type="text" /></div>
<div i18n>Before <input type="text" /> After</div>
<div i18n>{apples, plural, =1 {One apple.} =other {Many apples.}}</div>
<div i18n>{apples, plural, =other {{bananas, plural, =other{Many apples and bananas.}}}}</div>
i18nPreserveWhitespaceForLegacyExtraction does not support changing ICU case text.
Test case is disabled by omitting the i18n attribute.
<div>{apples, plural, =1 {One apple.} =other {Many apples.}}</div>
`.trim(),
false /* preserveWhitespace */,
);
const multiLine = extractMessages(
`
<div i18n>
Hello, World!
</div>
<div i18n>
Hello {{ abc }}
</div>
<div i18n>
Start {{ abc }} End
</div>
<div i18n>
{{ first }} middle {{ end }}
</div>
<div i18n>
<a href="/foo">
First
Second
</a>
</div>
<div i18n>
Before
<a href="/foo">
First
Second
</a>
After
</div>
<div i18n>
<input type="text" />
</div>
<div i18n>
Before
<input type="text" />
After
</div>
<div i18n>{
apples, plural,
=1 {One apple.}
=other {Many apples.}
}</div>
<div i18n>{
apples, plural,
=other {{bananas, plural,
=other{Many apples and bananas.}
}}
}</div>
i18nPreserveWhitespaceForLegacyExtraction does not support changing ICU case text.
Test case is disabled by omitting the i18n attribute.
<div>{
apples, plural,
=1 {
One
apple.
}
=other {
Many
apples.
}
}</div>
`.trim(),
false /* preserveWhitespace */,
);
expect(multiLine.length).toBe(10);
expect(multiLine.map(({id}) => id)).toEqual(initial.map(({id}) => id));
});
it('from indenting a message', () => {
const initial = extractMessages(
`
<div i18n>
Hello, World!
</div>
<div i18n>
Hello {{ abc }}
</div>
<div i18n>
Start {{ abc }} End
</div>
<div i18n>
{{ first }} middle {{ end }}
</div>
<div i18n>
<a href="/foo">
Foo
</a>
</div>
<div i18n>
Before
<a href="/foo">Link</a>
After
</div>
<div i18n>
<input type="text" />
</div>
<div i18n>
Before <input type="text" /> After
</div>
<div i18n>{
apples, plural,
=1 {One apple.}
=other {Many apples.}
}</div>
<div i18n>{
apples, plural,
=other {{bananas, plural,
=other{Many apples and bananas.}
}}
}</div>
i18nPreserveWhitespaceForLegacyExtraction does not support indenting ICU case text.
Test case is disabled by omitting the i18n attribute.
<div>{
apples, plural,
=1 {
One
apple.
}
=other {
Many
apples.
}
}</div>
`.trim(),
false /* preserveWhitespace */,
);
const indented = extractMessages(
`
<div id="container">
<div i18n>
Hello, World!
</div>
<div i18n>
Hello {{ abc }}
</div>
<div i18n>
Start {{ abc }} End
</div>
<div i18n>
{{ first }} middle {{ end }}
</div>
<div i18n>
<a href="/foo">
Foo
</a>
</div>
<div i18n>
Before
<a href="/foo">Link</a>
After
</div>
<div i18n>
<input type="text" />
</div>
<div i18n>
Before <input type="text" /> After
</div>
<div i18n>{
apples, plural,
=1 {One apple.}
=other {Many apples.}
}</div>
<div i18n>{
apples, plural,
=other {{bananas, plural,
=other{Many apples and bananas.}
}}
}</div>
i18nPreserveWhitespaceForLegacyExtraction does not support indenting ICU case text.
Test case is disabled by omitting the i18n attribute.
<div>{
apples, plural,
=1 {
One
apple.
}
=other {
Many
apples.
}
}</div>
</div>
`.trim(),
false /* preserveWhitespace */,
);
expect(indented.length).toBe(10);
expect(indented.map(({id}) => id)).toEqual(initial.map(({id}) => id));
});
it('from adjusting line wrapping', () => {
const initial = extractMessages(
`
<div i18n>
This is a long message which maybe
exceeds line length.
</div>
<div i18n>
Hello {{ veryLongExpressionWhichMaybeExceedsLineLength | async }}
</div>
<div i18n>
This is a long {{ abc }} which maybe
exceeds line length.
</div>
<div i18n>
{{ first }} long message {{ end }}
</div>
<div i18n>
<a href="/foo" veryLongAttributeWhichMaybeExceedsLineLength>
This is a long message which maybe
exceeds line length.
</a>
</div>
<div i18n>
This is a
long <a href="/foo" veryLongAttributeWhichMaybeExceedsLineLength>message</a> which
maybe exceeds line length.
</div>
<div i18n>
<input type="text" veryLongAttributeWhichMaybeExceedsLineLength />
</div>
<div i18n>
Before <input type="text" veryLongAttributeWhichMaybeExceedsLineLength /> After
</div>
i18nPreserveWhitespaceForLegacyExtraction does not support line wrapping ICU case text.
Test case is disabled by omitting the i18n attribute.
<div>{
apples, plural, =other {Very long text which maybe exceeds line length.}
}</div>
`.trim(),
false /* preserveWhitespace */,
);
const adjusted = extractMessages(
`
<div i18n>
This is a long message which
maybe exceeds line length.
</div>
<div i18n>
Hello {{
veryLongExpressionWhichMaybeExceedsLineLength
| async
}}
</div>
<div i18n>
This is a long {{ abc }} which
maybe exceeds line length.
</div>
<div i18n>
{{ first }}
long message
{{ end }}
</div>
<div i18n>
<a
href="/foo"
veryLongAttributeWhichMaybeExceedsLineLength>
This is a long message which
maybe exceeds line length.
</a>
</div>
<div i18n>
This is a long
<a
href="/foo"
veryLongAttributeWhichMaybeExceedsLineLength>
message
</a>
which maybe exceeds line length.
</div>
<div i18n>
<input
type="text"
veryLongAttributeWhichMaybeExceedsLineLength
/>
</div>
<div i18n>
Before
<input
type="text"
veryLongAttributeWhichMaybeExceedsLineLength
/>
After
</div>
i18nPreserveWhitespaceForLegacyExtraction does not support line wrapping ICU case text.
Test case is disabled by omitting the i18n attribute.
<div>{
apples, plural, =other {
Very long text which
maybe exceeds line length.
}
}</div>
`.trim(),
false /* preserveWhitespace */,
);
expect(adjusted.length).toBe(8);
expect(adjusted.map(({id}) => id)).toEqual(initial.map(({id}) => id));
}); | {
"end_byte": 7245,
"start_byte": 556,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/whitespace_sensitivity_spec.ts"
} |
angular/packages/compiler/test/i18n/whitespace_sensitivity_spec.ts_7251_11060 | it('from trimming significant whitespace', () => {
const initial = extractMessages(
`
<div i18n> Hello, World! </div>
<div i18n> Hello {{ abc }} </div>
<div i18n> Start {{ abc }} End </div>
<div i18n> {{ first }} middle {{ end }} </div>
<div i18n> <a href="/foo">Foo</a> </div>
<div i18n><a href="/foo"> Foo </a></div>
<div i18n> Before <a href="/foo">Link</a> After </div>
<div i18n> <input type="text" /> </div>
<div i18n> Before <input type="text" /> After </div>
i18nPreserveWhitespaceForLegacyExtraction does not support trimming ICU case text.
Test case is disabled by omitting the i18n attribute.
<div>Hello {
apples, plural,
=1 { One apple. }
=other { Many apples. }
}</div>
`.trim(),
false /* preserveWhitespace */,
);
const trimmed = extractMessages(
`
<div i18n>Hello, World!</div>
<div i18n>Hello {{ abc }}</div>
<div i18n>Start {{ abc }} End</div>
<div i18n>{{ first }} middle {{ end }}</div>
<div i18n><a href="/foo">Foo</a></div>
<div i18n><a href="/foo">Foo</a></div>
<div i18n>Before <a href="/foo">Link</a> After</div>
<div i18n><input type="text" /></div>
<div i18n>Before <input type="text" /> After</div>
i18nPreserveWhitespaceForLegacyExtraction does not support trimming ICU case text.
Test case is disabled by omitting the i18n attribute.
<div>Hello {
apples, plural,
=1 {One apple.}
=other {Many apples.}
}</div>
`.trim(),
false /* preserveWhitespace */,
);
expect(trimmed.length).toBe(9);
expect(trimmed).toEqual(initial);
});
});
});
interface AssertableMessage {
id: string;
text: string;
}
/**
* Serializes a message for easy assertion that the meaningful text did not change.
* For example: This does not include expression source, because that is allowed to
* change without affecting message IDs or extracted placeholders.
*/
const debugSerializer = new (class implements i18n.Visitor {
visitText(text: i18n.Text): string {
return text.value;
}
visitContainer(container: i18n.Container): string {
return `[${container.children.map((child) => child.visit(this)).join(', ')}]`;
}
visitIcu(icu: i18n.Icu): string {
const strCases = Object.keys(icu.cases).map(
(k: string) => `${k} {${icu.cases[k].visit(this)}}`,
);
return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`;
}
visitTagPlaceholder(ph: i18n.TagPlaceholder): string {
return ph.isVoid
? `<ph tag name="${ph.startName}"/>`
: `<ph tag name="${ph.startName}">${ph.children
.map((child) => child.visit(this))
.join(', ')}</ph name="${ph.closeName}">`;
}
visitPlaceholder(ph: i18n.Placeholder): string {
return `<ph name="${ph.name}"/>`;
}
visitIcuPlaceholder(ph: i18n.IcuPlaceholder): string {
return `<ph icu name="${ph.name}"/>`;
}
visitBlockPlaceholder(ph: i18n.BlockPlaceholder): string {
return `<ph block name="${ph.startName}">${ph.children
.map((child) => child.visit(this))
.join(', ')}</ph name="${ph.closeName}">`;
}
})();
function extractMessages(source: string, preserveWhitespace: boolean): AssertableMessage[] {
const bundle = new MessageBundle(
new HtmlParser(),
[] /* implicitTags */,
{} /* implicitAttrs */,
undefined /* locale */,
preserveWhitespace,
);
const errors = bundle.updateFromTemplate(source, 'url', DEFAULT_INTERPOLATION_CONFIG);
if (errors.length !== 0) {
throw new Error(
`Failed to parse template:\n${errors.map((err) => err.toString()).join('\n\n')}`,
);
}
const messages = bundle.getMessages();
const xmbSerializer = new Xmb();
return messages.map((message) => ({
id: xmbSerializer.digest(message),
text: message.nodes.map((node) => node.visit(debugSerializer)).join(''),
}));
} | {
"end_byte": 11060,
"start_byte": 7251,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/whitespace_sensitivity_spec.ts"
} |
angular/packages/compiler/test/i18n/translation_bundle_spec.ts_0_7146 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {MissingTranslationStrategy} from '@angular/core';
import * as i18n from '../../src/i18n/i18n_ast';
import {TranslationBundle} from '../../src/i18n/translation_bundle';
import * as html from '../../src/ml_parser/ast';
import {ParseLocation, ParseSourceFile, ParseSourceSpan} from '../../src/parse_util';
import {serializeNodes} from '../ml_parser/util/util';
import {_extractMessages} from './i18n_parser_spec';
describe('TranslationBundle', () => {
const file = new ParseSourceFile('content', 'url');
const startLocation = new ParseLocation(file, 0, 0, 0);
const endLocation = new ParseLocation(file, 0, 0, 7);
const span = new ParseSourceSpan(startLocation, endLocation);
const srcNode = new i18n.Text('src', span);
it('should translate a plain text', () => {
const msgMap = {foo: [new i18n.Text('bar', null!)]};
const tb = new TranslationBundle(msgMap, null, (_) => 'foo');
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
expect(serializeNodes(tb.get(msg))).toEqual(['bar']);
});
it('should translate html-like plain text', () => {
const msgMap = {foo: [new i18n.Text('<p>bar</p>', null!)]};
const tb = new TranslationBundle(msgMap, null, (_) => 'foo');
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
const nodes = tb.get(msg);
expect(nodes.length).toEqual(1);
const textNode: html.Text = nodes[0] as any;
expect(textNode instanceof html.Text).toEqual(true);
expect(textNode.value).toBe('<p>bar</p>');
});
it('should translate a message with placeholder', () => {
const msgMap = {
foo: [new i18n.Text('bar', null!), new i18n.Placeholder('', 'ph1', null!)],
};
const phMap = {
ph1: createPlaceholder('*phContent*'),
};
const tb = new TranslationBundle(msgMap, null, (_) => 'foo');
const msg = new i18n.Message([srcNode], phMap, {}, 'm', 'd', 'i');
expect(serializeNodes(tb.get(msg))).toEqual(['bar*phContent*']);
});
it('should translate a message with placeholder referencing messages', () => {
const msgMap = {
foo: [
new i18n.Text('--', null!),
new i18n.Placeholder('', 'ph1', null!),
new i18n.Text('++', null!),
],
ref: [new i18n.Text('*refMsg*', null!)],
};
const refMsg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
const msg = new i18n.Message([srcNode], {}, {ph1: refMsg}, 'm', 'd', 'i');
let count = 0;
const digest = (_: any) => (count++ ? 'ref' : 'foo');
const tb = new TranslationBundle(msgMap, null, digest);
expect(serializeNodes(tb.get(msg))).toEqual(['--*refMsg*++']);
});
it('should use the original message or throw when a translation is not found', () => {
const src = `<some-tag>some text{{ some_expression }}</some-tag>{count, plural, =0 {no} few {a <b>few</b>}}`;
const messages = _extractMessages(`<div i18n>${src}</div>`);
const digest = (_: any) => `no matching id`;
// Empty message map -> use source messages in Ignore mode
let tb = new TranslationBundle({}, null, digest, null!, MissingTranslationStrategy.Ignore);
expect(serializeNodes(tb.get(messages[0])).join('')).toEqual(src);
// Empty message map -> use source messages in Warning mode
tb = new TranslationBundle({}, null, digest, null!, MissingTranslationStrategy.Warning);
expect(serializeNodes(tb.get(messages[0])).join('')).toEqual(src);
// Empty message map -> throw in Error mode
tb = new TranslationBundle({}, null, digest, null!, MissingTranslationStrategy.Error);
expect(() => serializeNodes(tb.get(messages[0])).join('')).toThrow();
});
describe('errors reporting', () => {
it('should report unknown placeholders', () => {
const msgMap = {
foo: [new i18n.Text('bar', null!), new i18n.Placeholder('', 'ph1', span)],
};
const tb = new TranslationBundle(msgMap, null, (_) => 'foo');
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
expect(() => tb.get(msg)).toThrowError(/Unknown placeholder/);
});
it('should report missing translation', () => {
const tb = new TranslationBundle(
{},
null,
(_) => 'foo',
null!,
MissingTranslationStrategy.Error,
);
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
expect(() => tb.get(msg)).toThrowError(/Missing translation for message "foo"/);
});
it('should report missing translation with MissingTranslationStrategy.Warning', () => {
const log: string[] = [];
const console = {
log: (msg: string) => {
throw `unexpected`;
},
warn: (msg: string) => log.push(msg),
};
const tb = new TranslationBundle(
{},
'en',
(_) => 'foo',
null!,
MissingTranslationStrategy.Warning,
console,
);
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
expect(() => tb.get(msg)).not.toThrowError();
expect(log.length).toEqual(1);
expect(log[0]).toMatch(/Missing translation for message "foo" for locale "en"/);
});
it('should not report missing translation with MissingTranslationStrategy.Ignore', () => {
const tb = new TranslationBundle(
{},
null,
(_) => 'foo',
null!,
MissingTranslationStrategy.Ignore,
);
const msg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
expect(() => tb.get(msg)).not.toThrowError();
});
it('should report missing referenced message', () => {
const msgMap = {
foo: [new i18n.Placeholder('', 'ph1', span)],
};
const refMsg = new i18n.Message([srcNode], {}, {}, 'm', 'd', 'i');
const msg = new i18n.Message([srcNode], {}, {ph1: refMsg}, 'm', 'd', 'i');
let count = 0;
const digest = (_: any) => (count++ ? 'ref' : 'foo');
const tb = new TranslationBundle(
msgMap,
null,
digest,
null!,
MissingTranslationStrategy.Error,
);
expect(() => tb.get(msg)).toThrowError(/Missing translation for message "ref"/);
});
it('should report invalid translated html', () => {
const msgMap = {
foo: [new i18n.Text('text', null!), new i18n.Placeholder('', 'ph1', null!)],
};
const phMap = {
ph1: createPlaceholder('</b>'),
};
const tb = new TranslationBundle(msgMap, null, (_) => 'foo');
const msg = new i18n.Message([srcNode], phMap, {}, 'm', 'd', 'i');
expect(() => tb.get(msg)).toThrowError(/Unexpected closing tag "b"/);
});
});
});
function createPlaceholder(text: string): i18n.MessagePlaceholder {
const file = new ParseSourceFile(text, 'file://test');
const start = new ParseLocation(file, 0, 0, 0);
const end = new ParseLocation(file, text.length, 0, text.length);
return {
text,
sourceSpan: new ParseSourceSpan(start, end),
};
}
| {
"end_byte": 7146,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/translation_bundle_spec.ts"
} |
angular/packages/compiler/test/i18n/extractor_merger_spec.ts_0_6957 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {DEFAULT_INTERPOLATION_CONFIG, HtmlParser} from '@angular/compiler';
import {MissingTranslationStrategy} from '@angular/core';
import {digest, serializeNodes as serializeI18nNodes} from '../../src/i18n/digest';
import {extractMessages, mergeTranslations} from '../../src/i18n/extractor_merger';
import * as i18n from '../../src/i18n/i18n_ast';
import {TranslationBundle} from '../../src/i18n/translation_bundle';
import * as html from '../../src/ml_parser/ast';
import {serializeNodes as serializeHtmlNodes} from '../ml_parser/util/util';
describe('Extractor', () => {
describe('elements', () => {
it('should extract from elements', () => {
expect(extract('<div i18n="m|d|e">text<span>nested</span></div>')).toEqual([
[
['text', '<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'],
'm',
'd|e',
'',
],
]);
});
it('should extract from attributes', () => {
expect(
extract(
'<div i18n="m1|d1"><span i18n-title="m2|d2" title="single child">nested</span></div>',
),
).toEqual([
[['<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'], 'm1', 'd1', ''],
[['single child'], 'm2', 'd2', ''],
]);
});
it('should extract from attributes with id', () => {
expect(
extract(
'<div i18n="m1|d1@@i1"><span i18n-title="m2|d2@@i2" title="single child">nested</span></div>',
),
).toEqual([
[['<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'], 'm1', 'd1', 'i1'],
[['single child'], 'm2', 'd2', 'i2'],
]);
});
it('should trim whitespace from custom ids (but not meanings)', () => {
expect(extract('<div i18n="\n m1|d1@@i1\n ">test</div>')).toEqual([
[['test'], '\n m1', 'd1', 'i1'],
]);
});
it('should extract from attributes without meaning and with id', () => {
expect(
extract(
'<div i18n="d1@@i1"><span i18n-title="d2@@i2" title="single child">nested</span></div>',
),
).toEqual([
[['<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'], '', 'd1', 'i1'],
[['single child'], '', 'd2', 'i2'],
]);
});
it('should extract from attributes with id only', () => {
expect(
extract(
'<div i18n="@@i1"><span i18n-title="@@i2" title="single child">nested</span></div>',
),
).toEqual([
[['<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'], '', '', 'i1'],
[['single child'], '', '', 'i2'],
]);
});
it('should extract from ICU messages', () => {
expect(
extract(
'<div i18n="m|d">{count, plural, =0 { <p i18n-title i18n-desc title="title" desc="desc"></p>}}</div>',
),
).toEqual([
[
['{count, plural, =0 {[<ph tag name="START_PARAGRAPH"></ph name="CLOSE_PARAGRAPH">]}}'],
'm',
'd',
'',
],
[['title'], '', '', ''],
[['desc'], '', '', ''],
]);
});
it('should not create a message for empty elements', () => {
expect(extract('<div i18n="m|d"></div>')).toEqual([]);
});
it('should not create a message for placeholder-only elements', () => {
expect(extract('<div i18n="m|d">{{ foo }}</div>')).toEqual([]);
});
it('should ignore implicit elements in translatable elements', () => {
expect(extract('<div i18n="m|d"><p></p></div>', ['p'])).toEqual([
[['<ph tag name="START_PARAGRAPH"></ph name="CLOSE_PARAGRAPH">'], 'm', 'd', ''],
]);
});
});
describe('blocks', () => {
it('should extract from elements inside blocks', () => {
expect(
extract(
'@switch (value) {' +
'@case (1) {<div i18n="a|b|c">one <span>nested</span></div>}' +
'@case (2) {<strong i18n="d|e|f">two <span>nested</span></strong>}' +
'@default {<strong i18n="g|h|i">default <span>nested</span></strong>}' +
'}',
),
).toEqual([
[
['one ', '<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'],
'a',
'b|c',
'',
],
[
['two ', '<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'],
'd',
'e|f',
'',
],
[
['default ', '<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'],
'g',
'h|i',
'',
],
]);
});
it('should extract from i18n comment blocks inside blocks', () => {
expect(
extract(
'@switch (value) {' +
'@case (1) {<!-- i18n: oneMeaning|oneDesc -->one message<!-- /i18n -->}' +
'@case (2) {<!-- i18n: twoMeaning|twoDesc -->two message<!-- /i18n -->}' +
'@default {<!-- i18n: defaultMeaning|defaultDesc -->default message<!-- /i18n -->}' +
'}',
),
).toEqual([
[['one message'], 'oneMeaning', 'oneDesc', ''],
[['two message'], 'twoMeaning', 'twoDesc', ''],
[['default message'], 'defaultMeaning', 'defaultDesc', ''],
]);
});
it('should extract ICUs from elements inside blocks', () => {
expect(
extract(
'@switch (value) {' +
'@case (1) {<div i18n="a|b">{count, plural, =0 {oneText}}</div>}' +
'@case (2) {<div i18n="c|d">{count, plural, =0 {twoText}}</div>}' +
'@default {<div i18n="e|f">{count, plural, =0 {defaultText}}</div>}' +
'}',
),
).toEqual([
[['{count, plural, =0 {[oneText]}}'], 'a', 'b', ''],
[['{count, plural, =0 {[twoText]}}'], 'c', 'd', ''],
[['{count, plural, =0 {[defaultText]}}'], 'e', 'f', ''],
]);
});
it('should not extract messages from ICUs directly inside blocks', () => {
const expression = '{count, plural, =0 {text}}';
expect(
extract(
`@switch (value) {` +
`@case (1) {${expression}}` +
`@case (2) {${expression}}` +
`@default {${expression}}` +
`}`,
),
).toEqual([]);
});
it('should handle blocks inside of translated elements', () => {
expect(
extract('<span i18n="a|b|c">@if (cond) {main content} @else {else content}</span>`'),
).toEqual([
[
[
'<ph block name="START_BLOCK_IF">main content</ph name="CLOSE_BLOCK_IF">',
' ',
'<ph block name="START_BLOCK_ELSE">else content</ph name="CLOSE_BLOCK_ELSE">',
],
'a',
'b|c',
'',
],
]);
});
}); | {
"end_byte": 6957,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/extractor_merger_spec.ts"
} |
angular/packages/compiler/test/i18n/extractor_merger_spec.ts_6961_11832 | describe('i18n comment blocks', () => {
it('should extract from blocks', () => {
expect(
extract(`<!-- i18n: meaning1|desc1 -->message1<!-- /i18n -->
<!-- i18n: desc2 -->message2<!-- /i18n -->
<!-- i18n -->message3<!-- /i18n -->
<!-- i18n: meaning4|desc4@@id4 -->message4<!-- /i18n -->
<!-- i18n: @@id5 -->message5<!-- /i18n -->`),
).toEqual([
[['message1'], 'meaning1', 'desc1', ''],
[['message2'], '', 'desc2', ''],
[['message3'], '', '', ''],
[['message4'], 'meaning4', 'desc4', 'id4'],
[['message5'], '', '', 'id5'],
]);
});
it('should ignore implicit elements in blocks', () => {
expect(extract('<!-- i18n:m|d --><p></p><!-- /i18n -->', ['p'])).toEqual([
[['<ph tag name="START_PARAGRAPH"></ph name="CLOSE_PARAGRAPH">'], 'm', 'd', ''],
]);
});
it('should extract siblings', () => {
expect(
extract(
`<!-- i18n -->text<p>html<b>nested</b></p>{count, plural, =0 {<span>html</span>}}{{interp}}<!-- /i18n -->`,
),
).toEqual([
[
['{count, plural, =0 {[<ph tag name="START_TAG_SPAN">html</ph name="CLOSE_TAG_SPAN">]}}'],
'',
'',
'',
],
[
[
'text',
'<ph tag name="START_PARAGRAPH">html, <ph tag' +
' name="START_BOLD_TEXT">nested</ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">',
'<ph icu name="ICU">{count, plural, =0 {[<ph tag' +
' name="START_TAG_SPAN">html</ph name="CLOSE_TAG_SPAN">]}}</ph>',
'[<ph name="INTERPOLATION">interp</ph>]',
],
'',
'',
'',
],
]);
});
it('should ignore other comments', () => {
expect(
extract(`<!-- i18n: meaning1|desc1@@id1 --><!-- other -->message1<!-- /i18n -->`),
).toEqual([[['message1'], 'meaning1', 'desc1', 'id1']]);
});
it('should not create a message for empty blocks', () => {
expect(extract(`<!-- i18n: meaning1|desc1 --><!-- /i18n -->`)).toEqual([]);
});
});
describe('ICU messages', () => {
it('should extract ICU messages from translatable elements', () => {
// single message when ICU is the only children
expect(extract('<div i18n="m|d">{count, plural, =0 {text}}</div>')).toEqual([
[['{count, plural, =0 {[text]}}'], 'm', 'd', ''],
]);
// single message when ICU is the only (implicit) children
expect(extract('<div>{count, plural, =0 {text}}</div>', ['div'])).toEqual([
[['{count, plural, =0 {[text]}}'], '', '', ''],
]);
// one message for the element content and one message for the ICU
expect(extract('<div i18n="m|d@@i">before{count, plural, =0 {text}}after</div>')).toEqual([
[
['before', '<ph icu name="ICU">{count, plural, =0 {[text]}}</ph>', 'after'],
'm',
'd',
'i',
],
[['{count, plural, =0 {[text]}}'], '', '', ''],
]);
});
it('should extract ICU messages from translatable block', () => {
// single message when ICU is the only children
expect(extract('<!-- i18n:m|d -->{count, plural, =0 {text}}<!-- /i18n -->')).toEqual([
[['{count, plural, =0 {[text]}}'], 'm', 'd', ''],
]);
// one message for the block content and one message for the ICU
expect(
extract('<!-- i18n:m|d -->before{count, plural, =0 {text}}after<!-- /i18n -->'),
).toEqual([
[['{count, plural, =0 {[text]}}'], '', '', ''],
[['before', '<ph icu name="ICU">{count, plural, =0 {[text]}}</ph>', 'after'], 'm', 'd', ''],
]);
});
it('should not extract ICU messages outside of i18n sections', () => {
expect(extract('{count, plural, =0 {text}}')).toEqual([]);
});
it('should ignore nested ICU messages', () => {
expect(
extract('<div i18n="m|d">{count, plural, =0 { {sex, select, male {m}} }}</div>'),
).toEqual([[['{count, plural, =0 {[{sex, select, male {[m]}}, ]}}'], 'm', 'd', '']]);
});
it('should ignore implicit elements in non translatable ICU messages', () => {
expect(
extract(
'<div i18n="m|d@@i">{count, plural, =0 { {sex, select, male {<p>ignore</p>}}' +
' }}</div>',
['p'],
),
).toEqual([
[
[
'{count, plural, =0 {[{sex, select, male {[<ph tag name="START_PARAGRAPH">ignore</ph name="CLOSE_PARAGRAPH">]}}, ]}}',
],
'm',
'd',
'i',
],
]);
});
it('should ignore implicit elements in non translatable ICU messages', () => {
expect(extract('{count, plural, =0 { {sex, select, male {<p>ignore</p>}} }}', ['p'])).toEqual(
[],
);
});
}); | {
"end_byte": 11832,
"start_byte": 6961,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/extractor_merger_spec.ts"
} |
angular/packages/compiler/test/i18n/extractor_merger_spec.ts_11836_17703 | describe('attributes', () => {
it('should extract from attributes outside of translatable sections', () => {
expect(extract('<div i18n-title="m|d@@i" title="msg"></div>')).toEqual([
[['msg'], 'm', 'd', 'i'],
]);
});
it('should extract from attributes in translatable elements', () => {
expect(extract('<div i18n><p><b i18n-title="m|d@@i" title="msg"></b></p></div>')).toEqual([
[
[
'<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph' +
' name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">',
],
'',
'',
'',
],
[['msg'], 'm', 'd', 'i'],
]);
});
it('should extract from attributes in translatable blocks', () => {
expect(
extract('<!-- i18n --><p><b i18n-title="m|d" title="msg"></b></p><!-- /i18n -->'),
).toEqual([
[['msg'], 'm', 'd', ''],
[
[
'<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph' +
' name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">',
],
'',
'',
'',
],
]);
});
it('should extract from attributes in translatable ICUs', () => {
expect(
extract(`<!-- i18n -->{count, plural, =0 {<p><b i18n-title="m|d@@i"
title="msg"></b></p>}}<!-- /i18n -->`),
).toEqual([
[['msg'], 'm', 'd', 'i'],
[
[
'{count, plural, =0 {[<ph tag name="START_PARAGRAPH"><ph tag' +
' name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">]}}',
],
'',
'',
'',
],
]);
});
it('should extract from attributes in non translatable ICUs', () => {
expect(extract('{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}')).toEqual([
[['msg'], 'm', 'd', ''],
]);
});
it('should not create a message for empty attributes', () => {
expect(extract('<div i18n-title="m|d" title></div>')).toEqual([]);
});
it('should not create a message for placeholder-only attributes', () => {
expect(extract('<div i18n-title="m|d" title="{{ foo }}"></div>')).toEqual([]);
});
});
describe('implicit elements', () => {
it('should extract from implicit elements', () => {
expect(extract('<b>bold</b><i>italic</i>', ['b'])).toEqual([[['bold'], '', '', '']]);
});
it('should allow nested implicit elements', () => {
let result: any[] = undefined!;
expect(() => {
result = extract('<div>outer<div>inner</div></div>', ['div']);
}).not.toThrow();
expect(result).toEqual([
[['outer', '<ph tag name="START_TAG_DIV">inner</ph name="CLOSE_TAG_DIV">'], '', '', ''],
]);
});
});
describe('implicit attributes', () => {
it('should extract implicit attributes', () => {
expect(
extract('<b title="bb">bold</b><i title="ii">italic</i>', [], {'b': ['title']}),
).toEqual([[['bb'], '', '', '']]);
});
});
describe('errors', () => {
describe('elements', () => {
it('should report nested translatable elements', () => {
expect(extractErrors(`<p i18n><b i18n></b></p>`)).toEqual([
[
'Could not mark an element as translatable inside a translatable section',
'<b i18n></b>',
],
]);
});
it('should report translatable elements in implicit elements', () => {
expect(extractErrors(`<p><b i18n></b></p>`, ['p'])).toEqual([
[
'Could not mark an element as translatable inside a translatable section',
'<b i18n></b>',
],
]);
});
it('should report translatable elements in translatable blocks', () => {
expect(extractErrors(`<!-- i18n --><b i18n></b><!-- /i18n -->`)).toEqual([
[
'Could not mark an element as translatable inside a translatable section',
'<b i18n></b>',
],
]);
});
});
describe('blocks', () => {
it('should report nested blocks', () => {
expect(extractErrors(`<!-- i18n --><!-- i18n --><!-- /i18n --><!-- /i18n -->`)).toEqual([
['Could not start a block inside a translatable section', '<!-- i18n -->'],
['Trying to close an unopened block', '<!-- /i18n -->'],
]);
});
it('should report unclosed blocks', () => {
expect(extractErrors(`<!-- i18n -->`)).toEqual([['Unclosed block', '<!-- i18n -->']]);
});
it('should report translatable blocks in translatable elements', () => {
expect(extractErrors(`<p i18n><!-- i18n --><!-- /i18n --></p>`)).toEqual([
['Could not start a block inside a translatable section', '<!-- i18n -->'],
['Trying to close an unopened block', '<!-- /i18n -->'],
]);
});
it('should report translatable blocks in implicit elements', () => {
expect(extractErrors(`<p><!-- i18n --><!-- /i18n --></p>`, ['p'])).toEqual([
['Could not start a block inside a translatable section', '<!-- i18n -->'],
['Trying to close an unopened block', '<!-- /i18n -->'],
]);
});
it('should report when start and end of a block are not at the same level', () => {
expect(extractErrors(`<!-- i18n --><p><!-- /i18n --></p>`)).toEqual([
['I18N blocks should not cross element boundaries', '<!-- /i18n -->'],
['Unclosed block', '<p><!-- /i18n --></p>'],
]);
expect(extractErrors(`<p><!-- i18n --></p><!-- /i18n -->`)).toEqual([
['I18N blocks should not cross element boundaries', '<!-- /i18n -->'],
['Unclosed block', '<!-- /i18n -->'],
]);
});
});
});
}); | {
"end_byte": 17703,
"start_byte": 11836,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/extractor_merger_spec.ts"
} |
angular/packages/compiler/test/i18n/extractor_merger_spec.ts_17705_24878 | describe('Merger', () => {
describe('elements', () => {
it('should merge elements', () => {
const HTML = `<p i18n="m|d">foo</p>`;
expect(fakeTranslate(HTML)).toEqual('<p>**foo**</p>');
});
it('should merge nested elements', () => {
const HTML = `<div>before<p i18n="m|d">foo</p><!-- comment --></div>`;
expect(fakeTranslate(HTML)).toEqual('<div>before<p>**foo**</p></div>');
});
it('should merge empty messages', () => {
const HTML = `<div i18n>some element</div>`;
const htmlNodes: html.Node[] = parseHtml(HTML);
const messages: i18n.Message[] = extractMessages(
htmlNodes,
DEFAULT_INTERPOLATION_CONFIG,
[],
{},
/* preserveSignificantWhitespace */ true,
).messages;
expect(messages.length).toEqual(1);
const i18nMsgMap: {[id: string]: i18n.Node[]} = {};
i18nMsgMap[digest(messages[0])] = [];
const translations = new TranslationBundle(i18nMsgMap, null, digest);
const output = mergeTranslations(
htmlNodes,
translations,
DEFAULT_INTERPOLATION_CONFIG,
[],
{},
);
expect(output.errors).toEqual([]);
expect(serializeHtmlNodes(output.rootNodes).join('')).toEqual(`<div></div>`);
});
});
describe('i18n comment blocks', () => {
it('should console.warn if we use i18n comments', () => {
// TODO(ocombe): expect a warning message when we have a proper log service
extract('<!-- i18n --><p><b i18n-title="m|d" title="msg"></b></p><!-- /i18n -->');
});
it('should merge blocks', () => {
const HTML = `before<!-- i18n --><p>foo</p><span><i>bar</i></span><!-- /i18n -->after`;
expect(fakeTranslate(HTML)).toEqual(
'before**[ph tag name="START_PARAGRAPH">foo[/ph name="CLOSE_PARAGRAPH">[ph tag' +
' name="START_TAG_SPAN">[ph tag name="START_ITALIC_TEXT">bar[/ph' +
' name="CLOSE_ITALIC_TEXT">[/ph name="CLOSE_TAG_SPAN">**after',
);
});
it('should merge nested blocks', () => {
const HTML = `<div>before<!-- i18n --><p>foo</p><span><i>bar</i></span><!-- /i18n -->after</div>`;
expect(fakeTranslate(HTML)).toEqual(
'<div>before**[ph tag name="START_PARAGRAPH">foo[/ph name="CLOSE_PARAGRAPH">[ph' +
' tag name="START_TAG_SPAN">[ph tag name="START_ITALIC_TEXT">bar[/ph' +
' name="CLOSE_ITALIC_TEXT">[/ph name="CLOSE_TAG_SPAN">**after</div>',
);
});
});
describe('attributes', () => {
it('should merge attributes', () => {
const HTML = `<p i18n-title="m|d" title="foo"></p>`;
expect(fakeTranslate(HTML)).toEqual('<p title="**foo**"></p>');
});
it('should merge attributes with ids', () => {
const HTML = `<p i18n-title="@@id" title="foo"></p>`;
expect(fakeTranslate(HTML)).toEqual('<p title="**foo**"></p>');
});
it('should merge nested attributes', () => {
const HTML = `<div>{count, plural, =0 {<p i18n-title title="foo"></p>}}</div>`;
expect(fakeTranslate(HTML)).toEqual(
'<div>{count, plural, =0 {<p title="**foo**"></p>}}</div>',
);
});
it('should merge attributes without values', () => {
const HTML = `<p i18n-title="m|d" title=""></p>`;
expect(fakeTranslate(HTML)).toEqual('<p title=""></p>');
});
it('should merge empty attributes', () => {
const HTML = `<div i18n-title title="some attribute">some element</div>`;
const htmlNodes: html.Node[] = parseHtml(HTML);
const messages: i18n.Message[] = extractMessages(
htmlNodes,
DEFAULT_INTERPOLATION_CONFIG,
[],
{},
/* preserveSignificantWhitespace */ true,
).messages;
expect(messages.length).toEqual(1);
const i18nMsgMap: {[id: string]: i18n.Node[]} = {};
i18nMsgMap[digest(messages[0])] = [];
const translations = new TranslationBundle(i18nMsgMap, null, digest);
const output = mergeTranslations(
htmlNodes,
translations,
DEFAULT_INTERPOLATION_CONFIG,
[],
{},
);
expect(output.errors).toEqual([]);
expect(serializeHtmlNodes(output.rootNodes).join('')).toEqual(
`<div title="">some element</div>`,
);
});
});
describe('no translations', () => {
it('should remove i18n attributes', () => {
const HTML = `<p i18n="m|d">foo</p>`;
expect(fakeNoTranslate(HTML)).toEqual('<p>foo</p>');
});
it('should remove i18n- attributes', () => {
const HTML = `<p i18n-title="m|d" title="foo"></p>`;
expect(fakeNoTranslate(HTML)).toEqual('<p title="foo"></p>');
});
it('should remove i18n comment blocks', () => {
const HTML = `before<!-- i18n --><p>foo</p><span><i>bar</i></span><!-- /i18n -->after`;
expect(fakeNoTranslate(HTML)).toEqual('before<p>foo</p><span><i>bar</i></span>after');
});
it('should remove nested i18n markup', () => {
const HTML = `<!-- i18n --><span someAttr="ok">foo</span><div>{count, plural, =0 {<p i18n-title title="foo"></p>}}</div><!-- /i18n -->`;
expect(fakeNoTranslate(HTML)).toEqual(
'<span someAttr="ok">foo</span><div>{count, plural, =0 {<p title="foo"></p>}}</div>',
);
});
});
});
function parseHtml(html: string): html.Node[] {
const htmlParser = new HtmlParser();
const parseResult = htmlParser.parse(html, 'extractor spec', {tokenizeExpansionForms: true});
if (parseResult.errors.length > 1) {
throw new Error(`unexpected parse errors: ${parseResult.errors.join('\n')}`);
}
return parseResult.rootNodes;
}
function fakeTranslate(
content: string,
implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {},
): string {
const htmlNodes: html.Node[] = parseHtml(content);
const messages: i18n.Message[] = extractMessages(
htmlNodes,
DEFAULT_INTERPOLATION_CONFIG,
implicitTags,
implicitAttrs,
/* preserveSignificantWhitespace */ true,
).messages;
const i18nMsgMap: {[id: string]: i18n.Node[]} = {};
messages.forEach((message) => {
const id = digest(message);
const text = serializeI18nNodes(message.nodes).join('').replace(/</g, '[');
i18nMsgMap[id] = [new i18n.Text(`**${text}**`, null!)];
});
const translationBundle = new TranslationBundle(i18nMsgMap, null, digest);
const output = mergeTranslations(
htmlNodes,
translationBundle,
DEFAULT_INTERPOLATION_CONFIG,
implicitTags,
implicitAttrs,
);
expect(output.errors).toEqual([]);
return serializeHtmlNodes(output.rootNodes).join('');
}
function fakeNoTranslate(
content: string,
implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {},
): string {
const htmlNodes: html.Node[] = parseHtml(content);
const translationBundle = new TranslationBundle(
{},
null,
digest,
undefined,
MissingTranslationStrategy.Ignore,
console,
);
const output = mergeTranslations(
htmlNodes,
translationBundle,
DEFAULT_INTERPOLATION_CONFIG,
implicitTags,
implicitAttrs,
);
expect(output.errors).toEqual([]);
return serializeHtmlNodes(output.rootNodes).join('');
} | {
"end_byte": 24878,
"start_byte": 17705,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/extractor_merger_spec.ts"
} |
angular/packages/compiler/test/i18n/extractor_merger_spec.ts_24880_25905 | function extract(
html: string,
implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {},
): [string[], string, string, string][] {
const result = extractMessages(
parseHtml(html),
DEFAULT_INTERPOLATION_CONFIG,
implicitTags,
implicitAttrs,
/* preserveSignificantWhitespace */ true,
);
if (result.errors.length > 0) {
throw new Error(`unexpected errors: ${result.errors.join('\n')}`);
}
return result.messages.map((message) => [
serializeI18nNodes(message.nodes),
message.meaning,
message.description,
message.id,
]) as [string[], string, string, string][];
}
function extractErrors(
html: string,
implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {},
): any[] {
const errors = extractMessages(
parseHtml(html),
DEFAULT_INTERPOLATION_CONFIG,
implicitTags,
implicitAttrs,
/* preserveSignificantWhitespace */ true,
).errors;
return errors.map((e): [string, string] => [e.msg, e.span.toString()]);
} | {
"end_byte": 25905,
"start_byte": 24880,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/extractor_merger_spec.ts"
} |
angular/packages/compiler/test/i18n/message_bundle_spec.ts_0_2036 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {serializeNodes} from '../../src/i18n/digest';
import * as i18n from '../../src/i18n/i18n_ast';
import {MessageBundle} from '../../src/i18n/message_bundle';
import {Serializer} from '../../src/i18n/serializers/serializer';
import {DEFAULT_INTERPOLATION_CONFIG} from '../../src/ml_parser/defaults';
import {HtmlParser} from '../../src/ml_parser/html_parser';
describe('MessageBundle', () => {
describe('Messages', () => {
let messages: MessageBundle;
beforeEach(() => {
messages = new MessageBundle(new HtmlParser(), [], {});
});
it('should extract the message to the catalog', () => {
messages.updateFromTemplate(
'<p i18n="m|d">Translate Me</p>',
'url',
DEFAULT_INTERPOLATION_CONFIG,
);
expect(humanizeMessages(messages)).toEqual(['Translate Me (m|d)']);
});
it('should extract and dedup messages', () => {
messages.updateFromTemplate(
'<p i18n="m|d@@1">Translate Me</p><p i18n="@@2">Translate Me</p><p i18n="@@2">Translate Me</p>',
'url',
DEFAULT_INTERPOLATION_CONFIG,
);
expect(humanizeMessages(messages)).toEqual(['Translate Me (m|d)', 'Translate Me (|)']);
});
});
});
class _TestSerializer extends Serializer {
override write(messages: i18n.Message[]): string {
return messages
.map((msg) => `${serializeNodes(msg.nodes)} (${msg.meaning}|${msg.description})`)
.join('//');
}
override load(
content: string,
url: string,
): {locale: string | null; i18nNodesByMsgId: {[id: string]: i18n.Node[]}} {
return {locale: null, i18nNodesByMsgId: {}};
}
override digest(msg: i18n.Message): string {
return msg.id || `default`;
}
}
function humanizeMessages(catalog: MessageBundle): string[] {
return catalog.write(new _TestSerializer()).split('//');
}
| {
"end_byte": 2036,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/message_bundle_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff2_spec.ts_0_2059 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {Xliff2} from '@angular/compiler/src/i18n/serializers/xliff2';
import {waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {
configureCompiler,
createComponent,
HTML,
serializeTranslations,
validateHtml,
} from './integration_common';
// TODO(alxhub): figure out if this test is still relevant.
xdescribe('i18n XLIFF integration spec', () => {
describe('(with LF line endings)', () => {
beforeEach(waitForAsync(() =>
configureCompiler(XLIFF2_TOMERGE + LF_LINE_ENDING_XLIFF2_TOMERGE, 'xlf2')));
it('should extract from templates', () => {
const serializer = new Xliff2();
const serializedXliff2 = serializeTranslations(HTML, serializer);
XLIFF2_EXTRACTED.forEach((x) => {
expect(serializedXliff2).toContain(x);
});
expect(serializedXliff2).toContain(LF_LINE_ENDING_XLIFF2_EXTRACTED);
});
it('should translate templates', () => {
const {tb, cmp, el} = createComponent(HTML);
validateHtml(tb, cmp, el);
});
});
describe('(with CRLF line endings', () => {
beforeEach(waitForAsync(() =>
configureCompiler(XLIFF2_TOMERGE + CRLF_LINE_ENDING_XLIFF2_TOMERGE, 'xlf2')));
it('should extract from templates (with CRLF line endings)', () => {
const serializer = new Xliff2();
const serializedXliff = serializeTranslations(HTML.replace(/\n/g, '\r\n'), serializer);
XLIFF2_EXTRACTED.forEach((x) => {
expect(serializedXliff).toContain(x);
});
expect(serializedXliff).toContain(CRLF_LINE_ENDING_XLIFF2_EXTRACTED);
});
it('should translate templates (with CRLF line endings)', () => {
const {tb, cmp, el} = createComponent(HTML.replace(/\n/g, '\r\n'));
validateHtml(tb, cmp, el);
});
});
});
const XLIFF2_TOMERGE = ` | {
"end_byte": 2059,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff2_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff2_spec.ts_0_6476 |
<unit id="615790887472569365">
<segment>
<source>i18n attribute on tags</source>
<target>attributs i18n sur les balises</target>
</segment>
</unit>
<unit id="3707494640264351337">
<segment>
<source>nested</source>
<target>imbriqué</target>
</segment>
</unit>
<unit id="5539162898278769904">
<segment>
<source>nested</source>
<target>imbriqué</target>
</segment>
</unit>
<unit id="3780349238193953556">
<segment>
<source><pc id="0" equivStart="START_ITALIC_TEXT" equivEnd="CLOSE_ITALIC_TEXT" type="fmt" dispStart="<i>" dispEnd="</i>">with placeholders</pc></source>
<target><pc id="0" equivStart="START_ITALIC_TEXT" equivEnd="CLOSE_ITALIC_TEXT" type="fmt" dispStart="<i>" dispEnd="</i>">avec des espaces réservés</pc></target>
</segment>
</unit>
<unit id="5415448997399451992">
<notes>
<note category="location">file.ts:11</note>
</notes>
<segment>
<source><pc id="0" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>">with <pc id="1" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>">nested</pc> placeholders</pc></source>
<target><pc id="0" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>">avec <pc id="1" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>">espaces réservés</pc> imbriqués</pc></target>
</segment>
</unit>
<unit id="5525133077318024839">
<segment>
<source>on not translatable node</source>
<target>sur des balises non traductibles</target>
</segment>
</unit>
<unit id="2174788525135228764">
<segment>
<source><b>bold</b></source>
<target><b>gras</b></target>
</segment>
</unit>
<unit id="8670732454866344690">
<segment>
<source>on translatable node</source>
<target>sur des balises traductibles</target>
</segment>
</unit>
<unit id="4593805537723189714">
<segment>
<source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">many</pc>} }</source>
<target>{VAR_PLURAL, plural, =0 {zero} =1 {un} =2 {deux} other {<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">beaucoup</pc>} }</target>
</segment>
</unit>
<unit id="703464324060964421">
<segment>
<source>
<ph id="0" equiv="ICU" disp="{sex, select, other {...} male {...} female {...}}"/>
</source>
<target><ph id="0" equiv="ICU" disp="{sex, select, other {...} male {...} female {...}}"/></target>
</segment>
</unit>
<unit id="5430374139308914421">
<notes>
<note category="location">file.ts:23</note>
</notes>
<segment>
<source>{VAR_SELECT, select, other {other} male {m} female {female} }</source>
<target>{VAR_SELECT, select, other {autre} male {homme} female {femme} }</target>
</segment>
</unit>
<unit id="1300564767229037107">
<notes>
<note category="location">file.ts:25,27</note>
</notes>
<segment>
<source>
<ph id="0" equiv="ICU" disp="{sexB, select, male {...} female {...}}"/>
</source>
<target><ph id="0" equiv="ICU" disp="{sexB, select, male {...} female {...}}"/></target>
</segment>
</unit>
<unit id="2500580913783245106">
<segment>
<source>{VAR_SELECT, select, male {m} female {f} }</source>
<target>{VAR_SELECT, select, male {homme} female {femme} }</target>
</segment>
</unit>
<unit id="4851788426695310455">
<segment>
<source><ph id="0" equiv="INTERPOLATION" disp="{{ "count = " + count }}"/></source>
<target><ph id="0" equiv="INTERPOLATION" disp="{{ "count = " + count }}"/></target>
</segment>
</unit>
<unit id="9013357158046221374">
<segment>
<source>sex = <ph id="0" equiv="INTERPOLATION" disp="{{ sex }}"/></source>
<target>sexe = <ph id="0" equiv="INTERPOLATION" disp="{{ sex }}"/></target>
</segment>
</unit>
<unit id="8324617391167353662">
<segment>
<source><ph id="0" equiv="CUSTOM_NAME" disp="{{ "custom name" //i18n(ph="CUSTOM_NAME") }}"/></source>
<target><ph id="0" equiv="CUSTOM_NAME" disp="{{ "custom name" //i18n(ph="CUSTOM_NAME") }}"/></target>
</segment>
</unit>
<unit id="7685649297917455806">
<segment>
<source>in a translatable section</source>
<target>dans une section traductible</target>
</segment>
</unit>
<unit id="2329001734457059408">
<segment>
<source>
<pc id="0" equivStart="START_HEADING_LEVEL1" equivEnd="CLOSE_HEADING_LEVEL1" type="other" dispStart="<h1>" dispEnd="</h1>">Markers in html comments</pc>
<pc id="1" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"></pc>
<pc id="2" equivStart="START_TAG_DIV_1" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"><ph id="3" equiv="ICU" disp="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/></pc>
</source>
<target>
<pc id="0" equivStart="START_HEADING_LEVEL1" equivEnd="CLOSE_HEADING_LEVEL1" type="other" dispStart="<h1>" dispEnd="</h1>">Balises dans les commentaires html</pc>
<pc id="1" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"></pc>
<pc id="2" equivStart="START_TAG_DIV_1" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"><ph id="3" equiv="ICU" disp="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/></pc>
</target>
</segment>
</unit>
<unit id="1491627405349178954">
<segment>
<source>it <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">should</pc> work</source> | {
"end_byte": 6476,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff2_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff2_spec.ts_6477_11094 | source>
<target>sexe = <ph id="0" equiv="INTERPOLATION" disp="{{ sex }}"/></target>
</segment>
</unit>
<unit id="8324617391167353662">
<segment>
<source><ph id="0" equiv="CUSTOM_NAME" disp="{{ "custom name" //i18n(ph="CUSTOM_NAME") }}"/></source>
<target><ph id="0" equiv="CUSTOM_NAME" disp="{{ "custom name" //i18n(ph="CUSTOM_NAME") }}"/></target>
</segment>
</unit>
<unit id="7685649297917455806">
<segment>
<source>in a translatable section</source>
<target>dans une section traductible</target>
</segment>
</unit>
<unit id="2329001734457059408">
<segment>
<source>
<pc id="0" equivStart="START_HEADING_LEVEL1" equivEnd="CLOSE_HEADING_LEVEL1" type="other" dispStart="<h1>" dispEnd="</h1>">Markers in html comments</pc>
<pc id="1" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"></pc>
<pc id="2" equivStart="START_TAG_DIV_1" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"><ph id="3" equiv="ICU" disp="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/></pc>
</source>
<target>
<pc id="0" equivStart="START_HEADING_LEVEL1" equivEnd="CLOSE_HEADING_LEVEL1" type="other" dispStart="<h1>" dispEnd="</h1>">Balises dans les commentaires html</pc>
<pc id="1" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"></pc>
<pc id="2" equivStart="START_TAG_DIV_1" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"><ph id="3" equiv="ICU" disp="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/></pc>
</target>
</segment>
</unit>
<unit id="1491627405349178954">
<segment>
<source>it <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">should</pc> work</source>
<target>ca <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">devrait</pc> marcher</target>
</segment>
</unit>
<unit id="i18n16">
<segment>
<source>with an explicit ID</source>
<target>avec un ID explicite</target>
</segment>
</unit>
<unit id="i18n17">
<segment>
<source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">many</pc>} }</source>
<target>{VAR_PLURAL, plural, =0 {zero} =1 {un} =2 {deux} other {<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">beaucoup</pc>} }</target>
</segment>
</unit>
<unit id="4035252431381981115">
<segment>
<source>foo<pc id="0" equivStart="START_LINK" equivEnd="CLOSE_LINK" type="link" dispStart="<a>" dispEnd="</a>">bar</pc></source>
<target>FOO<pc id="0" equivStart="START_LINK" equivEnd="CLOSE_LINK" type="link" dispStart="<a>" dispEnd="</a>">BAR</pc></target>
</segment>
</unit>
<unit id="5339604010413301604">
<segment>
<source><ph id="0" equiv="MAP NAME" disp="{{ 'test' //i18n(ph="map name") }}"/></source>
<target><ph id="0" equiv="MAP NAME" disp="{{ 'test' //i18n(ph="map name") }}"/></target>
</segment>
</unit>`;
const LF_LINE_ENDING_XLIFF2_TOMERGE = ` <unit id="4085484936881858615">
<segment>
<source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <ph id="0" equiv="INTERPOLATION" disp="{{response.getItemsList().length}}"/> results} }</source>
<target>{VAR_PLURAL, plural, =0 {Pas de réponse} =1 {Une réponse} other {<ph id="0" equiv="INTERPOLATION" disp="{{response.getItemsList().length}}"/> réponses} }</target>
</segment>
</unit>
`;
const CRLF_LINE_ENDING_XLIFF2_TOMERGE = ` <unit id="4085484936881858615">
<segment>
<source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <ph id="0" equiv="INTERPOLATION" disp="{{response.getItemsList().length}}"/> results} }</source>
<target>{VAR_PLURAL, plural, =0 {Pas de réponse} =1 {Une réponse} other {<ph id="0" equiv="INTERPOLATION" disp="{{response.getItemsList().length}}"/> réponses} }</target>
</segment>
</unit>
`;
const XLIFF | {
"end_byte": 11094,
"start_byte": 6477,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff2_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff2_spec.ts_11096_17497 | EXTRACTED = [
` <unit id="615790887472569365">
<notes>
<note category="location">file.ts:3</note>
</notes>
<segment>
<source>i18n attribute on tags</source>
</segment>
</unit>`,
` <unit id="3707494640264351337">
<notes>
<note category="location">file.ts:5</note>
</notes>
<segment>
<source>nested</source>
</segment>
</unit>`,
` <unit id="5539162898278769904">
<notes>
<note category="meaning">different meaning</note>
<note category="location">file.ts:7</note>
</notes>
<segment>
<source>nested</source>
</segment>
</unit>`,
` <unit id="3780349238193953556">
<notes>
<note category="location">file.ts:9</note>
<note category="location">file.ts:10</note>
</notes>
<segment>
<source><pc id="0" equivStart="START_ITALIC_TEXT" equivEnd="CLOSE_ITALIC_TEXT" type="fmt" dispStart="<i>" dispEnd="</i>">with placeholders</pc></source>
</segment>
</unit>`,
` <unit id="5415448997399451992">
<notes>
<note category="location">file.ts:11</note>
</notes>
<segment>
<source><pc id="0" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>">with <pc id="1" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>">nested</pc> placeholders</pc></source>
</segment>
</unit>`,
` <unit id="5525133077318024839">
<notes>
<note category="location">file.ts:14</note>
</notes>
<segment>
<source>on not translatable node</source>
</segment>
</unit>`,
` <unit id="2174788525135228764">
<notes>
<note category="location">file.ts:14</note>
</notes>
<segment>
<source><b>bold</b></source>
</segment>
</unit>`,
` <unit id="8670732454866344690">
<notes>
<note category="location">file.ts:15</note>
</notes>
<segment>
<source>on translatable node</source>
</segment>
</unit>`,
` <unit id="4593805537723189714">
<notes>
<note category="location">file.ts:20</note>
<note category="location">file.ts:37</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">many</pc>} }</source>
</segment>
</unit>`,
` <unit id="703464324060964421">
<notes>
<note category="location">file.ts:22,24</note>
</notes>
<segment>
<source>
<ph id="0" equiv="ICU" disp="{sex, select, male {...} female {...} other {...}}"/>
</source>
</segment>
</unit>`,
` <unit id="5430374139308914421">
<notes>
<note category="location">file.ts:23</note>
</notes>
<segment>
<source>{VAR_SELECT, select, male {m} female {f} other {other} }</source>
</segment>
</unit>`,
` <unit id="1300564767229037107">
<notes>
<note category="location">file.ts:25,27</note>
</notes>
<segment>
<source>
<ph id="0" equiv="ICU" disp="{sexB, select, male {...} female {...}}"/>
</source>
</segment>
</unit>`,
` <unit id="2500580913783245106">
<notes>
<note category="location">file.ts:26</note>
</notes>
<segment>
<source>{VAR_SELECT, select, male {m} female {f} }</source>
</segment>
</unit>`,
` <unit id="4851788426695310455">
<notes>
<note category="location">file.ts:29</note>
</notes>
<segment>
<source><ph id="0" equiv="INTERPOLATION" disp="{{ "count = " + count }}"/></source>
</segment>
</unit>`,
` <unit id="9013357158046221374">
<notes>
<note category="location">file.ts:30</note>
</notes>
<segment>
<source>sex = <ph id="0" equiv="INTERPOLATION" disp="{{ sex }}"/></source>
</segment>
</unit>`,
` <unit id="8324617391167353662">
<notes>
<note category="location">file.ts:31</note>
</notes>
<segment>
<source><ph id="0" equiv="CUSTOM_NAME" disp="{{ "custom name" //i18n(ph="CUSTOM_NAME") }}"/></source>
</segment>
</unit>`,
` <unit id="7685649297917455806">
<notes>
<note category="location">file.ts:36</note>
<note category="location">file.ts:54</note>
</notes>
<segment>
<source>in a translatable section</source>
</segment>
</unit>`,
` <unit id="2329001734457059408">
<notes>
<note category="location">file.ts:34,38</note>
</notes>
<segment>
<source>
<pc id="0" equivStart="START_HEADING_LEVEL1" equivEnd="CLOSE_HEADING_LEVEL1" type="other" dispStart="<h1>" dispEnd="</h1>">Markers in html comments</pc>
<pc id="1" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"></pc>
<pc id="2" equivStart="START_TAG_DIV_1" equivEnd="CLOSE_TAG_DIV" type="other" dispStart="<div>" dispEnd="</div>"><ph id="3" equiv="ICU" disp="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/></pc>
</source>
</segment>
</unit>`,
` <unit id="1491627405349178954">
<notes>
<note category="location">file.ts:40</note>
</notes>
<segment>
<source>it <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">should</pc> work</source>
</segment>
</unit>`,
` <unit id="i18n16">
<notes>
<note category="location">file.ts:42</note>
</notes>
<segment>
<source>with an explicit ID</source>
</segment>
</unit>`,
` <unit id="i18n17">
<notes>
<note category="location">file.ts:43</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">many</pc>} }</source>
</segment>
</unit>`,
` <unit | {
"end_byte": 17497,
"start_byte": 11096,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff2_spec.ts"
} |
angular/packages/compiler/test/i18n/integration_xliff2_spec.ts_17500_19000 | ="4035252431381981115">
<notes>
<note category="location">file.ts:54</note>
</notes>
<segment>
<source>foo<pc id="0" equivStart="START_LINK" equivEnd="CLOSE_LINK" type="link" dispStart="<a>" dispEnd="</a>">bar</pc></source>
</segment>
</unit>`,
` <unit id="5339604010413301604">
<notes>
<note category="location">file.ts:56</note>
</notes>
<segment>
<source><ph id="0" equiv="MAP NAME" disp="{{ 'test' //i18n(ph="map name") }}"/></source>
</segment>
</unit>`,
];
const LF_LINE_ENDING_XLIFF2_EXTRACTED = ` <unit id="4085484936881858615">
<notes>
<note category="description">desc</note>
<note category="location">file.ts:46,52</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <ph id="0" equiv="INTERPOLATION" disp="{{response.getItemsList().length}}"/> results} }</source>
</segment>
</unit>`;
const CRLF_LINE_ENDING_XLIFF2_EXTRACTED = ` <unit id="4085484936881858615">
<notes>
<note category="description">desc</note>
<note category="location">file.ts:46,52</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <ph id="0" equiv="INTERPOLATION" disp="{{response.getItemsList().length}}"/> results} }</source>
</segment>
</unit>`;
| {
"end_byte": 19000,
"start_byte": 17500,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/integration_xliff2_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/i18n_ast_spec.ts_0_2236 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as i18n from '@angular/compiler/src/i18n/i18n_ast';
import {serializeNodes} from '../../../src/i18n/digest';
import {_extractMessages} from '../i18n_parser_spec';
describe('i18n AST', () => {
describe('CloneVisitor', () => {
it('should clone an AST', () => {
const messages = _extractMessages(
'<div i18n="m|d">b{count, plural, =0 {{sex, select, male {m}}}}a</div>',
);
const nodes = messages[0].nodes;
const text = serializeNodes(nodes).join('');
expect(text).toEqual(
'b<ph icu name="ICU">{count, plural, =0 {[{sex, select, male {[m]}}]}}</ph>a',
);
const visitor = new i18n.CloneVisitor();
const cloneNodes = nodes.map((n) => n.visit(visitor));
expect(serializeNodes(nodes)).toEqual(serializeNodes(cloneNodes));
nodes.forEach((n: i18n.Node, i: number) => {
expect(n).toEqual(cloneNodes[i]);
expect(n).not.toBe(cloneNodes[i]);
});
});
});
describe('RecurseVisitor', () => {
it('should visit all nodes', () => {
const visitor = new RecurseVisitor();
const container = new i18n.Container(
[
new i18n.Text('', null!),
new i18n.Placeholder('', '', null!),
new i18n.IcuPlaceholder(null!, '', null!),
],
null!,
);
const tag = new i18n.TagPlaceholder('', {}, '', '', [container], false, null!, null, null);
const icu = new i18n.Icu('', '', {tag}, null!);
icu.visit(visitor);
expect(visitor.textCount).toEqual(1);
expect(visitor.phCount).toEqual(1);
expect(visitor.icuPhCount).toEqual(1);
});
});
});
class RecurseVisitor extends i18n.RecurseVisitor {
textCount = 0;
phCount = 0;
icuPhCount = 0;
override visitText(text: i18n.Text, context?: any): any {
this.textCount++;
}
override visitPlaceholder(ph: i18n.Placeholder, context?: any): any {
this.phCount++;
}
override visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): any {
this.icuPhCount++;
}
}
| {
"end_byte": 2236,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/i18n_ast_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xml_helper_spec.ts_0_1511 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as xml from '../../../src/i18n/serializers/xml_helper';
describe('XML helper', () => {
it('should serialize XML declaration', () => {
expect(xml.serialize([new xml.Declaration({version: '1.0'})])).toEqual(
'<?xml version="1.0" ?>',
);
});
it('should serialize text node', () => {
expect(xml.serialize([new xml.Text('foo bar')])).toEqual('foo bar');
});
it('should escape text nodes', () => {
expect(xml.serialize([new xml.Text('<>')])).toEqual('<>');
});
it('should serialize xml nodes without children', () => {
expect(xml.serialize([new xml.Tag('el', {foo: 'bar'}, [])])).toEqual('<el foo="bar"/>');
});
it('should serialize xml nodes with children', () => {
expect(
xml.serialize([
new xml.Tag('parent', {}, [new xml.Tag('child', {}, [new xml.Text('content')])]),
]),
).toEqual('<parent><child>content</child></parent>');
});
it('should serialize node lists', () => {
expect(
xml.serialize([new xml.Tag('el', {order: '0'}, []), new xml.Tag('el', {order: '1'}, [])]),
).toEqual('<el order="0"/><el order="1"/>');
});
it('should escape attribute values', () => {
expect(xml.serialize([new xml.Tag('el', {foo: '<">'}, [])])).toEqual(
'<el foo="<">"/>',
);
});
});
| {
"end_byte": 1511,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xml_helper_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff_spec.ts_0_1234 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {escapeRegExp} from '@angular/compiler/src/util';
import {serializeNodes} from '../../../src/i18n/digest';
import {MessageBundle} from '../../../src/i18n/message_bundle';
import {Xliff} from '../../../src/i18n/serializers/xliff';
import {DEFAULT_INTERPOLATION_CONFIG} from '../../../src/ml_parser/defaults';
import {HtmlParser} from '../../../src/ml_parser/html_parser';
const HTML = `
<p i18n-title title="translatable attribute">not translatable</p>
<p i18n>translatable element <b>with placeholders</b> {{ interpolation}}</p>
<!-- i18n -->{ count, plural, =0 {<p>test</p>}}<!-- /i18n -->
<p i18n="m|d">foo</p>
<p i18n="m|d">foo</p>
<p i18n="m|d@@i">foo</p>
<p i18n="@@bar">foo</p>
<p i18n="ph names"><br><img><div></div></p>
<p i18n="@@baz">{ count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} }}</p>
<p i18n>Test: { count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} } =other {a lot}}</p>
<p i18n>multi
lines</p>
<p i18n>translatable element @if (foo) {with} @else if (bar) {blocks}</p>
`; | {
"end_byte": 1234,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff_spec.ts_1236_7032 | const WRITE_XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="983775b9a51ce14b036be72d4cfd65d68d64e231" datatype="html">
<source>translatable attribute</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">2</context>
</context-group>
</trans-unit>
<trans-unit id="ec1d033f2436133c14ab038286c4f5df4697484a" datatype="html">
<source>translatable element <x id="START_BOLD_TEXT" ctype="x-b" equiv-text="<b>"/>with placeholders<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="</b>"/> <x id="INTERPOLATION" equiv-text="{{ interpolation}}"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">3</context>
</context-group>
</trans-unit>
<trans-unit id="e2ccf3d131b15f54aa1fcf1314b1ca77c14bfcc2" datatype="html">
<source>{VAR_PLURAL, plural, =0 {<x id="START_PARAGRAPH" ctype="x-p" equiv-text="<p>"/>test<x id="CLOSE_PARAGRAPH" ctype="x-p" equiv-text="</p>"/>} }</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">4</context>
</context-group>
</trans-unit>
<trans-unit id="db3e0a6a5a96481f60aec61d98c3eecddef5ac23" datatype="html">
<source>foo</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">5</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">6</context>
</context-group>
<note priority="1" from="description">d</note>
<note priority="1" from="meaning">m</note>
</trans-unit>
<trans-unit id="i" datatype="html">
<source>foo</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">7</context>
</context-group>
<note priority="1" from="description">d</note>
<note priority="1" from="meaning">m</note>
</trans-unit>
<trans-unit id="bar" datatype="html">
<source>foo</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">8</context>
</context-group>
</trans-unit>
<trans-unit id="d7fa2d59aaedcaa5309f13028c59af8c85b8c49d" datatype="html">
<source><x id="LINE_BREAK" ctype="lb" equiv-text="<br/>"/><x id="TAG_IMG" ctype="image" equiv-text="<img/>"/><x id="START_TAG_DIV" ctype="x-div" equiv-text="<div>"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="</div>"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">9</context>
</context-group>
<note priority="1" from="description">ph names</note>
</trans-unit>
<trans-unit id="baz" datatype="html">
<source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p" equiv-text="<p>"/>deeply nested<x id="CLOSE_PARAGRAPH" ctype="x-p" equiv-text="</p>"/>} } } }</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">10</context>
</context-group>
</trans-unit>
<trans-unit id="52ffa620dcd76247a56d5331f34e73f340a43cdb" datatype="html">
<source>Test: <x id="ICU" equiv-text="{ count, plural, =0 {...} =other {...}}"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">11</context>
</context-group>
</trans-unit>
<trans-unit id="1503afd0ccc20ff01d5e2266a9157b7b342ba494" datatype="html">
<source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p" equiv-text="<p>"/>deeply nested<x id="CLOSE_PARAGRAPH" ctype="x-p" equiv-text="</p>"/>} } } =other {a lot} }</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">11</context>
</context-group>
</trans-unit>
<trans-unit id="fcfa109b0e152d4c217dbc02530be0bcb8123ad1" datatype="html">
<source>multi
lines</source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">12</context>
</context-group>
</trans-unit>
<trans-unit id="3e17847a6823c7777ca57c7338167badca0f4d19" datatype="html">
<source>translatable element <x id="START_BLOCK_IF" ctype="x-if" equiv-text="@if"/>with<x id="CLOSE_BLOCK_IF" ctype="x-if" equiv-text="}"/> <x id="START_BLOCK_ELSE_IF" ctype="x-else-if" equiv-text="@else if"/>blocks<x id="CLOSE_BLOCK_ELSE_IF" ctype="x-else-if" equiv-text="}"/></source>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">14</context>
</context-group>
</trans-unit>
</body>
</file>
</xliff>
`;
const LOAD_XLIFF = ` | {
"end_byte": 7032,
"start_byte": 1236,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff_spec.ts_0_6963 | <?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" target-language="fr" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="983775b9a51ce14b036be72d4cfd65d68d64e231" datatype="html">
<source>translatable attribute</source>
<target>etubirtta elbatalsnart</target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">1</context>
</context-group>
</trans-unit>
<trans-unit id="ec1d033f2436133c14ab038286c4f5df4697484a" datatype="html">
<source>translatable element <x id="START_BOLD_TEXT" ctype="b"/>with placeholders<x id="CLOSE_BOLD_TEXT" ctype="b"/> <x id="INTERPOLATION"/></source>
<target><x id="INTERPOLATION"/> footnemele elbatalsnart <x id="START_BOLD_TEXT" ctype="x-b"/>sredlohecalp htiw<x id="CLOSE_BOLD_TEXT" ctype="x-b"/></target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">2</context>
</context-group>
</trans-unit>
<trans-unit id="e2ccf3d131b15f54aa1fcf1314b1ca77c14bfcc2" datatype="html">
<source>{VAR_PLURAL, plural, =0 {<x id="START_PARAGRAPH" ctype="x-p"/>test<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} }</source>
<target>{VAR_PLURAL, plural, =0 {<x id="START_PARAGRAPH" ctype="x-p"/>TEST<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} }</target>
</trans-unit>
<trans-unit id="db3e0a6a5a96481f60aec61d98c3eecddef5ac23" datatype="html">
<source>foo</source>
<target>oof</target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">3</context>
</context-group>
<note priority="1" from="description">d</note>
<note priority="1" from="meaning">m</note>
</trans-unit>
<trans-unit id="i" datatype="html">
<source>foo</source>
<target>toto</target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">4</context>
</context-group>
<note priority="1" from="description">d</note>
<note priority="1" from="meaning">m</note>
</trans-unit>
<trans-unit id="bar" datatype="html">
<source>foo</source>
<target>tata</target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">5</context>
</context-group>
</trans-unit>
<trans-unit id="d7fa2d59aaedcaa5309f13028c59af8c85b8c49d" datatype="html">
<source><x id="LINE_BREAK" ctype="lb"/><x id="TAG_IMG" ctype="image"/><x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/></source>
<target><x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/><x id="TAG_IMG" ctype="image"/><x id="LINE_BREAK" ctype="lb"/></target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">6</context>
</context-group>
<note priority="1" from="description">ph names</note>
</trans-unit>
<trans-unit id="empty target" datatype="html">
<source><x id="LINE_BREAK" ctype="lb"/><x id="TAG_IMG" ctype="image"/><x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/></source>
<target/>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">6</context>
</context-group>
<note priority="1" from="description">ph names</note>
</trans-unit>
<trans-unit id="baz" datatype="html">
<source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>deeply nested<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } }</source>
<target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>profondément imbriqué<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } }</target>
</trans-unit>
<trans-unit id="52ffa620dcd76247a56d5331f34e73f340a43cdb" datatype="html">
<source>Test: <x id="ICU" equiv-text="{ count, plural, =0 {...} =other {...}}"/></source>
<target>Test: <x id="ICU" equiv-text="{ count, plural, =0 {...} =other {...}}"/></target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">11</context>
</context-group>
</trans-unit>
<trans-unit id="1503afd0ccc20ff01d5e2266a9157b7b342ba494" datatype="html">
<source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>deeply nested<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } =other {a lot} }</source>
<target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>profondément imbriqué<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } =other {beaucoup} }</target>
</trans-unit>
<trans-unit id="fcfa109b0e152d4c217dbc02530be0bcb8123ad1" datatype="html">
<source>multi
lines</source>
<target>multi
lignes</target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">12</context>
</context-group>
</trans-unit>
<trans-unit id="3e17847a6823c7777ca57c7338167badca0f4d19" datatype="html">
<source>translatable element <x id="START_BLOCK_IF" ctype="x-if" equiv-text="@if"/>with<x id="CLOSE_BLOCK_IF" ctype="x-if" equiv-text="}"/> <x id="START_BLOCK_ELSE_IF" ctype="x-else-if" equiv-text="@else if"/>blocks<x id="CLOSE_BLOCK_ELSE_IF" ctype="x-else-if" equiv-text="}"/></source>
<target>élément traduisible <x id="START_BLOCK_IF" ctype="x-if" equiv-text="@if"/>avec<x id="CLOSE_BLOCK_IF" ctype="x-if" equiv-text="}"/> <x id="START_BLOCK_ELSE_IF" ctype="x-else-if" equiv-text="@else if"/>des blocs<x id="CLOSE_BLOCK_ELSE_IF" ctype="x-else-if" equiv-text="}"/></target>
<context-group purpose="location">
<context context-type="sourcefile">file.ts</context>
<context context-type="linenumber">14</context>
</context-group>
</trans-unit>
<trans-unit id="mrk-test">
<source>First sentence.</source>
<seg-source>
<invalid-tag>Should not be parsed</invalid-tag>
</seg-source>
<target>Translated <mrk mtype="seg" mid="1">first sentence</mrk>.</target>
</trans-unit>
<trans-unit id="mrk-test2">
<source>First sentence. Second sentence.</source>
<seg-source> | {
"end_byte": 6963,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff_spec.ts_6964_7215 | /trans-unit>
</body>
</file>
</xliff>
`;
const LOAD_XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" target-language="fr" datatype="plaintext" orig | {
"end_byte": 7215,
"start_byte": 6964,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff_spec.ts_14247_15210 | scribe('XLIFF serializer', () => {
const serializer = new Xliff();
function toXliff(html: string, locale: string | null = null): string {
const catalog = new MessageBundle(new HtmlParser(), [], {}, locale);
catalog.updateFromTemplate(html, 'file.ts', DEFAULT_INTERPOLATION_CONFIG);
return catalog.write(serializer);
}
function loadAsMap(xliff: string): {[id: string]: string} {
const {i18nNodesByMsgId} = serializer.load(xliff, 'url');
const msgMap: {[id: string]: string} = {};
Object.keys(i18nNodesByMsgId).forEach(
(id) => (msgMap[id] = serializeNodes(i18nNodesByMsgId[id]).join('')),
);
return msgMap;
}
describe('write', () => {
it('should write a valid xliff file', () => {
expect(toXliff(HTML)).toEqual(WRITE_XLIFF);
});
it('should write a valid xliff file with a source language', () => {
expect(toXliff(HTML, 'fr')).toContain('file source-language="fr"');
});
});
de | {
"end_byte": 15210,
"start_byte": 14247,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff_spec.ts_15214_21358 | be('load', () => {
it('should load XLIFF files', () => {
expect(loadAsMap(LOAD_XLIFF)).toEqual({
'983775b9a51ce14b036be72d4cfd65d68d64e231': 'etubirtta elbatalsnart',
'ec1d033f2436133c14ab038286c4f5df4697484a':
'<ph name="INTERPOLATION"/> footnemele elbatalsnart <ph name="START_BOLD_TEXT"/>sredlohecalp htiw<ph name="CLOSE_BOLD_TEXT"/>',
'e2ccf3d131b15f54aa1fcf1314b1ca77c14bfcc2':
'{VAR_PLURAL, plural, =0 {[<ph name="START_PARAGRAPH"/>, TEST, <ph name="CLOSE_PARAGRAPH"/>]}}',
'db3e0a6a5a96481f60aec61d98c3eecddef5ac23': 'oof',
'i': 'toto',
'bar': 'tata',
'd7fa2d59aaedcaa5309f13028c59af8c85b8c49d':
'<ph name="START_TAG_DIV"/><ph name="CLOSE_TAG_DIV"/><ph name="TAG_IMG"/><ph name="LINE_BREAK"/>',
'empty target': '',
'baz':
'{VAR_PLURAL, plural, =0 {[{VAR_SELECT, select, other {[<ph name="START_PARAGRAPH"/>, profondément imbriqué, <ph name="CLOSE_PARAGRAPH"/>]}}, ]}}',
'52ffa620dcd76247a56d5331f34e73f340a43cdb': 'Test: <ph name="ICU"/>',
'1503afd0ccc20ff01d5e2266a9157b7b342ba494':
'{VAR_PLURAL, plural, =0 {[{VAR_SELECT, select, other {[<ph' +
' name="START_PARAGRAPH"/>, profondément imbriqué, <ph name="CLOSE_PARAGRAPH"/>]}}, ]}, =other {[beaucoup]}}',
'fcfa109b0e152d4c217dbc02530be0bcb8123ad1': `multi
lignes`,
'3e17847a6823c7777ca57c7338167badca0f4d19':
'élément traduisible <ph name="START_BLOCK_IF"/>avec<ph name="CLOSE_BLOCK_IF"/> <ph name="START_BLOCK_ELSE_IF"/>des blocs<ph name="CLOSE_BLOCK_ELSE_IF"/>',
'mrk-test': 'Translated first sentence.',
'mrk-test2': 'Translated first sentence.',
});
});
it('should return the target locale', () => {
expect(serializer.load(LOAD_XLIFF, 'url').locale).toEqual('fr');
});
it('should ignore alt-trans targets', () => {
const XLIFF = `
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" target-language="fr" datatype="plaintext" original="ng2.template">
<body>
<trans-unit datatype="html" approved="no" id="registration.submit">
<source>Continue</source>
<target state="translated" xml:lang="de">Weiter</target>
<context-group purpose="location">
<context context-type="sourcefile">src/app/auth/registration-form/registration-form.component.html</context>
<context context-type="linenumber">69</context>
</context-group>
<?sid 1110954287-0?>
<alt-trans origin="autoFuzzy" tool="Swordfish" match-quality="71" ts="63">
<source xml:lang="en">Content</source>
<target state="translated" xml:lang="de">Content</target>
</alt-trans>
</trans-unit>
</body>
</file>
</xliff>`;
expect(loadAsMap(XLIFF)).toEqual({'registration.submit': 'Weiter'});
});
describe('structure errors', () => {
it('should throw when a trans-unit has no translation', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="missingtarget">
<source/>
</trans-unit>
</body>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(/Message missingtarget misses a translation/);
});
it('should throw when a trans-unit has no id attribute', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="ng2.template">
<body>
<trans-unit datatype="html">
<source/>
<target/>
</trans-unit>
</body>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(/<trans-unit> misses the "id" attribute/);
});
it('should throw on duplicate trans-unit id', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="deadbeef">
<source/>
<target/>
</trans-unit>
<trans-unit id="deadbeef">
<source/>
<target/>
</trans-unit>
</body>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(/Duplicated translations for msg deadbeef/);
});
});
describe('message errors', () => {
it('should throw on unknown message tags', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="deadbeef" datatype="html">
<source/>
<target><b>msg should contain only ph tags</b></target>
</trans-unit>
</body>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(
new RegExp(escapeRegExp(`[ERROR ->]<b>msg should contain only ph tags</b>`)),
);
});
it('should throw when a placeholder misses an id attribute', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="deadbeef" datatype="html">
<source/>
<target><x/></target>
</trans-unit>
</body>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(new RegExp(escapeRegExp(`<x> misses the "id" attribute`)));
});
});
});
});
| {
"end_byte": 21358,
"start_byte": 15214,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xmb_spec.ts_0_4263 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {MessageBundle} from '@angular/compiler/src/i18n/message_bundle';
import {Xmb} from '@angular/compiler/src/i18n/serializers/xmb';
import {DEFAULT_INTERPOLATION_CONFIG} from '@angular/compiler/src/ml_parser/defaults';
import {HtmlParser} from '@angular/compiler/src/ml_parser/html_parser';
describe('XMB serializer', () => {
const HTML = `
<p>not translatable</p>
<p i18n>translatable element <b>with placeholders</b> {{ interpolation}}</p>
<!-- i18n -->{ count, plural, =0 {<p>test</p>}}<!-- /i18n -->
<p i18n="m|d">foo</p>
<p i18n="m|d@@i">foo</p>
<p i18n="@@bar">foo</p>
<p i18n="@@baz">{ count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} }}</p>
<p i18n>Test: { count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} } =other {a lot}}</p>
<p i18n>multi
lines</p>
<p i18n>translatable element @if (foo) {with} @else if (bar) {blocks}</p>`;
const XMB = `<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE messagebundle [
<!ELEMENT messagebundle (msg)*>
<!ATTLIST messagebundle class CDATA #IMPLIED>
<!ELEMENT msg (#PCDATA|ph|source)*>
<!ATTLIST msg id CDATA #IMPLIED>
<!ATTLIST msg seq CDATA #IMPLIED>
<!ATTLIST msg name CDATA #IMPLIED>
<!ATTLIST msg desc CDATA #IMPLIED>
<!ATTLIST msg meaning CDATA #IMPLIED>
<!ATTLIST msg obsolete (obsolete) #IMPLIED>
<!ATTLIST msg xml:space (default|preserve) "default">
<!ATTLIST msg is_hidden CDATA #IMPLIED>
<!ELEMENT source (#PCDATA)>
<!ELEMENT ph (#PCDATA|ex)*>
<!ATTLIST ph name CDATA #REQUIRED>
<!ELEMENT ex (#PCDATA)>
]>
<messagebundle handler="angular">
<msg id="7056919470098446707"><source>file.ts:3</source>translatable element <ph name="START_BOLD_TEXT"><ex><b></ex><b></ph>with placeholders<ph name="CLOSE_BOLD_TEXT"><ex></b></ex></b></ph> <ph name="INTERPOLATION"><ex>{{ interpolation}}</ex>{{ interpolation}}</ph></msg>
<msg id="2981514368455622387"><source>file.ts:4</source>{VAR_PLURAL, plural, =0 {<ph name="START_PARAGRAPH"><ex><p></ex><p></ph>test<ph name="CLOSE_PARAGRAPH"><ex></p></ex></p></ph>} }</msg>
<msg id="7999024498831672133" desc="d" meaning="m"><source>file.ts:5</source>foo</msg>
<msg id="i" desc="d" meaning="m"><source>file.ts:6</source>foo</msg>
<msg id="bar"><source>file.ts:7</source>foo</msg>
<msg id="baz"><source>file.ts:8</source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<ph name="START_PARAGRAPH"><ex><p></ex><p></ph>deeply nested<ph name="CLOSE_PARAGRAPH"><ex></p></ex></p></ph>} } } }</msg>
<msg id="6997386649824869937"><source>file.ts:9</source>Test: <ph name="ICU"><ex>{ count, plural, =0 {...} =other {...}}</ex>{ count, plural, =0 {...} =other {...}}</ph></msg>
<msg id="5229984852258993423"><source>file.ts:9</source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<ph name="START_PARAGRAPH"><ex><p></ex><p></ph>deeply nested<ph name="CLOSE_PARAGRAPH"><ex></p></ex></p></ph>} } } =other {a lot} }</msg>
<msg id="2340165783990709777"><source>file.ts:10,11</source>multi
lines</msg>
<msg id="6618832065070552029"><source>file.ts:12</source>translatable element <ph name="START_BLOCK_IF"><ex>@if</ex>@if</ph>with<ph name="CLOSE_BLOCK_IF"><ex>}</ex>}</ph> <ph name="START_BLOCK_ELSE_IF"><ex>@else if</ex>@else if</ph>blocks<ph name="CLOSE_BLOCK_ELSE_IF"><ex>}</ex>}</ph></msg>
</messagebundle>
`;
it('should write a valid xmb file', () => {
expect(toXmb(HTML, 'file.ts')).toEqual(XMB);
// the locale is not specified in the xmb file
expect(toXmb(HTML, 'file.ts', 'fr')).toEqual(XMB);
});
it('should throw when trying to load an xmb file', () => {
expect(() => {
const serializer = new Xmb();
serializer.load(XMB, 'url');
}).toThrowError(/Unsupported/);
});
});
function toXmb(html: string, url: string, locale: string | null = null): string {
const catalog = new MessageBundle(new HtmlParser(), [], {}, locale);
const serializer = new Xmb();
catalog.updateFromTemplate(html, url, DEFAULT_INTERPOLATION_CONFIG);
return catalog.write(serializer);
}
| {
"end_byte": 4263,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xmb_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xtb_spec.ts_0_7217 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {escapeRegExp} from '@angular/compiler/src/util';
import {serializeNodes} from '../../../src/i18n/digest';
import * as i18n from '../../../src/i18n/i18n_ast';
import {Xtb} from '../../../src/i18n/serializers/xtb';
describe('XTB serializer', () => {
const serializer = new Xtb();
function loadAsMap(xtb: string): {[id: string]: string} {
const {i18nNodesByMsgId} = serializer.load(xtb, 'url');
const msgMap: {[id: string]: string} = {};
Object.keys(i18nNodesByMsgId).forEach((id) => {
msgMap[id] = serializeNodes(i18nNodesByMsgId[id]).join('');
});
return msgMap;
}
describe('load', () => {
it('should load XTB files with a doctype', () => {
const XTB = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE translationbundle [<!ELEMENT translationbundle (translation)*>
<!ATTLIST translationbundle lang CDATA #REQUIRED>
<!ELEMENT translation (#PCDATA|ph)*>
<!ATTLIST translation id CDATA #REQUIRED>
<!ELEMENT ph EMPTY>
<!ATTLIST ph name CDATA #REQUIRED>
]>
<translationbundle>
<translation id="8841459487341224498">rab</translation>
</translationbundle>`;
expect(loadAsMap(XTB)).toEqual({'8841459487341224498': 'rab'});
});
it('should load XTB files without placeholders', () => {
const XTB = `<?xml version="1.0" encoding="UTF-8"?>
<translationbundle>
<translation id="8841459487341224498">rab</translation>
</translationbundle>`;
expect(loadAsMap(XTB)).toEqual({'8841459487341224498': 'rab'});
});
it('should return the target locale', () => {
const XTB = `<?xml version="1.0" encoding="UTF-8"?>
<translationbundle lang='fr'>
<translation id="8841459487341224498">rab</translation>
</translationbundle>`;
expect(serializer.load(XTB, 'url').locale).toEqual('fr');
});
it('should load XTB files with placeholders', () => {
const XTB = `<?xml version="1.0" encoding="UTF-8"?>
<translationbundle>
<translation id="8877975308926375834"><ph name="START_PARAGRAPH"/>rab<ph name="CLOSE_PARAGRAPH"/></translation>
</translationbundle>`;
expect(loadAsMap(XTB)).toEqual({
'8877975308926375834': '<ph name="START_PARAGRAPH"/>rab<ph name="CLOSE_PARAGRAPH"/>',
});
});
it('should replace ICU placeholders with their translations', () => {
const XTB = `<?xml version="1.0" encoding="UTF-8" ?>
<translationbundle>
<translation id="7717087045075616176">*<ph name="ICU"/>*</translation>
<translation id="5115002811911870583">{VAR_PLURAL, plural, =1 {<ph name="START_PARAGRAPH"/>rab<ph name="CLOSE_PARAGRAPH"/>}}</translation>
</translationbundle>`;
expect(loadAsMap(XTB)).toEqual({
'7717087045075616176': `*<ph name="ICU"/>*`,
'5115002811911870583': `{VAR_PLURAL, plural, =1 {[<ph name="START_PARAGRAPH"/>, rab, <ph name="CLOSE_PARAGRAPH"/>]}}`,
});
});
it('should load complex XTB files', () => {
const XTB = `<?xml version="1.0" encoding="UTF-8" ?>
<translationbundle>
<translation id="8281795707202401639"><ph name="INTERPOLATION"/><ph name="START_BOLD_TEXT"/>rab<ph name="CLOSE_BOLD_TEXT"/> oof</translation>
<translation id="5115002811911870583">{VAR_PLURAL, plural, =1 {<ph name="START_PARAGRAPH"/>rab<ph name="CLOSE_PARAGRAPH"/>}}</translation>
<translation id="130772889486467622">oof</translation>
<translation id="4739316421648347533">{VAR_PLURAL, plural, =1 {{VAR_GENDER, gender, male {<ph name="START_PARAGRAPH"/>rab<ph name="CLOSE_PARAGRAPH"/>}} }}</translation>
</translationbundle>`;
expect(loadAsMap(XTB)).toEqual({
'8281795707202401639': `<ph name="INTERPOLATION"/><ph name="START_BOLD_TEXT"/>rab<ph name="CLOSE_BOLD_TEXT"/> oof`,
'5115002811911870583': `{VAR_PLURAL, plural, =1 {[<ph name="START_PARAGRAPH"/>, rab, <ph name="CLOSE_PARAGRAPH"/>]}}`,
'130772889486467622': `oof`,
'4739316421648347533': `{VAR_PLURAL, plural, =1 {[{VAR_GENDER, gender, male {[<ph name="START_PARAGRAPH"/>, rab, <ph name="CLOSE_PARAGRAPH"/>]}}, ]}}`,
});
});
});
describe('errors', () => {
it('should be able to parse non-angular xtb files without error', () => {
const XTB = `<?xml version="1.0" encoding="UTF-8" ?>
<translationbundle>
<translation id="angular">is great</translation>
<translation id="non angular">is <invalid>less</invalid> {count, plural, =0 {{GREAT}}}</translation>
</translationbundle>`;
// Invalid messages should not cause the parser to throw
let i18nNodesByMsgId: {[id: string]: i18n.Node[]} = undefined!;
expect(() => {
i18nNodesByMsgId = serializer.load(XTB, 'url').i18nNodesByMsgId;
}).not.toThrow();
expect(Object.keys(i18nNodesByMsgId).length).toEqual(2);
expect(serializeNodes(i18nNodesByMsgId['angular']).join('')).toEqual('is great');
// Messages that contain unsupported feature should throw on access
expect(() => {
const read = i18nNodesByMsgId['non angular'];
}).toThrowError(/xtb parse errors/);
});
it('should throw on nested <translationbundle>', () => {
const XTB = '<translationbundle><translationbundle></translationbundle></translationbundle>';
expect(() => {
loadAsMap(XTB);
}).toThrowError(/<translationbundle> elements can not be nested/);
});
it('should throw when a <translation> has no id attribute', () => {
const XTB = `<translationbundle>
<translation></translation>
</translationbundle>`;
expect(() => {
loadAsMap(XTB);
}).toThrowError(/<translation> misses the "id" attribute/);
});
it('should throw when a placeholder has no name attribute', () => {
const XTB = `<translationbundle>
<translation id="1186013544048295927"><ph /></translation>
</translationbundle>`;
expect(() => {
loadAsMap(XTB);
}).toThrowError(/<ph> misses the "name" attribute/);
});
it('should throw on unknown xtb tags', () => {
const XTB = `<what></what>`;
expect(() => {
loadAsMap(XTB);
}).toThrowError(new RegExp(escapeRegExp(`Unexpected tag ("[ERROR ->]<what></what>")`)));
});
it('should throw on unknown message tags', () => {
const XTB = `<translationbundle>
<translation id="1186013544048295927"><b>msg should contain only ph tags</b></translation>
</translationbundle>`;
expect(() => {
loadAsMap(XTB);
}).toThrowError(new RegExp(escapeRegExp(`[ERROR ->]<b>msg should contain only ph tags</b>`)));
});
it('should throw on duplicate message id', () => {
const XTB = `<translationbundle>
<translation id="1186013544048295927">msg1</translation>
<translation id="1186013544048295927">msg2</translation>
</translationbundle>`;
expect(() => {
loadAsMap(XTB);
}).toThrowError(/Duplicated translations for msg 1186013544048295927/);
});
it('should throw when trying to save an xtb file', () => {
expect(() => {
serializer.write([], null);
}).toThrowError(/Unsupported/);
});
});
});
| {
"end_byte": 7217,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xtb_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff2_spec.ts_0_5825 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {escapeRegExp} from '@angular/compiler/src/util';
import {serializeNodes} from '../../../src/i18n/digest';
import {MessageBundle} from '../../../src/i18n/message_bundle';
import {Xliff2} from '../../../src/i18n/serializers/xliff2';
import {DEFAULT_INTERPOLATION_CONFIG} from '../../../src/ml_parser/defaults';
import {HtmlParser} from '../../../src/ml_parser/html_parser';
const HTML = `
<p i18n-title title="translatable attribute">not translatable</p>
<p i18n>translatable element <b>with placeholders</b> {{ interpolation}}</p>
<!-- i18n -->{ count, plural, =0 {<p>test</p>}}<!-- /i18n -->
<p i18n="m|d@@i">foo</p>
<p i18n="nested"><b><u>{{interpolation}} Text</u></b></p>
<p i18n="ph names"><br><img src="1.jpg"><img src="2.jpg"></p>
<p i18n="empty element">hello <span></span></p>
<p i18n="@@baz">{ count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} }}</p>
<p i18n>Test: { count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} } =other {a lot}}</p>
<p i18n>multi
lines</p>
<p i18n>translatable element @if (foo) {with} @else if (bar) {blocks}</p>
`;
const WRITE_XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en">
<file original="ng.template" id="ngi18n">
<unit id="1933478729560469763">
<notes>
<note category="location">file.ts:2</note>
</notes>
<segment>
<source>translatable attribute</source>
</segment>
</unit>
<unit id="7056919470098446707">
<notes>
<note category="location">file.ts:3</note>
</notes>
<segment>
<source>translatable element <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">with placeholders</pc> <ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/></source>
</segment>
</unit>
<unit id="2981514368455622387">
<notes>
<note category="location">file.ts:4</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">test</pc>} }</source>
</segment>
</unit>
<unit id="i">
<notes>
<note category="description">d</note>
<note category="meaning">m</note>
<note category="location">file.ts:5</note>
</notes>
<segment>
<source>foo</source>
</segment>
</unit>
<unit id="6440235004920703622">
<notes>
<note category="description">nested</note>
<note category="location">file.ts:6</note>
</notes>
<segment>
<source><pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>"><pc id="1" equivStart="START_UNDERLINED_TEXT" equivEnd="CLOSE_UNDERLINED_TEXT" type="fmt" dispStart="<u>" dispEnd="</u>"><ph id="2" equiv="INTERPOLATION" disp="{{interpolation}}"/> Text</pc></pc></source>
</segment>
</unit>
<unit id="8779402634269838862">
<notes>
<note category="description">ph names</note>
<note category="location">file.ts:7</note>
</notes>
<segment>
<source><ph id="0" equiv="LINE_BREAK" type="fmt" disp="<br/>"/><ph id="1" equiv="TAG_IMG" type="image" disp="<img/>"/><ph id="2" equiv="TAG_IMG_1" type="image" disp="<img/>"/></source>
</segment>
</unit>
<unit id="6536355551500405293">
<notes>
<note category="description">empty element</note>
<note category="location">file.ts:8</note>
</notes>
<segment>
<source>hello <pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other" dispStart="<span>" dispEnd="</span>"></pc></source>
</segment>
</unit>
<unit id="baz">
<notes>
<note category="location">file.ts:9</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">deeply nested</pc>} } } }</source>
</segment>
</unit>
<unit id="6997386649824869937">
<notes>
<note category="location">file.ts:10</note>
</notes>
<segment>
<source>Test: <ph id="0" equiv="ICU" disp="{ count, plural, =0 {...} =other {...}}"/></source>
</segment>
</unit>
<unit id="5229984852258993423">
<notes>
<note category="location">file.ts:10</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">deeply nested</pc>} } } =other {a lot} }</source>
</segment>
</unit>
<unit id="2340165783990709777">
<notes>
<note category="location">file.ts:11,12</note>
</notes>
<segment>
<source>multi
lines</source>
</segment>
</unit>
<unit id="6618832065070552029">
<notes>
<note category="location">file.ts:13</note>
</notes>
<segment>
<source>translatable element <pc id="0" equivStart="START_BLOCK_IF" equivEnd="CLOSE_BLOCK_IF" type="other" dispStart="@if" dispEnd="}">with</pc> <pc id="1" equivStart="START_BLOCK_ELSE_IF" equivEnd="CLOSE_BLOCK_ELSE_IF" type="other" dispStart="@else if" dispEnd="}">blocks</pc></source>
</segment>
</unit>
</file>
</xliff>
`;
const LOAD_XLIFF = ` | {
"end_byte": 5825,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff2_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff2_spec.ts_0_6322 | <?xml version="1.0" encoding="UTF-8" ?>
<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en" trgLang="fr">
<file original="ng.template" id="ngi18n">
<unit id="1933478729560469763">
<notes>
<note category="location">file.ts:2</note>
</notes>
<segment>
<source>translatable attribute</source>
<target>etubirtta elbatalsnart</target>
</segment>
</unit>
<unit id="7056919470098446707">
<notes>
<note category="location">file.ts:3</note>
</notes>
<segment>
<source>translatable element <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">with placeholders</pc> <ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/></source>
<target><ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/> <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">sredlohecalp htiw</pc> tnemele elbatalsnart</target>
</segment>
</unit>
<unit id="2981514368455622387">
<notes>
<note category="location">file.ts:4</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">test</pc>} }</source>
<target>{VAR_PLURAL, plural, =0 {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">TEST</pc>} }</target>
</segment>
</unit>
<unit id="i">
<notes>
<note category="description">d</note>
<note category="meaning">m</note>
<note category="location">file.ts:5</note>
</notes>
<segment>
<source>foo</source>
<target>oof</target>
</segment>
</unit>
<unit id="6440235004920703622">
<notes>
<note category="description">nested</note>
<note category="location">file.ts:6</note>
</notes>
<segment>
<source><pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>"><pc id="1" equivStart="START_UNDERLINED_TEXT" equivEnd="CLOSE_UNDERLINED_TEXT" type="fmt" dispStart="<u>" dispEnd="</u>"><ph id="2" equiv="INTERPOLATION" disp="{{interpolation}}"/> Text</pc></pc></source>
<target><pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>"><pc id="1" equivStart="START_UNDERLINED_TEXT" equivEnd="CLOSE_UNDERLINED_TEXT" type="fmt" dispStart="<u>" dispEnd="</u>">txeT <ph id="2" equiv="INTERPOLATION" disp="{{interpolation}}"/></pc></pc></target>
</segment>
</unit>
<unit id="8779402634269838862">
<notes>
<note category="description">ph names</note>
<note category="location">file.ts:7</note>
</notes>
<segment>
<source><ph id="0" equiv="LINE_BREAK" type="fmt" disp="<br/>"/><ph id="1" equiv="TAG_IMG" type="image" disp="<img/>"/><ph id="2" equiv="TAG_IMG_1" type="image" disp="<img/>"/></source>
<target><ph id="2" equiv="TAG_IMG_1" type="image" disp="<img/>"/><ph id="1" equiv="TAG_IMG" type="image" disp="<img/>"/><ph id="0" equiv="LINE_BREAK" type="fmt" disp="<br/>"/></target>
</segment>
</unit>
<unit id="6536355551500405293">
<notes>
<note category="description">empty element</note>
<note category="location">file.ts:8</note>
</notes>
<segment>
<source>hello <pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other" dispStart="<span>" dispEnd="</span>"></pc></source>
<target><pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other" dispStart="<span>" dispEnd="</span>"></pc> olleh</target>
</segment>
</unit>
<unit id="baz">
<notes>
<note category="location">file.ts:9</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">deeply nested</pc>} } } }</source>
<target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">profondément imbriqué</pc>} } } }</target>
</segment>
</unit>
<unit id="6997386649824869937">
<notes>
<note category="location">file.ts:10</note>
</notes>
<segment>
<source>Test: <ph id="0" equiv="ICU" disp="{ count, plural, =0 {...} =other {...}}"/></source>
<target>Test: <ph id="0" equiv="ICU" disp="{ count, plural, =0 {...} =other {...}}"/></target>
</segment>
</unit>
<unit id="5229984852258993423">
<notes>
<note category="location">file.ts:10</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">deeply nested</pc>} } } =other {a lot} }</source>
<target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">profondément imbriqué</pc>} } } =other {beaucoup} }</target>
</segment>
</unit>
<unit id="2340165783990709777">
<notes>
<note category="location">file.ts:11,12</note>
</notes>
<segment>
<source>multi
lines</source>
<target>multi
lignes</target>
</segment>
</unit>
<unit id="6618832065070552029">
<notes>
<note category="location">file.ts:13</note>
</notes>
<segment>
<source>translatable element <pc id="0" equivStart="START_BLOCK_IF" equivEnd="CLOSE_BLOCK_IF" type="other" dispStart="@if" dispEnd="}">with</pc> <pc id="1" equivStart="START_BLOCK_ELSE_IF" equivEnd="CLOSE_BLOCK_ELSE_IF" type="other" dispStart="@else if" dispEnd="}">blocks</pc></source> | {
"end_byte": 6322,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff2_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff2_spec.ts_6323_7597 | category="location">file.ts:3</note>
</notes>
<segment>
<source>translatable element <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">with placeholders</pc> <ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/></source>
<target><ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/> <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>">sredlohecalp htiw</pc> tnemele elbatalsnart</target>
</segment>
</unit>
<unit id="2981514368455622387">
<notes>
<note category="location">file.ts:4</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =0 {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">test</pc>} }</source>
<target>{VAR_PLURAL, plural, =0 {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="<p>" dispEnd="</p>">TEST</pc>} }</target>
</segment>
</unit>
<unit id="i">
<notes>
<note category="description">d</note>
<note category="meaning">m</note>
<note categor | {
"end_byte": 7597,
"start_byte": 6323,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff2_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/xliff2_spec.ts_13422_19632 | scribe('XLIFF 2.0 serializer', () => {
const serializer = new Xliff2();
function toXliff(html: string, locale: string | null = null): string {
const catalog = new MessageBundle(new HtmlParser(), [], {}, locale);
catalog.updateFromTemplate(html, 'file.ts', DEFAULT_INTERPOLATION_CONFIG);
return catalog.write(serializer);
}
function loadAsMap(xliff: string): {[id: string]: string} {
const {i18nNodesByMsgId} = serializer.load(xliff, 'url');
const msgMap: {[id: string]: string} = {};
Object.keys(i18nNodesByMsgId).forEach(
(id) => (msgMap[id] = serializeNodes(i18nNodesByMsgId[id]).join('')),
);
return msgMap;
}
describe('write', () => {
it('should write a valid xliff 2.0 file', () => {
expect(toXliff(HTML)).toEqual(WRITE_XLIFF);
});
it('should write a valid xliff 2.0 file with a source language', () => {
expect(toXliff(HTML, 'fr')).toContain('srcLang="fr"');
});
});
describe('load', () => {
it('should load XLIFF files', () => {
expect(loadAsMap(LOAD_XLIFF)).toEqual({
'1933478729560469763': 'etubirtta elbatalsnart',
'7056919470098446707':
'<ph name="INTERPOLATION"/> <ph name="START_BOLD_TEXT"/>sredlohecalp htiw<ph name="CLOSE_BOLD_TEXT"/> tnemele elbatalsnart',
'2981514368455622387':
'{VAR_PLURAL, plural, =0 {[<ph name="START_PARAGRAPH"/>, TEST, <ph name="CLOSE_PARAGRAPH"/>]}}',
'i': 'oof',
'6440235004920703622':
'<ph name="START_BOLD_TEXT"/><ph name="START_UNDERLINED_TEXT"/>txeT <ph name="INTERPOLATION"/><ph name="CLOSE_UNDERLINED_TEXT"/><ph name="CLOSE_BOLD_TEXT"/>',
'8779402634269838862': '<ph name="TAG_IMG_1"/><ph name="TAG_IMG"/><ph name="LINE_BREAK"/>',
'6536355551500405293': '<ph name="START_TAG_SPAN"/><ph name="CLOSE_TAG_SPAN"/> olleh',
'baz':
'{VAR_PLURAL, plural, =0 {[{VAR_SELECT, select, other {[<ph name="START_PARAGRAPH"/>, profondément imbriqué, <ph name="CLOSE_PARAGRAPH"/>]}}, ]}}',
'6997386649824869937': 'Test: <ph name="ICU"/>',
'5229984852258993423':
'{VAR_PLURAL, plural, =0 {[{VAR_SELECT, select, other {[<ph' +
' name="START_PARAGRAPH"/>, profondément imbriqué, <ph name="CLOSE_PARAGRAPH"/>]}}, ]}, =other {[beaucoup]}}',
'2340165783990709777': `multi
lignes`,
'6618832065070552029':
'élément traduisible <ph name="START_BLOCK_IF"/>avec<ph name="CLOSE_BLOCK_IF"/> <ph name="START_BLOCK_ELSE_IF"/>des blocs<ph name="CLOSE_BLOCK_ELSE_IF"/>',
'mrk-test': 'Vous pouvez utiliser votre propre namespace.',
'mrk-test2': 'Vous pouvez utiliser votre propre namespace.',
});
});
it('should return the target locale', () => {
expect(serializer.load(LOAD_XLIFF, 'url').locale).toEqual('fr');
});
});
describe('structure errors', () => {
it('should throw when a wrong xliff version is used', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="deadbeef">
<source/>
<target/>
</trans-unit>
</body>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(/The XLIFF file version 1.2 is not compatible with XLIFF 2.0 serializer/);
});
it('should throw when an unit has no translation', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en">
<file original="ng.template" id="ngi18n">
<unit id="missingtarget">
<segment>
<source/>
</segment>
</unit>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(/Message missingtarget misses a translation/);
});
it('should throw when an unit has no id attribute', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en">
<file original="ng.template" id="ngi18n">
<unit>
<segment>
<source/>
<target/>
</segment>
</unit>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(/<unit> misses the "id" attribute/);
});
it('should throw on duplicate unit id', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en">
<file original="ng.template" id="ngi18n">
<unit id="deadbeef">
<segment>
<source/>
<target/>
</segment>
</unit>
<unit id="deadbeef">
<segment>
<source/>
<target/>
</segment>
</unit>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(/Duplicated translations for msg deadbeef/);
});
});
describe('message errors', () => {
it('should throw on unknown message tags', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en">
<file original="ng.template" id="ngi18n">
<unit id="deadbeef">
<segment>
<source/>
<target><b>msg should contain only ph and pc tags</b></target>
</segment>
</unit>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(
new RegExp(escapeRegExp(`[ERROR ->]<b>msg should contain only ph and pc tags</b>`)),
);
});
it('should throw when a placeholder misses an id attribute', () => {
const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en">
<file original="ng.template" id="ngi18n">
<unit id="deadbeef">
<segment>
<source/>
<target><ph/></target>
</segment>
</unit>
</file>
</xliff>`;
expect(() => {
loadAsMap(XLIFF);
}).toThrowError(new RegExp(escapeRegExp(`<ph> misses the "equiv" attribute`)));
});
});
});
| {
"end_byte": 19632,
"start_byte": 13422,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/xliff2_spec.ts"
} |
angular/packages/compiler/test/i18n/serializers/placeholder_spec.ts_0_4533 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {PlaceholderRegistry} from '../../../src/i18n/serializers/placeholder';
describe('PlaceholderRegistry', () => {
let reg: PlaceholderRegistry;
beforeEach(() => {
reg = new PlaceholderRegistry();
});
describe('tag placeholder', () => {
it('should generate names for well known tags', () => {
expect(reg.getStartTagPlaceholderName('p', {}, false)).toEqual('START_PARAGRAPH');
expect(reg.getCloseTagPlaceholderName('p')).toEqual('CLOSE_PARAGRAPH');
});
it('should generate names for custom tags', () => {
expect(reg.getStartTagPlaceholderName('my-cmp', {}, false)).toEqual('START_TAG_MY-CMP');
expect(reg.getCloseTagPlaceholderName('my-cmp')).toEqual('CLOSE_TAG_MY-CMP');
});
it('should generate the same name for the same tag', () => {
expect(reg.getStartTagPlaceholderName('p', {}, false)).toEqual('START_PARAGRAPH');
expect(reg.getStartTagPlaceholderName('p', {}, false)).toEqual('START_PARAGRAPH');
});
it('should be case sensitive for tag name', () => {
expect(reg.getStartTagPlaceholderName('p', {}, false)).toEqual('START_PARAGRAPH');
expect(reg.getStartTagPlaceholderName('P', {}, false)).toEqual('START_PARAGRAPH_1');
expect(reg.getCloseTagPlaceholderName('p')).toEqual('CLOSE_PARAGRAPH');
expect(reg.getCloseTagPlaceholderName('P')).toEqual('CLOSE_PARAGRAPH_1');
});
it('should generate the same name for the same tag with the same attributes', () => {
expect(reg.getStartTagPlaceholderName('p', {foo: 'a', bar: 'b'}, false)).toEqual(
'START_PARAGRAPH',
);
expect(reg.getStartTagPlaceholderName('p', {foo: 'a', bar: 'b'}, false)).toEqual(
'START_PARAGRAPH',
);
expect(reg.getStartTagPlaceholderName('p', {bar: 'b', foo: 'a'}, false)).toEqual(
'START_PARAGRAPH',
);
});
it('should generate different names for the same tag with different attributes', () => {
expect(reg.getStartTagPlaceholderName('p', {foo: 'a', bar: 'b'}, false)).toEqual(
'START_PARAGRAPH',
);
expect(reg.getStartTagPlaceholderName('p', {foo: 'a'}, false)).toEqual('START_PARAGRAPH_1');
});
it('should be case sensitive for attributes', () => {
expect(reg.getStartTagPlaceholderName('p', {foo: 'a', bar: 'b'}, false)).toEqual(
'START_PARAGRAPH',
);
expect(reg.getStartTagPlaceholderName('p', {fOo: 'a', bar: 'b'}, false)).toEqual(
'START_PARAGRAPH_1',
);
expect(reg.getStartTagPlaceholderName('p', {fOo: 'a', bAr: 'b'}, false)).toEqual(
'START_PARAGRAPH_2',
);
});
it('should support void tags', () => {
expect(reg.getStartTagPlaceholderName('p', {}, true)).toEqual('PARAGRAPH');
expect(reg.getStartTagPlaceholderName('p', {}, true)).toEqual('PARAGRAPH');
expect(reg.getStartTagPlaceholderName('p', {other: 'true'}, true)).toEqual('PARAGRAPH_1');
});
});
describe('arbitrary placeholders', () => {
it('should generate the same name given the same name and content', () => {
expect(reg.getPlaceholderName('name', 'content')).toEqual('NAME');
expect(reg.getPlaceholderName('name', 'content')).toEqual('NAME');
});
it('should generate a different name given different content', () => {
expect(reg.getPlaceholderName('name', 'content1')).toEqual('NAME');
expect(reg.getPlaceholderName('name', 'content2')).toEqual('NAME_1');
expect(reg.getPlaceholderName('name', 'content3')).toEqual('NAME_2');
});
it('should generate a different name given different names', () => {
expect(reg.getPlaceholderName('name1', 'content')).toEqual('NAME1');
expect(reg.getPlaceholderName('name2', 'content')).toEqual('NAME2');
});
});
describe('block placeholders', () => {
it('should generate placeholders for a plain block', () => {
expect(reg.getStartBlockPlaceholderName('if', [])).toBe('START_BLOCK_IF');
expect(reg.getCloseBlockPlaceholderName('if')).toBe('CLOSE_BLOCK_IF');
});
it('should generate placeholders for a block with spaces in its name', () => {
expect(reg.getStartBlockPlaceholderName('else if', [])).toBe('START_BLOCK_ELSE_IF');
expect(reg.getCloseBlockPlaceholderName('else if')).toBe('CLOSE_BLOCK_ELSE_IF');
});
});
});
| {
"end_byte": 4533,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/i18n/serializers/placeholder_spec.ts"
} |
angular/packages/compiler/test/ml_parser/ast_spec_utils.ts_0_4392 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as html from '../../src/ml_parser/ast';
import {ParseTreeResult} from '../../src/ml_parser/parser';
import {ParseLocation} from '../../src/parse_util';
export function humanizeDom(parseResult: ParseTreeResult, addSourceSpan: boolean = false): any[] {
if (parseResult.errors.length > 0) {
const errorString = parseResult.errors.join('\n');
throw new Error(`Unexpected parse errors:\n${errorString}`);
}
return humanizeNodes(parseResult.rootNodes, addSourceSpan);
}
export function humanizeDomSourceSpans(parseResult: ParseTreeResult): any[] {
return humanizeDom(parseResult, true);
}
export function humanizeNodes(nodes: html.Node[], addSourceSpan: boolean = false): any[] {
const humanizer = new _Humanizer(addSourceSpan);
html.visitAll(humanizer, nodes);
return humanizer.result;
}
export function humanizeLineColumn(location: ParseLocation): string {
return `${location.line}:${location.col}`;
}
class _Humanizer implements html.Visitor {
result: any[] = [];
elDepth: number = 0;
constructor(private includeSourceSpan: boolean) {}
visitElement(element: html.Element, context: any): any {
const res = this._appendContext(element, [html.Element, element.name, this.elDepth++]);
if (this.includeSourceSpan) {
res.push(element.startSourceSpan.toString() ?? null);
res.push(element.endSourceSpan?.toString() ?? null);
}
this.result.push(res);
html.visitAll(this, element.attrs);
html.visitAll(this, element.children);
this.elDepth--;
}
visitAttribute(attribute: html.Attribute, context: any): any {
const valueTokens = attribute.valueTokens ?? [];
const res = this._appendContext(attribute, [
html.Attribute,
attribute.name,
attribute.value,
...valueTokens.map((token) => token.parts),
]);
this.result.push(res);
}
visitText(text: html.Text, context: any): any {
const res = this._appendContext(text, [
html.Text,
text.value,
this.elDepth,
...text.tokens.map((token) => token.parts),
]);
this.result.push(res);
}
visitComment(comment: html.Comment, context: any): any {
const res = this._appendContext(comment, [html.Comment, comment.value, this.elDepth]);
this.result.push(res);
}
visitExpansion(expansion: html.Expansion, context: any): any {
const res = this._appendContext(expansion, [
html.Expansion,
expansion.switchValue,
expansion.type,
this.elDepth++,
]);
this.result.push(res);
html.visitAll(this, expansion.cases);
this.elDepth--;
}
visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any {
const res = this._appendContext(expansionCase, [
html.ExpansionCase,
expansionCase.value,
this.elDepth,
]);
this.result.push(res);
}
visitBlock(block: html.Block, context: any) {
const res = this._appendContext(block, [html.Block, block.name, this.elDepth++]);
if (this.includeSourceSpan) {
res.push(block.startSourceSpan.toString() ?? null);
res.push(block.endSourceSpan?.toString() ?? null);
}
this.result.push(res);
html.visitAll(this, block.parameters);
html.visitAll(this, block.children);
this.elDepth--;
}
visitBlockParameter(parameter: html.BlockParameter, context: any) {
this.result.push(this._appendContext(parameter, [html.BlockParameter, parameter.expression]));
}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {
const res = this._appendContext(decl, [html.LetDeclaration, decl.name, decl.value]);
if (this.includeSourceSpan) {
res.push(decl.nameSpan?.toString() ?? null);
res.push(decl.valueSpan?.toString() ?? null);
}
this.result.push(res);
}
private _appendContext(ast: html.Node, input: any[]): any[] {
if (!this.includeSourceSpan) return input;
input.push(ast.sourceSpan.toString());
if (ast.sourceSpan.fullStart.offset !== ast.sourceSpan.start.offset) {
input.push(
ast.sourceSpan.fullStart.file.content.substring(
ast.sourceSpan.fullStart.offset,
ast.sourceSpan.end.offset,
),
);
}
return input;
}
}
| {
"end_byte": 4392,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/ast_spec_utils.ts"
} |
angular/packages/compiler/test/ml_parser/icu_ast_expander_spec.ts_0_5332 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as html from '../../src/ml_parser/ast';
import {HtmlParser} from '../../src/ml_parser/html_parser';
import {expandNodes, ExpansionResult} from '../../src/ml_parser/icu_ast_expander';
import {TokenizeOptions} from '../../src/ml_parser/lexer';
import {ParseError} from '../../src/parse_util';
import {humanizeNodes} from './ast_spec_utils';
describe('Expander', () => {
function expand(template: string, options: TokenizeOptions = {}): ExpansionResult {
const htmlParser = new HtmlParser();
const res = htmlParser.parse(template, 'url', {tokenizeExpansionForms: true, ...options});
return expandNodes(res.rootNodes);
}
it('should handle the plural expansion form', () => {
const res = expand(`{messages.length, plural,=0 {zero<b>bold</b>}}`);
expect(humanizeNodes(res.nodes)).toEqual([
[html.Element, 'ng-container', 0],
[html.Attribute, '[ngPlural]', 'messages.length'],
[html.Element, 'ng-template', 1],
[html.Attribute, 'ngPluralCase', '=0'],
[html.Text, 'zero', 2, ['zero']],
[html.Element, 'b', 2],
[html.Text, 'bold', 3, ['bold']],
]);
});
it('should handle nested expansion forms', () => {
const res = expand(`{messages.length, plural, =0 { {p.gender, select, male {m}} }}`);
expect(humanizeNodes(res.nodes)).toEqual([
[html.Element, 'ng-container', 0],
[html.Attribute, '[ngPlural]', 'messages.length'],
[html.Element, 'ng-template', 1],
[html.Attribute, 'ngPluralCase', '=0'],
[html.Element, 'ng-container', 2],
[html.Attribute, '[ngSwitch]', 'p.gender'],
[html.Element, 'ng-template', 3],
[html.Attribute, 'ngSwitchCase', 'male'],
[html.Text, 'm', 4, ['m']],
[html.Text, ' ', 2, [' ']],
]);
});
it('should correctly set source code positions', () => {
const nodes = expand(`{messages.length, plural,=0 {<b>bold</b>}}`).nodes;
const container: html.Element = <html.Element>nodes[0];
expect(container.sourceSpan.start.col).toEqual(0);
expect(container.sourceSpan.end.col).toEqual(42);
expect(container.startSourceSpan.start.col).toEqual(0);
expect(container.startSourceSpan.end.col).toEqual(42);
expect(container.endSourceSpan!.start.col).toEqual(0);
expect(container.endSourceSpan!.end.col).toEqual(42);
const switchExp = container.attrs[0];
expect(switchExp.sourceSpan.start.col).toEqual(1);
expect(switchExp.sourceSpan.end.col).toEqual(16);
const template: html.Element = <html.Element>container.children[0];
expect(template.sourceSpan.start.col).toEqual(25);
expect(template.sourceSpan.end.col).toEqual(41);
const switchCheck = template.attrs[0];
expect(switchCheck.sourceSpan.start.col).toEqual(25);
expect(switchCheck.sourceSpan.end.col).toEqual(28);
const b: html.Element = <html.Element>template.children[0];
expect(b.sourceSpan.start.col).toEqual(29);
expect(b.endSourceSpan!.end.col).toEqual(40);
});
it('should handle other special forms', () => {
const res = expand(`{person.gender, select, male {m} other {default}}`);
expect(humanizeNodes(res.nodes)).toEqual([
[html.Element, 'ng-container', 0],
[html.Attribute, '[ngSwitch]', 'person.gender'],
[html.Element, 'ng-template', 1],
[html.Attribute, 'ngSwitchCase', 'male'],
[html.Text, 'm', 2, ['m']],
[html.Element, 'ng-template', 1],
[html.Attribute, 'ngSwitchDefault', ''],
[html.Text, 'default', 2, ['default']],
]);
});
it('should parse an expansion form as a tag single child', () => {
const res = expand(`<div><span>{a, b, =4 {c}}</span></div>`);
expect(humanizeNodes(res.nodes)).toEqual([
[html.Element, 'div', 0],
[html.Element, 'span', 1],
[html.Element, 'ng-container', 2],
[html.Attribute, '[ngSwitch]', 'a'],
[html.Element, 'ng-template', 3],
[html.Attribute, 'ngSwitchCase', '=4'],
[html.Text, 'c', 4, ['c']],
]);
});
it('should parse an expansion forms inside of blocks', () => {
const res = expand('@if (cond) {{a, b, =4 {c}}@if (otherCond) {{d, e, =4 {f}}}}');
expect(humanizeNodes(res.nodes)).toEqual([
[html.Block, 'if', 0],
[html.BlockParameter, 'cond'],
[html.Element, 'ng-container', 1],
[html.Attribute, '[ngSwitch]', 'a'],
[html.Element, 'ng-template', 2],
[html.Attribute, 'ngSwitchCase', '=4'],
[html.Text, 'c', 3, ['c']],
[html.Block, 'if', 1],
[html.BlockParameter, 'otherCond'],
[html.Element, 'ng-container', 2],
[html.Attribute, '[ngSwitch]', 'd'],
[html.Element, 'ng-template', 3],
[html.Attribute, 'ngSwitchCase', '=4'],
[html.Text, 'f', 4, ['f']],
]);
});
describe('errors', () => {
it('should error on unknown plural cases', () => {
expect(humanizeErrors(expand('{n, plural, unknown {-}}').errors)).toEqual([
`Plural cases should be "=<number>" or one of zero, one, two, few, many, other`,
]);
});
});
});
function humanizeErrors(errors: ParseError[]): string[] {
return errors.map((error) => error.msg);
}
| {
"end_byte": 5332,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/icu_ast_expander_spec.ts"
} |
angular/packages/compiler/test/ml_parser/ast_serializer_spec.ts_0_1864 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {HtmlParser} from '@angular/compiler/src/ml_parser/html_parser';
import {serializeNodes} from './util/util';
describe('Node serializer', () => {
let parser: HtmlParser;
beforeEach(() => {
parser = new HtmlParser();
});
it('should support element', () => {
const html = '<p></p>';
const ast = parser.parse(html, 'url');
expect(serializeNodes(ast.rootNodes)).toEqual([html]);
});
it('should support attributes', () => {
const html = '<p k="value"></p>';
const ast = parser.parse(html, 'url');
expect(serializeNodes(ast.rootNodes)).toEqual([html]);
});
it('should support text', () => {
const html = 'some text';
const ast = parser.parse(html, 'url');
expect(serializeNodes(ast.rootNodes)).toEqual([html]);
});
it('should support expansion', () => {
const html = '{number, plural, =0 {none} =1 {one} other {many}}';
const ast = parser.parse(html, 'url', {tokenizeExpansionForms: true});
expect(serializeNodes(ast.rootNodes)).toEqual([html]);
});
it('should support comment', () => {
const html = '<!--comment-->';
const ast = parser.parse(html, 'url', {tokenizeExpansionForms: true});
expect(serializeNodes(ast.rootNodes)).toEqual([html]);
});
it('should support nesting', () => {
const html = `<div i18n="meaning|desc">
<span>{{ interpolation }}</span>
<!--comment-->
<p expansion="true">
{number, plural, =0 {{sex, select, other {<b>?</b>}}}}
</p>
</div>`;
const ast = parser.parse(html, 'url', {tokenizeExpansionForms: true});
expect(serializeNodes(ast.rootNodes)).toEqual([html]);
});
});
| {
"end_byte": 1864,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/ast_serializer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/BUILD.bazel_0_545 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
ts_library(
name = "ml_parser_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/compiler/test/ml_parser/util",
],
)
jasmine_node_test(
name = "ml_parser",
bootstrap = ["//tools/testing:node"],
deps = [
":ml_parser_lib",
],
)
karma_web_test_suite(
name = "ml_parser_web",
deps = [
":ml_parser_lib",
],
)
| {
"end_byte": 545,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/BUILD.bazel"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_0_1997 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as html from '../../src/ml_parser/ast';
import {HtmlParser} from '../../src/ml_parser/html_parser';
import {ParseTreeResult, TreeError} from '../../src/ml_parser/parser';
import {TokenType} from '../../src/ml_parser/tokens';
import {ParseError} from '../../src/parse_util';
import {
humanizeDom,
humanizeDomSourceSpans,
humanizeLineColumn,
humanizeNodes,
} from './ast_spec_utils';
describe('HtmlParser', () => {
let parser: HtmlParser;
beforeEach(() => {
parser = new HtmlParser();
});
describe('parse', () => {
describe('text nodes', () => {
it('should parse root level text nodes', () => {
expect(humanizeDom(parser.parse('a', 'TestComp'))).toEqual([[html.Text, 'a', 0, ['a']]]);
});
it('should parse text nodes inside regular elements', () => {
expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Text, 'a', 1, ['a']],
]);
});
it('should parse text nodes inside <ng-template> elements', () => {
expect(humanizeDom(parser.parse('<ng-template>a</ng-template>', 'TestComp'))).toEqual([
[html.Element, 'ng-template', 0],
[html.Text, 'a', 1, ['a']],
]);
});
it('should parse CDATA', () => {
expect(humanizeDom(parser.parse('<![CDATA[text]]>', 'TestComp'))).toEqual([
[html.Text, 'text', 0, ['text']],
]);
});
it('should normalize line endings within CDATA', () => {
const parsed = parser.parse('<![CDATA[ line 1 \r\n line 2 ]]>', 'TestComp');
expect(humanizeDom(parsed)).toEqual([
[html.Text, ' line 1 \n line 2 ', 0, [' line 1 \n line 2 ']],
]);
expect(parsed.errors).toEqual([]);
});
}); | {
"end_byte": 1997,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_2003_9663 | describe('elements', () => {
it('should parse root level elements', () => {
expect(humanizeDom(parser.parse('<div></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
]);
});
it('should parse elements inside of regular elements', () => {
expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Element, 'span', 1],
]);
});
it('should parse elements inside <ng-template> elements', () => {
expect(
humanizeDom(parser.parse('<ng-template><span></span></ng-template>', 'TestComp')),
).toEqual([
[html.Element, 'ng-template', 0],
[html.Element, 'span', 1],
]);
});
it('should support void elements', () => {
expect(
humanizeDom(parser.parse('<link rel="author license" href="/about">', 'TestComp')),
).toEqual([
[html.Element, 'link', 0],
[html.Attribute, 'rel', 'author license', ['author license']],
[html.Attribute, 'href', '/about', ['/about']],
]);
});
it('should not error on void elements from HTML5 spec', () => {
// https://html.spec.whatwg.org/multipage/syntax.html#syntax-elements without:
// <base> - it can be present in head only
// <meta> - it can be present in head only
// <command> - obsolete
// <keygen> - obsolete
[
'<map><area></map>',
'<div><br></div>',
'<colgroup><col></colgroup>',
'<div><embed></div>',
'<div><hr></div>',
'<div><img></div>',
'<div><input></div>',
'<object><param>/<object>',
'<audio><source></audio>',
'<audio><track></audio>',
'<p><wbr></p>',
].forEach((html) => {
expect(parser.parse(html, 'TestComp').errors).toEqual([]);
});
});
it('should close void elements on text nodes', () => {
expect(humanizeDom(parser.parse('<p>before<br>after</p>', 'TestComp'))).toEqual([
[html.Element, 'p', 0],
[html.Text, 'before', 1, ['before']],
[html.Element, 'br', 1],
[html.Text, 'after', 1, ['after']],
]);
});
it('should support optional end tags', () => {
expect(humanizeDom(parser.parse('<div><p>1<p>2</div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Element, 'p', 1],
[html.Text, '1', 2, ['1']],
[html.Element, 'p', 1],
[html.Text, '2', 2, ['2']],
]);
});
it('should support nested elements', () => {
expect(
humanizeDom(parser.parse('<ul><li><ul><li></li></ul></li></ul>', 'TestComp')),
).toEqual([
[html.Element, 'ul', 0],
[html.Element, 'li', 1],
[html.Element, 'ul', 2],
[html.Element, 'li', 3],
]);
});
/**
* Certain elements (like <tr> or <col>) require parent elements of a certain type (ex. <tr>
* can only be inside <tbody> / <thead>). The Angular HTML parser doesn't validate those
* HTML compliancy rules as "problematic" elements can be projected - in such case HTML (as
* written in an Angular template) might be "invalid" (spec-wise) but the resulting DOM will
* still be correct.
*/
it('should not wraps elements in a required parent', () => {
expect(humanizeDom(parser.parse('<div><tr></tr></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Element, 'tr', 1],
]);
});
it('should support explicit namespace', () => {
expect(humanizeDom(parser.parse('<myns:div></myns:div>', 'TestComp'))).toEqual([
[html.Element, ':myns:div', 0],
]);
});
it('should support implicit namespace', () => {
expect(humanizeDom(parser.parse('<svg></svg>', 'TestComp'))).toEqual([
[html.Element, ':svg:svg', 0],
]);
});
it('should propagate the namespace', () => {
expect(humanizeDom(parser.parse('<myns:div><p></p></myns:div>', 'TestComp'))).toEqual([
[html.Element, ':myns:div', 0],
[html.Element, ':myns:p', 1],
]);
});
it('should match closing tags case sensitive', () => {
const errors = parser.parse('<DiV><P></p></dIv>', 'TestComp').errors;
expect(errors.length).toEqual(2);
expect(humanizeErrors(errors)).toEqual([
[
'p',
'Unexpected closing tag "p". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:8',
],
[
'dIv',
'Unexpected closing tag "dIv". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:12',
],
]);
});
it('should support self closing void elements', () => {
expect(humanizeDom(parser.parse('<input />', 'TestComp'))).toEqual([
[html.Element, 'input', 0],
]);
});
it('should support self closing foreign elements', () => {
expect(humanizeDom(parser.parse('<math />', 'TestComp'))).toEqual([
[html.Element, ':math:math', 0],
]);
});
it('should ignore LF immediately after textarea, pre and listing', () => {
expect(
humanizeDom(
parser.parse(
'<p>\n</p><textarea>\n</textarea><pre>\n\n</pre><listing>\n\n</listing>',
'TestComp',
),
),
).toEqual([
[html.Element, 'p', 0],
[html.Text, '\n', 1, ['\n']],
[html.Element, 'textarea', 0],
[html.Element, 'pre', 0],
[html.Text, '\n', 1, ['\n']],
[html.Element, 'listing', 0],
[html.Text, '\n', 1, ['\n']],
]);
});
it('should normalize line endings in text', () => {
let parsed: ParseTreeResult;
parsed = parser.parse('<title> line 1 \r\n line 2 </title>', 'TestComp');
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'title', 0],
[html.Text, ' line 1 \n line 2 ', 1, [' line 1 \n line 2 ']],
]);
expect(parsed.errors).toEqual([]);
parsed = parser.parse('<script> line 1 \r\n line 2 </script>', 'TestComp');
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'script', 0],
[html.Text, ' line 1 \n line 2 ', 1, [' line 1 \n line 2 ']],
]);
expect(parsed.errors).toEqual([]);
parsed = parser.parse('<div> line 1 \r\n line 2 </div>', 'TestComp');
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'div', 0],
[html.Text, ' line 1 \n line 2 ', 1, [' line 1 \n line 2 ']],
]);
expect(parsed.errors).toEqual([]);
parsed = parser.parse('<span> line 1 \r\n line 2 </span>', 'TestComp');
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'span', 0],
[html.Text, ' line 1 \n line 2 ', 1, [' line 1 \n line 2 ']],
]);
expect(parsed.errors).toEqual([]);
});
it('should parse element with JavaScript keyword tag name', () => {
expect(humanizeDom(parser.parse('<constructor></constructor>', 'TestComp'))).toEqual([
[html.Element, 'constructor', 0],
]);
});
}); | {
"end_byte": 9663,
"start_byte": 2003,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_9669_16329 | describe('attributes', () => {
it('should parse attributes on regular elements case sensitive', () => {
expect(humanizeDom(parser.parse('<div kEy="v" key2=v2></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, 'kEy', 'v', ['v']],
[html.Attribute, 'key2', 'v2', ['v2']],
]);
});
it('should parse attributes containing interpolation', () => {
expect(humanizeDom(parser.parse('<div foo="1{{message}}2"></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, 'foo', '1{{message}}2', ['1'], ['{{', 'message', '}}'], ['2']],
]);
});
it('should parse attributes containing unquoted interpolation', () => {
expect(humanizeDom(parser.parse('<div foo={{message}}></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, 'foo', '{{message}}', [''], ['{{', 'message', '}}'], ['']],
]);
});
it('should parse bound inputs with expressions containing newlines', () => {
expect(
humanizeDom(
parser.parse(
`<app-component
[attr]="[
{text: 'some text',url:'//www.google.com'},
{text:'other text',url:'//www.google.com'}]"></app-component>`,
'TestComp',
),
),
).toEqual([
[html.Element, 'app-component', 0],
[
html.Attribute,
'[attr]',
`[
{text: 'some text',url:'//www.google.com'},
{text:'other text',url:'//www.google.com'}]`,
[
`[
{text: 'some text',url:'//www.google.com'},
{text:'other text',url:'//www.google.com'}]`,
],
],
]);
});
it('should parse attributes containing encoded entities', () => {
expect(humanizeDom(parser.parse('<div foo="&"></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, 'foo', '&', [''], ['&', '&'], ['']],
]);
});
it('should parse attributes containing unquoted interpolation', () => {
expect(humanizeDom(parser.parse('<div foo={{message}}></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, 'foo', '{{message}}', [''], ['{{', 'message', '}}'], ['']],
]);
});
it('should parse bound inputs with expressions containing newlines', () => {
expect(
humanizeDom(
parser.parse(
`<app-component
[attr]="[
{text: 'some text',url:'//www.google.com'},
{text:'other text',url:'//www.google.com'}]"></app-component>`,
'TestComp',
),
),
).toEqual([
[html.Element, 'app-component', 0],
[
html.Attribute,
'[attr]',
`[
{text: 'some text',url:'//www.google.com'},
{text:'other text',url:'//www.google.com'}]`,
[
`[
{text: 'some text',url:'//www.google.com'},
{text:'other text',url:'//www.google.com'}]`,
],
],
]);
});
it('should decode HTML entities in interpolated attributes', () => {
// Note that the detail of decoding corner-cases is tested in the
// "should decode HTML entities in interpolations" spec.
expect(
humanizeDomSourceSpans(parser.parse('<div foo="{{&}}"></div>', 'TestComp')),
).toEqual([
[
html.Element,
'div',
0,
'<div foo="{{&}}"></div>',
'<div foo="{{&}}">',
'</div>',
],
[html.Attribute, 'foo', '{{&}}', [''], ['{{', '&', '}}'], [''], 'foo="{{&}}"'],
]);
});
it('should normalize line endings within attribute values', () => {
const result = parser.parse('<div key=" \r\n line 1 \r\n line 2 "></div>', 'TestComp');
expect(humanizeDom(result)).toEqual([
[html.Element, 'div', 0],
[html.Attribute, 'key', ' \n line 1 \n line 2 ', [' \n line 1 \n line 2 ']],
]);
expect(result.errors).toEqual([]);
});
it('should parse attributes without values', () => {
expect(humanizeDom(parser.parse('<div k></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, 'k', ''],
]);
});
it('should parse attributes on svg elements case sensitive', () => {
expect(humanizeDom(parser.parse('<svg viewBox="0"></svg>', 'TestComp'))).toEqual([
[html.Element, ':svg:svg', 0],
[html.Attribute, 'viewBox', '0', ['0']],
]);
});
it('should parse attributes on <ng-template> elements', () => {
expect(humanizeDom(parser.parse('<ng-template k="v"></ng-template>', 'TestComp'))).toEqual([
[html.Element, 'ng-template', 0],
[html.Attribute, 'k', 'v', ['v']],
]);
});
it('should support namespace', () => {
expect(humanizeDom(parser.parse('<svg:use xlink:href="Port" />', 'TestComp'))).toEqual([
[html.Element, ':svg:use', 0],
[html.Attribute, ':xlink:href', 'Port', ['Port']],
]);
});
it('should support a prematurely terminated interpolation in attribute', () => {
const {errors, rootNodes} = parser.parse('<div p="{{ abc"><span></span>', 'TestComp');
expect(humanizeNodes(rootNodes, true)).toEqual([
[html.Element, 'div', 0, '<div p="{{ abc">', '<div p="{{ abc">', null],
[html.Attribute, 'p', '{{ abc', [''], ['{{', ' abc'], [''], 'p="{{ abc"'],
[html.Element, 'span', 1, '<span></span>', '<span>', '</span>'],
]);
expect(humanizeErrors(errors)).toEqual([]);
});
});
describe('comments', () => {
it('should preserve comments', () => {
expect(humanizeDom(parser.parse('<!-- comment --><div></div>', 'TestComp'))).toEqual([
[html.Comment, 'comment', 0],
[html.Element, 'div', 0],
]);
});
it('should normalize line endings within comments', () => {
expect(humanizeDom(parser.parse('<!-- line 1 \r\n line 2 -->', 'TestComp'))).toEqual([
[html.Comment, 'line 1 \n line 2', 0],
]);
});
}); | {
"end_byte": 16329,
"start_byte": 9669,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_16335_23466 | describe('expansion forms', () => {
it('should parse out expansion forms', () => {
const parsed = parser.parse(
`<div>before{messages.length, plural, =0 {You have <b>no</b> messages} =1 {One {{message}}}}after</div>`,
'TestComp',
{tokenizeExpansionForms: true},
);
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'div', 0],
[html.Text, 'before', 1, ['before']],
[html.Expansion, 'messages.length', 'plural', 1],
[html.ExpansionCase, '=0', 2],
[html.ExpansionCase, '=1', 2],
[html.Text, 'after', 1, ['after']],
]);
const cases = (<any>parsed.rootNodes[0]).children[1].cases;
expect(humanizeDom(new ParseTreeResult(cases[0].expression, []))).toEqual([
[html.Text, 'You have ', 0, ['You have ']],
[html.Element, 'b', 0],
[html.Text, 'no', 1, ['no']],
[html.Text, ' messages', 0, [' messages']],
]);
expect(humanizeDom(new ParseTreeResult(cases[1].expression, []))).toEqual([
[html.Text, 'One {{message}}', 0, ['One '], ['{{', 'message', '}}'], ['']],
]);
});
it('should normalize line-endings in expansion forms in inline templates if `i18nNormalizeLineEndingsInICUs` is true', () => {
const parsed = parser.parse(
`<div>\r\n` +
` {\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n` +
`</div>`,
'TestComp',
{
tokenizeExpansionForms: true,
escapedString: true,
i18nNormalizeLineEndingsInICUs: true,
},
);
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'div', 0],
[html.Text, '\n ', 1, ['\n ']],
[html.Expansion, '\n messages.length', 'plural', 1],
[html.ExpansionCase, '=0', 2],
[html.ExpansionCase, '=1', 2],
[html.Text, '\n', 1, ['\n']],
]);
const cases = (<any>parsed.rootNodes[0]).children[1].cases;
expect(humanizeDom(new ParseTreeResult(cases[0].expression, []))).toEqual([
[html.Text, 'You have \nno\n messages', 0, ['You have \nno\n messages']],
]);
expect(humanizeDom(new ParseTreeResult(cases[1].expression, []))).toEqual([
[html.Text, 'One {{message}}', 0, ['One '], ['{{', 'message', '}}'], ['']],
]);
expect(parsed.errors).toEqual([]);
});
it('should not normalize line-endings in ICU expressions in external templates when `i18nNormalizeLineEndingsInICUs` is not set', () => {
const parsed = parser.parse(
`<div>\r\n` +
` {\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n` +
`</div>`,
'TestComp',
{tokenizeExpansionForms: true, escapedString: true},
);
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'div', 0],
[html.Text, '\n ', 1, ['\n ']],
[html.Expansion, '\r\n messages.length', 'plural', 1],
[html.ExpansionCase, '=0', 2],
[html.ExpansionCase, '=1', 2],
[html.Text, '\n', 1, ['\n']],
]);
const cases = (<any>parsed.rootNodes[0]).children[1].cases;
expect(humanizeDom(new ParseTreeResult(cases[0].expression, []))).toEqual([
[html.Text, 'You have \nno\n messages', 0, ['You have \nno\n messages']],
]);
expect(humanizeDom(new ParseTreeResult(cases[1].expression, []))).toEqual([
[html.Text, 'One {{message}}', 0, ['One '], ['{{', 'message', '}}'], ['']],
]);
expect(parsed.errors).toEqual([]);
});
it('should normalize line-endings in expansion forms in external templates if `i18nNormalizeLineEndingsInICUs` is true', () => {
const parsed = parser.parse(
`<div>\r\n` +
` {\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n` +
`</div>`,
'TestComp',
{
tokenizeExpansionForms: true,
escapedString: false,
i18nNormalizeLineEndingsInICUs: true,
},
);
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'div', 0],
[html.Text, '\n ', 1, ['\n ']],
[html.Expansion, '\n messages.length', 'plural', 1],
[html.ExpansionCase, '=0', 2],
[html.ExpansionCase, '=1', 2],
[html.Text, '\n', 1, ['\n']],
]);
const cases = (<any>parsed.rootNodes[0]).children[1].cases;
expect(humanizeDom(new ParseTreeResult(cases[0].expression, []))).toEqual([
[html.Text, 'You have \nno\n messages', 0, ['You have \nno\n messages']],
]);
expect(humanizeDom(new ParseTreeResult(cases[1].expression, []))).toEqual([
[html.Text, 'One {{message}}', 0, ['One '], ['{{', 'message', '}}'], ['']],
]);
expect(parsed.errors).toEqual([]);
});
it('should not normalize line-endings in ICU expressions in external templates when `i18nNormalizeLineEndingsInICUs` is not set', () => {
const parsed = parser.parse(
`<div>\r\n` +
` {\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n` +
`</div>`,
'TestComp',
{tokenizeExpansionForms: true, escapedString: false},
);
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'div', 0],
[html.Text, '\n ', 1, ['\n ']],
[html.Expansion, '\r\n messages.length', 'plural', 1],
[html.ExpansionCase, '=0', 2],
[html.ExpansionCase, '=1', 2],
[html.Text, '\n', 1, ['\n']],
]);
const cases = (<any>parsed.rootNodes[0]).children[1].cases;
expect(humanizeDom(new ParseTreeResult(cases[0].expression, []))).toEqual([
[html.Text, 'You have \nno\n messages', 0, ['You have \nno\n messages']],
]);
expect(humanizeDom(new ParseTreeResult(cases[1].expression, []))).toEqual([
[html.Text, 'One {{message}}', 0, ['One '], ['{{', 'message', '}}'], ['']],
]);
expect(parsed.errors).toEqual([]);
});
it('should parse out expansion forms', () => {
const parsed = parser.parse(`<div><span>{a, plural, =0 {b}}</span></div>`, 'TestComp', {
tokenizeExpansionForms: true,
});
expect(humanizeDom(parsed)).toEqual([
[html.Element, 'div', 0],
[html.Element, 'span', 1],
[html.Expansion, 'a', 'plural', 2],
[html.ExpansionCase, '=0', 3],
]);
}); | {
"end_byte": 23466,
"start_byte": 16335,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_23474_29971 | it('should parse out nested expansion forms', () => {
const parsed = parser.parse(
`{messages.length, plural, =0 { {p.gender, select, male {m}} }}`,
'TestComp',
{tokenizeExpansionForms: true},
);
expect(humanizeDom(parsed)).toEqual([
[html.Expansion, 'messages.length', 'plural', 0],
[html.ExpansionCase, '=0', 1],
]);
const firstCase = (<any>parsed.rootNodes[0]).cases[0];
expect(humanizeDom(new ParseTreeResult(firstCase.expression, []))).toEqual([
[html.Expansion, 'p.gender', 'select', 0],
[html.ExpansionCase, 'male', 1],
[html.Text, ' ', 0, [' ']],
]);
});
it('should normalize line endings in nested expansion forms for inline templates, when `i18nNormalizeLineEndingsInICUs` is true', () => {
const parsed = parser.parse(
`{\r\n` +
` messages.length, plural,\r\n` +
` =0 { zero \r\n` +
` {\r\n` +
` p.gender, select,\r\n` +
` male {m}\r\n` +
` }\r\n` +
` }\r\n` +
`}`,
'TestComp',
{
tokenizeExpansionForms: true,
escapedString: true,
i18nNormalizeLineEndingsInICUs: true,
},
);
expect(humanizeDom(parsed)).toEqual([
[html.Expansion, '\n messages.length', 'plural', 0],
[html.ExpansionCase, '=0', 1],
]);
const expansion = parsed.rootNodes[0] as html.Expansion;
expect(humanizeDom(new ParseTreeResult(expansion.cases[0].expression, []))).toEqual([
[html.Text, 'zero \n ', 0, ['zero \n ']],
[html.Expansion, '\n p.gender', 'select', 0],
[html.ExpansionCase, 'male', 1],
[html.Text, '\n ', 0, ['\n ']],
]);
expect(parsed.errors).toEqual([]);
});
it('should not normalize line endings in nested expansion forms for inline templates, when `i18nNormalizeLineEndingsInICUs` is not defined', () => {
const parsed = parser.parse(
`{\r\n` +
` messages.length, plural,\r\n` +
` =0 { zero \r\n` +
` {\r\n` +
` p.gender, select,\r\n` +
` male {m}\r\n` +
` }\r\n` +
` }\r\n` +
`}`,
'TestComp',
{tokenizeExpansionForms: true, escapedString: true},
);
expect(humanizeDom(parsed)).toEqual([
[html.Expansion, '\r\n messages.length', 'plural', 0],
[html.ExpansionCase, '=0', 1],
]);
const expansion = parsed.rootNodes[0] as html.Expansion;
expect(humanizeDom(new ParseTreeResult(expansion.cases[0].expression, []))).toEqual([
[html.Text, 'zero \n ', 0, ['zero \n ']],
[html.Expansion, '\r\n p.gender', 'select', 0],
[html.ExpansionCase, 'male', 1],
[html.Text, '\n ', 0, ['\n ']],
]);
expect(parsed.errors).toEqual([]);
});
it('should not normalize line endings in nested expansion forms for external templates, when `i18nNormalizeLineEndingsInICUs` is not set', () => {
const parsed = parser.parse(
`{\r\n` +
` messages.length, plural,\r\n` +
` =0 { zero \r\n` +
` {\r\n` +
` p.gender, select,\r\n` +
` male {m}\r\n` +
` }\r\n` +
` }\r\n` +
`}`,
'TestComp',
{tokenizeExpansionForms: true},
);
expect(humanizeDom(parsed)).toEqual([
[html.Expansion, '\r\n messages.length', 'plural', 0],
[html.ExpansionCase, '=0', 1],
]);
const expansion = parsed.rootNodes[0] as html.Expansion;
expect(humanizeDom(new ParseTreeResult(expansion.cases[0].expression, []))).toEqual([
[html.Text, 'zero \n ', 0, ['zero \n ']],
[html.Expansion, '\r\n p.gender', 'select', 0],
[html.ExpansionCase, 'male', 1],
[html.Text, '\n ', 0, ['\n ']],
]);
expect(parsed.errors).toEqual([]);
});
it('should error when expansion form is not closed', () => {
const p = parser.parse(`{messages.length, plural, =0 {one}`, 'TestComp', {
tokenizeExpansionForms: true,
});
expect(humanizeErrors(p.errors)).toEqual([
[null, "Invalid ICU message. Missing '}'.", '0:34'],
]);
});
it('should support ICU expressions with cases that contain numbers', () => {
const p = parser.parse(`{sex, select, male {m} female {f} 0 {other}}`, 'TestComp', {
tokenizeExpansionForms: true,
});
expect(p.errors.length).toEqual(0);
});
it(`should support ICU expressions with cases that contain any character except '}'`, () => {
const p = parser.parse(`{a, select, b {foo} % bar {% bar}}`, 'TestComp', {
tokenizeExpansionForms: true,
});
expect(p.errors.length).toEqual(0);
});
it('should error when expansion case is not properly closed', () => {
const p = parser.parse(`{a, select, b {foo} % { bar {% bar}}`, 'TestComp', {
tokenizeExpansionForms: true,
});
expect(humanizeErrors(p.errors)).toEqual([
[
TokenType.RAW_TEXT,
'Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ \'{\' }}") to escape it.)',
'0:36',
],
[null, "Invalid ICU message. Missing '}'.", '0:22'],
]);
});
it('should error when expansion case is not closed', () => {
const p = parser.parse(`{messages.length, plural, =0 {one`, 'TestComp', {
tokenizeExpansionForms: true,
});
expect(humanizeErrors(p.errors)).toEqual([
[null, "Invalid ICU message. Missing '}'.", '0:29'],
]);
});
it('should error when invalid html in the case', () => {
const p = parser.parse(`{messages.length, plural, =0 {<b/>}`, 'TestComp', {
tokenizeExpansionForms: true,
});
expect(humanizeErrors(p.errors)).toEqual([
['b', 'Only void, custom and foreign elements can be self closed "b"', '0:30'],
]);
});
}); | {
"end_byte": 29971,
"start_byte": 23474,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_29977_36804 | describe('blocks', () => {
it('should parse a block', () => {
expect(humanizeDom(parser.parse('@foo (a b; c d){hello}', 'TestComp'))).toEqual([
[html.Block, 'foo', 0],
[html.BlockParameter, 'a b'],
[html.BlockParameter, 'c d'],
[html.Text, 'hello', 1, ['hello']],
]);
});
it('should parse a block with an HTML element', () => {
expect(humanizeDom(parser.parse('@defer {<my-cmp/>}', 'TestComp'))).toEqual([
[html.Block, 'defer', 0],
[html.Element, 'my-cmp', 1],
]);
});
it('should parse a block containing mixed plain text and HTML', () => {
expect(
humanizeDom(
parser.parse(
'@switch (expr) {' +
'@case (1) {hello<my-cmp/>there}' +
'@case (two) {<p>Two...</p>}' +
'@case (isThree(3)) {T<strong>htr<i>e</i>e</strong>!}' +
'}',
'TestComp',
),
),
).toEqual([
[html.Block, 'switch', 0],
[html.BlockParameter, 'expr'],
[html.Block, 'case', 1],
[html.BlockParameter, '1'],
[html.Text, 'hello', 2, ['hello']],
[html.Element, 'my-cmp', 2],
[html.Text, 'there', 2, ['there']],
[html.Block, 'case', 1],
[html.BlockParameter, 'two'],
[html.Element, 'p', 2],
[html.Text, 'Two...', 3, ['Two...']],
[html.Block, 'case', 1],
[html.BlockParameter, 'isThree(3)'],
[html.Text, 'T', 2, ['T']],
[html.Element, 'strong', 2],
[html.Text, 'htr', 3, ['htr']],
[html.Element, 'i', 3],
[html.Text, 'e', 4, ['e']],
[html.Text, 'e', 3, ['e']],
[html.Text, '!', 2, ['!']],
]);
});
it('should parse nested blocks', () => {
const markup =
`<root-sibling-one/>` +
`@root {` +
`<outer-child-one/>` +
`<outer-child-two>` +
`@child (childParam === 1) {` +
`@innerChild (innerChild1 === foo) {` +
`<inner-child-one/>` +
`@grandChild {` +
`@innerGrandChild {` +
`<inner-grand-child-one/>` +
`}` +
`@innerGrandChild {` +
`<inner-grand-child-two/>` +
`}` +
`}` +
`}` +
`@innerChild {` +
`<inner-child-two/>` +
`}` +
`}` +
`</outer-child-two>` +
`@outerChild (outerChild1; outerChild2) {` +
`<outer-child-three/>` +
`}` +
`} <root-sibling-two/>`;
expect(humanizeDom(parser.parse(markup, 'TestComp'))).toEqual([
[html.Element, 'root-sibling-one', 0],
[html.Block, 'root', 0],
[html.Element, 'outer-child-one', 1],
[html.Element, 'outer-child-two', 1],
[html.Block, 'child', 2],
[html.BlockParameter, 'childParam === 1'],
[html.Block, 'innerChild', 3],
[html.BlockParameter, 'innerChild1 === foo'],
[html.Element, 'inner-child-one', 4],
[html.Block, 'grandChild', 4],
[html.Block, 'innerGrandChild', 5],
[html.Element, 'inner-grand-child-one', 6],
[html.Block, 'innerGrandChild', 5],
[html.Element, 'inner-grand-child-two', 6],
[html.Block, 'innerChild', 3],
[html.Element, 'inner-child-two', 4],
[html.Block, 'outerChild', 1],
[html.BlockParameter, 'outerChild1'],
[html.BlockParameter, 'outerChild2'],
[html.Element, 'outer-child-three', 2],
[html.Text, ' ', 0, [' ']],
[html.Element, 'root-sibling-two', 0],
]);
});
it('should infer namespace through block boundary', () => {
expect(humanizeDom(parser.parse('<svg>@if (cond) {<circle/>}</svg>', 'TestComp'))).toEqual([
[html.Element, ':svg:svg', 0],
[html.Block, 'if', 1],
[html.BlockParameter, 'cond'],
[html.Element, ':svg:circle', 2],
]);
});
it('should parse an empty block', () => {
expect(humanizeDom(parser.parse('@foo{}', 'TestComp'))).toEqual([[html.Block, 'foo', 0]]);
});
it('should parse a block with void elements', () => {
expect(humanizeDom(parser.parse('@foo {<br>}', 'TestComp'))).toEqual([
[html.Block, 'foo', 0],
[html.Element, 'br', 1],
]);
});
it('should close void elements used right before a block', () => {
expect(humanizeDom(parser.parse('<img>@foo {hello}', 'TestComp'))).toEqual([
[html.Element, 'img', 0],
[html.Block, 'foo', 0],
[html.Text, 'hello', 1, ['hello']],
]);
});
it('should report an unclosed block', () => {
const errors = parser.parse('@foo {hello', 'TestComp').errors;
expect(errors.length).toEqual(1);
expect(humanizeErrors(errors)).toEqual([['foo', 'Unclosed block "foo"', '0:0']]);
});
it('should report an unexpected block close', () => {
const errors = parser.parse('hello}', 'TestComp').errors;
expect(errors.length).toEqual(1);
expect(humanizeErrors(errors)).toEqual([
[
null,
'Unexpected closing block. The block may have been closed earlier. If you meant to write the } character, you should use the "}" HTML entity instead.',
'0:5',
],
]);
});
it('should report unclosed tags inside of a block', () => {
const errors = parser.parse('@foo {<strong>hello}', 'TestComp').errors;
expect(errors.length).toEqual(1);
expect(humanizeErrors(errors)).toEqual([
[
null,
'Unexpected closing block. The block may have been closed earlier. If you meant to write the } character, you should use the "}" HTML entity instead.',
'0:19',
],
]);
});
it('should report an unexpected closing tag inside a block', () => {
const errors = parser.parse('<div>@if (cond) {hello</div>}', 'TestComp').errors;
expect(errors.length).toEqual(2);
expect(humanizeErrors(errors)).toEqual([
[
'div',
'Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:22',
],
[
null,
'Unexpected closing block. The block may have been closed earlier. If you meant to write the } character, you should use the "}" HTML entity instead.',
'0:28',
],
]);
}); | {
"end_byte": 36804,
"start_byte": 29977,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_36812_41788 | it('should store the source locations of blocks', () => {
const markup =
'@switch (expr) {' +
'@case (1) {<div>hello</div>world}' +
'@case (two) {Two}' +
'@case (isThree(3)) {Placeholde<strong>r</strong>}' +
'}';
expect(humanizeDomSourceSpans(parser.parse(markup, 'TestComp'))).toEqual([
[
html.Block,
'switch',
0,
'@switch (expr) {@case (1) {<div>hello</div>world}@case (two) {Two}@case (isThree(3)) {Placeholde<strong>r</strong>}}',
'@switch (expr) {',
'}',
],
[html.BlockParameter, 'expr', 'expr'],
[html.Block, 'case', 1, '@case (1) {<div>hello</div>world}', '@case (1) {', '}'],
[html.BlockParameter, '1', '1'],
[html.Element, 'div', 2, '<div>hello</div>', '<div>', '</div>'],
[html.Text, 'hello', 3, ['hello'], 'hello'],
[html.Text, 'world', 2, ['world'], 'world'],
[html.Block, 'case', 1, '@case (two) {Two}', '@case (two) {', '}'],
[html.BlockParameter, 'two', 'two'],
[html.Text, 'Two', 2, ['Two'], 'Two'],
[
html.Block,
'case',
1,
'@case (isThree(3)) {Placeholde<strong>r</strong>}',
'@case (isThree(3)) {',
'}',
],
[html.BlockParameter, 'isThree(3)', 'isThree(3)'],
[html.Text, 'Placeholde', 2, ['Placeholde'], 'Placeholde'],
[html.Element, 'strong', 2, '<strong>r</strong>', '<strong>', '</strong>'],
[html.Text, 'r', 3, ['r'], 'r'],
]);
});
it('should parse an incomplete block with no parameters', () => {
const result = parser.parse('Use the @Input() decorator', 'TestComp');
expect(humanizeNodes(result.rootNodes, true)).toEqual([
[html.Text, 'Use the ', 0, ['Use the '], 'Use the '],
[html.Block, 'Input', 0, '@Input() ', '@Input() ', null],
[html.Text, 'decorator', 0, ['decorator'], 'decorator'],
]);
expect(humanizeErrors(result.errors)).toEqual([
[
'Input',
'Incomplete block "Input". If you meant to write the @ character, you should use the "@" HTML entity instead.',
'0:8',
],
]);
});
it('should parse an incomplete block with no parameters', () => {
const result = parser.parse('Use @Input({alias: "foo"}) to alias your input', 'TestComp');
expect(humanizeNodes(result.rootNodes, true)).toEqual([
[html.Text, 'Use ', 0, ['Use '], 'Use '],
[html.Block, 'Input', 0, '@Input({alias: "foo"}) ', '@Input({alias: "foo"}) ', null],
[html.BlockParameter, '{alias: "foo"}', '{alias: "foo"}'],
[html.Text, 'to alias your input', 0, ['to alias your input'], 'to alias your input'],
]);
expect(humanizeErrors(result.errors)).toEqual([
[
'Input',
'Incomplete block "Input". If you meant to write the @ character, you should use the "@" HTML entity instead.',
'0:4',
],
]);
});
});
describe('let declaration', () => {
it('should parse a let declaration', () => {
expect(humanizeDom(parser.parse('@let foo = 123;', 'TestCmp'))).toEqual([
[html.LetDeclaration, 'foo', '123'],
]);
});
it('should parse a let declaration that is nested in a parent', () => {
expect(
humanizeDom(parser.parse('@grandparent {@parent {@let foo = 123;}}', 'TestCmp')),
).toEqual([
[html.Block, 'grandparent', 0],
[html.Block, 'parent', 1],
[html.LetDeclaration, 'foo', '123'],
]);
});
it('should store the source location of a @let declaration', () => {
expect(humanizeDomSourceSpans(parser.parse('@let foo = 123 + 456;', 'TestCmp'))).toEqual([
[html.LetDeclaration, 'foo', '123 + 456', '@let foo = 123 + 456', 'foo', '123 + 456'],
]);
});
it('should report an error for an incomplete let declaration', () => {
expect(humanizeErrors(parser.parse('@let foo =', 'TestCmp').errors)).toEqual([
[
'foo',
'Incomplete @let declaration "foo". @let declarations must be written as `@let <name> = <value>;`',
'0:0',
],
]);
});
it('should store the locations of an incomplete let declaration', () => {
const parseResult = parser.parse('@let foo =', 'TestCmp');
// It's expected that errors will be reported for the incomplete declaration,
// but we still want to check the spans since they're important even for broken templates.
parseResult.errors = [];
expect(humanizeDomSourceSpans(parseResult)).toEqual([
[html.LetDeclaration, 'foo', '', '@let foo =', 'foo =', ''],
]);
});
}); | {
"end_byte": 41788,
"start_byte": 36812,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_41794_49133 | describe('source spans', () => {
it('should store the location', () => {
expect(
humanizeDomSourceSpans(
parser.parse('<div [prop]="v1" (e)="do()" attr="v2" noValue>\na\n</div>', ' TestComp'),
),
).toEqual([
[
html.Element,
'div',
0,
'<div [prop]="v1" (e)="do()" attr="v2" noValue>\na\n</div>',
'<div [prop]="v1" (e)="do()" attr="v2" noValue>',
'</div>',
],
[html.Attribute, '[prop]', 'v1', ['v1'], '[prop]="v1"'],
[html.Attribute, '(e)', 'do()', ['do()'], '(e)="do()"'],
[html.Attribute, 'attr', 'v2', ['v2'], 'attr="v2"'],
[html.Attribute, 'noValue', '', 'noValue'],
[html.Text, '\na\n', 1, ['\na\n'], '\na\n'],
]);
});
it('should set the start and end source spans', () => {
const node = <html.Element>parser.parse('<div>a</div>', 'TestComp').rootNodes[0];
expect(node.startSourceSpan.start.offset).toEqual(0);
expect(node.startSourceSpan.end.offset).toEqual(5);
expect(node.endSourceSpan!.start.offset).toEqual(6);
expect(node.endSourceSpan!.end.offset).toEqual(12);
});
// This checks backward compatibility with a previous version of the lexer, which would
// treat interpolation expressions as regular HTML escapable text.
it('should decode HTML entities in interpolations', () => {
expect(
humanizeDomSourceSpans(
parser.parse(
'{{&}}' +
'{{▾}}' +
'{{▾}}' +
'{{&unknown;}}' +
'{{& (no semi-colon)}}' +
'{{&#xyz; (invalid hex)}}' +
'{{BE; (invalid decimal)}}',
'TestComp',
),
),
).toEqual([
[
html.Text,
'{{&}}' +
'{{\u25BE}}' +
'{{\u25BE}}' +
'{{&unknown;}}' +
'{{& (no semi-colon)}}' +
'{{&#xyz; (invalid hex)}}' +
'{{BE; (invalid decimal)}}',
0,
[''],
['{{', '&', '}}'],
[''],
['{{', '▾', '}}'],
[''],
['{{', '▾', '}}'],
[''],
['{{', '&unknown;', '}}'],
[''],
['{{', '& (no semi-colon)', '}}'],
[''],
['{{', '&#xyz; (invalid hex)', '}}'],
[''],
['{{', 'BE; (invalid decimal)', '}}'],
[''],
'{{&}}' +
'{{▾}}' +
'{{▾}}' +
'{{&unknown;}}' +
'{{& (no semi-colon)}}' +
'{{&#xyz; (invalid hex)}}' +
'{{BE; (invalid decimal)}}',
],
]);
});
it('should support interpolations in text', () => {
expect(
humanizeDomSourceSpans(parser.parse('<div> pre {{ value }} post </div>', 'TestComp')),
).toEqual([
[html.Element, 'div', 0, '<div> pre {{ value }} post </div>', '<div>', '</div>'],
[
html.Text,
' pre {{ value }} post ',
1,
[' pre '],
['{{', ' value ', '}}'],
[' post '],
' pre {{ value }} post ',
],
]);
});
it('should not set the end source span for void elements', () => {
expect(humanizeDomSourceSpans(parser.parse('<div><br></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0, '<div><br></div>', '<div>', '</div>'],
[html.Element, 'br', 1, '<br>', '<br>', null],
]);
});
it('should not set the end source span for multiple void elements', () => {
expect(humanizeDomSourceSpans(parser.parse('<div><br><hr></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0, '<div><br><hr></div>', '<div>', '</div>'],
[html.Element, 'br', 1, '<br>', '<br>', null],
[html.Element, 'hr', 1, '<hr>', '<hr>', null],
]);
});
it('should not set the end source span for standalone void elements', () => {
expect(humanizeDomSourceSpans(parser.parse('<br>', 'TestComp'))).toEqual([
[html.Element, 'br', 0, '<br>', '<br>', null],
]);
});
it('should set the end source span for standalone self-closing elements', () => {
expect(humanizeDomSourceSpans(parser.parse('<br/>', 'TestComp'))).toEqual([
[html.Element, 'br', 0, '<br/>', '<br/>', '<br/>'],
]);
});
it('should set the end source span for self-closing elements', () => {
expect(humanizeDomSourceSpans(parser.parse('<div><br/></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0, '<div><br/></div>', '<div>', '</div>'],
[html.Element, 'br', 1, '<br/>', '<br/>', '<br/>'],
]);
});
it('should not include leading trivia from the following node of an element in the end source', () => {
expect(
humanizeDomSourceSpans(
parser.parse('<input type="text" />\n\n\n <span>\n</span>', 'TestComp', {
leadingTriviaChars: [' ', '\n', '\r', '\t'],
}),
),
).toEqual([
[
html.Element,
'input',
0,
'<input type="text" />',
'<input type="text" />',
'<input type="text" />',
],
[html.Attribute, 'type', 'text', ['text'], 'type="text"'],
[html.Text, '\n\n\n ', 0, ['\n\n\n '], '', '\n\n\n '],
[html.Element, 'span', 0, '<span>\n</span>', '<span>', '</span>'],
[html.Text, '\n', 1, ['\n'], '', '\n'],
]);
});
it('should not set the end source span for elements that are implicitly closed', () => {
expect(humanizeDomSourceSpans(parser.parse('<div><p></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0, '<div><p></div>', '<div>', '</div>'],
[html.Element, 'p', 1, '<p>', '<p>', null],
]);
expect(humanizeDomSourceSpans(parser.parse('<div><li>A<li>B</div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0, '<div><li>A<li>B</div>', '<div>', '</div>'],
[html.Element, 'li', 1, '<li>', '<li>', null],
[html.Text, 'A', 2, ['A'], 'A'],
[html.Element, 'li', 1, '<li>', '<li>', null],
[html.Text, 'B', 2, ['B'], 'B'],
]);
});
it('should support expansion form', () => {
expect(
humanizeDomSourceSpans(
parser.parse('<div>{count, plural, =0 {msg}}</div>', 'TestComp', {
tokenizeExpansionForms: true,
}),
),
).toEqual([
[html.Element, 'div', 0, '<div>{count, plural, =0 {msg}}</div>', '<div>', '</div>'],
[html.Expansion, 'count', 'plural', 1, '{count, plural, =0 {msg}}'],
[html.ExpansionCase, '=0', 2, '=0 {msg}'],
]);
});
it('should not report a value span for an attribute without a value', () => {
const ast = parser.parse('<div bar></div>', 'TestComp');
expect((ast.rootNodes[0] as html.Element).attrs[0].valueSpan).toBeUndefined();
}); | {
"end_byte": 49133,
"start_byte": 41794,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_49141_53639 | it('should report a value span for an attribute with a value', () => {
const ast = parser.parse('<div bar="12"></div>', 'TestComp');
const attr = (ast.rootNodes[0] as html.Element).attrs[0];
expect(attr.valueSpan!.start.offset).toEqual(10);
expect(attr.valueSpan!.end.offset).toEqual(12);
});
it('should report a value span for an unquoted attribute value', () => {
const ast = parser.parse('<div bar=12></div>', 'TestComp');
const attr = (ast.rootNodes[0] as html.Element).attrs[0];
expect(attr.valueSpan!.start.offset).toEqual(9);
expect(attr.valueSpan!.end.offset).toEqual(11);
});
});
describe('visitor', () => {
it('should visit text nodes', () => {
const result = humanizeDom(parser.parse('text', 'TestComp'));
expect(result).toEqual([[html.Text, 'text', 0, ['text']]]);
});
it('should visit element nodes', () => {
const result = humanizeDom(parser.parse('<div></div>', 'TestComp'));
expect(result).toEqual([[html.Element, 'div', 0]]);
});
it('should visit attribute nodes', () => {
const result = humanizeDom(parser.parse('<div id="foo"></div>', 'TestComp'));
expect(result).toContain([html.Attribute, 'id', 'foo', ['foo']]);
});
it('should visit all nodes', () => {
const result = parser.parse(
'<div id="foo"><span id="bar">a</span><span>b</span></div>',
'TestComp',
);
const accumulator: html.Node[] = [];
const visitor = new (class implements html.Visitor {
visit(node: html.Node, context: any) {
accumulator.push(node);
}
visitElement(element: html.Element, context: any): any {
html.visitAll(this, element.attrs);
html.visitAll(this, element.children);
}
visitAttribute(attribute: html.Attribute, context: any): any {}
visitText(text: html.Text, context: any): any {}
visitComment(comment: html.Comment, context: any): any {}
visitExpansion(expansion: html.Expansion, context: any): any {
html.visitAll(this, expansion.cases);
}
visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any {}
visitBlock(block: html.Block, context: any) {
html.visitAll(this, block.parameters);
html.visitAll(this, block.children);
}
visitBlockParameter(parameter: html.BlockParameter, context: any) {}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {}
})();
html.visitAll(visitor, result.rootNodes);
expect(accumulator.map((n) => n.constructor)).toEqual([
html.Element,
html.Attribute,
html.Element,
html.Attribute,
html.Text,
html.Element,
html.Text,
]);
});
it('should skip typed visit if visit() returns a truthy value', () => {
const visitor = new (class implements html.Visitor {
visit(node: html.Node, context: any) {
return true;
}
visitElement(element: html.Element, context: any): any {
throw Error('Unexpected');
}
visitAttribute(attribute: html.Attribute, context: any): any {
throw Error('Unexpected');
}
visitText(text: html.Text, context: any): any {
throw Error('Unexpected');
}
visitComment(comment: html.Comment, context: any): any {
throw Error('Unexpected');
}
visitExpansion(expansion: html.Expansion, context: any): any {
throw Error('Unexpected');
}
visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any {
throw Error('Unexpected');
}
visitBlock(block: html.Block, context: any) {
throw Error('Unexpected');
}
visitBlockParameter(parameter: html.BlockParameter, context: any) {
throw Error('Unexpected');
}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {
throw Error('Unexpected');
}
})();
const result = parser.parse('<div id="foo"></div><div id="bar"></div>', 'TestComp');
const traversal = html.visitAll(visitor, result.rootNodes);
expect(traversal).toEqual([true, true]);
});
}); | {
"end_byte": 53639,
"start_byte": 49141,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_parser_spec.ts_53645_59449 | describe('errors', () => {
it('should report unexpected closing tags', () => {
const errors = parser.parse('<div></p></div>', 'TestComp').errors;
expect(errors.length).toEqual(1);
expect(humanizeErrors(errors)).toEqual([
[
'p',
'Unexpected closing tag "p". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:5',
],
]);
});
it('gets correct close tag for parent when a child is not closed', () => {
const {errors, rootNodes} = parser.parse('<div><span></div>', 'TestComp');
expect(errors.length).toEqual(1);
expect(humanizeErrors(errors)).toEqual([
[
'div',
'Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:11',
],
]);
expect(humanizeNodes(rootNodes, true)).toEqual([
[html.Element, 'div', 0, '<div><span></div>', '<div>', '</div>'],
[html.Element, 'span', 1, '<span>', '<span>', null],
]);
});
describe('incomplete element tag', () => {
it('should parse and report incomplete tags after the tag name', () => {
const {errors, rootNodes} = parser.parse('<div<span><div </span>', 'TestComp');
expect(humanizeNodes(rootNodes, true)).toEqual([
[html.Element, 'div', 0, '<div', '<div', null],
[html.Element, 'span', 0, '<span><div </span>', '<span>', '</span>'],
[html.Element, 'div', 1, '<div ', '<div ', null],
]);
expect(humanizeErrors(errors)).toEqual([
['div', 'Opening tag "div" not terminated.', '0:0'],
['div', 'Opening tag "div" not terminated.', '0:10'],
]);
});
it('should parse and report incomplete tags after attribute', () => {
const {errors, rootNodes} = parser.parse('<div class="hi" sty<span></span>', 'TestComp');
expect(humanizeNodes(rootNodes, true)).toEqual([
[html.Element, 'div', 0, '<div class="hi" sty', '<div class="hi" sty', null],
[html.Attribute, 'class', 'hi', ['hi'], 'class="hi"'],
[html.Attribute, 'sty', '', 'sty'],
[html.Element, 'span', 0, '<span></span>', '<span>', '</span>'],
]);
expect(humanizeErrors(errors)).toEqual([
['div', 'Opening tag "div" not terminated.', '0:0'],
]);
});
it('should parse and report incomplete tags after quote', () => {
const {errors, rootNodes} = parser.parse('<div "<span></span>', 'TestComp');
expect(humanizeNodes(rootNodes, true)).toEqual([
[html.Element, 'div', 0, '<div ', '<div ', null],
[html.Text, '"', 0, ['"'], '"'],
[html.Element, 'span', 0, '<span></span>', '<span>', '</span>'],
]);
expect(humanizeErrors(errors)).toEqual([
['div', 'Opening tag "div" not terminated.', '0:0'],
]);
});
it('should report subsequent open tags without proper close tag', () => {
const errors = parser.parse('<div</div>', 'TestComp').errors;
expect(errors.length).toEqual(2);
expect(humanizeErrors(errors)).toEqual([
['div', 'Opening tag "div" not terminated.', '0:0'],
// TODO(ayazhafiz): the following error is unnecessary and can be pruned if we keep
// track of the incomplete tag names.
[
'div',
'Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:4',
],
]);
});
});
it('should report closing tag for void elements', () => {
const errors = parser.parse('<input></input>', 'TestComp').errors;
expect(errors.length).toEqual(1);
expect(humanizeErrors(errors)).toEqual([
['input', 'Void elements do not have end tags "input"', '0:7'],
]);
});
it('should report self closing html element', () => {
const errors = parser.parse('<p />', 'TestComp').errors;
expect(errors.length).toEqual(1);
expect(humanizeErrors(errors)).toEqual([
['p', 'Only void, custom and foreign elements can be self closed "p"', '0:0'],
]);
});
it('should not report self closing custom element', () => {
expect(parser.parse('<my-cmp />', 'TestComp').errors).toEqual([]);
});
it('should also report lexer errors', () => {
const errors = parser.parse('<!-err--><div></p></div>', 'TestComp').errors;
expect(errors.length).toEqual(2);
expect(humanizeErrors(errors)).toEqual([
[TokenType.COMMENT_START, 'Unexpected character "e"', '0:3'],
[
'p',
'Unexpected closing tag "p". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:14',
],
]);
});
});
});
});
export function humanizeErrors(errors: ParseError[]): any[] {
return errors.map((e) => {
if (e instanceof TreeError) {
// Parser errors
return [<any>e.elementName, e.msg, humanizeLineColumn(e.span.start)];
}
// Tokenizer errors
return [(<any>e).tokenType, e.msg, humanizeLineColumn(e.span.start)];
});
} | {
"end_byte": 59449,
"start_byte": 53645,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_parser_spec.ts"
} |
angular/packages/compiler/test/ml_parser/html_whitespaces_spec.ts_0_6093 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as html from '../../src/ml_parser/ast';
import {NGSP_UNICODE} from '../../src/ml_parser/entities';
import {HtmlParser} from '../../src/ml_parser/html_parser';
import {PRESERVE_WS_ATTR_NAME, removeWhitespaces} from '../../src/ml_parser/html_whitespaces';
import {TokenizeOptions} from '../../src/ml_parser/lexer';
import {humanizeDom} from './ast_spec_utils';
describe('removeWhitespaces', () => {
function parseAndRemoveWS(template: string, options?: TokenizeOptions): any[] {
return humanizeDom(
removeWhitespaces(
new HtmlParser().parse(template, 'TestComp', options),
true /* preserveSignificantWhitespace */,
),
);
}
it('should remove blank text nodes', () => {
expect(parseAndRemoveWS(' ')).toEqual([]);
expect(parseAndRemoveWS('\n')).toEqual([]);
expect(parseAndRemoveWS('\t')).toEqual([]);
expect(parseAndRemoveWS(' \t \n ')).toEqual([]);
});
it('should remove whitespaces (space, tab, new line) between elements', () => {
expect(parseAndRemoveWS('<br> <br>\t<br>\n<br>')).toEqual([
[html.Element, 'br', 0],
[html.Element, 'br', 0],
[html.Element, 'br', 0],
[html.Element, 'br', 0],
]);
});
it('should remove whitespaces from child text nodes', () => {
expect(parseAndRemoveWS('<div><span> </span></div>')).toEqual([
[html.Element, 'div', 0],
[html.Element, 'span', 1],
]);
});
it('should remove whitespaces from the beginning and end of a template', () => {
expect(parseAndRemoveWS(` <br>\t`)).toEqual([[html.Element, 'br', 0]]);
});
it('should convert &ngsp; to a space and preserve it', () => {
expect(parseAndRemoveWS('<div><span>foo</span>&ngsp;<span>bar</span></div>')).toEqual([
[html.Element, 'div', 0],
[html.Element, 'span', 1],
[html.Text, 'foo', 2, ['foo']],
[html.Text, ' ', 1, [''], [NGSP_UNICODE, '&ngsp;'], ['']],
[html.Element, 'span', 1],
[html.Text, 'bar', 2, ['bar']],
]);
});
it('should replace multiple whitespaces with one space', () => {
expect(parseAndRemoveWS('\n\n\nfoo\t\t\t')).toEqual([[html.Text, ' foo ', 0, [' foo ']]]);
expect(parseAndRemoveWS(' \n foo \t ')).toEqual([[html.Text, ' foo ', 0, [' foo ']]]);
});
it('should remove whitespace inside of blocks', () => {
const markup = '@if (cond) {<br> <br>\t<br>\n<br>}';
expect(parseAndRemoveWS(markup)).toEqual([
[html.Block, 'if', 0],
[html.BlockParameter, 'cond'],
[html.Element, 'br', 1],
[html.Element, 'br', 1],
[html.Element, 'br', 1],
[html.Element, 'br', 1],
]);
});
it('should not replace ', () => {
expect(parseAndRemoveWS(' ')).toEqual([
[html.Text, '\u00a0', 0, [''], ['\u00a0', ' '], ['']],
]);
});
it('should not replace sequences of ', () => {
expect(parseAndRemoveWS(' foo ')).toEqual([
[
html.Text,
'\u00a0\u00a0foo\u00a0\u00a0',
0,
[''],
['\u00a0', ' '],
[''],
['\u00a0', ' '],
['foo'],
['\u00a0', ' '],
[''],
['\u00a0', ' '],
[''],
],
]);
});
it('should not replace single tab and newline with spaces', () => {
expect(parseAndRemoveWS('\nfoo')).toEqual([[html.Text, '\nfoo', 0, ['\nfoo']]]);
expect(parseAndRemoveWS('\tfoo')).toEqual([[html.Text, '\tfoo', 0, ['\tfoo']]]);
});
it('should preserve single whitespaces between interpolations', () => {
expect(parseAndRemoveWS(`{{fooExp}} {{barExp}}`)).toEqual([
[
html.Text,
'{{fooExp}} {{barExp}}',
0,
[''],
['{{', 'fooExp', '}}'],
[' '],
['{{', 'barExp', '}}'],
[''],
],
]);
expect(parseAndRemoveWS(`{{fooExp}}\t{{barExp}}`)).toEqual([
[
html.Text,
'{{fooExp}}\t{{barExp}}',
0,
[''],
['{{', 'fooExp', '}}'],
['\t'],
['{{', 'barExp', '}}'],
[''],
],
]);
expect(parseAndRemoveWS(`{{fooExp}}\n{{barExp}}`)).toEqual([
[
html.Text,
'{{fooExp}}\n{{barExp}}',
0,
[''],
['{{', 'fooExp', '}}'],
['\n'],
['{{', 'barExp', '}}'],
[''],
],
]);
});
it('should preserve whitespaces around interpolations', () => {
expect(parseAndRemoveWS(` {{exp}} `)).toEqual([
[html.Text, ' {{exp}} ', 0, [' '], ['{{', 'exp', '}}'], [' ']],
]);
});
it('should preserve whitespaces around ICU expansions', () => {
expect(
parseAndRemoveWS(`<span> {a, b, =4 {c}} </span>`, {tokenizeExpansionForms: true}),
).toEqual([
[html.Element, 'span', 0],
[html.Text, ' ', 1, [' ']],
[html.Expansion, 'a', 'b', 1],
[html.ExpansionCase, '=4', 2],
[html.Text, ' ', 1, [' ']],
]);
});
it('should preserve whitespaces inside <pre> elements', () => {
expect(parseAndRemoveWS(`<pre><strong>foo</strong>\n<strong>bar</strong></pre>`)).toEqual([
[html.Element, 'pre', 0],
[html.Element, 'strong', 1],
[html.Text, 'foo', 2, ['foo']],
[html.Text, '\n', 1, ['\n']],
[html.Element, 'strong', 1],
[html.Text, 'bar', 2, ['bar']],
]);
});
it('should skip whitespace trimming in <textarea>', () => {
expect(parseAndRemoveWS(`<textarea>foo\n\n bar</textarea>`)).toEqual([
[html.Element, 'textarea', 0],
[html.Text, 'foo\n\n bar', 1, ['foo\n\n bar']],
]);
});
it(`should preserve whitespaces inside elements annotated with ${PRESERVE_WS_ATTR_NAME}`, () => {
expect(parseAndRemoveWS(`<div ${PRESERVE_WS_ATTR_NAME}><img> <img></div>`)).toEqual([
[html.Element, 'div', 0],
[html.Element, 'img', 1],
[html.Text, ' ', 1, [' ']],
[html.Element, 'img', 1],
]);
});
});
| {
"end_byte": 6093,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/html_whitespaces_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_0_6484 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {getHtmlTagDefinition} from '../../src/ml_parser/html_tags';
import {TokenError, tokenize, TokenizeOptions, TokenizeResult} from '../../src/ml_parser/lexer';
import {Token, TokenType} from '../../src/ml_parser/tokens';
import {ParseLocation, ParseSourceFile, ParseSourceSpan} from '../../src/parse_util';
describe('HtmlLexer', () => {
describe('line/column numbers', () => {
it('should work without newlines', () => {
expect(tokenizeAndHumanizeLineColumn('<t>a</t>')).toEqual([
[TokenType.TAG_OPEN_START, '0:0'],
[TokenType.TAG_OPEN_END, '0:2'],
[TokenType.TEXT, '0:3'],
[TokenType.TAG_CLOSE, '0:4'],
[TokenType.EOF, '0:8'],
]);
});
it('should work with one newline', () => {
expect(tokenizeAndHumanizeLineColumn('<t>\na</t>')).toEqual([
[TokenType.TAG_OPEN_START, '0:0'],
[TokenType.TAG_OPEN_END, '0:2'],
[TokenType.TEXT, '0:3'],
[TokenType.TAG_CLOSE, '1:1'],
[TokenType.EOF, '1:5'],
]);
});
it('should work with multiple newlines', () => {
expect(tokenizeAndHumanizeLineColumn('<t\n>\na</t>')).toEqual([
[TokenType.TAG_OPEN_START, '0:0'],
[TokenType.TAG_OPEN_END, '1:0'],
[TokenType.TEXT, '1:1'],
[TokenType.TAG_CLOSE, '2:1'],
[TokenType.EOF, '2:5'],
]);
});
it('should work with CR and LF', () => {
expect(tokenizeAndHumanizeLineColumn('<t\n>\r\na\r</t>')).toEqual([
[TokenType.TAG_OPEN_START, '0:0'],
[TokenType.TAG_OPEN_END, '1:0'],
[TokenType.TEXT, '1:1'],
[TokenType.TAG_CLOSE, '2:1'],
[TokenType.EOF, '2:5'],
]);
});
it('should skip over leading trivia for source-span start', () => {
expect(
tokenizeAndHumanizeFullStart('<t>\n \t a</t>', {leadingTriviaChars: ['\n', ' ', '\t']}),
).toEqual([
[TokenType.TAG_OPEN_START, '0:0', '0:0'],
[TokenType.TAG_OPEN_END, '0:2', '0:2'],
[TokenType.TEXT, '1:3', '0:3'],
[TokenType.TAG_CLOSE, '1:4', '1:4'],
[TokenType.EOF, '1:8', '1:8'],
]);
});
});
describe('content ranges', () => {
it('should only process the text within the range', () => {
expect(
tokenizeAndHumanizeSourceSpans(
'pre 1\npre 2\npre 3 `line 1\nline 2\nline 3` post 1\n post 2\n post 3',
{range: {startPos: 19, startLine: 2, startCol: 7, endPos: 39}},
),
).toEqual([
[TokenType.TEXT, 'line 1\nline 2\nline 3'],
[TokenType.EOF, ''],
]);
});
it('should take into account preceding (non-processed) lines and columns', () => {
expect(
tokenizeAndHumanizeLineColumn(
'pre 1\npre 2\npre 3 `line 1\nline 2\nline 3` post 1\n post 2\n post 3',
{range: {startPos: 19, startLine: 2, startCol: 7, endPos: 39}},
),
).toEqual([
[TokenType.TEXT, '2:7'],
[TokenType.EOF, '4:6'],
]);
});
});
describe('comments', () => {
it('should parse comments', () => {
expect(tokenizeAndHumanizeParts('<!--t\ne\rs\r\nt-->')).toEqual([
[TokenType.COMMENT_START],
[TokenType.RAW_TEXT, 't\ne\ns\nt'],
[TokenType.COMMENT_END],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('<!--t\ne\rs\r\nt-->')).toEqual([
[TokenType.COMMENT_START, '<!--'],
[TokenType.RAW_TEXT, 't\ne\rs\r\nt'],
[TokenType.COMMENT_END, '-->'],
[TokenType.EOF, ''],
]);
});
it('should report <!- without -', () => {
expect(tokenizeAndHumanizeErrors('<!-a')).toEqual([
[TokenType.COMMENT_START, 'Unexpected character "a"', '0:3'],
]);
});
it('should report missing end comment', () => {
expect(tokenizeAndHumanizeErrors('<!--')).toEqual([
[TokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:4'],
]);
});
it('should accept comments finishing by too many dashes (even number)', () => {
expect(tokenizeAndHumanizeSourceSpans('<!-- test ---->')).toEqual([
[TokenType.COMMENT_START, '<!--'],
[TokenType.RAW_TEXT, ' test --'],
[TokenType.COMMENT_END, '-->'],
[TokenType.EOF, ''],
]);
});
it('should accept comments finishing by too many dashes (odd number)', () => {
expect(tokenizeAndHumanizeSourceSpans('<!-- test --->')).toEqual([
[TokenType.COMMENT_START, '<!--'],
[TokenType.RAW_TEXT, ' test -'],
[TokenType.COMMENT_END, '-->'],
[TokenType.EOF, ''],
]);
});
});
describe('doctype', () => {
it('should parse doctypes', () => {
expect(tokenizeAndHumanizeParts('<!DOCTYPE html>')).toEqual([
[TokenType.DOC_TYPE, 'DOCTYPE html'],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('<!DOCTYPE html>')).toEqual([
[TokenType.DOC_TYPE, '<!DOCTYPE html>'],
[TokenType.EOF, ''],
]);
});
it('should report missing end doctype', () => {
expect(tokenizeAndHumanizeErrors('<!')).toEqual([
[TokenType.DOC_TYPE, 'Unexpected character "EOF"', '0:2'],
]);
});
});
describe('CDATA', () => {
it('should parse CDATA', () => {
expect(tokenizeAndHumanizeParts('<![CDATA[t\ne\rs\r\nt]]>')).toEqual([
[TokenType.CDATA_START],
[TokenType.RAW_TEXT, 't\ne\ns\nt'],
[TokenType.CDATA_END],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('<![CDATA[t\ne\rs\r\nt]]>')).toEqual([
[TokenType.CDATA_START, '<![CDATA['],
[TokenType.RAW_TEXT, 't\ne\rs\r\nt'],
[TokenType.CDATA_END, ']]>'],
[TokenType.EOF, ''],
]);
});
it('should report <![ without CDATA[', () => {
expect(tokenizeAndHumanizeErrors('<![a')).toEqual([
[TokenType.CDATA_START, 'Unexpected character "a"', '0:3'],
]);
});
it('should report missing end cdata', () => {
expect(tokenizeAndHumanizeErrors('<![CDATA[')).toEqual([
[TokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:9'],
]);
});
}); | {
"end_byte": 6484,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_6488_12176 | describe('open tags', () => {
it('should parse open tags without prefix', () => {
expect(tokenizeAndHumanizeParts('<test>')).toEqual([
[TokenType.TAG_OPEN_START, '', 'test'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse namespace prefix', () => {
expect(tokenizeAndHumanizeParts('<ns1:test>')).toEqual([
[TokenType.TAG_OPEN_START, 'ns1', 'test'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse void tags', () => {
expect(tokenizeAndHumanizeParts('<test/>')).toEqual([
[TokenType.TAG_OPEN_START, '', 'test'],
[TokenType.TAG_OPEN_END_VOID],
[TokenType.EOF],
]);
});
it('should allow whitespace after the tag name', () => {
expect(tokenizeAndHumanizeParts('<test >')).toEqual([
[TokenType.TAG_OPEN_START, '', 'test'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('<test>')).toEqual([
[TokenType.TAG_OPEN_START, '<test'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.EOF, ''],
]);
});
describe('tags', () => {
it('terminated with EOF', () => {
expect(tokenizeAndHumanizeSourceSpans('<div')).toEqual([
[TokenType.INCOMPLETE_TAG_OPEN, '<div'],
[TokenType.EOF, ''],
]);
});
it('after tag name', () => {
expect(tokenizeAndHumanizeSourceSpans('<div<span><div</span>')).toEqual([
[TokenType.INCOMPLETE_TAG_OPEN, '<div'],
[TokenType.TAG_OPEN_START, '<span'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.INCOMPLETE_TAG_OPEN, '<div'],
[TokenType.TAG_CLOSE, '</span>'],
[TokenType.EOF, ''],
]);
});
it('in attribute', () => {
expect(tokenizeAndHumanizeSourceSpans('<div class="hi" sty<span></span>')).toEqual([
[TokenType.INCOMPLETE_TAG_OPEN, '<div'],
[TokenType.ATTR_NAME, 'class'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 'hi'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_NAME, 'sty'],
[TokenType.TAG_OPEN_START, '<span'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TAG_CLOSE, '</span>'],
[TokenType.EOF, ''],
]);
});
it('after quote', () => {
expect(tokenizeAndHumanizeSourceSpans('<div "<span></span>')).toEqual([
[TokenType.INCOMPLETE_TAG_OPEN, '<div'],
[TokenType.TEXT, '"'],
[TokenType.TAG_OPEN_START, '<span'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TAG_CLOSE, '</span>'],
[TokenType.EOF, ''],
]);
});
});
describe('escapable raw text', () => {
it('should parse text', () => {
expect(tokenizeAndHumanizeParts(`<title>t\ne\rs\r\nt</title>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, 't\ne\ns\nt'],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should detect entities', () => {
expect(tokenizeAndHumanizeParts(`<title>&</title>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, ''],
[TokenType.ENCODED_ENTITY, '&', '&'],
[TokenType.ESCAPABLE_RAW_TEXT, ''],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should ignore other opening tags', () => {
expect(tokenizeAndHumanizeParts(`<title>a<div></title>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, 'a<div>'],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should ignore other closing tags', () => {
expect(tokenizeAndHumanizeParts(`<title>a</test></title>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, 'a</test>'],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans(`<title>a</title>`)).toEqual([
[TokenType.TAG_OPEN_START, '<title'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.ESCAPABLE_RAW_TEXT, 'a'],
[TokenType.TAG_CLOSE, '</title>'],
[TokenType.EOF, ''],
]);
});
});
describe('parsable data', () => {
it('should parse an SVG <title> tag', () => {
expect(tokenizeAndHumanizeParts(`<svg:title>test</svg:title>`)).toEqual([
[TokenType.TAG_OPEN_START, 'svg', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'test'],
[TokenType.TAG_CLOSE, 'svg', 'title'],
[TokenType.EOF],
]);
});
it('should parse an SVG <title> tag with children', () => {
expect(tokenizeAndHumanizeParts(`<svg:title><f>test</f></svg:title>`)).toEqual([
[TokenType.TAG_OPEN_START, 'svg', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_OPEN_START, '', 'f'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'test'],
[TokenType.TAG_CLOSE, '', 'f'],
[TokenType.TAG_CLOSE, 'svg', 'title'],
[TokenType.EOF],
]);
});
}); | {
"end_byte": 12176,
"start_byte": 6488,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_12182_18301 | describe('expansion forms', () => {
it('should parse an expansion form', () => {
expect(
tokenizeAndHumanizeParts('{one.two, three, =4 {four} =5 {five} foo {bar} }', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=5'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'five'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, 'foo'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'bar'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
});
it('should parse an expansion form with text elements surrounding it', () => {
expect(
tokenizeAndHumanizeParts('before{one.two, three, =4 {four}}after', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.TEXT, 'before'],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, 'after'],
[TokenType.EOF],
]);
});
it('should parse an expansion form as a tag single child', () => {
expect(
tokenizeAndHumanizeParts('<div><span>{a, b, =4 {c}}</span></div>', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'div'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_OPEN_START, '', 'span'],
[TokenType.TAG_OPEN_END],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'a'],
[TokenType.RAW_TEXT, 'b'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'c'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TAG_CLOSE, '', 'span'],
[TokenType.TAG_CLOSE, '', 'div'],
[TokenType.EOF],
]);
});
it('should parse an expansion form with whitespace surrounding it', () => {
expect(
tokenizeAndHumanizeParts('<div><span> {a, b, =4 {c}} </span></div>', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'div'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_OPEN_START, '', 'span'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, ' '],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'a'],
[TokenType.RAW_TEXT, 'b'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'c'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, ' '],
[TokenType.TAG_CLOSE, '', 'span'],
[TokenType.TAG_CLOSE, '', 'div'],
[TokenType.EOF],
]);
});
it('should parse an expansion forms with elements in it', () => {
expect(
tokenizeAndHumanizeParts('{one.two, three, =4 {four <b>a</b>}}', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four '],
[TokenType.TAG_OPEN_START, '', 'b'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'a'],
[TokenType.TAG_CLOSE, '', 'b'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
});
it('should parse an expansion forms containing an interpolation', () => {
expect(
tokenizeAndHumanizeParts('{one.two, three, =4 {four {{a}}}}', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four '],
[TokenType.INTERPOLATION, '{{', 'a', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
});
it('should parse nested expansion forms', () => {
expect(
tokenizeAndHumanizeParts(`{one.two, three, =4 { {xx, yy, =x {one}} }}`, {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'xx'],
[TokenType.RAW_TEXT, 'yy'],
[TokenType.EXPANSION_CASE_VALUE, '=x'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'one'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, ' '],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
}); | {
"end_byte": 18301,
"start_byte": 12182,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_18309_23420 | describe('[line ending normalization', () => {
describe('{escapedString: true}', () => {
it('should normalize line-endings in expansion forms if `i18nNormalizeLineEndingsInICUs` is true', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n`,
{
tokenizeExpansionForms: true,
escapedString: true,
i18nNormalizeLineEndingsInICUs: true,
},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'You have \nno\n messages'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=1'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'One '],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions).toEqual([]);
});
it('should not normalize line-endings in ICU expressions when `i18nNormalizeLineEndingsInICUs` is not defined', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n`,
{tokenizeExpansionForms: true, escapedString: true},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'You have \nno\n messages'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=1'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'One '],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions!.length).toBe(1);
expect(result.nonNormalizedIcuExpressions![0].sourceSpan.toString()).toEqual(
'\r\n messages.length',
);
});
it('should not normalize line endings in nested expansion forms when `i18nNormalizeLineEndingsInICUs` is not defined', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length, plural,\r\n` +
` =0 { zero \r\n` +
` {\r\n` +
` p.gender, select,\r\n` +
` male {m}\r\n` +
` }\r\n` +
` }\r\n` +
`}`,
{tokenizeExpansionForms: true, escapedString: true},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'zero \n '],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n p.gender'],
[TokenType.RAW_TEXT, 'select'],
[TokenType.EXPANSION_CASE_VALUE, 'male'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'm'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n '],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions!.length).toBe(2);
expect(result.nonNormalizedIcuExpressions![0].sourceSpan.toString()).toEqual(
'\r\n messages.length',
);
expect(result.nonNormalizedIcuExpressions![1].sourceSpan.toString()).toEqual(
'\r\n p.gender',
);
});
}); | {
"end_byte": 23420,
"start_byte": 18309,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_23430_30361 | describe('{escapedString: false}', () => {
it('should normalize line-endings in expansion forms if `i18nNormalizeLineEndingsInICUs` is true', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n`,
{
tokenizeExpansionForms: true,
escapedString: false,
i18nNormalizeLineEndingsInICUs: true,
},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'You have \nno\n messages'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=1'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'One '],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions).toEqual([]);
});
it('should not normalize line-endings in ICU expressions when `i18nNormalizeLineEndingsInICUs` is not defined', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n`,
{tokenizeExpansionForms: true, escapedString: false},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'You have \nno\n messages'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=1'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'One '],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions!.length).toBe(1);
expect(result.nonNormalizedIcuExpressions![0].sourceSpan.toString()).toEqual(
'\r\n messages.length',
);
});
it('should not normalize line endings in nested expansion forms when `i18nNormalizeLineEndingsInICUs` is not defined', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length, plural,\r\n` +
` =0 { zero \r\n` +
` {\r\n` +
` p.gender, select,\r\n` +
` male {m}\r\n` +
` }\r\n` +
` }\r\n` +
`}`,
{tokenizeExpansionForms: true},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'zero \n '],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n p.gender'],
[TokenType.RAW_TEXT, 'select'],
[TokenType.EXPANSION_CASE_VALUE, 'male'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'm'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n '],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions!.length).toBe(2);
expect(result.nonNormalizedIcuExpressions![0].sourceSpan.toString()).toEqual(
'\r\n messages.length',
);
expect(result.nonNormalizedIcuExpressions![1].sourceSpan.toString()).toEqual(
'\r\n p.gender',
);
});
});
});
});
describe('errors', () => {
it('should report unescaped "{" on error', () => {
expect(
tokenizeAndHumanizeErrors(`<p>before { after</p>`, {tokenizeExpansionForms: true}),
).toEqual([
[
TokenType.RAW_TEXT,
`Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)`,
'0:21',
],
]);
});
it('should report unescaped "{" as an error, even after a prematurely terminated interpolation', () => {
expect(
tokenizeAndHumanizeErrors(`<code>{{b}<!---->}</code><pre>import {a} from 'a';</pre>`, {
tokenizeExpansionForms: true,
}),
).toEqual([
[
TokenType.RAW_TEXT,
`Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)`,
'0:56',
],
]);
});
it('should include 2 lines of context in message', () => {
const src = '111\n222\n333\nE\n444\n555\n666\n';
const file = new ParseSourceFile(src, 'file://');
const location = new ParseLocation(file, 12, 123, 456);
const span = new ParseSourceSpan(location, location);
const error = new TokenError('**ERROR**', null!, span);
expect(error.toString()).toEqual(
`**ERROR** ("\n222\n333\n[ERROR ->]E\n444\n555\n"): file://@123:456`,
);
});
});
describe('unicode characters', () => {
it('should support unicode characters', () => {
expect(tokenizeAndHumanizeSourceSpans(`<p>İ</p>`)).toEqual([
[TokenType.TAG_OPEN_START, '<p'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TEXT, 'İ'],
[TokenType.TAG_CLOSE, '</p>'],
[TokenType.EOF, ''],
]);
});
});
| {
"end_byte": 30361,
"start_byte": 23430,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_30367_38158 | scribe('(processing escaped strings)', () => {
it('should unescape standard escape sequences', () => {
expect(tokenizeAndHumanizeParts("\\' \\' \\'", {escapedString: true})).toEqual([
[TokenType.TEXT, "' ' '"],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\" \\" \\"', {escapedString: true})).toEqual([
[TokenType.TEXT, '" " "'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\` \\` \\`', {escapedString: true})).toEqual([
[TokenType.TEXT, '` ` `'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\\\ \\\\ \\\\', {escapedString: true})).toEqual([
[TokenType.TEXT, '\\ \\ \\'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\n \\n \\n', {escapedString: true})).toEqual([
[TokenType.TEXT, '\n \n \n'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\r{{\\r}}\\r', {escapedString: true})).toEqual([
// post processing converts `\r` to `\n`
[TokenType.TEXT, '\n'],
[TokenType.INTERPOLATION, '{{', '\n', '}}'],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\v \\v \\v', {escapedString: true})).toEqual([
[TokenType.TEXT, '\v \v \v'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\t \\t \\t', {escapedString: true})).toEqual([
[TokenType.TEXT, '\t \t \t'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\b \\b \\b', {escapedString: true})).toEqual([
[TokenType.TEXT, '\b \b \b'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\f \\f \\f', {escapedString: true})).toEqual([
[TokenType.TEXT, '\f \f \f'],
[TokenType.EOF],
]);
expect(
tokenizeAndHumanizeParts('\\\' \\" \\` \\\\ \\n \\r \\v \\t \\b \\f', {
escapedString: true,
}),
).toEqual([[TokenType.TEXT, '\' " ` \\ \n \n \v \t \b \f'], [TokenType.EOF]]);
});
it('should unescape null sequences', () => {
expect(tokenizeAndHumanizeParts('\\0', {escapedString: true})).toEqual([[TokenType.EOF]]);
// \09 is not an octal number so the \0 is taken as EOF
expect(tokenizeAndHumanizeParts('\\09', {escapedString: true})).toEqual([[TokenType.EOF]]);
});
it('should unescape octal sequences', () => {
// \19 is read as an octal `\1` followed by a normal char `9`
// \1234 is read as an octal `\123` followed by a normal char `4`
// \999 is not an octal number so its backslash just gets removed.
expect(
tokenizeAndHumanizeParts('\\001 \\01 \\1 \\12 \\223 \\19 \\2234 \\999', {
escapedString: true,
}),
).toEqual([[TokenType.TEXT, '\x01 \x01 \x01 \x0A \x93 \x019 \x934 999'], [TokenType.EOF]]);
});
it('should unescape hex sequences', () => {
expect(tokenizeAndHumanizeParts('\\x12 \\x4F \\xDC', {escapedString: true})).toEqual([
[TokenType.TEXT, '\x12 \x4F \xDC'],
[TokenType.EOF],
]);
});
it('should report an error on an invalid hex sequence', () => {
expect(tokenizeAndHumanizeErrors('\\xGG', {escapedString: true})).toEqual([
[null, 'Invalid hexadecimal escape sequence', '0:2'],
]);
expect(tokenizeAndHumanizeErrors('abc \\x xyz', {escapedString: true})).toEqual([
[TokenType.TEXT, 'Invalid hexadecimal escape sequence', '0:6'],
]);
expect(tokenizeAndHumanizeErrors('abc\\x', {escapedString: true})).toEqual([
[TokenType.TEXT, 'Unexpected character "EOF"', '0:5'],
]);
});
it('should unescape fixed length Unicode sequences', () => {
expect(tokenizeAndHumanizeParts('\\u0123 \\uABCD', {escapedString: true})).toEqual([
[TokenType.TEXT, '\u0123 \uABCD'],
[TokenType.EOF],
]);
});
it('should error on an invalid fixed length Unicode sequence', () => {
expect(tokenizeAndHumanizeErrors('\\uGGGG', {escapedString: true})).toEqual([
[null, 'Invalid hexadecimal escape sequence', '0:2'],
]);
});
it('should unescape variable length Unicode sequences', () => {
expect(
tokenizeAndHumanizeParts('\\u{01} \\u{ABC} \\u{1234} \\u{123AB}', {escapedString: true}),
).toEqual([[TokenType.TEXT, '\u{01} \u{ABC} \u{1234} \u{123AB}'], [TokenType.EOF]]);
});
it('should error on an invalid variable length Unicode sequence', () => {
expect(tokenizeAndHumanizeErrors('\\u{GG}', {escapedString: true})).toEqual([
[null, 'Invalid hexadecimal escape sequence', '0:3'],
]);
});
it('should unescape line continuations', () => {
expect(tokenizeAndHumanizeParts('abc\\\ndef', {escapedString: true})).toEqual([
[TokenType.TEXT, 'abcdef'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\\nx\\\ny\\\n', {escapedString: true})).toEqual([
[TokenType.TEXT, 'xy'],
[TokenType.EOF],
]);
});
it('should remove backslash from "non-escape" sequences', () => {
expect(tokenizeAndHumanizeParts('a g ~', {escapedString: true})).toEqual([
[TokenType.TEXT, 'a g ~'],
[TokenType.EOF],
]);
});
it('should unescape sequences in plain text', () => {
expect(
tokenizeAndHumanizeParts('abc\ndef\\nghi\\tjkl\\`\\\'\\"mno', {escapedString: true}),
).toEqual([[TokenType.TEXT, 'abc\ndef\nghi\tjkl`\'"mno'], [TokenType.EOF]]);
});
it('should unescape sequences in raw text', () => {
expect(
tokenizeAndHumanizeParts('<script>abc\ndef\\nghi\\tjkl\\`\\\'\\"mno</script>', {
escapedString: true,
}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'script'],
[TokenType.TAG_OPEN_END],
[TokenType.RAW_TEXT, 'abc\ndef\nghi\tjkl`\'"mno'],
[TokenType.TAG_CLOSE, '', 'script'],
[TokenType.EOF],
]);
});
it('should unescape sequences in escapable raw text', () => {
expect(
tokenizeAndHumanizeParts('<title>abc\ndef\\nghi\\tjkl\\`\\\'\\"mno</title>', {
escapedString: true,
}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, 'abc\ndef\nghi\tjkl`\'"mno'],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should parse over escape sequences in tag definitions', () => {
expect(
tokenizeAndHumanizeParts('<t a=\\"b\\" \\n c=\\\'d\\\'>', {escapedString: true}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_NAME, '', 'c'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.ATTR_VALUE_TEXT, 'd'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse over escaped new line in tag definitions', () => {
const text = '<t\\n></t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
});
| {
"end_byte": 38158,
"start_byte": 30367,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_38166_43419 | ('should parse over escaped characters in tag definitions', () => {
const text = '<t\u{000013}></t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
});
it('should unescape characters in tag names', () => {
const text = '<t\\x64></t\\x64>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 'td'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 'td'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeSourceSpans(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '<t\\x64'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TAG_CLOSE, '</t\\x64>'],
[TokenType.EOF, ''],
]);
});
it('should unescape characters in attributes', () => {
const text = '<t \\x64="\\x65"></t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'd'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 'e'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
});
it('should parse over escaped new line in attribute values', () => {
const text = '<t a=b\\n></t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
});
it('should tokenize the correct span when there are escape sequences', () => {
const text =
'selector: "app-root",\ntemplate: "line 1\\n\\"line 2\\"\\nline 3",\ninputs: []';
const range = {
startPos: 33,
startLine: 1,
startCol: 10,
endPos: 59,
};
expect(tokenizeAndHumanizeParts(text, {range, escapedString: true})).toEqual([
[TokenType.TEXT, 'line 1\n"line 2"\nline 3'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeSourceSpans(text, {range, escapedString: true})).toEqual([
[TokenType.TEXT, 'line 1\\n\\"line 2\\"\\nline 3'],
[TokenType.EOF, ''],
]);
});
it('should account for escape sequences when computing source spans ', () => {
const text =
'<t>line 1</t>\n' + // <- unescaped line break
'<t>line 2</t>\\n' + // <- escaped line break
'<t>line 3\\\n' + // <- line continuation
'</t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'line 1'],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.TEXT, '\n'],
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'line 2'],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.TEXT, '\n'],
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'line 3'], // <- line continuation does not appear in token
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeLineColumn(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '0:0'],
[TokenType.TAG_OPEN_END, '0:2'],
[TokenType.TEXT, '0:3'],
[TokenType.TAG_CLOSE, '0:9'],
[TokenType.TEXT, '0:13'], // <- real newline increments the row
[TokenType.TAG_OPEN_START, '1:0'],
[TokenType.TAG_OPEN_END, '1:2'],
[TokenType.TEXT, '1:3'],
[TokenType.TAG_CLOSE, '1:9'],
[TokenType.TEXT, '1:13'], // <- escaped newline does not increment the row
[TokenType.TAG_OPEN_START, '1:15'],
[TokenType.TAG_OPEN_END, '1:17'],
[TokenType.TEXT, '1:18'], // <- the line continuation increments the row
[TokenType.TAG_CLOSE, '2:0'],
[TokenType.EOF, '2:4'],
]);
expect(tokenizeAndHumanizeSourceSpans(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '<t'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TEXT, 'line 1'],
[TokenType.TAG_CLOSE, '</t>'],
[TokenType.TEXT, '\n'],
[TokenType.TAG_OPEN_START, '<t'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TEXT, 'line 2'],
[TokenType.TAG_CLOSE, '</t>'],
[TokenType.TEXT, '\\n'],
[TokenType.TAG_OPEN_START, '<t'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TEXT, 'line 3\\\n'],
[TokenType.TAG_CLOSE, '</t>'],
[TokenType.EOF, ''],
]);
});
});
| {
"end_byte": 43419,
"start_byte": 38166,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_43425_51966 | scribe('blocks', () => {
it('should parse a block without parameters', () => {
const expected = [
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
];
expect(tokenizeAndHumanizeParts('@foo {hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo () {hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo(){hello}')).toEqual(expected);
});
it('should parse a block with parameters', () => {
expect(tokenizeAndHumanizeParts('@for (item of items; track item.id) {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'for'],
[TokenType.BLOCK_PARAMETER, 'item of items'],
[TokenType.BLOCK_PARAMETER, 'track item.id'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with a trailing semicolon after the parameters', () => {
expect(tokenizeAndHumanizeParts('@for (item of items;) {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'for'],
[TokenType.BLOCK_PARAMETER, 'item of items'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with a space in its name', () => {
expect(tokenizeAndHumanizeParts('@else if {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'else if'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@else if (foo !== 2) {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'else if'],
[TokenType.BLOCK_PARAMETER, 'foo !== 2'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with an arbitrary amount of spaces around the parentheses', () => {
const expected = [
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_PARAMETER, 'a'],
[TokenType.BLOCK_PARAMETER, 'b'],
[TokenType.BLOCK_PARAMETER, 'c'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
];
expect(tokenizeAndHumanizeParts('@foo(a; b; c){hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo (a; b; c) {hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo(a; b; c) {hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo (a; b; c){hello}')).toEqual(expected);
});
it('should parse a block with multiple trailing semicolons', () => {
expect(tokenizeAndHumanizeParts('@for (item of items;;;;;) {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'for'],
[TokenType.BLOCK_PARAMETER, 'item of items'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with trailing whitespace', () => {
expect(tokenizeAndHumanizeParts('@foo {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with no trailing semicolon', () => {
expect(tokenizeAndHumanizeParts('@for (item of items){hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'for'],
[TokenType.BLOCK_PARAMETER, 'item of items'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should handle semicolons, braces and parentheses used in a block parameter', () => {
const input = `@foo (a === ";"; b === ')'; c === "("; d === '}'; e === "{") {hello}`;
expect(tokenizeAndHumanizeParts(input)).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_PARAMETER, `a === ";"`],
[TokenType.BLOCK_PARAMETER, `b === ')'`],
[TokenType.BLOCK_PARAMETER, `c === "("`],
[TokenType.BLOCK_PARAMETER, `d === '}'`],
[TokenType.BLOCK_PARAMETER, `e === "{"`],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should handle object literals and function calls in block parameters', () => {
expect(
tokenizeAndHumanizeParts(
`@foo (on a({a: 1, b: 2}, false, {c: 3}); when b({d: 4})) {hello}`,
),
).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_PARAMETER, 'on a({a: 1, b: 2}, false, {c: 3})'],
[TokenType.BLOCK_PARAMETER, 'when b({d: 4})'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse block with unclosed parameters', () => {
expect(tokenizeAndHumanizeParts(`@foo (a === b {hello}`)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, 'foo'],
[TokenType.BLOCK_PARAMETER, 'a === b {hello}'],
[TokenType.EOF],
]);
});
it('should parse block with stray parentheses in the parameter position', () => {
expect(tokenizeAndHumanizeParts(`@foo a === b) {hello}`)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, 'foo a'],
[TokenType.TEXT, '=== b) {hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse @ as an incomplete block', () => {
expect(tokenizeAndHumanizeParts(`@`)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, ''],
[TokenType.EOF],
]);
});
it('should parse space followed by @ as an incomplete block', () => {
expect(tokenizeAndHumanizeParts(` @`)).toEqual([
[TokenType.TEXT, ' '],
[TokenType.INCOMPLETE_BLOCK_OPEN, ''],
[TokenType.EOF],
]);
});
it('should parse @ followed by space as an incomplete block', () => {
expect(tokenizeAndHumanizeParts(`@ `)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, ''],
[TokenType.TEXT, ' '],
[TokenType.EOF],
]);
});
it('should parse @ followed by newline and text as an incomplete block', () => {
expect(tokenizeAndHumanizeParts(`@\nfoo`)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, ''],
[TokenType.TEXT, '\nfoo'],
[TokenType.EOF],
]);
});
it('should parse incomplete block with no name', () => {
expect(tokenizeAndHumanizeParts(`foo bar @ baz clink`)).toEqual([
[TokenType.TEXT, 'foo bar '],
[TokenType.INCOMPLETE_BLOCK_OPEN, ''],
[TokenType.TEXT, ' baz clink'],
[TokenType.EOF],
]);
});
it('should parse incomplete block with space, then name', () => {
expect(tokenizeAndHumanizeParts(`@ if`)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, ''],
[TokenType.TEXT, ' if'],
[TokenType.EOF],
]);
});
it('should report invalid quotes in a parameter', () => {
expect(tokenizeAndHumanizeErrors(`@foo (a === ") {hello}`)).toEqual([
[TokenType.BLOCK_PARAMETER, 'Unexpected character "EOF"', '0:22'],
]);
expect(tokenizeAndHumanizeErrors(`@foo (a === "hi') {hello}`)).toEqual([
[TokenType.BLOCK_PARAMETER, 'Unexpected character "EOF"', '0:25'],
]);
});
it('should report unclosed object literal inside a parameter', () => {
expect(tokenizeAndHumanizeParts(`@foo ({invalid: true) hello}`)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, 'foo'],
[TokenType.BLOCK_PARAMETER, '{invalid: true'],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
| {
"end_byte": 51966,
"start_byte": 43425,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_51974_59191 | ('should handle a semicolon used in a nested string inside a block parameter', () => {
expect(tokenizeAndHumanizeParts(`@if (condition === "';'") {hello}`)).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, `condition === "';'"`],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should handle a semicolon next to an escaped quote used in a block parameter', () => {
expect(tokenizeAndHumanizeParts('@if (condition === "\\";") {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'condition === "\\";"'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse mixed text and html content in a block', () => {
expect(tokenizeAndHumanizeParts('@if (a === 1) {foo <b>bar</b> baz}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'a === 1'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'foo '],
[TokenType.TAG_OPEN_START, '', 'b'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'bar'],
[TokenType.TAG_CLOSE, '', 'b'],
[TokenType.TEXT, ' baz'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse HTML tags with attributes containing curly braces inside blocks', () => {
expect(tokenizeAndHumanizeParts('@if (a === 1) {<div a="}" b="{"></div>}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'a === 1'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TAG_OPEN_START, '', 'div'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, '}'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_NAME, '', 'b'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, '{'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 'div'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse HTML tags with attribute containing block syntax', () => {
expect(tokenizeAndHumanizeParts('<div a="@if (foo) {}"></div>')).toEqual([
[TokenType.TAG_OPEN_START, '', 'div'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, '@if (foo) {}'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 'div'],
[TokenType.EOF],
]);
});
it('should parse nested blocks', () => {
expect(
tokenizeAndHumanizeParts(
'@if (a) {' +
'hello a' +
'@if {' +
'hello unnamed' +
'@if (b) {' +
'hello b' +
'@if (c) {' +
'hello c' +
'}' +
'}' +
'}' +
'}',
),
).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'a'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello a'],
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello unnamed'],
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'b'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello b'],
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'c'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello c'],
[TokenType.BLOCK_CLOSE],
[TokenType.BLOCK_CLOSE],
[TokenType.BLOCK_CLOSE],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block containing an expansion', () => {
const result = tokenizeAndHumanizeParts(
'@foo {{one.two, three, =4 {four} =5 {five} foo {bar} }}',
{tokenizeExpansionForms: true},
);
expect(result).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_OPEN_END],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=5'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'five'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, 'foo'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'bar'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block containing an interpolation', () => {
expect(tokenizeAndHumanizeParts('@foo {{{message}}}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse an incomplete block start without parameters with surrounding text', () => {
expect(tokenizeAndHumanizeParts('My email frodo@baggins.com')).toEqual([
[TokenType.TEXT, 'My email frodo'],
[TokenType.INCOMPLETE_BLOCK_OPEN, 'baggins'],
[TokenType.TEXT, '.com'],
[TokenType.EOF],
]);
});
it('should parse an incomplete block start at the end of the input', () => {
expect(tokenizeAndHumanizeParts('My username is @frodo')).toEqual([
[TokenType.TEXT, 'My username is '],
[TokenType.INCOMPLETE_BLOCK_OPEN, 'frodo'],
[TokenType.EOF],
]);
});
it('should parse an incomplete block start with parentheses but without params', () => {
expect(tokenizeAndHumanizeParts('Use the @Input() decorator')).toEqual([
[TokenType.TEXT, 'Use the '],
[TokenType.INCOMPLETE_BLOCK_OPEN, 'Input'],
[TokenType.TEXT, 'decorator'],
[TokenType.EOF],
]);
});
it('should parse an incomplete block start with parentheses and params', () => {
expect(tokenizeAndHumanizeParts('Use @Input({alias: "foo"}) to alias the input')).toEqual([
[TokenType.TEXT, 'Use '],
[TokenType.INCOMPLETE_BLOCK_OPEN, 'Input'],
[TokenType.BLOCK_PARAMETER, '{alias: "foo"}'],
[TokenType.TEXT, 'to alias the input'],
[TokenType.EOF],
]);
});
});
});
| {
"end_byte": 59191,
"start_byte": 51974,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_59195_66290 | scribe('@let declarations', () => {
it('should parse a @let declaration', () => {
expect(tokenizeAndHumanizeParts('@let foo = 123 + 456;')).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '123 + 456'],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
it('should parse @let declarations with arbitrary number of spaces', () => {
const expected = [
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '123 + 456'],
[TokenType.LET_END],
[TokenType.EOF],
];
expect(
tokenizeAndHumanizeParts('@let foo = 123 + 456;'),
).toEqual(expected);
expect(tokenizeAndHumanizeParts('@let foo=123 + 456;')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@let foo =123 + 456;')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@let foo= 123 + 456;')).toEqual(expected);
});
it('should parse a @let declaration with newlines before/after its name', () => {
const expected = [
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '123'],
[TokenType.LET_END],
[TokenType.EOF],
];
expect(tokenizeAndHumanizeParts('@let\nfoo = 123;')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@let \nfoo = 123;')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@let \n foo = 123;')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@let foo\n= 123;')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@let foo\n = 123;')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@let foo \n = 123;')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@let \n foo \n = 123;')).toEqual(expected);
});
it('should parse a @let declaration with new lines in its value', () => {
expect(tokenizeAndHumanizeParts('@let foo = \n123 + \n 456 + \n789\n;')).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '123 + \n 456 + \n789\n'],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
it('should parse a @let declaration inside of a block', () => {
expect(tokenizeAndHumanizeParts('@block {@let foo = 123 + 456;}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'block'],
[TokenType.BLOCK_OPEN_END],
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '123 + 456'],
[TokenType.LET_END],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse @let declaration using semicolon inside of a string', () => {
expect(tokenizeAndHumanizeParts(`@let foo = 'a; b';`)).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, `'a; b'`],
[TokenType.LET_END],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts(`@let foo = "';'";`)).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, `"';'"`],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
it('should parse @let declaration using escaped quotes in a string', () => {
const markup = `@let foo = '\\';\\'' + "\\",";`;
expect(tokenizeAndHumanizeParts(markup)).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, `'\\';\\'' + "\\","`],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
it('should parse @let declaration using function calls in its value', () => {
const markup = '@let foo = fn(a, b) + fn2(c, d, e);';
expect(tokenizeAndHumanizeParts(markup)).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, 'fn(a, b) + fn2(c, d, e)'],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
it('should parse @let declarations using array literals in their value', () => {
expect(tokenizeAndHumanizeParts('@let foo = [1, 2, 3];')).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '[1, 2, 3]'],
[TokenType.LET_END],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@let foo = [0, [foo[1]], 3];')).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '[0, [foo[1]], 3]'],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
it('should parse @let declarations using object literals', () => {
expect(tokenizeAndHumanizeParts('@let foo = {a: 1, b: {c: something + 2}};')).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '{a: 1, b: {c: something + 2}}'],
[TokenType.LET_END],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@let foo = {};')).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '{}'],
[TokenType.LET_END],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@let foo = {foo: ";"};')).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '{foo: ";"}'],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
it('should parse a @let declaration containing complex expression', () => {
const markup = '@let foo = fn({a: 1, b: [otherFn([{c: ";"}], 321, {d: [\',\']})]});';
expect(tokenizeAndHumanizeParts(markup)).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, 'fn({a: 1, b: [otherFn([{c: ";"}], 321, {d: [\',\']})]})'],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
it('should handle @let declaration with invalid syntax in the value', () => {
expect(tokenizeAndHumanizeErrors(`@let foo = ";`)).toEqual([
[TokenType.LET_VALUE, 'Unexpected character "EOF"', '0:13'],
]);
expect(tokenizeAndHumanizeParts(`@let foo = {a: 1,;`)).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '{a: 1,'],
[TokenType.LET_END],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts(`@let foo = [1, ;`)).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, '[1, '],
[TokenType.LET_END],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts(`@let foo = fn(;`)).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, 'fn('],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
// This case is a bit odd since an `@let` without a value is invalid,
// but it will be validated further down in the parsing pipeline.
it('should parse a @let declaration without a value', () => {
expect(tokenizeAndHumanizeParts('@let foo =;')).toEqual([
[TokenType.LET_START, 'foo'],
[TokenType.LET_VALUE, ''],
[TokenType.LET_END],
[TokenType.EOF],
]);
});
it('should handle no space after @let', () => {
expect(tokenizeAndHumanizeParts('@letFoo = 123;')).toEqual([
[TokenType.INCOMPLETE_LET, '@let'],
[TokenType.TEXT, 'Foo = 123;'],
[TokenType.EOF],
]);
});
| {
"end_byte": 66290,
"start_byte": 59195,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_66296_68441 | ('should handle unsupported characters in the name of @let', () => {
expect(tokenizeAndHumanizeParts('@let foo\\bar = 123;')).toEqual([
[TokenType.INCOMPLETE_LET, 'foo'],
[TokenType.TEXT, '\\bar = 123;'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@let #foo = 123;')).toEqual([
[TokenType.INCOMPLETE_LET, ''],
[TokenType.TEXT, '#foo = 123;'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@let foo\nbar = 123;')).toEqual([
[TokenType.INCOMPLETE_LET, 'foo'],
[TokenType.TEXT, 'bar = 123;'],
[TokenType.EOF],
]);
});
it('should handle digits in the name of an @let', () => {
expect(tokenizeAndHumanizeParts('@let a123 = foo;')).toEqual([
[TokenType.LET_START, 'a123'],
[TokenType.LET_VALUE, 'foo'],
[TokenType.LET_END],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@let 123a = 123;')).toEqual([
[TokenType.INCOMPLETE_LET, ''],
[TokenType.TEXT, '123a = 123;'],
[TokenType.EOF],
]);
});
it('should handle an @let declaration without an ending token', () => {
expect(tokenizeAndHumanizeParts('@let foo = 123 + 456')).toEqual([
[TokenType.INCOMPLETE_LET, 'foo'],
[TokenType.LET_VALUE, '123 + 456'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@let foo = 123 + 456 ')).toEqual([
[TokenType.INCOMPLETE_LET, 'foo'],
[TokenType.LET_VALUE, '123 + 456 '],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@let foo = 123, bar = 456')).toEqual([
[TokenType.INCOMPLETE_LET, 'foo'],
[TokenType.LET_VALUE, '123, bar = 456'],
[TokenType.EOF],
]);
});
it('should not parse @let inside an interpolation', () => {
expect(tokenizeAndHumanizeParts('{{ @let foo = 123; }}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' @let foo = 123; ', '}}'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
});
});
| {
"end_byte": 68441,
"start_byte": 66296,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_68445_75817 | scribe('attributes', () => {
it('should parse attributes without prefix', () => {
expect(tokenizeAndHumanizeParts('<t a>')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes with interpolation', () => {
expect(tokenizeAndHumanizeParts('<t a="{{v}}" b="s{{m}}e" c="s{{m//c}}e">')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ATTR_VALUE_INTERPOLATION, '{{', 'v', '}}'],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_NAME, '', 'b'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 's'],
[TokenType.ATTR_VALUE_INTERPOLATION, '{{', 'm', '}}'],
[TokenType.ATTR_VALUE_TEXT, 'e'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_NAME, '', 'c'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 's'],
[TokenType.ATTR_VALUE_INTERPOLATION, '{{', 'm//c', '}}'],
[TokenType.ATTR_VALUE_TEXT, 'e'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should end interpolation on an unescaped matching quote', () => {
expect(tokenizeAndHumanizeParts('<t a="{{ a \\" \' b ">')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ATTR_VALUE_INTERPOLATION, '{{', ' a \\" \' b '],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts("<t a='{{ a \" \\' b '>")).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ATTR_VALUE_INTERPOLATION, '{{', ' a " \\\' b '],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes with prefix', () => {
expect(tokenizeAndHumanizeParts('<t ns1:a>')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, 'ns1', 'a'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes whose prefix is not valid', () => {
expect(tokenizeAndHumanizeParts('<t (ns1:a)>')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', '(ns1:a)'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes with single quote value', () => {
expect(tokenizeAndHumanizeParts("<t a='b'>")).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes with double quote value', () => {
expect(tokenizeAndHumanizeParts('<t a="b">')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes with unquoted value', () => {
expect(tokenizeAndHumanizeParts('<t a=b>')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes with unquoted interpolation value', () => {
expect(tokenizeAndHumanizeParts('<a a={{link.text}}>')).toEqual([
[TokenType.TAG_OPEN_START, '', 'a'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ATTR_VALUE_INTERPOLATION, '{{', 'link.text', '}}'],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse bound inputs with expressions containing newlines', () => {
expect(
tokenizeAndHumanizeParts(`<app-component
[attr]="[
{text: 'some text',url:'//www.google.com'},
{text:'other text',url:'//www.google.com'}]">`),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'app-component'],
[TokenType.ATTR_NAME, '', '[attr]'],
[TokenType.ATTR_QUOTE, '"'],
[
TokenType.ATTR_VALUE_TEXT,
'[\n' +
" {text: 'some text',url:'//www.google.com'},\n" +
" {text:'other text',url:'//www.google.com'}]",
],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes with empty quoted value', () => {
expect(tokenizeAndHumanizeParts('<t a="">')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse bound inputs with expressions containing newlines', () => {
expect(
tokenizeAndHumanizeParts(`<app-component
[attr]="[
{text: 'some text',url:'//www.google.com'},
{text:'other text',url:'//www.google.com'}]">`),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'app-component'],
[TokenType.ATTR_NAME, '', '[attr]'],
[TokenType.ATTR_QUOTE, '"'],
[
TokenType.ATTR_VALUE_TEXT,
'[\n' +
" {text: 'some text',url:'//www.google.com'},\n" +
" {text:'other text',url:'//www.google.com'}]",
],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should allow whitespace', () => {
expect(tokenizeAndHumanizeParts('<t a = b >')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes with entities in values', () => {
expect(tokenizeAndHumanizeParts('<t a="AA">')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ENCODED_ENTITY, 'A', 'A'],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ENCODED_ENTITY, 'A', 'A'],
[TokenType.ATTR_VALUE_TEXT, ''],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
| {
"end_byte": 75817,
"start_byte": 68445,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_75823_81330 | ('should not decode entities without trailing ";"', () => {
expect(tokenizeAndHumanizeParts('<t a="&" b="c&&d">')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, '&'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_NAME, '', 'b'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 'c&&d'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse attributes with "&" in values', () => {
expect(tokenizeAndHumanizeParts('<t a="b && c &">')).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 'b && c &'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse values with CR and LF', () => {
expect(tokenizeAndHumanizeParts("<t a='t\ne\rs\r\nt'>")).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.ATTR_VALUE_TEXT, 't\ne\ns\nt'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('<t a=b>')).toEqual([
[TokenType.TAG_OPEN_START, '<t'],
[TokenType.ATTR_NAME, 'a'],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.EOF, ''],
]);
});
it('should report missing closing single quote', () => {
expect(tokenizeAndHumanizeErrors("<t a='b>")).toEqual([
[TokenType.ATTR_VALUE_TEXT, 'Unexpected character "EOF"', '0:8'],
]);
});
it('should report missing closing double quote', () => {
expect(tokenizeAndHumanizeErrors('<t a="b>')).toEqual([
[TokenType.ATTR_VALUE_TEXT, 'Unexpected character "EOF"', '0:8'],
]);
});
});
describe('closing tags', () => {
it('should parse closing tags without prefix', () => {
expect(tokenizeAndHumanizeParts('</test>')).toEqual([
[TokenType.TAG_CLOSE, '', 'test'],
[TokenType.EOF],
]);
});
it('should parse closing tags with prefix', () => {
expect(tokenizeAndHumanizeParts('</ns1:test>')).toEqual([
[TokenType.TAG_CLOSE, 'ns1', 'test'],
[TokenType.EOF],
]);
});
it('should allow whitespace', () => {
expect(tokenizeAndHumanizeParts('</ test >')).toEqual([
[TokenType.TAG_CLOSE, '', 'test'],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('</test>')).toEqual([
[TokenType.TAG_CLOSE, '</test>'],
[TokenType.EOF, ''],
]);
});
it('should report missing name after </', () => {
expect(tokenizeAndHumanizeErrors('</')).toEqual([
[TokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:2'],
]);
});
it('should report missing >', () => {
expect(tokenizeAndHumanizeErrors('</test')).toEqual([
[TokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:6'],
]);
});
});
describe('entities', () => {
it('should parse named entities', () => {
expect(tokenizeAndHumanizeParts('a&b')).toEqual([
[TokenType.TEXT, 'a'],
[TokenType.ENCODED_ENTITY, '&', '&'],
[TokenType.TEXT, 'b'],
[TokenType.EOF],
]);
});
it('should parse hexadecimal entities', () => {
expect(tokenizeAndHumanizeParts('AA')).toEqual([
[TokenType.TEXT, ''],
[TokenType.ENCODED_ENTITY, 'A', 'A'],
[TokenType.TEXT, ''],
[TokenType.ENCODED_ENTITY, 'A', 'A'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
});
it('should parse decimal entities', () => {
expect(tokenizeAndHumanizeParts('A')).toEqual([
[TokenType.TEXT, ''],
[TokenType.ENCODED_ENTITY, 'A', 'A'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('a&b')).toEqual([
[TokenType.TEXT, 'a'],
[TokenType.ENCODED_ENTITY, '&'],
[TokenType.TEXT, 'b'],
[TokenType.EOF, ''],
]);
});
it('should report malformed/unknown entities', () => {
expect(tokenizeAndHumanizeErrors('&tbo;')).toEqual([
[
TokenType.ENCODED_ENTITY,
'Unknown entity "tbo" - use the "&#<decimal>;" or "&#x<hex>;" syntax',
'0:0',
],
]);
expect(tokenizeAndHumanizeErrors('sdf;')).toEqual([
[
TokenType.ENCODED_ENTITY,
'Unable to parse entity "s" - decimal character reference entities must end with ";"',
'0:4',
],
]);
expect(tokenizeAndHumanizeErrors('
sdf;')).toEqual([
[
TokenType.ENCODED_ENTITY,
'Unable to parse entity "
s" - hexadecimal character reference entities must end with ";"',
'0:5',
],
]);
expect(tokenizeAndHumanizeErrors('઼')).toEqual([
[TokenType.ENCODED_ENTITY, 'Unexpected character "EOF"', '0:6'],
]);
});
});
| {
"end_byte": 81330,
"start_byte": 75823,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_81334_89182 | scribe('regular text', () => {
it('should parse text', () => {
expect(tokenizeAndHumanizeParts('a')).toEqual([[TokenType.TEXT, 'a'], [TokenType.EOF]]);
});
it('should parse interpolation', () => {
expect(
tokenizeAndHumanizeParts('{{ a }}b{{ c // comment }}d{{ e "}} \' " f }}g{{ h // " i }}'),
).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' a ', '}}'],
[TokenType.TEXT, 'b'],
[TokenType.INTERPOLATION, '{{', ' c // comment ', '}}'],
[TokenType.TEXT, 'd'],
[TokenType.INTERPOLATION, '{{', ' e "}} \' " f ', '}}'],
[TokenType.TEXT, 'g'],
[TokenType.INTERPOLATION, '{{', ' h // " i ', '}}'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeSourceSpans('{{ a }}b{{ c // comment }}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{ a }}'],
[TokenType.TEXT, 'b'],
[TokenType.INTERPOLATION, '{{ c // comment }}'],
[TokenType.TEXT, ''],
[TokenType.EOF, ''],
]);
});
it('should parse interpolation with custom markers', () => {
expect(
tokenizeAndHumanizeParts('{% a %}', {interpolationConfig: {start: '{%', end: '%}'}}),
).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{%', ' a ', '%}'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
});
it('should handle CR & LF in text', () => {
expect(tokenizeAndHumanizeParts('t\ne\rs\r\nt')).toEqual([
[TokenType.TEXT, 't\ne\ns\nt'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeSourceSpans('t\ne\rs\r\nt')).toEqual([
[TokenType.TEXT, 't\ne\rs\r\nt'],
[TokenType.EOF, ''],
]);
});
it('should handle CR & LF in interpolation', () => {
expect(tokenizeAndHumanizeParts('{{t\ne\rs\r\nt}}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', 't\ne\ns\nt', '}}'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeSourceSpans('{{t\ne\rs\r\nt}}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{t\ne\rs\r\nt}}'],
[TokenType.TEXT, ''],
[TokenType.EOF, ''],
]);
});
it('should parse entities', () => {
expect(tokenizeAndHumanizeParts('a&b')).toEqual([
[TokenType.TEXT, 'a'],
[TokenType.ENCODED_ENTITY, '&', '&'],
[TokenType.TEXT, 'b'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeSourceSpans('a&b')).toEqual([
[TokenType.TEXT, 'a'],
[TokenType.ENCODED_ENTITY, '&'],
[TokenType.TEXT, 'b'],
[TokenType.EOF, ''],
]);
});
it('should parse text starting with "&"', () => {
expect(tokenizeAndHumanizeParts('a && b &')).toEqual([
[TokenType.TEXT, 'a && b &'],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('a')).toEqual([
[TokenType.TEXT, 'a'],
[TokenType.EOF, ''],
]);
});
it('should allow "<" in text nodes', () => {
expect(tokenizeAndHumanizeParts('{{ a < b ? c : d }}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' a < b ? c : d ', '}}'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeSourceSpans('<p>a<b</p>')).toEqual([
[TokenType.TAG_OPEN_START, '<p'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TEXT, 'a'],
[TokenType.INCOMPLETE_TAG_OPEN, '<b'],
[TokenType.TAG_CLOSE, '</p>'],
[TokenType.EOF, ''],
]);
expect(tokenizeAndHumanizeParts('< a>')).toEqual([[TokenType.TEXT, '< a>'], [TokenType.EOF]]);
});
it('should break out of interpolation in text token on valid start tag', () => {
expect(tokenizeAndHumanizeParts('{{ a <b && c > d }}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' a '],
[TokenType.TEXT, ''],
[TokenType.TAG_OPEN_START, '', 'b'],
[TokenType.ATTR_NAME, '', '&&'],
[TokenType.ATTR_NAME, '', 'c'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, ' d '],
[TokenType.BLOCK_CLOSE],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should break out of interpolation in text token on valid comment', () => {
expect(tokenizeAndHumanizeParts('{{ a }<!---->}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' a }'],
[TokenType.TEXT, ''],
[TokenType.COMMENT_START],
[TokenType.RAW_TEXT, ''],
[TokenType.COMMENT_END],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should end interpolation on a valid closing tag', () => {
expect(tokenizeAndHumanizeParts('<p>{{ a </p>')).toEqual([
[TokenType.TAG_OPEN_START, '', 'p'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' a '],
[TokenType.TEXT, ''],
[TokenType.TAG_CLOSE, '', 'p'],
[TokenType.EOF],
]);
});
it('should break out of interpolation in text token on valid CDATA', () => {
expect(tokenizeAndHumanizeParts('{{ a }<![CDATA[]]>}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' a }'],
[TokenType.TEXT, ''],
[TokenType.CDATA_START],
[TokenType.RAW_TEXT, ''],
[TokenType.CDATA_END],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should ignore invalid start tag in interpolation', () => {
// Note that if the `<=` is considered an "end of text" then the following `{` would
// incorrectly be considered part of an ICU.
expect(
tokenizeAndHumanizeParts(`<code>{{'<={'}}</code>`, {tokenizeExpansionForms: true}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'code'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', "'<={'", '}}'],
[TokenType.TEXT, ''],
[TokenType.TAG_CLOSE, '', 'code'],
[TokenType.EOF],
]);
});
it('should parse start tags quotes in place of an attribute name as text', () => {
expect(tokenizeAndHumanizeParts('<t ">')).toEqual([
[TokenType.INCOMPLETE_TAG_OPEN, '', 't'],
[TokenType.TEXT, '">'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts("<t '>")).toEqual([
[TokenType.INCOMPLETE_TAG_OPEN, '', 't'],
[TokenType.TEXT, "'>"],
[TokenType.EOF],
]);
});
it('should parse start tags quotes in place of an attribute name (after a valid attribute)', () => {
expect(tokenizeAndHumanizeParts('<t a="b" ">')).toEqual([
[TokenType.INCOMPLETE_TAG_OPEN, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.ATTR_QUOTE, '"'],
// TODO(ayazhafiz): the " symbol should be a synthetic attribute,
// allowing us to complete the opening tag correctly.
[TokenType.TEXT, '">'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts("<t a='b' '>")).toEqual([
[TokenType.INCOMPLETE_TAG_OPEN, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.ATTR_QUOTE, "'"],
// TODO(ayazhafiz): the ' symbol should be a synthetic attribute,
// allowing us to complete the opening tag correctly.
[TokenType.TEXT, "'>"],
[TokenType.EOF],
]);
});
| {
"end_byte": 89182,
"start_byte": 81334,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_89188_94998 | ('should be able to escape {', () => {
expect(tokenizeAndHumanizeParts('{{ "{" }}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' "{" ', '}}'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
});
it('should be able to escape {{', () => {
expect(tokenizeAndHumanizeParts('{{ "{{" }}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' "{{" ', '}}'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
});
it('should capture everything up to the end of file in the interpolation expression part if there are mismatched quotes', () => {
expect(tokenizeAndHumanizeParts('{{ "{{a}}\' }}')).toEqual([
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', ' "{{a}}\' }}'],
[TokenType.TEXT, ''],
[TokenType.EOF],
]);
});
it('should treat expansion form as text when they are not parsed', () => {
expect(
tokenizeAndHumanizeParts('<span>{a, b, =4 {c}}</span>', {
tokenizeExpansionForms: false,
tokenizeBlocks: false,
}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'span'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, '{a, b, =4 {c}}'],
[TokenType.TAG_CLOSE, '', 'span'],
[TokenType.EOF],
]);
});
});
describe('raw text', () => {
it('should parse text', () => {
expect(tokenizeAndHumanizeParts(`<script>t\ne\rs\r\nt</script>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'script'],
[TokenType.TAG_OPEN_END],
[TokenType.RAW_TEXT, 't\ne\ns\nt'],
[TokenType.TAG_CLOSE, '', 'script'],
[TokenType.EOF],
]);
});
it('should not detect entities', () => {
expect(tokenizeAndHumanizeParts(`<script>&</SCRIPT>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'script'],
[TokenType.TAG_OPEN_END],
[TokenType.RAW_TEXT, '&'],
[TokenType.TAG_CLOSE, '', 'script'],
[TokenType.EOF],
]);
});
it('should ignore other opening tags', () => {
expect(tokenizeAndHumanizeParts(`<script>a<div></script>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'script'],
[TokenType.TAG_OPEN_END],
[TokenType.RAW_TEXT, 'a<div>'],
[TokenType.TAG_CLOSE, '', 'script'],
[TokenType.EOF],
]);
});
it('should ignore other closing tags', () => {
expect(tokenizeAndHumanizeParts(`<script>a</test></script>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'script'],
[TokenType.TAG_OPEN_END],
[TokenType.RAW_TEXT, 'a</test>'],
[TokenType.TAG_CLOSE, '', 'script'],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans(`<script>a</script>`)).toEqual([
[TokenType.TAG_OPEN_START, '<script'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.RAW_TEXT, 'a'],
[TokenType.TAG_CLOSE, '</script>'],
[TokenType.EOF, ''],
]);
});
});
describe('escapable raw text', () => {
it('should parse text', () => {
expect(tokenizeAndHumanizeParts(`<title>t\ne\rs\r\nt</title>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, 't\ne\ns\nt'],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should detect entities', () => {
expect(tokenizeAndHumanizeParts(`<title>&</title>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, ''],
[TokenType.ENCODED_ENTITY, '&', '&'],
[TokenType.ESCAPABLE_RAW_TEXT, ''],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should ignore other opening tags', () => {
expect(tokenizeAndHumanizeParts(`<title>a<div></title>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, 'a<div>'],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should ignore other closing tags', () => {
expect(tokenizeAndHumanizeParts(`<title>a</test></title>`)).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, 'a</test>'],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans(`<title>a</title>`)).toEqual([
[TokenType.TAG_OPEN_START, '<title'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.ESCAPABLE_RAW_TEXT, 'a'],
[TokenType.TAG_CLOSE, '</title>'],
[TokenType.EOF, ''],
]);
});
});
describe('parsable data', () => {
it('should parse an SVG <title> tag', () => {
expect(tokenizeAndHumanizeParts(`<svg:title>test</svg:title>`)).toEqual([
[TokenType.TAG_OPEN_START, 'svg', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'test'],
[TokenType.TAG_CLOSE, 'svg', 'title'],
[TokenType.EOF],
]);
});
it('should parse an SVG <title> tag with children', () => {
expect(tokenizeAndHumanizeParts(`<svg:title><f>test</f></svg:title>`)).toEqual([
[TokenType.TAG_OPEN_START, 'svg', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_OPEN_START, '', 'f'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'test'],
[TokenType.TAG_CLOSE, '', 'f'],
[TokenType.TAG_CLOSE, 'svg', 'title'],
[TokenType.EOF],
]);
});
});
| {
"end_byte": 94998,
"start_byte": 89188,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_95002_100807 | scribe('expansion forms', () => {
it('should parse an expansion form', () => {
expect(
tokenizeAndHumanizeParts('{one.two, three, =4 {four} =5 {five} foo {bar} }', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=5'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'five'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, 'foo'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'bar'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
});
it('should parse an expansion form with text elements surrounding it', () => {
expect(
tokenizeAndHumanizeParts('before{one.two, three, =4 {four}}after', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.TEXT, 'before'],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, 'after'],
[TokenType.EOF],
]);
});
it('should parse an expansion form as a tag single child', () => {
expect(
tokenizeAndHumanizeParts('<div><span>{a, b, =4 {c}}</span></div>', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'div'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_OPEN_START, '', 'span'],
[TokenType.TAG_OPEN_END],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'a'],
[TokenType.RAW_TEXT, 'b'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'c'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TAG_CLOSE, '', 'span'],
[TokenType.TAG_CLOSE, '', 'div'],
[TokenType.EOF],
]);
});
it('should parse an expansion form with whitespace surrounding it', () => {
expect(
tokenizeAndHumanizeParts('<div><span> {a, b, =4 {c}} </span></div>', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'div'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_OPEN_START, '', 'span'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, ' '],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'a'],
[TokenType.RAW_TEXT, 'b'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'c'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, ' '],
[TokenType.TAG_CLOSE, '', 'span'],
[TokenType.TAG_CLOSE, '', 'div'],
[TokenType.EOF],
]);
});
it('should parse an expansion forms with elements in it', () => {
expect(
tokenizeAndHumanizeParts('{one.two, three, =4 {four <b>a</b>}}', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four '],
[TokenType.TAG_OPEN_START, '', 'b'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'a'],
[TokenType.TAG_CLOSE, '', 'b'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
});
it('should parse an expansion forms containing an interpolation', () => {
expect(
tokenizeAndHumanizeParts('{one.two, three, =4 {four {{a}}}}', {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four '],
[TokenType.INTERPOLATION, '{{', 'a', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
});
it('should parse nested expansion forms', () => {
expect(
tokenizeAndHumanizeParts(`{one.two, three, =4 { {xx, yy, =x {one}} }}`, {
tokenizeExpansionForms: true,
}),
).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'xx'],
[TokenType.RAW_TEXT, 'yy'],
[TokenType.EXPANSION_CASE_VALUE, '=x'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'one'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, ' '],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
});
| {
"end_byte": 100807,
"start_byte": 95002,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_100813_105708 | scribe('[line ending normalization', () => {
describe('{escapedString: true}', () => {
it('should normalize line-endings in expansion forms if `i18nNormalizeLineEndingsInICUs` is true', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n`,
{
tokenizeExpansionForms: true,
escapedString: true,
i18nNormalizeLineEndingsInICUs: true,
},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'You have \nno\n messages'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=1'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'One '],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions).toEqual([]);
});
it('should not normalize line-endings in ICU expressions when `i18nNormalizeLineEndingsInICUs` is not defined', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n`,
{tokenizeExpansionForms: true, escapedString: true},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'You have \nno\n messages'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=1'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'One '],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions!.length).toBe(1);
expect(result.nonNormalizedIcuExpressions![0].sourceSpan.toString()).toEqual(
'\r\n messages.length',
);
});
it('should not normalize line endings in nested expansion forms when `i18nNormalizeLineEndingsInICUs` is not defined', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length, plural,\r\n` +
` =0 { zero \r\n` +
` {\r\n` +
` p.gender, select,\r\n` +
` male {m}\r\n` +
` }\r\n` +
` }\r\n` +
`}`,
{tokenizeExpansionForms: true, escapedString: true},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'zero \n '],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n p.gender'],
[TokenType.RAW_TEXT, 'select'],
[TokenType.EXPANSION_CASE_VALUE, 'male'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'm'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n '],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions!.length).toBe(2);
expect(result.nonNormalizedIcuExpressions![0].sourceSpan.toString()).toEqual(
'\r\n messages.length',
);
expect(result.nonNormalizedIcuExpressions![1].sourceSpan.toString()).toEqual(
'\r\n p.gender',
);
});
});
| {
"end_byte": 105708,
"start_byte": 100813,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_105716_112335 | scribe('{escapedString: false}', () => {
it('should normalize line-endings in expansion forms if `i18nNormalizeLineEndingsInICUs` is true', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n`,
{
tokenizeExpansionForms: true,
escapedString: false,
i18nNormalizeLineEndingsInICUs: true,
},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'You have \nno\n messages'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=1'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'One '],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions).toEqual([]);
});
it('should not normalize line-endings in ICU expressions when `i18nNormalizeLineEndingsInICUs` is not defined', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length,\r\n` +
` plural,\r\n` +
` =0 {You have \r\nno\r\n messages}\r\n` +
` =1 {One {{message}}}}\r\n`,
{tokenizeExpansionForms: true, escapedString: false},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'You have \nno\n messages'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=1'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'One '],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions!.length).toBe(1);
expect(result.nonNormalizedIcuExpressions![0].sourceSpan.toString()).toEqual(
'\r\n messages.length',
);
});
it('should not normalize line endings in nested expansion forms when `i18nNormalizeLineEndingsInICUs` is not defined', () => {
const result = tokenizeWithoutErrors(
`{\r\n` +
` messages.length, plural,\r\n` +
` =0 { zero \r\n` +
` {\r\n` +
` p.gender, select,\r\n` +
` male {m}\r\n` +
` }\r\n` +
` }\r\n` +
`}`,
{tokenizeExpansionForms: true},
);
expect(humanizeParts(result.tokens)).toEqual([
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n messages.length'],
[TokenType.RAW_TEXT, 'plural'],
[TokenType.EXPANSION_CASE_VALUE, '=0'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'zero \n '],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, '\r\n p.gender'],
[TokenType.RAW_TEXT, 'select'],
[TokenType.EXPANSION_CASE_VALUE, 'male'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'm'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.TEXT, '\n '],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.EOF],
]);
expect(result.nonNormalizedIcuExpressions!.length).toBe(2);
expect(result.nonNormalizedIcuExpressions![0].sourceSpan.toString()).toEqual(
'\r\n messages.length',
);
expect(result.nonNormalizedIcuExpressions![1].sourceSpan.toString()).toEqual(
'\r\n p.gender',
);
});
});
});
});
describe('errors', () => {
it('should report unescaped "{" on error', () => {
expect(
tokenizeAndHumanizeErrors(`<p>before { after</p>`, {tokenizeExpansionForms: true}),
).toEqual([
[
TokenType.RAW_TEXT,
`Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)`,
'0:21',
],
]);
});
it('should report unescaped "{" as an error, even after a prematurely terminated interpolation', () => {
expect(
tokenizeAndHumanizeErrors(`<code>{{b}<!---->}</code><pre>import {a} from 'a';</pre>`, {
tokenizeExpansionForms: true,
}),
).toEqual([
[
TokenType.RAW_TEXT,
`Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)`,
'0:56',
],
]);
});
it('should include 2 lines of context in message', () => {
const src = '111\n222\n333\nE\n444\n555\n666\n';
const file = new ParseSourceFile(src, 'file://');
const location = new ParseLocation(file, 12, 123, 456);
const span = new ParseSourceSpan(location, location);
const error = new TokenError('**ERROR**', null!, span);
expect(error.toString()).toEqual(
`**ERROR** ("\n222\n333\n[ERROR ->]E\n444\n555\n"): file://@123:456`,
);
});
});
describe('unicode characters', () => {
it('should support unicode characters', () => {
expect(tokenizeAndHumanizeSourceSpans(`<p>İ</p>`)).toEqual([
[TokenType.TAG_OPEN_START, '<p'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TEXT, 'İ'],
[TokenType.TAG_CLOSE, '</p>'],
[TokenType.EOF, ''],
]);
});
});
| {
"end_byte": 112335,
"start_byte": 105716,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.