_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/localize/init/PACKAGE.md_0_171
The `@angular/localize` package exposes the `$localize` function in the global namespace, which can be used to tag i18n messages in your code that needs to be translated.
{ "end_byte": 171, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/init/PACKAGE.md" }
angular/packages/localize/init/BUILD.bazel_0_775
load("//tools:defaults.bzl", "ts_library") load("//adev/shared-docs/pipeline/api-gen:generate_api_docs.bzl", "generate_api_docs") package(default_visibility = ["//visibility:public"]) exports_files(["package.json"]) ts_library( name = "init", srcs = glob( [ "**/*.ts", ], ), module_name = "@angular/localize/init", deps = [ "//packages/localize", "@npm//@types/node", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "localize_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", ], entry_point = ":index.ts", module_name = "@angular/localize/init", )
{ "end_byte": 775, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/init/BUILD.bazel" }
angular/packages/localize/init/index.ts_0_496
/** * @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 { ɵ$localize as $localize, ɵLocalizeFn as LocalizeFn, ɵTranslateFn as TranslateFn, } from '@angular/localize'; export {$localize, LocalizeFn, TranslateFn}; // Attach $localize to the global context, as a side-effect of this module. (globalThis as any).$localize = $localize;
{ "end_byte": 496, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/init/index.ts" }
angular/packages/localize/tools/esbuild.config.js_0_669
/** * @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 */ module.exports = { resolveExtensions: ['.mjs'], // Note: `@bazel/esbuild` has a bug and does not pass-through the format from Starlark. format: 'esm', banner: { // Workaround for: https://github.com/evanw/esbuild/issues/946 // TODO: Remove this workaround in the future once devmode is ESM as well. js: ` import {createRequire as __cjsCompatRequire} from 'module'; const require = __cjsCompatRequire(import.meta.url); `, }, };
{ "end_byte": 669, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/esbuild.config.js" }
angular/packages/localize/tools/README.md_0_202
### Disclaimer The localize tools are consumed via the Angular CLI. The programmatic APIs are not considered officially supported though and are not subject to the breaking change guarantees of SemVer.
{ "end_byte": 202, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/README.md" }
angular/packages/localize/tools/BUILD.bazel_0_1461
load("@npm//@bazel/esbuild:index.bzl", "esbuild", "esbuild_config") load("//tools:defaults.bzl", "extract_types", "pkg_npm", "ts_library") ts_library( name = "tools", srcs = glob( [ "**/*.ts", ], ), visibility = ["//packages/localize/tools:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/private", "//packages/localize", "@npm//@babel/core", "@npm//@types/babel__core", "@npm//@types/node", "@npm//@types/yargs", "@npm//fast-glob", ], ) esbuild_config( name = "esbuild_config", config_file = "esbuild.config.js", ) esbuild( name = "bundles", config = ":esbuild_config", entry_points = [ ":index.ts", ":src/extract/cli.ts", ":src/migrate/cli.ts", ":src/translate/cli.ts", ], external = [ "@angular/localize", "@angular/compiler", "@angular/compiler-cli/private/localize", "@babel/core", "yargs", "fast-glob", ], format = "esm", platform = "node", splitting = True, target = "node12", deps = [ ":tools", ], ) extract_types( name = "api_type_definitions", deps = [":tools"], ) pkg_npm( name = "npm_package", srcs = ["README.md"], visibility = ["//packages/localize:__pkg__"], deps = [ ":api_type_definitions", ":bundles", ], )
{ "end_byte": 1461, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/BUILD.bazel" }
angular/packages/localize/tools/index.ts_0_2445
/** * @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 */ // Note: Before changing any exports here, consult with the Angular tooling team // as the CLI heavily relies on exports declared here. import {NodeJSFileSystem, setFileSystem} from '@angular/compiler-cli/private/localize'; setFileSystem(new NodeJSFileSystem()); export {DiagnosticHandlingStrategy, Diagnostics} from './src/diagnostics'; export {checkDuplicateMessages} from './src/extract/duplicates'; export {MessageExtractor} from './src/extract/extraction'; export {ArbTranslationSerializer} from './src/extract/translation_files/arb_translation_serializer'; export {SimpleJsonTranslationSerializer} from './src/extract/translation_files/json_translation_serializer'; export {LegacyMessageIdMigrationSerializer} from './src/extract/translation_files/legacy_message_id_migration_serializer'; export {Xliff1TranslationSerializer} from './src/extract/translation_files/xliff1_translation_serializer'; export {Xliff2TranslationSerializer} from './src/extract/translation_files/xliff2_translation_serializer'; export {XmbTranslationSerializer} from './src/extract/translation_files/xmb_translation_serializer'; export { buildLocalizeReplacement, isGlobalIdentifier, translate, unwrapExpressionsFromTemplateLiteral, unwrapMessagePartsFromLocalizeCall, unwrapMessagePartsFromTemplateLiteral, unwrapSubstitutionsFromLocalizeCall, } from './src/source_file_utils'; export {makeEs2015TranslatePlugin} from './src/translate/source_files/es2015_translate_plugin'; export {makeEs5TranslatePlugin} from './src/translate/source_files/es5_translate_plugin'; export {makeLocalePlugin} from './src/translate/source_files/locale_plugin'; export {ArbTranslationParser} from './src/translate/translation_files/translation_parsers/arb_translation_parser'; export {SimpleJsonTranslationParser} from './src/translate/translation_files/translation_parsers/simple_json_translation_parser'; export {Xliff1TranslationParser} from './src/translate/translation_files/translation_parsers/xliff1_translation_parser'; export {Xliff2TranslationParser} from './src/translate/translation_files/translation_parsers/xliff2_translation_parser'; export {XtbTranslationParser} from './src/translate/translation_files/translation_parsers/xtb_translation_parser';
{ "end_byte": 2445, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/index.ts" }
angular/packages/localize/tools/test/diagnostics_spec.ts_0_1928
/** * @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 {Diagnostics} from '../src/diagnostics'; describe('Diagnostics', () => { describe('formatDiagnostics', () => { it('should just return the message passed in if there are no errors nor warnings', () => { const diagnostics = new Diagnostics(); expect(diagnostics.formatDiagnostics('This is a message')).toEqual('This is a message'); }); it('should return a string with all the errors listed', () => { const diagnostics = new Diagnostics(); diagnostics.error('Error 1'); diagnostics.error('Error 2'); diagnostics.error('Error 3'); expect(diagnostics.formatDiagnostics('This is a message')).toEqual( 'This is a message\nERRORS:\n - Error 1\n - Error 2\n - Error 3', ); }); it('should return a string with all the warnings listed', () => { const diagnostics = new Diagnostics(); diagnostics.warn('Warning 1'); diagnostics.warn('Warning 2'); diagnostics.warn('Warning 3'); expect(diagnostics.formatDiagnostics('This is a message')).toEqual( 'This is a message\nWARNINGS:\n - Warning 1\n - Warning 2\n - Warning 3', ); }); it('should return a string with all the errors and warnings listed', () => { const diagnostics = new Diagnostics(); diagnostics.warn('Warning 1'); diagnostics.warn('Warning 2'); diagnostics.error('Error 1'); diagnostics.error('Error 2'); diagnostics.warn('Warning 3'); diagnostics.error('Error 3'); expect(diagnostics.formatDiagnostics('This is a message')).toEqual( 'This is a message\nERRORS:\n - Error 1\n - Error 2\n - Error 3\nWARNINGS:\n - Warning 1\n - Warning 2\n - Warning 3', ); }); }); });
{ "end_byte": 1928, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/diagnostics_spec.ts" }
angular/packages/localize/tools/test/BUILD.bazel_0_965
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*.ts"], ), visibility = ["//packages/localize/tools/test:__subpackages__"], deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/private", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/logging/testing", "//packages/localize", "//packages/localize/src/utils", "//packages/localize/tools", "//packages/localize/tools/test/helpers", "@npm//@babel/generator", "@npm//@types/babel__generator", "@npm//fast-glob", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", "@npm//fast-glob", ], )
{ "end_byte": 965, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/BUILD.bazel" }
angular/packages/localize/tools/test/source_file_utils_spec.ts_0_4110
/** * @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 { absoluteFrom, getFileSystem, PathManipulation, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {ɵmakeTemplateObject} from '@angular/localize'; import babel, {NodePath, TransformOptions, template, types as t} from '@babel/core'; import _generate from '@babel/generator'; // Babel is a CJS package and misuses the `default` named binding: // https://github.com/babel/babel/issues/15269. const generate = (_generate as any)['default'] as typeof _generate; import { buildLocalizeReplacement, getLocation, isArrayOfExpressions, isGlobalIdentifier, isNamedIdentifier, isStringLiteralArray, unwrapMessagePartsFromLocalizeCall, unwrapMessagePartsFromTemplateLiteral, unwrapStringLiteralArray, unwrapSubstitutionsFromLocalizeCall, wrapInParensIfNecessary, } from '../src/source_file_utils'; import {runInNativeFileSystem} from './helpers'; runInNativeFileSystem(() => { let fs: PathManipulation; beforeEach(() => (fs = getFileSystem())); describe('utils', () => { describe('isNamedIdentifier()', () => { it('should return true if the expression is an identifier with name `$localize`', () => { const taggedTemplate = getTaggedTemplate('$localize ``;'); expect(isNamedIdentifier(taggedTemplate.get('tag'), '$localize')).toBe(true); }); it('should return false if the expression is an identifier without the name `$localize`', () => { const taggedTemplate = getTaggedTemplate('other ``;'); expect(isNamedIdentifier(taggedTemplate.get('tag'), '$localize')).toBe(false); }); it('should return false if the expression is not an identifier', () => { const taggedTemplate = getTaggedTemplate('$localize() ``;'); expect(isNamedIdentifier(taggedTemplate.get('tag'), '$localize')).toBe(false); }); }); describe('isGlobalIdentifier()', () => { it('should return true if the identifier is at the top level and not declared', () => { const taggedTemplate = getTaggedTemplate('$localize ``;'); expect(isGlobalIdentifier(taggedTemplate.get('tag') as NodePath<t.Identifier>)).toBe(true); }); it('should return true if the identifier is in a block scope and not declared', () => { const taggedTemplate = getTaggedTemplate('function foo() { $localize ``; } foo();'); expect(isGlobalIdentifier(taggedTemplate.get('tag') as NodePath<t.Identifier>)).toBe(true); }); it('should return false if the identifier is declared locally', () => { const taggedTemplate = getTaggedTemplate('function $localize() {} $localize ``;'); expect(isGlobalIdentifier(taggedTemplate.get('tag') as NodePath<t.Identifier>)).toBe(false); }); it('should return false if the identifier is a function parameter', () => { const taggedTemplate = getTaggedTemplate('function foo($localize) { $localize ``; }'); expect(isGlobalIdentifier(taggedTemplate.get('tag') as NodePath<t.Identifier>)).toBe(false); }); }); describe('buildLocalizeReplacement', () => { it('should interleave the `messageParts` with the `substitutions`', () => { const messageParts = ɵmakeTemplateObject(['a', 'b', 'c'], ['a', 'b', 'c']); const substitutions = [t.numericLiteral(1), t.numericLiteral(2)]; const expression = buildLocalizeReplacement(messageParts, substitutions); expect(generate(expression).code).toEqual('"a" + 1 + "b" + 2 + "c"'); }); it('should wrap "binary expression" substitutions in parentheses', () => { const messageParts = ɵmakeTemplateObject(['a', 'b'], ['a', 'b']); const binary = t.binaryExpression('+', t.numericLiteral(1), t.numericLiteral(2)); const expression = buildLocalizeReplacement(messageParts, [binary]); expect(generate(expression).code).toEqual('"a" + (1 + 2) + "b"'); }); });
{ "end_byte": 4110, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/source_file_utils_spec.ts" }
angular/packages/localize/tools/test/source_file_utils_spec.ts_4116_11667
cribe('unwrapMessagePartsFromLocalizeCall', () => { it('should return an array of string literals and locations from a direct call to a tag function', () => { const localizeCall = getLocalizeCall(`$localize(['a', 'b\\t', 'c'], 1, 2)`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(locations).toEqual([ { start: {line: 0, column: 11}, end: {line: 0, column: 14}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 0, column: 16}, end: {line: 0, column: 21}, file: absoluteFrom('/test/file.js'), text: `'b\\t'`, }, { start: {line: 0, column: 23}, end: {line: 0, column: 26}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should return an array of string literals and locations from a downleveled tagged template', () => { let localizeCall = getLocalizeCall( `$localize(__makeTemplateObject(['a', 'b\\t', 'c'], ['a', 'b\\\\t', 'c']), 1, 2)`, ); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\\t', 'c']); expect(locations).toEqual([ { start: {line: 0, column: 51}, end: {line: 0, column: 54}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 0, column: 56}, end: {line: 0, column: 62}, file: absoluteFrom('/test/file.js'), text: `'b\\\\t'`, }, { start: {line: 0, column: 64}, end: {line: 0, column: 67}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should return an array of string literals and locations from a (Babel helper) downleveled tagged template', () => { let localizeCall = getLocalizeCall( `$localize(babelHelpers.taggedTemplateLiteral(['a', 'b\\t', 'c'], ['a', 'b\\\\t', 'c']), 1, 2)`, ); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\\t', 'c']); expect(locations).toEqual([ { start: {line: 0, column: 65}, end: {line: 0, column: 68}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 0, column: 70}, end: {line: 0, column: 76}, file: absoluteFrom('/test/file.js'), text: `'b\\\\t'`, }, { start: {line: 0, column: 78}, end: {line: 0, column: 81}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should return an array of string literals and locations from a memoized downleveled tagged template', () => { let localizeCall = getLocalizeCall(` var _templateObject; $localize(_templateObject || (_templateObject = __makeTemplateObject(['a', 'b\\t', 'c'], ['a', 'b\\\\t', 'c'])), 1, 2)`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\\t', 'c']); expect(locations).toEqual([ { start: {line: 2, column: 105}, end: {line: 2, column: 108}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 2, column: 110}, end: {line: 2, column: 116}, file: absoluteFrom('/test/file.js'), text: `'b\\\\t'`, }, { start: {line: 2, column: 118}, end: {line: 2, column: 121}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should return an array of string literals and locations from a memoized (inlined Babel helper) downleveled tagged template', () => { let localizeCall = getLocalizeCall(` var e,t,n; $localize(e || ( t=["a","b\t","c"], n || (n=t.slice(0)), e = Object.freeze( Object.defineProperties(t, { raw: { value: Object.freeze(n) } }) ) ), 1,2 )`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\t', 'c']); expect(locations).toEqual([ { start: {line: 4, column: 21}, end: {line: 4, column: 24}, file: absoluteFrom('/test/file.js'), text: `"a"`, }, { start: {line: 4, column: 25}, end: {line: 4, column: 29}, file: absoluteFrom('/test/file.js'), text: `"b\t"`, }, { start: {line: 4, column: 30}, end: {line: 4, column: 33}, file: absoluteFrom('/test/file.js'), text: `"c"`, }, ]); }); it('should return an array of string literals and locations from a lazy load template helper', () => { let localizeCall = getLocalizeCall(` function _templateObject() { var e = _taggedTemplateLiteral(['a', 'b\\t', 'c'], ['a', 'b\\\\t', 'c']); return _templateObject = function() { return e }, e } $localize(_templateObject(), 1, 2)`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\\t', 'c']); expect(locations).toEqual([ { start: {line: 2, column: 61}, end: {line: 2, column: 64}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 2, column: 66}, end: {line: 2, column: 72}, file: absoluteFrom('/test/file.js'), text: `'b\\\\t'`, }, { start: {line: 2, column: 74}, end: {line: 2, column: 77}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should remove a lazy load template helper', () => { let localizeCall = getLocalizeCall(` function _templateObject() { var e = _taggedTemplateLiteral(['a', 'b', 'c'], ['a', 'b', 'c']); return _templateObject = function() { return e }, e } $localize(_templateObject(), 1, 2)`); const localizeStatement = localizeCall.parentPath as NodePath<t.ExpressionStatement>; const statements = localizeStatement.container as object[]; expect(statements.length).toEqual(2); unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(statements.length).toEqual(1); expect(statements[0]).toBe(localizeStatement.node); }); });
{ "end_byte": 11667, "start_byte": 4116, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/source_file_utils_spec.ts" }
angular/packages/localize/tools/test/source_file_utils_spec.ts_11673_19617
cribe('unwrapSubstitutionsFromLocalizeCall', () => { it('should return the substitutions and locations from a direct call to a tag function', () => { const call = getLocalizeCall(`$localize(['a', 'b\t', 'c'], 1, 2)`); const [substitutions, locations] = unwrapSubstitutionsFromLocalizeCall(call, fs); expect((substitutions as t.NumericLiteral[]).map((s) => s.value)).toEqual([1, 2]); expect(locations).toEqual([ { start: {line: 0, column: 28}, end: {line: 0, column: 29}, file: absoluteFrom('/test/file.js'), text: '1', }, { start: {line: 0, column: 31}, end: {line: 0, column: 32}, file: absoluteFrom('/test/file.js'), text: '2', }, ]); }); it('should return the substitutions and locations from a downleveled tagged template', () => { const call = getLocalizeCall( `$localize(__makeTemplateObject(['a', 'b', 'c'], ['a', 'b', 'c']), 1, 2)`, ); const [substitutions, locations] = unwrapSubstitutionsFromLocalizeCall(call, fs); expect((substitutions as t.NumericLiteral[]).map((s) => s.value)).toEqual([1, 2]); expect(locations).toEqual([ { start: {line: 0, column: 66}, end: {line: 0, column: 67}, file: absoluteFrom('/test/file.js'), text: '1', }, { start: {line: 0, column: 69}, end: {line: 0, column: 70}, file: absoluteFrom('/test/file.js'), text: '2', }, ]); }); }); describe('unwrapMessagePartsFromTemplateLiteral', () => { it('should return a TemplateStringsArray built from the template literal elements', () => { const taggedTemplate = getTaggedTemplate('$localize `a${1}b\\t${2}c`;'); expect( unwrapMessagePartsFromTemplateLiteral(taggedTemplate.get('quasi').get('quasis'), fs)[0], ).toEqual(ɵmakeTemplateObject(['a', 'b\t', 'c'], ['a', 'b\\t', 'c'])); }); }); describe('wrapInParensIfNecessary', () => { it('should wrap the expression in parentheses if it is binary', () => { const ast = template.ast`a + b` as t.ExpressionStatement; const wrapped = wrapInParensIfNecessary(ast.expression); expect(t.isParenthesizedExpression(wrapped)).toBe(true); }); it('should return the expression untouched if it is not binary', () => { const ast = template.ast`a` as t.ExpressionStatement; const wrapped = wrapInParensIfNecessary(ast.expression); expect(t.isParenthesizedExpression(wrapped)).toBe(false); }); }); describe('unwrapStringLiteralArray', () => { it('should return an array of string from an array expression', () => { const array = getFirstExpression(`['a', 'b', 'c']`); const [expressions, locations] = unwrapStringLiteralArray(array, fs); expect(expressions).toEqual(['a', 'b', 'c']); expect(locations).toEqual([ { start: {line: 0, column: 1}, end: {line: 0, column: 4}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 0, column: 6}, end: {line: 0, column: 9}, file: absoluteFrom('/test/file.js'), text: `'b'`, }, { start: {line: 0, column: 11}, end: {line: 0, column: 14}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should throw an error if any elements of the array are not literal strings', () => { const array = getFirstExpression(`['a', 2, 'c']`); expect(() => unwrapStringLiteralArray(array, fs)).toThrowError( 'Unexpected messageParts for `$localize` (expected an array of strings).', ); }); }); describe('isStringLiteralArray()', () => { it('should return true if the ast is an array of strings', () => { const ast = template.ast`['a', 'b', 'c']` as t.ExpressionStatement; expect(isStringLiteralArray(ast.expression)).toBe(true); }); it('should return false if the ast is not an array', () => { const ast = template.ast`'a'` as t.ExpressionStatement; expect(isStringLiteralArray(ast.expression)).toBe(false); }); it('should return false if at least on of the array elements is not a string', () => { const ast = template.ast`['a', 1, 'b']` as t.ExpressionStatement; expect(isStringLiteralArray(ast.expression)).toBe(false); }); }); describe('isArrayOfExpressions()', () => { it('should return true if all the nodes are expressions', () => { const call = getFirstExpression<t.CallExpression>('foo(a, b, c);'); expect(isArrayOfExpressions(call.get('arguments'))).toBe(true); }); it('should return false if any of the nodes is not an expression', () => { const call = getFirstExpression<t.CallExpression>('foo(a, b, ...c);'); expect(isArrayOfExpressions(call.get('arguments'))).toBe(false); }); }); describe('getLocation()', () => { it('should return a plain object containing the start, end and file of a NodePath', () => { const taggedTemplate = getTaggedTemplate('const x = $localize `message`;', { filename: 'src/test.js', sourceRoot: fs.resolve('/project'), }); const location = getLocation(fs, taggedTemplate)!; expect(location).toBeDefined(); expect(location.start).toEqual({line: 0, column: 10}); expect(location.start.constructor.name).toEqual('Object'); expect(location.end).toEqual({line: 0, column: 29}); expect(location.end?.constructor.name).toEqual('Object'); expect(location.file).toEqual(fs.resolve('/project/src/test.js')); }); it('should return `undefined` if the NodePath has no filename', () => { const taggedTemplate = getTaggedTemplate('const x = $localize ``;', { sourceRoot: fs.resolve('/project'), filename: undefined, }); const location = getLocation(fs, taggedTemplate); expect(location).toBeUndefined(); }); }); }); }); function getTaggedTemplate( code: string, options?: TransformOptions, ): NodePath<t.TaggedTemplateExpression> { return getExpressions<t.TaggedTemplateExpression>(code, options).find((e) => e.isTaggedTemplateExpression(), )!; } function getFirstExpression<T extends t.Expression>( code: string, options?: TransformOptions, ): NodePath<T> { return getExpressions<T>(code, options)[0]; } function getExpressions<T extends t.Expression>( code: string, options?: TransformOptions, ): NodePath<T>[] { const expressions: NodePath<t.Expression>[] = []; babel.transformSync(code, { code: false, filename: 'test/file.js', cwd: '/', plugins: [ { visitor: { Expression: (path: NodePath<t.Expression>) => { expressions.push(path); }, }, }, ], ...options, }); return expressions as NodePath<T>[]; } function getLocalizeCall(code: string): NodePath<t.CallExpression> { let callPaths: NodePath<t.CallExpression>[] = []; babel.transformSync(code, { code: false, filename: 'test/file.js', cwd: '/', plugins: [ { visitor: { CallExpression(path) { callPaths.push(path); }, }, }, ], }); const localizeCall = callPaths.find((p) => { const callee = p.get('callee'); return callee.isIdentifier() && callee.node.name === '$localize'; }); if (!localizeCall) { throw new Error(`$localize cannot be found in ${code}`); } return localizeCall; }
{ "end_byte": 19617, "start_byte": 11673, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/source_file_utils_spec.ts" }
angular/packages/localize/tools/test/translate/translator_spec.ts_0_5816
/** * @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 { absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, PathSegment, relativeFrom, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {Diagnostics as Diagnostics} from '../../src/diagnostics'; import {OutputPathFn} from '../../src/translate/output_path'; import {TranslationBundle, TranslationHandler, Translator} from '../../src/translate/translator'; runInEachFileSystem(() => { describe('Translator', () => { let fs: FileSystem; let distDirectory: AbsoluteFsPath; let imgDirectory: AbsoluteFsPath; let file1Path: PathSegment; let imgPath: PathSegment; beforeEach(() => { fs = getFileSystem(); distDirectory = absoluteFrom('/dist'); imgDirectory = absoluteFrom('/dist/images'); file1Path = relativeFrom('file1.js'); imgPath = relativeFrom('images/img.gif'); fs.ensureDir(imgDirectory); fs.writeFile(fs.resolve(distDirectory, file1Path), 'resource file 1'); fs.writeFile(fs.resolve(distDirectory, imgPath), Buffer.from('resource file 2')); }); describe('translateFiles()', () => { it('should call FileSystem.readFileBuffer load the resource file contents', () => { const translator = new Translator(fs, [new MockTranslationHandler()], new Diagnostics()); spyOn(fs, 'readFileBuffer').and.callThrough(); translator.translateFiles([file1Path, imgPath], distDirectory, mockOutputPathFn, []); expect(fs.readFileBuffer).toHaveBeenCalledWith(fs.resolve(distDirectory, file1Path)); expect(fs.readFileBuffer).toHaveBeenCalledWith(fs.resolve(distDirectory, imgPath)); }); it('should call `canTranslate()` and `translate()` for each file', () => { const diagnostics = new Diagnostics(); const handler = new MockTranslationHandler(true); const translator = new Translator(fs, [handler], diagnostics); translator.translateFiles([file1Path, imgPath], distDirectory, mockOutputPathFn, []); expect(handler.log).toEqual([ 'canTranslate(file1.js, resource file 1)', `translate(${distDirectory}, file1.js, resource file 1, ...)`, 'canTranslate(images/img.gif, resource file 2)', `translate(${distDirectory}, images/img.gif, resource file 2, ...)`, ]); }); it('should pass the sourceLocale through to `translate()` if provided', () => { const diagnostics = new Diagnostics(); const handler = new MockTranslationHandler(true); const translator = new Translator(fs, [handler], diagnostics); translator.translateFiles( [file1Path, imgPath], distDirectory, mockOutputPathFn, [], 'en-US', ); expect(handler.log).toEqual([ 'canTranslate(file1.js, resource file 1)', `translate(${distDirectory}, file1.js, resource file 1, ..., en-US)`, 'canTranslate(images/img.gif, resource file 2)', `translate(${distDirectory}, images/img.gif, resource file 2, ..., en-US)`, ]); }); it('should stop at the first handler that can handle each file', () => { const diagnostics = new Diagnostics(); const handler1 = new MockTranslationHandler(false); const handler2 = new MockTranslationHandler(true); const handler3 = new MockTranslationHandler(true); const translator = new Translator(fs, [handler1, handler2, handler3], diagnostics); translator.translateFiles([file1Path, imgPath], distDirectory, mockOutputPathFn, []); expect(handler1.log).toEqual([ 'canTranslate(file1.js, resource file 1)', 'canTranslate(images/img.gif, resource file 2)', ]); expect(handler2.log).toEqual([ 'canTranslate(file1.js, resource file 1)', `translate(${distDirectory}, file1.js, resource file 1, ...)`, 'canTranslate(images/img.gif, resource file 2)', `translate(${distDirectory}, images/img.gif, resource file 2, ...)`, ]); }); it('should error if none of the handlers can handle the file', () => { const diagnostics = new Diagnostics(); const handler = new MockTranslationHandler(false); const translator = new Translator(fs, [handler], diagnostics); translator.translateFiles([file1Path, imgPath], distDirectory, mockOutputPathFn, []); expect(diagnostics.messages).toEqual([ {type: 'error', message: `Unable to handle resource file: ${file1Path}`}, {type: 'error', message: `Unable to handle resource file: ${imgPath}`}, ]); }); }); }); class MockTranslationHandler implements TranslationHandler { log: string[] = []; constructor(private _canTranslate: boolean = true) {} canTranslate(relativePath: string, contents: Uint8Array) { this.log.push(`canTranslate(${relativePath}, ${contents})`); return this._canTranslate; } translate( _diagnostics: Diagnostics, rootPath: string, relativePath: string, contents: Uint8Array, _outputPathFn: OutputPathFn, _translations: TranslationBundle[], sourceLocale?: string, ) { this.log.push( `translate(${rootPath}, ${relativePath}, ${contents}, ...` + (sourceLocale !== undefined ? `, ${sourceLocale})` : ')'), ); } } function mockOutputPathFn(locale: string, relativePath: string) { return `translations/${locale}/${relativePath}`; } });
{ "end_byte": 5816, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translator_spec.ts" }
angular/packages/localize/tools/test/translate/output_path_spec.ts_0_2152
/** * @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 { absoluteFrom, getFileSystem, PathManipulation, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {getOutputPathFn} from '../../src/translate/output_path'; runInEachFileSystem(() => { let fs: PathManipulation; beforeEach(() => (fs = getFileSystem())); describe('getOutputPathFn()', () => { it('should return a function that joins the `outputPath` and the `relativePath`', () => { const fn = getOutputPathFn(fs, absoluteFrom('/output/path')); expect(fn('en', 'relative/path')).toEqual(absoluteFrom('/output/path/relative/path')); expect(fn('en', '../parent/path')).toEqual(absoluteFrom('/output/parent/path')); }); it('should return a function that interpolates the `{{LOCALE}}` in the middle of the `outputPath`', () => { const fn = getOutputPathFn(fs, absoluteFrom('/output/{{LOCALE}}/path')); expect(fn('en', 'relative/path')).toEqual(absoluteFrom('/output/en/path/relative/path')); expect(fn('fr', 'relative/path')).toEqual(absoluteFrom('/output/fr/path/relative/path')); }); it('should return a function that interpolates the `{{LOCALE}}` in the middle of a path segment in the `outputPath`', () => { const fn = getOutputPathFn(fs, absoluteFrom('/output-{{LOCALE}}-path')); expect(fn('en', 'relative/path')).toEqual(absoluteFrom('/output-en-path/relative/path')); expect(fn('fr', 'relative/path')).toEqual(absoluteFrom('/output-fr-path/relative/path')); }); it('should return a function that interpolates the `{{LOCALE}}` at the end of the `outputPath`', () => { const fn = getOutputPathFn(fs, absoluteFrom('/output/{{LOCALE}}')); expect(fn('en', 'relative/path')).toEqual(absoluteFrom('/output/en/relative/path')); expect(fn('fr', 'relative/path')).toEqual(absoluteFrom('/output/fr/relative/path')); }); }); });
{ "end_byte": 2152, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/output_path_spec.ts" }
angular/packages/localize/tools/test/translate/integration/main_spec.ts_0_7585
/** * @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 { absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {loadTestDirectory} from '@angular/compiler-cli/src/ngtsc/testing'; import path from 'path'; import url from 'url'; import {Diagnostics} from '../../../src/diagnostics'; import {translateFiles} from '../../../src/translate/index'; import {getOutputPathFn} from '../../../src/translate/output_path'; import {runInNativeFileSystem} from '../../helpers'; const currentDir = path.dirname(url.fileURLToPath(import.meta.url)); runInNativeFileSystem(() => { describe('translateFiles()', () => { let fs: FileSystem; let testDir: AbsoluteFsPath; let testFilesDir: AbsoluteFsPath; let translationFilesDir: AbsoluteFsPath; beforeEach(() => { fs = getFileSystem(); testDir = absoluteFrom('/test'); testFilesDir = fs.resolve(testDir, 'test_files'); loadTestDirectory(fs, path.resolve(path.join(currentDir, 'test_files')), testFilesDir); translationFilesDir = fs.resolve(testDir, 'test_files'); loadTestDirectory(fs, path.resolve(path.join(currentDir, 'locales')), translationFilesDir); }); it('should copy non-code files to the destination folders', () => { const diagnostics = new Diagnostics(); const outputPathFn = getOutputPathFn(fs, fs.resolve(testDir, '{{LOCALE}}')); translateFiles({ sourceRootPath: testFilesDir, sourceFilePaths: ['test-1.txt', 'test-2.txt'], outputPathFn, translationFilePaths: resolveAll(translationFilesDir, [ 'messages.de.json', 'messages.es.xlf', 'messages.fr.xlf', 'messages.it.xtb', ]), translationFileLocales: [], diagnostics, missingTranslation: 'error', duplicateTranslation: 'error', }); expect(diagnostics.messages.length).toEqual(0); expect(fs.readFile(fs.resolve(testDir, 'fr', 'test-1.txt'))).toEqual( 'Contents of test-1.txt', ); expect(fs.readFile(fs.resolve(testDir, 'fr', 'test-2.txt'))).toEqual( 'Contents of test-2.txt', ); expect(fs.readFile(fs.resolve(testDir, 'de', 'test-1.txt'))).toEqual( 'Contents of test-1.txt', ); expect(fs.readFile(fs.resolve(testDir, 'de', 'test-2.txt'))).toEqual( 'Contents of test-2.txt', ); expect(fs.readFile(fs.resolve(testDir, 'es', 'test-1.txt'))).toEqual( 'Contents of test-1.txt', ); expect(fs.readFile(fs.resolve(testDir, 'es', 'test-2.txt'))).toEqual( 'Contents of test-2.txt', ); expect(fs.readFile(fs.resolve(testDir, 'it', 'test-1.txt'))).toEqual( 'Contents of test-1.txt', ); expect(fs.readFile(fs.resolve(testDir, 'it', 'test-2.txt'))).toEqual( 'Contents of test-2.txt', ); }); it('should translate and copy source-code files to the destination folders', () => { const diagnostics = new Diagnostics(); const outputPathFn = getOutputPathFn(fs, fs.resolve(testDir, '{{LOCALE}}')); translateFiles({ sourceRootPath: testFilesDir, sourceFilePaths: ['test.js'], outputPathFn, translationFilePaths: resolveAll(translationFilesDir, [ 'messages.de.json', 'messages.es.xlf', 'messages.fr.xlf', 'messages.it.xtb', ]), translationFileLocales: [], diagnostics, missingTranslation: 'error', duplicateTranslation: 'error', }); expect(diagnostics.messages.length).toEqual(0); expect(fs.readFile(fs.resolve(testDir, 'fr', 'test.js'))).toEqual( `var name="World";var message="Bonjour, "+name+"!";`, ); expect(fs.readFile(fs.resolve(testDir, 'de', 'test.js'))).toEqual( `var name="World";var message="Guten Tag, "+name+"!";`, ); expect(fs.readFile(fs.resolve(testDir, 'es', 'test.js'))).toEqual( `var name="World";var message="Hola, "+name+"!";`, ); expect(fs.readFile(fs.resolve(testDir, 'it', 'test.js'))).toEqual( `var name="World";var message="Ciao, "+name+"!";`, ); }); it('should translate and copy source-code files overriding the locales', () => { const diagnostics = new Diagnostics(); const outputPathFn = getOutputPathFn(fs, fs.resolve(testDir, '{{LOCALE}}')); translateFiles({ sourceRootPath: testFilesDir, sourceFilePaths: ['test.js'], outputPathFn, translationFilePaths: resolveAll(translationFilesDir, [ 'messages.de.json', 'messages.es.xlf', 'messages.fr.xlf', 'messages.it.xtb', ]), translationFileLocales: ['xde', undefined, 'fr'], diagnostics, missingTranslation: 'error', duplicateTranslation: 'error', }); expect(diagnostics.messages.length).toEqual(1); expect(diagnostics.messages).toContain({ type: 'warning', message: `The provided locale "xde" does not match the target locale "de" found in the translation file "${fs.resolve( translationFilesDir, 'messages.de.json', )}".`, }); expect(fs.readFile(fs.resolve(testDir, 'xde', 'test.js'))).toEqual( `var name="World";var message="Guten Tag, "+name+"!";`, ); expect(fs.readFile(fs.resolve(testDir, 'es', 'test.js'))).toEqual( `var name="World";var message="Hola, "+name+"!";`, ); expect(fs.readFile(fs.resolve(testDir, 'fr', 'test.js'))).toEqual( `var name="World";var message="Bonjour, "+name+"!";`, ); expect(fs.readFile(fs.resolve(testDir, 'it', 'test.js'))).toEqual( `var name="World";var message="Ciao, "+name+"!";`, ); }); it('should merge translation files, if more than one provided, and translate source-code', () => { const diagnostics = new Diagnostics(); const outputPathFn = getOutputPathFn(fs, fs.resolve(testDir, '{{LOCALE}}')); translateFiles({ sourceRootPath: testFilesDir, sourceFilePaths: ['test-extra.js'], outputPathFn, translationFilePaths: resolveAllRecursive(translationFilesDir, [ ['messages.de.json', 'messages-extra.de.json'], 'messages.es.xlf', ]), translationFileLocales: [], diagnostics, missingTranslation: 'error', duplicateTranslation: 'error', }); expect(diagnostics.messages.length).toEqual(1); // There is no "extra" translation in the `es` locale translation file. expect(diagnostics.messages[0]).toEqual({ type: 'error', message: 'No translation found for "customExtra" ("Goodbye, {$PH}!").', }); // The `de` locale translates the `customExtra` message because it is in the // `messages-extra.de.json` file that was merged. expect(fs.readFile(fs.resolve(testDir, 'de', 'test-extra.js'))).toEqual( `var name="World";var message="Guten Tag, "+name+"!";var message="Auf wiedersehen, "+name+"!";`, ); // The `es` locale does not translate `customExtra` because there is no translation for it. expect(fs.readFile(fs.resolve(testDir, 'es', 'test-extra.js'))).toEqual( `var name="World";var message="Hola, "+name+"!";var message="Goodbye, "+name+"!";`, ); });
{ "end_byte": 7585, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/main_spec.ts" }
angular/packages/localize/tools/test/translate/integration/main_spec.ts_7591_10276
it('should transform and/or copy files to the destination folders', () => { const diagnostics = new Diagnostics(); const outputPathFn = getOutputPathFn(fs, fs.resolve(testDir, '{{LOCALE}}')); translateFiles({ sourceRootPath: testFilesDir, sourceFilePaths: ['test-1.txt', 'test-2.txt', 'test.js'], outputPathFn, translationFilePaths: resolveAll(translationFilesDir, [ 'messages.de.json', 'messages.es.xlf', 'messages.fr.xlf', 'messages.it.xtb', ]), translationFileLocales: [], diagnostics, missingTranslation: 'error', duplicateTranslation: 'error', }); expect(diagnostics.messages.length).toEqual(0); expect(fs.readFile(fs.resolve(testDir, 'fr', 'test-1.txt'))).toEqual( 'Contents of test-1.txt', ); expect(fs.readFile(fs.resolve(testDir, 'fr', 'test-2.txt'))).toEqual( 'Contents of test-2.txt', ); expect(fs.readFile(fs.resolve(testDir, 'de', 'test-1.txt'))).toEqual( 'Contents of test-1.txt', ); expect(fs.readFile(fs.resolve(testDir, 'de', 'test-2.txt'))).toEqual( 'Contents of test-2.txt', ); expect(fs.readFile(fs.resolve(testDir, 'es', 'test-1.txt'))).toEqual( 'Contents of test-1.txt', ); expect(fs.readFile(fs.resolve(testDir, 'es', 'test-2.txt'))).toEqual( 'Contents of test-2.txt', ); expect(fs.readFile(fs.resolve(testDir, 'it', 'test-1.txt'))).toEqual( 'Contents of test-1.txt', ); expect(fs.readFile(fs.resolve(testDir, 'it', 'test-2.txt'))).toEqual( 'Contents of test-2.txt', ); expect(fs.readFile(fs.resolve(testDir, 'fr', 'test.js'))).toEqual( `var name="World";var message="Bonjour, "+name+"!";`, ); expect(fs.readFile(fs.resolve(testDir, 'de', 'test.js'))).toEqual( `var name="World";var message="Guten Tag, "+name+"!";`, ); expect(fs.readFile(fs.resolve(testDir, 'es', 'test.js'))).toEqual( `var name="World";var message="Hola, "+name+"!";`, ); expect(fs.readFile(fs.resolve(testDir, 'it', 'test.js'))).toEqual( `var name="World";var message="Ciao, "+name+"!";`, ); }); function resolveAll(rootPath: string, paths: string[]): string[] { return paths.map((p) => fs.resolve(rootPath, p)); } function resolveAllRecursive( rootPath: string, paths: (string | string[])[], ): (string | string[])[] { return paths.map((p) => Array.isArray(p) ? p.map((p2) => fs.resolve(rootPath, p2)) : fs.resolve(rootPath, p), ); } }); });
{ "end_byte": 10276, "start_byte": 7591, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/main_spec.ts" }
angular/packages/localize/tools/test/translate/integration/BUILD.bazel_0_842
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*_spec.ts"], ), deps = [ "//packages:types", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/testing", "//packages/localize/tools", "//packages/localize/tools/test/helpers", ], ) jasmine_node_test( name = "integration", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/localize/tools/test/translate/integration/locales", "//packages/localize/tools/test/translate/integration/test_files", ], deps = [ ":test_lib", "@npm//fast-glob", "@npm//yargs", ], )
{ "end_byte": 842, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/BUILD.bazel" }
angular/packages/localize/tools/test/translate/integration/locales/messages.it.xtb_0_438
<?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 lang="it"> <translation id="3291030485717846467">Ciao, <ph name="PH"/>!</translation> </translationbundle>
{ "end_byte": 438, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/locales/messages.it.xtb" }
angular/packages/localize/tools/test/translate/integration/locales/messages.fr.xlf_0_436
<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="3291030485717846467"> <notes> <note category="location">file.ts:2</note> </notes> <segment> <source>Hello, <ph id="1" equiv="PH" />!</source> <target>Bonjour, <ph id="1" equiv="PH" />!</target> </segment> </unit> </file> </xliff>
{ "end_byte": 436, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/locales/messages.fr.xlf" }
angular/packages/localize/tools/test/translate/integration/locales/messages.es.xlf_0_565
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" target-language="es" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="3291030485717846467" datatype="html"> <source>Hello, <x id="PH"/>!</source> <target>Hola, <x id="PH"/>!</target> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">2</context> </context-group> </trans-unit> </body> </file> </xliff>
{ "end_byte": 565, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/locales/messages.es.xlf" }
angular/packages/localize/tools/test/translate/integration/locales/BUILD.bazel_0_349
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") package(default_visibility = ["//packages/localize/tools/test/translate/integration:__pkg__"]) # Use copy_to_bin since filegroup doesn't seem to work on Windows. copy_to_bin( name = "locales", srcs = glob([ "**/*.json", "**/*.xlf", "**/*.xtb", ]), )
{ "end_byte": 349, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/locales/BUILD.bazel" }
angular/packages/localize/tools/test/translate/integration/test_files/test.js_0_62
var name = 'World'; var message = $localize`Hello, ${name}!`;
{ "end_byte": 62, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/test_files/test.js" }
angular/packages/localize/tools/test/translate/integration/test_files/test-extra.js_0_121
var name = 'World'; var message = $localize`Hello, ${name}!`; var message = $localize`:@@customExtra:Goodbye, ${name}!`;
{ "end_byte": 121, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/test_files/test-extra.js" }
angular/packages/localize/tools/test/translate/integration/test_files/BUILD.bazel_0_330
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") package(default_visibility = ["//packages/localize/tools/test/translate/integration:__pkg__"]) # Use copy_to_bin since filegroup doesn't seem to work on Windows. copy_to_bin( name = "test_files", srcs = glob([ "**/*.js", "**/*.txt", ]), )
{ "end_byte": 330, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/test_files/BUILD.bazel" }
angular/packages/localize/tools/test/translate/integration/test_files/test-1.txt_0_22
Contents of test-1.txt
{ "end_byte": 22, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/test_files/test-1.txt" }
angular/packages/localize/tools/test/translate/integration/test_files/test-2.txt_0_22
Contents of test-2.txt
{ "end_byte": 22, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/integration/test_files/test-2.txt" }
angular/packages/localize/tools/test/translate/asset_files/asset_file_translation_handler_spec.ts_0_3086
/** * @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 { absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, PathSegment, relativeFrom, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {Diagnostics} from '../../../src/diagnostics'; import {AssetTranslationHandler} from '../../../src/translate/asset_files/asset_translation_handler'; import {TranslationBundle} from '../../../src/translate/translator'; runInEachFileSystem(() => { describe('AssetTranslationHandler', () => { let fs: FileSystem; let rootPath: AbsoluteFsPath; let filePath: PathSegment; let enTranslationPath: AbsoluteFsPath; let enUSTranslationPath: AbsoluteFsPath; let frTranslationPath: AbsoluteFsPath; beforeEach(() => { fs = getFileSystem(); rootPath = absoluteFrom('/src/path'); filePath = relativeFrom('relative/path'); enTranslationPath = absoluteFrom('/translations/en/relative/path'); enUSTranslationPath = absoluteFrom('/translations/en-US/relative/path'); frTranslationPath = absoluteFrom('/translations/fr/relative/path'); }); describe('canTranslate()', () => { it('should always return true', () => { const handler = new AssetTranslationHandler(fs); expect(handler.canTranslate(filePath, Buffer.from('contents'))).toBe(true); }); }); describe('translate()', () => { it('should write the translated file for each translation locale', () => { const diagnostics = new Diagnostics(); const handler = new AssetTranslationHandler(fs); const translations = [ {locale: 'en', translations: {}}, {locale: 'fr', translations: {}}, ]; const contents = Buffer.from('contents'); handler.translate( diagnostics, rootPath, filePath, contents, mockOutputPathFn, translations, ); expect(fs.readFileBuffer(enTranslationPath)).toEqual(contents); expect(fs.readFileBuffer(frTranslationPath)).toEqual(contents); }); it('should write the translated file to the source locale if provided', () => { const diagnostics = new Diagnostics(); const handler = new AssetTranslationHandler(fs); const translations: TranslationBundle[] = []; const contents = Buffer.from('contents'); const sourceLocale = 'en-US'; handler.translate( diagnostics, rootPath, filePath, contents, mockOutputPathFn, translations, sourceLocale, ); expect(fs.readFileBuffer(enUSTranslationPath)).toEqual(contents); }); }); }); function mockOutputPathFn(locale: string, relativePath: string) { return `/translations/${locale}/${relativePath}`; } });
{ "end_byte": 3086, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/asset_files/asset_file_translation_handler_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_loader_spec.ts_0_946
/** * @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 { absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {ɵParsedTranslation, ɵparseTranslation} from '@angular/localize'; import {DiagnosticHandlingStrategy, Diagnostics} from '../../../src/diagnostics'; import {TranslationLoader} from '../../../src/translate/translation_files/translation_loader'; import {SimpleJsonTranslationParser} from '../../../src/translate/translation_files/translation_parsers/simple_json_translation_parser'; import { ParseAnalysis, TranslationParser, } from '../../../src/translate/translation_files/translation_parsers/translation_parser';
{ "end_byte": 946, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_loader_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_loader_spec.ts_948_10140
nInEachFileSystem(() => { describe('TranslationLoader', () => { describe('loadBundles()', () => { const alwaysCanParse = () => true; const neverCanParse = () => false; let fs: FileSystem; let enTranslationPath: AbsoluteFsPath; const enTranslationContent = '{"locale": "en", "translations": {"a": "A"}}'; let frTranslationPath: AbsoluteFsPath; const frTranslationContent = '{"locale": "fr", "translations": {"a": "A"}}'; let frExtraTranslationPath: AbsoluteFsPath; const frExtraTranslationContent = '{"locale": "fr", "translations": {"b": "B"}}'; let jsonParser: SimpleJsonTranslationParser; beforeEach(() => { fs = getFileSystem(); enTranslationPath = absoluteFrom('/src/locale/messages.en.json'); frTranslationPath = absoluteFrom('/src/locale/messages.fr.json'); frExtraTranslationPath = absoluteFrom('/src/locale/extra.fr.json'); fs.ensureDir(absoluteFrom('/src/locale')); fs.writeFile(enTranslationPath, enTranslationContent); fs.writeFile(frTranslationPath, frTranslationContent); fs.writeFile(frExtraTranslationPath, frExtraTranslationContent); jsonParser = new SimpleJsonTranslationParser(); }); it('should call `analyze()` and `parse()` for each file', () => { const diagnostics = new Diagnostics(); const parser = new MockTranslationParser(alwaysCanParse, 'fr'); const loader = new TranslationLoader(fs, [parser], 'error', diagnostics); loader.loadBundles([[enTranslationPath], [frTranslationPath]], []); expect(parser.log).toEqual([ `canParse(${enTranslationPath}, ${enTranslationContent})`, `parse(${enTranslationPath}, ${enTranslationContent})`, `canParse(${frTranslationPath}, ${frTranslationContent})`, `parse(${frTranslationPath}, ${frTranslationContent})`, ]); }); it('should stop at the first parser that can parse each file', () => { const diagnostics = new Diagnostics(); const parser1 = new MockTranslationParser(neverCanParse); const parser2 = new MockTranslationParser(alwaysCanParse, 'fr'); const parser3 = new MockTranslationParser(alwaysCanParse, 'en'); const loader = new TranslationLoader(fs, [parser1, parser2, parser3], 'error', diagnostics); loader.loadBundles([[enTranslationPath], [frTranslationPath]], []); expect(parser1.log).toEqual([ `canParse(${enTranslationPath}, ${enTranslationContent})`, `canParse(${frTranslationPath}, ${frTranslationContent})`, ]); expect(parser2.log).toEqual([ `canParse(${enTranslationPath}, ${enTranslationContent})`, `parse(${enTranslationPath}, ${enTranslationContent})`, `canParse(${frTranslationPath}, ${frTranslationContent})`, `parse(${frTranslationPath}, ${frTranslationContent})`, ]); }); it('should return locale and translations parsed from each file', () => { const translations = {}; const diagnostics = new Diagnostics(); const parser = new MockTranslationParser(alwaysCanParse, 'pl', translations); const loader = new TranslationLoader(fs, [parser], 'error', diagnostics); const result = loader.loadBundles([[enTranslationPath], [frTranslationPath]], []); expect(result).toEqual([ {locale: 'pl', translations, diagnostics: new Diagnostics()}, {locale: 'pl', translations, diagnostics: new Diagnostics()}, ]); }); it('should return the provided locale if there is no parsed locale', () => { const translations = {}; const diagnostics = new Diagnostics(); const parser = new MockTranslationParser(alwaysCanParse, undefined, translations); const loader = new TranslationLoader(fs, [parser], 'error', diagnostics); const result = loader.loadBundles([[enTranslationPath], [frTranslationPath]], ['en', 'fr']); expect(result).toEqual([ {locale: 'en', translations, diagnostics: new Diagnostics()}, {locale: 'fr', translations, diagnostics: new Diagnostics()}, ]); }); it('should merge multiple translation files, if given, for a each locale', () => { const diagnostics = new Diagnostics(); const loader = new TranslationLoader(fs, [jsonParser], 'error', diagnostics); const result = loader.loadBundles([[frTranslationPath, frExtraTranslationPath]], []); expect(result).toEqual([ { locale: 'fr', translations: {'a': ɵparseTranslation('A'), 'b': ɵparseTranslation('B')}, diagnostics: new Diagnostics(), }, ]); }); const allDiagnosticModes: DiagnosticHandlingStrategy[] = ['ignore', 'warning', 'error']; allDiagnosticModes.forEach((mode) => it(`should ${mode} on duplicate messages when merging multiple translation files`, () => { const diagnostics = new Diagnostics(); const loader = new TranslationLoader(fs, [jsonParser], mode, diagnostics); // Change the fs-extra file to have the same translations as fr. fs.writeFile(frExtraTranslationPath, frTranslationContent); const result = loader.loadBundles([[frTranslationPath, frExtraTranslationPath]], []); expect(result).toEqual([ { locale: 'fr', translations: {'a': ɵparseTranslation('A')}, diagnostics: jasmine.any(Diagnostics), }, ]); if (mode === 'error' || mode === 'warning') { expect(diagnostics.messages).toEqual([ { type: mode, message: `Duplicate translations for message "a" when merging "${frExtraTranslationPath}".`, }, ]); } }), ); it('should warn if the provided locales do not match the parsed locales', () => { const diagnostics = new Diagnostics(); const loader = new TranslationLoader(fs, [jsonParser], 'error', diagnostics); loader.loadBundles([[enTranslationPath], [frTranslationPath]], [undefined, 'es']); expect(diagnostics.messages.length).toEqual(1); expect(diagnostics.messages).toContain({ type: 'warning', message: `The provided locale "es" does not match the target locale "fr" found in the translation file "${frTranslationPath}".`, }); }); it('should warn on differing target locales when merging multiple translation files', () => { const diagnostics = new Diagnostics(); const fr1 = absoluteFrom('/src/locale/messages-1.fr.json'); fs.writeFile(fr1, '{"locale":"fr", "translations": {"a": "A"}}'); const fr2 = absoluteFrom('/src/locale/messages-2.fr.json'); fs.writeFile(fr2, '{"locale":"fr", "translations": {"b": "B"}}'); const de = absoluteFrom('/src/locale/messages.de.json'); fs.writeFile(de, '{"locale":"de", "translations": {"c": "C"}}'); const loader = new TranslationLoader(fs, [jsonParser], 'error', diagnostics); const result = loader.loadBundles([[fr1, fr2, de]], []); expect(result).toEqual([ { locale: 'fr', translations: { 'a': ɵparseTranslation('A'), 'b': ɵparseTranslation('B'), 'c': ɵparseTranslation('C'), }, diagnostics: jasmine.any(Diagnostics), }, ]); expect(diagnostics.messages).toEqual([ { type: 'warning', message: `When merging multiple translation files, the target locale "de" found in "${de}" ` + `does not match the target locale "fr" found in earlier files ["${fr1}", "${fr2}"].`, }, ]); }); it('should throw an error if there is no provided nor parsed target locale', () => { const translations = {}; const diagnostics = new Diagnostics(); const parser = new MockTranslationParser(alwaysCanParse, undefined, translations); const loader = new TranslationLoader(fs, [parser], 'error', diagnostics); expect(() => loader.loadBundles([[enTranslationPath]], [])).toThrowError( `The translation file "${enTranslationPath}" does not contain a target locale and no explicit locale was provided for this file.`, ); }); it('should error if none of the parsers can parse the file', () => { const diagnostics = new Diagnostics(); const parser = new MockTranslationParser(neverCanParse); const loader = new TranslationLoader(fs, [parser], 'error', diagnostics); expect(() => loader.loadBundles([[enTranslationPath], [frTranslationPath]], []), ).toThrowError( `There is no "TranslationParser" that can parse this translation file: ${enTranslationPath}.\n` + `MockTranslationParser cannot parse translation file.\n` + `WARNINGS:\n - This is a mock failure warning.`, ); }); }); }); clas
{ "end_byte": 10140, "start_byte": 948, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_loader_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_loader_spec.ts_10144_11055
ckTranslationParser implements TranslationParser { log: string[] = []; constructor( private _canParse: (filePath: string) => boolean, private _locale?: string, private _translations: Record<string, ɵParsedTranslation> = {}, ) {} analyze(filePath: string, fileContents: string): ParseAnalysis<true> { const diagnostics = new Diagnostics(); diagnostics.warn('This is a mock failure warning.'); this.log.push(`canParse(${filePath}, ${fileContents})`); return this._canParse(filePath) ? {canParse: true, hint: true, diagnostics} : {canParse: false, diagnostics}; } parse(filePath: string, fileContents: string) { this.log.push(`parse(${filePath}, ${fileContents})`); return { locale: this._locale, translations: this._translations, diagnostics: new Diagnostics(), }; } } });
{ "end_byte": 11055, "start_byte": 10144, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_loader_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xtb_translation_parser_spec.ts_0_3868
/** * @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, ɵmakeParsedTranslation} from '@angular/localize'; import { ParseAnalysis, ParsedTranslationBundle, } from '../../../../src/translate/translation_files/translation_parsers/translation_parser'; import {XtbTranslationParser} from '../../../../src/translate/translation_files/translation_parsers/xtb_translation_parser'; describe('XtbTranslationParser', () => { describe('analyze()', () => { it('should return true if the file extension is `.xtb` or `.xmb` and it contains the `<translationbundle>` tag', () => { const parser = new XtbTranslationParser(); expect(parser.analyze('/some/file.xtb', '<translationbundle>').canParse).toBeTrue(); expect(parser.analyze('/some/file.xmb', '<translationbundle>').canParse).toBeTrue(); expect(parser.analyze('/some/file.xtb', '<translationbundle lang="en">').canParse).toBeTrue(); expect(parser.analyze('/some/file.xmb', '<translationbundle lang="en">').canParse).toBeTrue(); expect(parser.analyze('/some/file.json', '<translationbundle>').canParse).toBeFalse(); expect(parser.analyze('/some/file.xmb', '').canParse).toBeFalse(); expect(parser.analyze('/some/file.xtb', '').canParse).toBeFalse(); }); }); describe('analyze()', () => { it('should return a success object if the file extension is `.xtb` or `.xmb` and it contains the `<translationbundle>` tag', () => { const parser = new XtbTranslationParser(); expect(parser.analyze('/some/file.xtb', '<translationbundle>')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); expect(parser.analyze('/some/file.xmb', '<translationbundle>')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); expect(parser.analyze('/some/file.xtb', '<translationbundle lang="en">')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); expect(parser.analyze('/some/file.xmb', '<translationbundle lang="en">')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); }); it('should return a failure object if the file is not valid XTB', () => { const parser = new XtbTranslationParser(); expect(parser.analyze('/some/file.json', '<translationbundle>')).toEqual( jasmine.objectContaining({canParse: false}), ); expect(parser.analyze('/some/file.xmb', '')).toEqual( jasmine.objectContaining({ canParse: false, }), ); expect(parser.analyze('/some/file.xtb', '')).toEqual( jasmine.objectContaining({ canParse: false, }), ); }); it('should return a diagnostics object when the file is not a valid format', () => { let results: ParseAnalysis<any>; const parser = new XtbTranslationParser(); results = parser.analyze('/some/file.xtb', '<moo>'); expect(results.diagnostics.messages).toEqual([ { type: 'warning', message: 'The XML file does not contain a <translationbundle> root node.', }, ]); results = parser.analyze('/some/file.xtb', '<translationbundle></translation>'); expect(results.diagnostics.messages).toEqual([ { type: 'error', message: 'Unexpected closing tag "translation". 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 ("<translationbundle>[ERROR ->]</translation>"): /some/file.xtb@0:19', }, ]); }); });
{ "end_byte": 3868, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xtb_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xtb_translation_parser_spec.ts_3872_10319
scribe(`parse()`, () => { const doParse: (fileName: string, XTB: string) => ParsedTranslationBundle = (fileName, XTB) => { const parser = new XtbTranslationParser(); const analysis = parser.analyze(fileName, XTB); if (!analysis.canParse) { throw new Error('expected XTB to be valid'); } return parser.parse(fileName, XTB, analysis.hint); }; const expectToFail: ( fileName: string, XLIFF: string, errorMatcher: RegExp, diagnosticMessage: string, ) => void = (fileName, XLIFF, _errorMatcher, diagnosticMessage) => { const result = doParse(fileName, XLIFF); expect(result.diagnostics.messages.length).toEqual(1); expect(result.diagnostics.messages[0].message).toEqual(diagnosticMessage); }; it('should extract the locale from the file contents', () => { const XTB = ` <?xml version="1.0" encoding="UTF-8"?> <translationbundle lang='fr'> <translation id="8841459487341224498">rab</translation> </translationbundle> `; const result = doParse('/some/file.xtb', XTB); expect(result.locale).toEqual('fr'); }); it('should extract basic messages', () => { 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> `; const result = doParse('/some/file.xtb', XTB); expect(result.translations['8841459487341224498']).toEqual(ɵmakeParsedTranslation(['rab'])); }); it('should extract translations with simple 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> `; const result = doParse('/some/file.xtb', XTB); expect(result.translations['8877975308926375834']).toEqual( ɵmakeParsedTranslation(['', 'rab', ''], ['START_PARAGRAPH', 'CLOSE_PARAGRAPH']), ); }); it('should extract nested placeholder containers (i.e. nested HTML elements)', () => { /** * Source HTML: * * ``` * <div i18n> * translatable <span>element <b>with placeholders</b></span> {{ interpolation}} * </div> * ``` */ const XLIFF = [ `<?xml version="1.0" encoding="UTF-8"?>`, `<translationbundle>`, ` <translation id="9051630253697141670">` + `<ph name="START_TAG_SPAN"/><ph name="INTERPOLATION"/> tnemele<ph name="CLOSE_TAG_SPAN"/> elbatalsnart <ph name="START_BOLD_TEXT"/>sredlohecalp htiw<ph name="CLOSE_BOLD_TEXT"/>` + `</translation>`, `</translationbundle>`, ].join('\n'); const result = doParse('/some/file.xtb', XLIFF); expect( result.translations[ ɵcomputeMsgId( 'translatable {$START_TAG_SPAN}element {$START_BOLD_TEXT}with placeholders' + '{$CLOSE_BOLD_TEXT}{$CLOSE_TAG_SPAN} {$INTERPOLATION}', ) ], ).toEqual( ɵmakeParsedTranslation( ['', '', ' tnemele', ' elbatalsnart ', 'sredlohecalp htiw', ''], [ 'START_TAG_SPAN', 'INTERPOLATION', 'CLOSE_TAG_SPAN', 'START_BOLD_TEXT', 'CLOSE_BOLD_TEXT', ], ), ); }); it('should extract translations with simple ICU expressions', () => { 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> `; const result = doParse('/some/file.xtb', XTB); expect(result.translations['7717087045075616176']).toEqual( ɵmakeParsedTranslation(['*', '*'], ['ICU']), ); expect(result.translations['5115002811911870583']).toEqual( ɵmakeParsedTranslation( ['{VAR_PLURAL, plural, =1 {{START_PARAGRAPH}rab{CLOSE_PARAGRAPH}}}'], [], ), ); }); it('should extract translations with duplicate source messages', () => { const XTB = ` <translationbundle> <translation id="9205907420411818817">oof</translation> <translation id="i">toto</translation> <translation id="bar">tata</translation> </translationbundle> `; const result = doParse('/some/file.xtb', XTB); expect(result.translations[ɵcomputeMsgId('foo')]).toEqual(ɵmakeParsedTranslation(['oof'])); expect(result.translations['i']).toEqual(ɵmakeParsedTranslation(['toto'])); expect(result.translations['bar']).toEqual(ɵmakeParsedTranslation(['tata'])); }); it('should extract translations with only placeholders, which are re-ordered', () => { const XTB = ` <translationbundle>, <translation id="7118057989405618448"><ph name="TAG_IMG_1"/><ph name="TAG_IMG"/><ph name="LINE_BREAK"/></translation> </translationbundle> `; const result = doParse('/some/file.xtb', XTB); expect(result.translations[ɵcomputeMsgId('{$LINE_BREAK}{$TAG_IMG}{$TAG_IMG_1}')]).toEqual( ɵmakeParsedTranslation(['', '', '', ''], ['TAG_IMG_1', 'TAG_IMG', 'LINE_BREAK']), ); }); it('should extract translations with empty target', () => { /** * Source HTML: * * ``` * <div i18n>hello <span></span></div> * ``` */ const XTB = ` <translationbundle> <translation id="2826198357052921524"></translation> </translationbundle> `; const result = doParse('/some/file.xtb', XTB); expect( result.translations[ɵcomputeMsgId('hello {$START_TAG_SPAN}{$CLOSE_TAG_SPAN}')], ).toEqual(ɵmakeParsedTranslation([''])); }); it('should
{ "end_byte": 10319, "start_byte": 3872, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xtb_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xtb_translation_parser_spec.ts_10325_17664
ct translations with deeply nested ICUs', () => { /** * Source HTML: * * ``` * Test: { count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} } =other {a lot}} * ``` * * Note that the message gets split into two translation units: * * The first one contains the outer message with an `ICU` placeholder * * The second one is the ICU expansion itself * * Note that special markers `VAR_PLURAL` and `VAR_SELECT` are added, which are then replaced by IVY at runtime with the actual values being rendered by the ICU expansion. */ const XTB = ` <translationbundle> <translation id="980940425376233536">Le test: <ph name="ICU" equiv-text="{ count, plural, =0 {...} =other {...}}"/></translation> <translation id="5207293143089349404">{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<ph name="START_PARAGRAPH"/>profondément imbriqué<ph name="CLOSE_PARAGRAPH"/>}}} =other {beaucoup}}</translation> </translationbundle> `; const result = doParse('/some/file.xtb', XTB); expect(result.translations[ɵcomputeMsgId('Test: {$ICU}')]).toEqual( ɵmakeParsedTranslation(['Le test: ', ''], ['ICU']), ); expect( result.translations[ ɵcomputeMsgId( '{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {{START_PARAGRAPH}deeply nested{CLOSE_PARAGRAPH}}}} =other {beaucoup}}', ) ], ).toEqual( ɵmakeParsedTranslation([ '{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {{START_PARAGRAPH}profondément imbriqué{CLOSE_PARAGRAPH}}}} =other {beaucoup}}', ]), ); }); it('should extract translations containing multiple lines', () => { /** * Source HTML: * * ``` * <div i18n>multi * lines</div> * ``` */ const XTB = ` <translationbundle> <translation id="2340165783990709777">multi\nlignes</translation> </translationbundle> `; const result = doParse('/some/file.xtb', XTB); expect(result.translations[ɵcomputeMsgId('multi\nlines')]).toEqual( ɵmakeParsedTranslation(['multi\nlignes']), ); }); it('should warn on unrecognised ICU messages', () => { // See https://github.com/angular/angular/issues/14046 const XTB = [ `<translationbundle>`, ` <translation id="valid">This is a valid message</translation>`, ` <translation id="invalid">{REGION_COUNT_1, plural, =0 {unused plural form} =1 {1 region} other {{REGION_COUNT_2} regions}}</translation>`, `</translationbundle>`, ].join('\n'); // Parsing the file should not fail const result = doParse('/some/file.xtb', XTB); // We should be able to read the valid message expect(result.translations['valid']).toEqual( ɵmakeParsedTranslation(['This is a valid message']), ); // Trying to access the invalid message should fail expect(result.translations['invalid']).toBeUndefined(); expect(result.diagnostics.messages).toContain({ type: 'warning', message: [ `Could not parse message with id "invalid" - perhaps it has an unrecognised ICU format?`, `Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) ("id">{REGION_COUNT_1, plural, =0 {unused plural form} =1 {1 region} other {{REGION_COUNT_2} regions}}[ERROR ->]</translation>`, `</translationbundle>"): /some/file.xtb@2:124`, `Invalid ICU message. Missing '}'. ("n>`, ` <translation id="invalid">{REGION_COUNT_1, plural, =0 {unused plural form} =1 {1 region} other [ERROR ->]{{REGION_COUNT_2} regions}}</translation>`, `</translationbundle>"): /some/file.xtb@2:97`, ].join('\n'), }); }); describe('[structure errors]', () => { it('should throw when there are nested translationbundle tags', () => { const XTB = '<translationbundle><translationbundle></translationbundle></translationbundle>'; expectToFail( '/some/file.xtb', XTB, /Failed to parse "\/some\/file.xtb" as XMB\/XTB format/, `Unexpected <translationbundle> tag. ("<translationbundle>[ERROR ->]<translationbundle></translationbundle></translationbundle>"): /some/file.xtb@0:19`, ); }); it('should throw when a translation has no id attribute', () => { const XTB = [ `<translationbundle>`, ` <translation></translation>`, `</translationbundle>`, ].join('\n'); expectToFail( '/some/file.xtb', XTB, /Missing required "id" attribute/, [ `Missing required "id" attribute on <translation> element. ("<translationbundle>`, ` [ERROR ->]<translation></translation>`, `</translationbundle>"): /some/file.xtb@1:2`, ].join('\n'), ); }); it('should throw on duplicate translation id', () => { const XTB = [ `<translationbundle>`, ` <translation id="deadbeef"></translation>`, ` <translation id="deadbeef"></translation>`, `</translationbundle>`, ].join('\n'); expectToFail( '/some/file.xtb', XTB, /Duplicated translations for message "deadbeef"/, [ `Duplicated translations for message "deadbeef" ("<translationbundle>`, ` <translation id="deadbeef"></translation>`, ` [ERROR ->]<translation id="deadbeef"></translation>`, `</translationbundle>"): /some/file.xtb@2:2`, ].join('\n'), ); }); }); describe('[message errors]', () => { it('should throw on unknown message tags', () => { const XTB = [ `<translationbundle>`, ` <translation id="deadbeef">`, ` <source/>`, ` </translation>`, `</translationbundle>`, ].join('\n'); expectToFail( '/some/file.xtb', XTB, /Invalid element found in message/, [ `Error: Invalid element found in message.`, `At /some/file.xtb@2:4:`, `...`, ` <translation id="deadbeef">`, ` [ERROR ->]<source/>`, ` </translation>`, `...`, ``, ].join('\n'), ); }); it('should throw when a placeholder misses a name attribute', () => { const XTB = [ `<translationbundle>`, ` <translation id="deadbeef"><ph/></translation>`, `</translationbundle>`, ].join('\n'); expectToFail( '/some/file.xtb', XTB, /required "name" attribute/gi, [ `Error: Missing required "name" attribute:`, `At /some/file.xtb@1:29:`, `...<translationbundle>`, ` <translation id="deadbeef">[ERROR ->]<ph/></translation>`, `</translationbundle>...`, ``, ].join('\n'), ); }); }); }); });
{ "end_byte": 17664, "start_byte": 10325, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xtb_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts_0_4704
/** * @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, ɵmakeParsedTranslation} from '@angular/localize'; import { ParseAnalysis, ParsedTranslationBundle, } from '../../../../src/translate/translation_files/translation_parsers/translation_parser'; import {Xliff2TranslationParser} from '../../../../src/translate/translation_files/translation_parsers/xliff2_translation_parser'; describe('Xliff2TranslationParser', () => { describe('analyze()', () => { it('should return true if the file contains an <xliff> element with version="2.0" attribute', () => { const parser = new Xliff2TranslationParser(); expect( parser.analyze( '/some/file.xlf', '<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0">', ).canParse, ).toBeTrue(); expect( parser.analyze( '/some/file.json', '<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0">', ).canParse, ).toBeTrue(); expect(parser.analyze('/some/file.xliff', '<xliff version="2.0">').canParse).toBeTrue(); expect(parser.analyze('/some/file.json', '<xliff version="2.0">').canParse).toBeTrue(); expect(parser.analyze('/some/file.xlf', '<xliff>').canParse).toBeFalse(); expect(parser.analyze('/some/file.xlf', '<xliff version="1.2">').canParse).toBeFalse(); expect(parser.analyze('/some/file.xlf', '').canParse).toBeFalse(); expect(parser.analyze('/some/file.json', '').canParse).toBeFalse(); }); }); describe('analyze', () => { it('should return a success object if the file contains an <xliff> element with version="2.0" attribute', () => { const parser = new Xliff2TranslationParser(); expect( parser.analyze( '/some/file.xlf', '<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0">', ), ).toEqual(jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)})); expect( parser.analyze( '/some/file.json', '<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0">', ), ).toEqual(jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)})); expect(parser.analyze('/some/file.xliff', '<xliff version="2.0">')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); expect(parser.analyze('/some/file.json', '<xliff version="2.0">')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); }); it('should return a failure object if the file cannot be parsed as XLIFF 2.0', () => { const parser = new Xliff2TranslationParser(); expect(parser.analyze('/some/file.xlf', '<xliff>')).toEqual( jasmine.objectContaining({ canParse: false, }), ); expect(parser.analyze('/some/file.xlf', '<xliff version="1.2">')).toEqual( jasmine.objectContaining({canParse: false}), ); expect(parser.analyze('/some/file.xlf', '')).toEqual( jasmine.objectContaining({ canParse: false, }), ); expect(parser.analyze('/some/file.json', '')).toEqual( jasmine.objectContaining({ canParse: false, }), ); }); it('should return a diagnostics object when the file is not a valid format', () => { let result: ParseAnalysis<any>; const parser = new Xliff2TranslationParser(); result = parser.analyze('/some/file.xlf', '<moo>'); expect(result.diagnostics.messages).toEqual([ {type: 'warning', message: 'The XML file does not contain a <xliff> root node.'}, ]); result = parser.analyze('/some/file.xlf', '<xliff version="1.2">'); expect(result.diagnostics.messages).toEqual([ { type: 'warning', message: 'The <xliff> node does not have the required attribute: version="2.0". ("[WARNING ->]<xliff version="1.2">"): /some/file.xlf@0:0', }, ]); result = parser.analyze('/some/file.xlf', '<xliff version="2.0"></file>'); expect(result.diagnostics.messages).toEqual([ { type: 'error', message: 'Unexpected closing tag "file". 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 ("<xliff version="2.0">[ERROR ->]</file>"): /some/file.xlf@0:21', }, ]); }); });
{ "end_byte": 4704, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts_4708_11491
scribe(`parse()`, () => { const doParse: (fileName: string, XLIFF: string) => ParsedTranslationBundle = ( fileName, XLIFF, ) => { const parser = new Xliff2TranslationParser(); const analysis = parser.analyze(fileName, XLIFF); if (!analysis.canParse) { throw new Error('expected XLIFF to be valid'); } return parser.parse(fileName, XLIFF, analysis.hint); }; const expectToFail: ( fileName: string, XLIFF: string, errorMatcher: RegExp, diagnosticMessage: string, ) => void = (fileName, XLIFF, _errorMatcher, diagnosticMessage) => { const result = doParse(fileName, XLIFF); expect(result.diagnostics.messages.length).toBeGreaterThan(0); expect(result.diagnostics.messages.pop()!.message).toEqual(diagnosticMessage); }; it('should extract the locale from the file contents', () => { const XLIFF = ` <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en" trgLang="fr"> <file original="ng.template" id="ngi18n"> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.locale).toEqual('fr'); }); it('should return undefined locale if there is no locale in the file', () => { const XLIFF = ` <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en"> <file original="ng.template" id="ngi18n"> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.locale).toBeUndefined(); }); it('should extract basic messages', () => { /** * Source HTML: * * ``` * <div i18n>translatable attribute</div> * ``` */ const XLIFF = ` <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> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('translatable attribute', '')]).toEqual( ɵmakeParsedTranslation(['etubirtta elbatalsnart']), ); }); it('should extract translations with simple placeholders', () => { /** * Source HTML: * * ``` * <div i18n>translatable element <b>with placeholders</b> {{ interpolation}}</div> * ``` */ const XLIFF = [ `<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="6949438802869886378">`, ` <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="&lt;b&gt;" dispEnd="&lt;/b&gt;">with placeholders</pc> <ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/></source>`, ` <target><ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/> tnemele elbatalsnart <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;">sredlohecalp htiw</pc></target>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>`, ].join('\n'); const result = doParse('/some/file.xlf', XLIFF); expect( result.translations[ ɵcomputeMsgId( 'translatable element {$START_BOLD_TEXT}with placeholders{$CLOSE_BOLD_TEXT} {$INTERPOLATION}', ) ], ).toEqual( ɵmakeParsedTranslation( ['', ' tnemele elbatalsnart ', 'sredlohecalp htiw', ''], ['INTERPOLATION', 'START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], ), ); }); it('should extract nested placeholder containers (i.e. nested HTML elements)', () => { /** * Source HTML: * * ``` * <div i18n> * translatable <span>element <b>with placeholders</b></span> {{ interpolation}} * </div> * ``` */ const XLIFF = ` <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="9051630253697141670"> <notes> <note category="location">file.ts:3</note> </notes> <segment> <source>translatable <pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other" dispStart="&lt;span&gt;" dispEnd="&lt;/span&gt;">element <pc id="1" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;">with placeholders</pc></pc> <ph id="2" equiv="INTERPOLATION" disp="{{ interpolation}}"/></source><target><pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="fmt" dispStart="&lt;span&gt;" dispEnd="&lt;/span&gt;"><ph id="2" equiv="INTERPOLATION" disp="{{ interpolation}}"/> tnemele</pc> elbatalsnart <pc id="1" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;">sredlohecalp htiw</pc></target> </segment> </unit> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect( result.translations[ ɵcomputeMsgId( 'translatable {$START_TAG_SPAN}element {$START_BOLD_TEXT}with placeholders' + '{$CLOSE_BOLD_TEXT}{$CLOSE_TAG_SPAN} {$INTERPOLATION}', ) ], ).toEqual( ɵmakeParsedTranslation( ['', '', ' tnemele', ' elbatalsnart ', 'sredlohecalp htiw', ''], [ 'START_TAG_SPAN', 'INTERPOLATION', 'CLOSE_TAG_SPAN', 'START_BOLD_TEXT', 'CLOSE_BOLD_TEXT', ], ), ); }); it
{ "end_byte": 11491, "start_byte": 4708, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts_11497_18048
ld extract translations with simple ICU expressions', () => { /** * Source HTML: * * ``` * <div i18n>{VAR_PLURAL, plural, =0 {<p>test</p>} }</div> * ``` */ const XLIFF = ` <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="2874455947211586270"> <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="&lt;p&gt;" dispEnd="&lt;/p&gt;">test</pc>} }</source> <target>{VAR_PLURAL, plural, =0 {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">TEST</pc>} }</target> </segment> </unit> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect( result.translations[ ɵcomputeMsgId('{VAR_PLURAL, plural, =0 {{START_PARAGRAPH}test{CLOSE_PARAGRAPH}}}') ], ).toEqual( ɵmakeParsedTranslation( ['{VAR_PLURAL, plural, =0 {{START_PARAGRAPH}TEST{CLOSE_PARAGRAPH}}}'], [], ), ); }); it('should extract translations with duplicate source messages', () => { /** * Source HTML: * * ``` * <div i18n>foo</div> * <div i18n="m|d@@i">foo</div> * <div i18=""m|d@@bar>foo</div> * ``` */ const XLIFF = ` <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="9205907420411818817"> <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="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>toto</target> </segment> </unit> <unit id="bar"> <notes> <note category="description">d</note> <note category="meaning">m</note> <note category="location">file.ts:5</note> </notes> <segment> <source>foo</source> <target>tata</target> </segment> </unit> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('foo')]).toEqual(ɵmakeParsedTranslation(['oof'])); expect(result.translations['i']).toEqual(ɵmakeParsedTranslation(['toto'])); expect(result.translations['bar']).toEqual(ɵmakeParsedTranslation(['tata'])); }); it('should extract translations with only placeholders, which are re-ordered', () => { /** * Source HTML: * * ``` * <div i18n><br><img/><img/></div> * ``` */ const XLIFF = ` <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="7118057989405618448"> <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="&lt;br/&gt;"/><ph id="1" equiv="TAG_IMG" type="image" disp="&lt;img/&gt;"/><ph id="2" equiv="TAG_IMG_1" type="image" disp="&lt;img/&gt;"/></source> <target><ph id="2" equiv="TAG_IMG_1" type="image" disp="&lt;img/&gt;"/><ph id="1" equiv="TAG_IMG" type="image" disp="&lt;img/&gt;"/><ph id="0" equiv="LINE_BREAK" type="fmt" disp="&lt;br/&gt;"/></target> </segment> </unit> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('{$LINE_BREAK}{$TAG_IMG}{$TAG_IMG_1}')]).toEqual( ɵmakeParsedTranslation(['', '', '', ''], ['TAG_IMG_1', 'TAG_IMG', 'LINE_BREAK']), ); }); it('should extract translations with empty target', () => { /** * Source HTML: * * ``` * <div i18n>hello <span></span></div> * ``` */ const XLIFF = ` <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="2826198357052921524"> <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="&lt;span&gt;" dispEnd="&lt;/span&gt;"></pc></source> <target></target> </segment> </unit> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect( result.translations[ɵcomputeMsgId('hello {$START_TAG_SPAN}{$CLOSE_TAG_SPAN}')], ).toEqual(ɵmakeParsedTranslation([''])); }); it('should e
{ "end_byte": 18048, "start_byte": 11497, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts_18054_25804
translations with deeply nested ICUs', () => { /** * Source HTML: * * ``` * Test: { count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} } * =other {a lot}} * ``` * * Note that the message gets split into two translation units: * * The first one contains the outer message with an `ICU` placeholder * * The second one is the ICU expansion itself * * Note that special markers `VAR_PLURAL` and `VAR_SELECT` are added, which are then * replaced by IVY at runtime with the actual values being rendered by the ICU * expansion. */ const XLIFF = ` <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="980940425376233536"> <notes> <note category="location">file.ts:10</note> </notes> <segment> <source>Test: <ph id="0" equiv="ICU" disp="{ count, plural, =0 {...} =other {...}}"/></source> <target>Le test: <ph id="0" equiv="ICU" disp="{ count, plural, =0 {...} =other {...}}"/></target> </segment> </unit> <unit id="5207293143089349404"> <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="&lt;p&gt;" dispEnd="&lt;/p&gt;">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="&lt;p&gt;" dispEnd="&lt;/p&gt;">profondément imbriqué</pc>}}} =other {beaucoup}}</target> </segment> </unit> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('Test: {$ICU}')]).toEqual( ɵmakeParsedTranslation(['Le test: ', ''], ['ICU']), ); expect( result.translations[ ɵcomputeMsgId( '{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {{START_PARAGRAPH}deeply nested{CLOSE_PARAGRAPH}}}} =other {beaucoup}}', ) ], ).toEqual( ɵmakeParsedTranslation([ '{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {{START_PARAGRAPH}profondément imbriqué{CLOSE_PARAGRAPH}}}} =other {beaucoup}}', ]), ); }); it('should extract translations containing multiple lines', () => { /** * Source HTML: * * ``` * <div i18n>multi * lines</div> * ``` */ const XLIFF = ` <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="2340165783990709777"> <notes> <note category="location">file.ts:11,12</note> </notes> <segment> <source>multi\nlines</source> <target>multi\nlignes</target> </segment> </unit> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('multi\nlines')]).toEqual( ɵmakeParsedTranslation(['multi\nlignes']), ); }); it('should extract translations with <mrk> elements', () => { const XLIFF = ` <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="mrk-test"> <segment> <source>First sentence.</source> <target>Translated <mrk id="m1" type="comment" ref="#n1">first sentence</mrk>.</target> </segment> </unit> <unit id="mrk-test2"> <segment> <source>First sentence. Second sentence.</source> <target>Translated <mrk id="m1" type="comment" ref="#n1"><mrk id="m2" type="comment" ref="#n1">first</mrk> sentence</mrk>.</target> </segment> </unit> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations['mrk-test']).toEqual( ɵmakeParsedTranslation(['Translated first sentence.']), ); expect(result.translations['mrk-test2']).toEqual( ɵmakeParsedTranslation(['Translated first sentence.']), ); }); it('should merge messages from each `<file>` element', () => { /** * Source HTML: * * ``` * <div i18n>translatable attribute</div> * ``` * * ``` * <div i18n>translatable element <b>with placeholders</b> {{ interpolation}}</div> * ``` */ const XLIFF = ` <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en" trgLang="fr"> <file original="ng.template" id="file-1"> <unit id="1933478729560469763"> <notes> <note category="location">file.ts:2</note> </notes> <segment> <source>translatable attribute</source> <target>etubirtta elbatalsnart</target> </segment> </unit> </file> <file original="ng.template" id="file-2"> <unit id="5057824347511785081"> <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="&lt;b&gt;" dispEnd="&lt;/b&gt;">with placeholders</pc> <ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/></source> <target><ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/> tnemele elbatalsnart <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;">sredlohecalp htiw</pc></target> </segment> </unit> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('translatable attribute', '')]).toEqual( ɵmakeParsedTranslation(['etubirtta elbatalsnart']), ); expect( result.translations[ ɵcomputeMsgId( 'translatable element {$START_BOLD_TEXT}with placeholders{$LOSE_BOLD_TEXT} {$INTERPOLATION}', ) ], ).toEqual( ɵmakeParsedTranslation( ['', ' tnemele elbatalsnart ', 'sredlohecalp htiw', ''], ['INTERPOLATION', 'START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], ), ); }); describe('[structure errors]
{ "end_byte": 25804, "start_byte": 18054, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts_25810_32549
=> { it('should provide a diagnostic warning when a trans-unit has no translation target but does have a source', () => { const XLIFF = [ `<?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="missingtarget">`, ` <segment>`, ` <source/>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>`, ].join('\n'); const result = doParse('/some/file.xlf', XLIFF); expect(result.diagnostics.messages.length).toEqual(1); expect(result.diagnostics.messages[0].message).toEqual( [ `Missing <target> element ("`, ` <file original="ng.template" id="ngi18n">`, ` <unit id="missingtarget">`, ` [WARNING ->]<segment>`, ` <source/>`, ` </segment>`, `"): /some/file.xlf@4:6`, ].join('\n'), ); }); it('should provide a diagnostic error when a trans-unit has no translation target nor source', () => { const XLIFF = [ `<?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="missingtarget">`, ` <segment>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /Missing required element: one of <target> or <source> is required/, [ `Missing required element: one of <target> or <source> is required ("`, ` <file original="ng.template" id="ngi18n">`, ` <unit id="missingtarget">`, ` [ERROR ->]<segment>`, ` </segment>`, ` </unit>`, `"): /some/file.xlf@4:6`, ].join('\n'), ); }); it('should provide a diagnostic error when a trans-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" trgLang="fr">`, ` <file original="ng.template" id="ngi18n">`, ` <unit>`, ` <segment>`, ` <source/>`, ` <target/>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /Missing required "id" attribute/, [ `Missing required "id" attribute on <trans-unit> element. ("s:tc:xliff:document:2.0" srcLang="en" trgLang="fr">`, ` <file original="ng.template" id="ngi18n">`, ` [ERROR ->]<unit>`, ` <segment>`, ` <source/>`, `"): /some/file.xlf@3:4`, ].join('\n'), ); }); it('should provide a diagnostic error on duplicate trans-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" trgLang="fr">`, ` <file original="ng.template" id="ngi18n">`, ` <unit id="deadbeef">`, ` <segment>`, ` <source/>`, ` <target/>`, ` </segment>`, ` </unit>`, ` <unit id="deadbeef">`, ` <segment>`, ` <source/>`, ` <target/>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /Duplicated translations for message "deadbeef"/, [ `Duplicated translations for message "deadbeef" ("`, ` </segment>`, ` </unit>`, ` [ERROR ->]<unit id="deadbeef">`, ` <segment>`, ` <source/>`, '"): /some/file.xlf@9:4', ].join('\n'), ); }); }); describe('[message errors]', () => { it('should provide a diagnostic error 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" trgLang="fr">`, ` <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>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /Invalid element found in message/, [ `Error: Invalid element found in message.`, `At /some/file.xlf@6:16:`, `...`, ` <source/>`, ` <target>[ERROR ->]<b>msg should contain only ph and pc tags</b></target>`, ` </segment>`, `...`, ``, ].join('\n'), ); }); it('should provide a diagnostic error 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" trgLang="fr">`, ` <file original="ng.template" id="ngi18n">`, ` <unit id="deadbeef">`, ` <segment>`, ` <source/>`, ` <target><ph/></target>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /Missing required "equiv" attribute/, [ `Error: Missing required "equiv" attribute:`, `At /some/file.xlf@6:16:`, `...`, ` <source/>`, ` <target>[ERROR ->]<ph/></target>`, ` </segment>`, `...`, ``, ].join('\n'), ); }); }); }); });
{ "end_byte": 32549, "start_byte": 25810, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff2_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/simple_json_spec.ts_0_3644
/** * @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 {ɵmakeTemplateObject} from '@angular/localize'; import {SimpleJsonTranslationParser} from '../../../../src/translate/translation_files/translation_parsers/simple_json_translation_parser'; import {ParsedTranslationBundle} from '../../../../src/translate/translation_files/translation_parsers/translation_parser'; describe('SimpleJsonTranslationParser', () => { describe('analyze()', () => { it('should return true if the file extension is `.json` and contains top level `locale` and `translations` properties', () => { const parser = new SimpleJsonTranslationParser(); expect(parser.analyze('/some/file.xlf', '').canParse).toBeFalse(); expect(parser.analyze('/some/file.json', '{}').canParse).toBeFalse(); expect(parser.analyze('/some/file.json', '{ "translations" : {} }').canParse).toBeFalse(); expect(parser.analyze('/some/file.json', '{ "locale" : "fr" }').canParse).toBeFalse(); expect( parser.analyze('/some/file.json', '{ "locale" : "fr", "translations" : {}}').canParse, ).toBeTrue(); }); }); describe('analyze()', () => { it('should return a success object if the file extension is `.json` and contains top level `locale` and `translations` properties', () => { const parser = new SimpleJsonTranslationParser(); expect(parser.analyze('/some/file.json', '{ "locale" : "fr", "translations" : {}}')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); }); it('should return a failure object if the file is not a valid format', () => { const parser = new SimpleJsonTranslationParser(); expect(parser.analyze('/some/file.xlf', '')).toEqual( jasmine.objectContaining({ canParse: false, }), ); expect(parser.analyze('/some/file.json', '{}')).toEqual( jasmine.objectContaining({ canParse: false, }), ); expect(parser.analyze('/some/file.json', '{ "translations" : {} }')).toEqual( jasmine.objectContaining({canParse: false}), ); expect(parser.analyze('/some/file.json', '{ "locale" : "fr" }')).toEqual( jasmine.objectContaining({canParse: false}), ); }); }); describe(`parse()`, () => { const doParse: (fileName: string, contents: string) => ParsedTranslationBundle = ( fileName, contents, ) => { const parser = new SimpleJsonTranslationParser(); const analysis = parser.analyze(fileName, contents); if (!analysis.canParse) { throw new Error('expected contents to be valid'); } return parser.parse(fileName, contents, analysis.hint); }; it('should extract the locale from the JSON contents', () => { const result = doParse('/some/file.json', '{"locale": "en", "translations": {}}'); expect(result.locale).toEqual('en'); }); it('should extract and process the translations from the JSON contents', () => { const result = doParse( '/some/file.json', `{ "locale": "fr", "translations": { "Hello, {$ph_1}!": "Bonjour, {$ph_1}!" } }`, ); expect(result.translations).toEqual({ 'Hello, {$ph_1}!': { text: 'Bonjour, {$ph_1}!', messageParts: ɵmakeTemplateObject(['Bonjour, ', '!'], ['Bonjour, ', '!']), placeholderNames: ['ph_1'], }, }); }); }); });
{ "end_byte": 3644, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/simple_json_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/arb_translation_parser_spec.ts_0_1953
/** * @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 {ɵmakeTemplateObject} from '@angular/localize'; import {ArbTranslationParser} from '../../../../src/translate/translation_files/translation_parsers/arb_translation_parser'; describe('SimpleArbTranslationParser', () => { describe('analyze()', () => { it('should return true if the file extension is `.json` and contains `@@locale` property', () => { const parser = new ArbTranslationParser(); expect(parser.analyze('/some/file.xlf', '').canParse).toBeFalse(); expect(parser.analyze('/some/file.json', 'xxx').canParse).toBeFalse(); expect(parser.analyze('/some/file.json', '{ "someKey": "someValue" }').canParse).toBeFalse(); expect( parser.analyze('/some/file.json', '{ "@@locale": "en", "someKey": "someValue" }').canParse, ).toBeTrue(); }); }); describe('parse()', () => { it('should extract the locale from the JSON contents', () => { const parser = new ArbTranslationParser(); const result = parser.parse('/some/file.json', '{"@@locale": "en"}'); expect(result.locale).toEqual('en'); }); it('should extract and process the translations from the JSON contents', () => { const parser = new ArbTranslationParser(); const result = parser.parse( '/some/file.json', `{ "@@locale": "fr", "customId": "Bonjour, {$ph_1}!", "@customId": { "type": "text", "description": "Some description" } }`, ); expect(result.translations).toEqual({ 'customId': { text: 'Bonjour, {$ph_1}!', messageParts: ɵmakeTemplateObject(['Bonjour, ', '!'], ['Bonjour, ', '!']), placeholderNames: ['ph_1'], }, }); }); }); });
{ "end_byte": 1953, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/arb_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts_0_4557
/** * @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, ɵmakeParsedTranslation} from '@angular/localize'; import { ParseAnalysis, ParsedTranslationBundle, } from '../../../../src/translate/translation_files/translation_parsers/translation_parser'; import {Xliff1TranslationParser} from '../../../../src/translate/translation_files/translation_parsers/xliff1_translation_parser'; describe('Xliff1TranslationParser', () => { describe('analyze()', () => { it('should return true only if the file contains an <xliff> element with version="1.2" attribute', () => { const parser = new Xliff1TranslationParser(); expect( parser.analyze( '/some/file.xlf', '<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">', ).canParse, ).toBeTrue(); expect( parser.analyze( '/some/file.json', '<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">', ).canParse, ).toBeTrue(); expect(parser.analyze('/some/file.xliff', '<xliff version="1.2">').canParse).toBeTrue(); expect(parser.analyze('/some/file.json', '<xliff version="1.2">').canParse).toBeTrue(); expect(parser.analyze('/some/file.xlf', '<xliff>').canParse).toBeFalse(); expect(parser.analyze('/some/file.xlf', '<xliff version="2.0">').canParse).toBeFalse(); expect(parser.analyze('/some/file.xlf', '').canParse).toBeFalse(); expect(parser.analyze('/some/file.json', '').canParse).toBeFalse(); }); }); describe('analyze()', () => { it('should return a success object if the file contains an <xliff> element with version="1.2" attribute', () => { const parser = new Xliff1TranslationParser(); expect(parser.analyze('/some/file.xlf', '<xliff version="1.2">')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); expect(parser.analyze('/some/file.json', '<xliff version="1.2">')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); expect(parser.analyze('/some/file.xliff', '<xliff version="1.2">')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); expect(parser.analyze('/some/file.json', '<xliff version="1.2">')).toEqual( jasmine.objectContaining({canParse: true, hint: jasmine.any(Object)}), ); }); it('should return a failure object if the file cannot be parsed as XLIFF 1.2', () => { const parser = new Xliff1TranslationParser(); expect(parser.analyze('/some/file.xlf', '<xliff>')).toEqual( jasmine.objectContaining({ canParse: false, }), ); expect(parser.analyze('/some/file.xlf', '<xliff version="2.0">')).toEqual( jasmine.objectContaining({canParse: false}), ); expect(parser.analyze('/some/file.xlf', '')).toEqual( jasmine.objectContaining({ canParse: false, }), ); expect(parser.analyze('/some/file.json', '')).toEqual( jasmine.objectContaining({ canParse: false, }), ); }); it('should return a diagnostics object when the file is not a valid format', () => { let result: ParseAnalysis<any>; const parser = new Xliff1TranslationParser(); result = parser.analyze('/some/file.xlf', '<moo>'); expect(result.diagnostics.messages).toEqual([ {type: 'warning', message: 'The XML file does not contain a <xliff> root node.'}, ]); result = parser.analyze('/some/file.xlf', '<xliff version="2.0">'); expect(result.diagnostics.messages).toEqual([ { type: 'warning', message: 'The <xliff> node does not have the required attribute: version="1.2". ("[WARNING ->]<xliff version="2.0">"): /some/file.xlf@0:0', }, ]); result = parser.analyze('/some/file.xlf', '<xliff version="1.2"></file>'); expect(result.diagnostics.messages).toEqual([ { type: 'error', message: 'Unexpected closing tag "file". 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 ("<xliff version="1.2">[ERROR ->]</file>"): /some/file.xlf@0:21', }, ]); }); });
{ "end_byte": 4557, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts_4561_11602
scribe(`parse()`, () => { const doParse: (fileName: string, XLIFF: string) => ParsedTranslationBundle = ( fileName, XLIFF, ) => { const parser = new Xliff1TranslationParser(); const analysis = parser.analyze(fileName, XLIFF); if (!analysis.canParse) { throw new Error('expected XLIFF to be valid'); } return parser.parse(fileName, XLIFF, analysis.hint); }; const expectToFail: ( fileName: string, XLIFF: string, errorMatcher: RegExp, diagnosticMessage: string, ) => void = (fileName, XLIFF, _errorMatcher, diagnosticMessage) => { const result = doParse(fileName, XLIFF); expect(result.diagnostics.messages.length).toBeGreaterThan(0); expect(result.diagnostics.messages.pop()!.message).toEqual(diagnosticMessage); }; it('should extract the locale from the last `<file>` element to contain a `target-language` attribute', () => { const XLIFF = ` <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" datatype="plaintext" original="ng2.template"> <body></body> </file> <file source-language="en" target-language="fr" datatype="plaintext" original="ng2.template"> <body></body> </file> <file source-language="en" datatype="plaintext" original="ng2.template"> <body></body> </file> <file source-language="en" target-language="de" datatype="plaintext" original="ng2.template"> <body></body> </file> <file source-language="en" datatype="plaintext" original="ng2.template"> <body></body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.locale).toEqual('de'); }); it('should return an undefined locale if there is no locale in the file', () => { const XLIFF = ` <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" datatype="plaintext" original="ng2.template"> <body> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.locale).toBeUndefined(); }); it('should extract basic messages', () => { /** * Source HTML: * * ``` * <div i18n>translatable attribute</div> * ``` */ 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 id="1933478729560469763" 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> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('translatable attribute')]).toEqual( ɵmakeParsedTranslation(['etubirtta elbatalsnart']), ); }); it('should extract translations with simple placeholders', () => { /** * Source HTML: * * ``` * <div i18n>translatable element <b>with placeholders</b> {{ interpolation}}</div> * ``` */ 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 id="5057824347511785081" 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"/> tnemele 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> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect( result.translations[ ɵcomputeMsgId( 'translatable element {$START_BOLD_TEXT}with placeholders{$LOSE_BOLD_TEXT} {$INTERPOLATION}', ) ], ).toEqual( ɵmakeParsedTranslation( ['', ' tnemele elbatalsnart ', 'sredlohecalp htiw', ''], ['INTERPOLATION', 'START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], ), ); }); it('should extract nested placeholder containers (i.e. nested HTML elements)', () => { /** * Source HTML: * * ``` * <div i18n> * translatable <span>element <b>with placeholders</b></span> {{ interpolation}} * </div> * ``` */ 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 id="9051630253697141670" datatype="html"> <source>translatable <x id="START_TAG_SPAN"/>element <x id="START_BOLD_TEXT"/>with placeholders<x id="CLOSE_BOLD_TEXT"/><x id="CLOSE_TAG_SPAN"/> <x id="INTERPOLATION"/></source> <target><x id="START_TAG_SPAN"/><x id="INTERPOLATION"/> tnemele<x id="CLOSE_TAG_SPAN"/> elbatalsnart <x id="START_BOLD_TEXT"/>sredlohecalp htiw<x id="CLOSE_BOLD_TEXT"/></target> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">3</context> </context-group> </trans-unit> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect( result.translations[ ɵcomputeMsgId( 'translatable {$START_TAG_SPAN}element {$START_BOLD_TEXT}with placeholders' + '{$CLOSE_BOLD_TEXT}{$CLOSE_TAG_SPAN} {$INTERPOLATION}', ) ], ).toEqual( ɵmakeParsedTranslation( ['', '', ' tnemele', ' elbatalsnart ', 'sredlohecalp htiw', ''], [ 'START_TAG_SPAN', 'INTERPOLATION', 'CLOSE_TAG_SPAN', 'START_BOLD_TEXT', 'CLOSE_BOLD_TEXT', ], ), ); }); it
{ "end_byte": 11602, "start_byte": 4561, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts_11608_18391
ld extract translations with placeholders containing hyphens', () => { /** * Source HTML: * * ``` * <div i18n><app-my-component></app-my-component> Welcome</div> * ``` */ 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 id="2877147807876214810" datatype="html"> <source><x id="START_TAG_APP-MY-COMPONENT" ctype="x-app-my-component" equiv-text="&lt;app-my-component&gt;"/><x id="CLOSE_TAG_APP-MY-COMPONENT" ctype="x-app-my-component" equiv-text="&lt;/app-my-component&gt;"/> Welcome</source> <context-group purpose="location"> <context context-type="sourcefile">src/app/app.component.html</context> <context context-type="linenumber">1</context> </context-group> <target><x id="START_TAG_APP-MY-COMPONENT" ctype="x-app-my-component" equiv-text="&lt;app-my-component&gt;"/><x id="CLOSE_TAG_APP-MY-COMPONENT" ctype="x-app-my-component" equiv-text="&lt;/app-my-component&gt;"/> Translate</target> </trans-unit> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); const id = ɵcomputeMsgId( '{$START_TAG_APP_MY_COMPONENT}{$CLOSE_TAG_APP_MY_COMPONENT} Welcome', ); expect(result.translations[id]).toEqual( ɵmakeParsedTranslation( ['', '', ' Translate'], ['START_TAG_APP_MY_COMPONENT', 'CLOSE_TAG_APP_MY_COMPONENT'], ), ); }); it('should extract translations with simple ICU expressions', () => { /** * Source HTML: * * ``` * <div i18n>{VAR_PLURAL, plural, =0 {<p>test</p>} }</div> * ``` */ 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 id="2874455947211586270" 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> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect( result.translations[ ɵcomputeMsgId('{VAR_PLURAL, plural, =0 {{START_PARAGRAPH}test{CLOSE_PARAGRAPH}}}') ], ).toEqual( ɵmakeParsedTranslation( ['{VAR_PLURAL, plural, =0 {{START_PARAGRAPH}TEST{CLOSE_PARAGRAPH}}}'], [], ), ); }); it('should extract translations with duplicate source messages', () => { /** * Source HTML: * * ``` * <div i18n>foo</div> * <div i18n="m|d@@i">foo</div> * <div i18=""m|d@@bar>foo</div> * ``` */ 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 id="9205907420411818817" 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> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('foo')]).toEqual(ɵmakeParsedTranslation(['oof'])); expect(result.translations['i']).toEqual(ɵmakeParsedTranslation(['toto'])); expect(result.translations['bar']).toEqual(ɵmakeParsedTranslation(['tata'])); }); it('should extract translations with only placeholders, which are re-ordered', () => { /** * Source HTML: * * ``` * <div i18n><br><img/><img/></div> * ``` */ 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 id="7118057989405618448" datatype="html"> <ph id="1" equiv="TAG_IMG" type="image" disp="&lt;img/&gt;"/><ph id="2" equiv="TAG_IMG_1" type="image" disp="&lt;img/&gt;"/> <source><x id="LINE_BREAK" ctype="lb"/><x id="TAG_IMG" ctype="image"/><x id="TAG_IMG_1" ctype="image"/></source> <target><x id="TAG_IMG_1" ctype="image"/><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> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('{$LINE_BREAK}{$TAG_IMG}{$TAG_IMG_1}')]).toEqual( ɵmakeParsedTranslation(['', '', '', ''], ['TAG_IMG_1', 'TAG_IMG', 'LINE_BREAK']), ); }); it('should e
{ "end_byte": 18391, "start_byte": 11608, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts_18397_26045
translations with empty target', () => { /** * Source HTML: * * ``` * <div i18n>hello <span></span></div> * ``` */ 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 id="2826198357052921524" datatype="html"> <source>hello <x id="START_TAG_SPAN" ctype="x-span"/><x id="CLOSE_TAG_SPAN" ctype="x-span"/></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> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect( result.translations[ɵcomputeMsgId('hello {$START_TAG_SPAN}{$CLOSE_TAG_SPAN}')], ).toEqual(ɵmakeParsedTranslation([''])); }); it('should extract translations with deeply nested ICUs', () => { /** * Source HTML: * * ``` * Test: { count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} } * =other {a lot}} * ``` * * Note that the message gets split into two translation units: * * The first one contains the outer message with an `ICU` placeholder * * The second one is the ICU expansion itself * * Note that special markers `VAR_PLURAL` and `VAR_SELECT` are added, which are then * replaced by IVY at runtime with the actual values being rendered by the ICU * expansion. */ 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 id="980940425376233536" datatype="html"> <source>Test: <x id="ICU" equiv-text="{ count, plural, =0 {...} =other {...}}"/></source> <target>Le 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="5207293143089349404" 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> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('Test: {$ICU}')]).toEqual( ɵmakeParsedTranslation(['Le test: ', ''], ['ICU']), ); expect( result.translations[ ɵcomputeMsgId( '{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {{START_PARAGRAPH}deeply nested{CLOSE_PARAGRAPH}}}} =other {beaucoup}}', ) ], ).toEqual( ɵmakeParsedTranslation([ '{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {{START_PARAGRAPH}profondément imbriqué{CLOSE_PARAGRAPH}}}} =other {beaucoup}}', ]), ); }); it('should extract translations containing multiple lines', () => { /** * Source HTML: * * ``` * <div i18n>multi * lines</div> * ``` */ 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 id="2340165783990709777" datatype="html"> <source>multi\nlines</source> <target>multi\nlignes</target> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">12</context> </context-group> </trans-unit> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('multi\nlines')]).toEqual( ɵmakeParsedTranslation(['multi\nlignes']), ); }); it('should extract translations with <mrk> elements', () => { 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 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> <invalid-tag>Should not be parsed</invalid-tag> </seg-source> <target>Translated <mrk mtype="seg" mid="1"><mrk mtype="seg" mid="2">first</mrk> sentence</mrk>.</target> </trans-unit> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations['mrk-test']).toEqual( ɵmakeParsedTranslation(['Translated first sentence.']), ); expect(result.translations['mrk-test2']).toEqual( ɵmakeParsedTranslation(['Translated first sentence.']), ); }); 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> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations['registration.submit']).toEqual( ɵmakeParsedTranslation(['Weiter']), ); }); it('should merge messages f
{ "end_byte": 26045, "start_byte": 18397, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts_26051_33134
ch `<file>` element', () => { /** * Source HTML: * * ``` * <div i18n>translatable attribute</div> * ``` * ``` * <div i18n>translatable element <b>with placeholders</b> {{ interpolation}}</div> * ``` */ 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="file-1"> <body> <trans-unit id="1933478729560469763" 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> </body> </file> <file source-language="en" target-language="fr" datatype="plaintext" original="file-2"> <body> <trans-unit id="5057824347511785081" 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"/> tnemele 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> </body> </file> </xliff> `; const result = doParse('/some/file.xlf', XLIFF); expect(result.translations[ɵcomputeMsgId('translatable attribute')]).toEqual( ɵmakeParsedTranslation(['etubirtta elbatalsnart']), ); expect( result.translations[ ɵcomputeMsgId( 'translatable element {$START_BOLD_TEXT}with placeholders{$LOSE_BOLD_TEXT} {$INTERPOLATION}', ) ], ).toEqual( ɵmakeParsedTranslation( ['', ' tnemele elbatalsnart ', 'sredlohecalp htiw', ''], ['INTERPOLATION', 'START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], ), ); }); describe('[structure errors]', () => { it('should warn when a trans-unit has no translation target but does have a source', () => { 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" target-language="fr" datatype="plaintext" original="ng2.template">`, ` <body>`, ` <trans-unit id="missingtarget">`, ` <source/>`, ` </trans-unit>`, ` </body>`, ` </file>`, `</xliff>`, ].join('\n'); const result = doParse('/some/file.xlf', XLIFF); expect(result.diagnostics.messages.length).toEqual(1); expect(result.diagnostics.messages[0].message).toEqual( [ `Missing <target> element ("e-language="en" target-language="fr" datatype="plaintext" original="ng2.template">`, ` <body>`, ` [WARNING ->]<trans-unit id="missingtarget">`, ` <source/>`, ` </trans-unit>`, `"): /some/file.xlf@4:6`, ].join('\n'), ); }); it('should fail when a trans-unit has no translation target nor source', () => { 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" target-language="fr" datatype="plaintext" original="ng2.template">`, ` <body>`, ` <trans-unit id="missingtarget">`, ` </trans-unit>`, ` </body>`, ` </file>`, `</xliff>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /Missing required element: one of <target> or <source> is required/, [ `Missing required element: one of <target> or <source> is required ("e-language="en" target-language="fr" datatype="plaintext" original="ng2.template">`, ` <body>`, ` [ERROR ->]<trans-unit id="missingtarget">`, ` </trans-unit>`, ` </body>`, `"): /some/file.xlf@4:6`, ].join('\n'), ); }); it('should fail 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" target-language="fr" datatype="plaintext" original="ng2.template">`, ` <body>`, ` <trans-unit datatype="html">`, ` <source/>`, ` <target/>`, ` </trans-unit>`, ` </body>`, ` </file>`, `</xliff>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /Missing required "id" attribute/, [ `Missing required "id" attribute on <trans-unit> element. ("e-language="en" target-language="fr" datatype="plaintext" original="ng2.template">`, ` <body>`, ` [ERROR ->]<trans-unit datatype="html">`, ` <source/>`, ` <target/>`, `"): /some/file.xlf@4:6`, ].join('\n'), ); }); it('should fail 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" target-language="fr" 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>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /Duplicated translations for message "deadbeef"/, [ `Duplicated translations for message "deadbeef" ("`, ` <target/>`, ` </trans-unit>`, ` [ERROR ->]<trans-unit id="deadbeef">`, ` <source/>`, ` <target/>`, `"): /some/file.xlf@8:6`, ].join('\n'), ); }); }); describe('[message errors]', ()
{ "end_byte": 33134, "start_byte": 26051, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts_33140_35375
it('should fail 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" target-language="fr" 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>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /Invalid element found in message/, [ `Error: Invalid element found in message.`, `At /some/file.xlf@6:16:`, `...`, ` <source/>`, ` <target>[ERROR ->]<b>msg should contain only ph tags</b></target>`, ` </trans-unit>`, `...`, ``, ].join('\n'), ); }); it('should fail 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" target-language="fr" datatype="plaintext" original="ng2.template">`, ` <body>`, ` <trans-unit id="deadbeef" datatype="html">`, ` <source/>`, ` <target><x/></target>`, ` </trans-unit>`, ` </body>`, ` </file>`, `</xliff>`, ].join('\n'); expectToFail( '/some/file.xlf', XLIFF, /required "id" attribute/gi, [ `Error: Missing required "id" attribute:`, `At /some/file.xlf@6:16:`, `...`, ` <source/>`, ` <target>[ERROR ->]<x/></target>`, ` </trans-unit>`, `...`, ``, ].join('\n'), ); }); }); }); });
{ "end_byte": 35375, "start_byte": 33140, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/translation_files/translation_parsers/xliff1_translation_parser_spec.ts" }
angular/packages/localize/tools/test/translate/source_files/es5_translate_plugin_spec.ts_0_999
/** * @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 { FileSystem, getFileSystem, PathSegment, relativeFrom, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {ɵcomputeMsgId, ɵparseTranslation} from '@angular/localize'; import {ɵParsedTranslation} from '@angular/localize/private'; import {transformSync} from '@babel/core'; import {Diagnostics} from '../../../src/diagnostics'; import {TranslatePluginOptions} from '../../../src/source_file_utils'; import {makeEs5TranslatePlugin} from '../../../src/translate/source_files/es5_translate_plugin'; import {runInNativeFileSystem} from '../../helpers'; runInNativeFileSystem(() => { let fs: FileSystem; let testPath: PathSegment; beforeEach(() => { fs = getFileSystem(); testPath = relativeFrom('app/dist/test.js'); }); describe('makeEs5Plugin', () => {
{ "end_byte": 999, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/source_files/es5_translate_plugin_spec.ts" }
angular/packages/localize/tools/test/translate/source_files/es5_translate_plugin_spec.ts_1000_8731
describe('(no translations)', () => { it('should transform `$localize` calls with binary expression', () => { const input = 'const b = 10;\n$localize(["try\\n", "\\n me"], 40 + b);'; const output = transformCode(input); expect(output).toEqual('const b = 10;\n"try\\n" + (40 + b) + "\\n me";'); }); it('should strip meta blocks', () => { const input = 'const b = 10;\n$localize([":description:try\\n", ":placeholder:\\n me"], 40 + b);'; const output = transformCode(input); expect(output).toEqual('const b = 10;\n"try\\n" + (40 + b) + "\\n me";'); }); it('should not strip escaped meta blocks', () => { const input = `$localize(__makeTemplateObject([':desc:try', 'me'], ['\\\\\\:desc:try', 'me']), 40 + 2);`; const output = transformCode(input); expect(output).toEqual('":desc:try" + (40 + 2) + "me";'); }); it('should transform nested `$localize` calls', () => { const input = '$localize(["a", "b", "c"], 1, $localize(["x", "y", "z"], 5, 6));'; const output = transformCode(input); expect(output).toEqual('"a" + 1 + "b" + ("x" + 5 + "y" + 6 + "z") + "c";'); }); it('should transform calls inside functions', () => { const input = 'function foo() { $localize(["a", "b", "c"], 1, 2); }'; const output = transformCode(input); expect(output).toEqual('function foo() {\n "a" + 1 + "b" + 2 + "c";\n}'); }); it('should ignore tags with the wrong name', () => { const input = 'other(["a", "b", "c"], 1, 2);'; const output = transformCode(input); expect(output).toEqual('other(["a", "b", "c"], 1, 2);'); }); it('should transform calls with different function name configured', () => { const input = 'other(["a", "b", "c"], 1, 2);'; const output = transformCode(input, {}, {localizeName: 'other'}); expect(output).toEqual('"a" + 1 + "b" + 2 + "c";'); }); it('should ignore tags if the identifier is not global', () => { const input = 'function foo($localize) { $localize(["a", "b", "c"], 1, 2); }'; const output = transformCode(input); expect(output).toEqual('function foo($localize) {\n $localize(["a", "b", "c"], 1, 2);\n}'); }); it('should handle template object helper calls', () => { const input = `$localize(__makeTemplateObject(['try', 'me'], ['try', 'me']), 40 + 2);`; const output = transformCode(input); expect(output).toEqual('"try" + (40 + 2) + "me";'); }); it('should handle template object aliased helper calls', () => { const input = `$localize(m(['try', 'me'], ['try', 'me']), 40 + 2);`; const output = transformCode(input); expect(output).toEqual('"try" + (40 + 2) + "me";'); }); it('should handle template object inline helper calls', () => { const input = `$localize((this&&this.__makeTemplateObject||function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e})(['try', 'me'], ['try', 'me']), 40 + 2);`; const output = transformCode(input); expect(output).toEqual('"try" + (40 + 2) + "me";'); }); it('should handle cached helper calls', () => { const input = `$localize(cachedObj||(cachedObj=__makeTemplateObject(['try', 'me'],['try', 'me'])),40 + 2)`; const output = transformCode(input); expect(output).toEqual('"try" + (40 + 2) + "me";'); }); it('should handle minified code', () => { const input = `$localize( cachedObj|| ( cookedParts=['try', 'me'], rawParts=['try', 'me'], Object.defineProperty? Object.defineProperty(cookedParts,"raw",{value:rawParts}): cookedParts.raw=rawParts, cachedObj=cookedParts ),40 + 2)`; const output = transformCode(input); expect(output).toEqual('"try" + (40 + 2) + "me";'); }); it('should handle lazy-load helper calls', () => { const input = ` function _templateObject2() { var e = _taggedTemplateLiteral([':escaped-colons:Welcome to the i18n app.'], ['\\\\\\:escaped-colons:Welcome to the i18n app.']); return _templateObject2 = function() { return e }, e } function _templateObject() { var e = _taggedTemplateLiteral([' Hello ', ':INTERPOLATION:! ']); return _templateObject = function() { return e }, e } function _taggedTemplateLiteral(e, t) { return t || (t = e.slice(0)), Object.freeze(Object.defineProperties(e, {raw: {value: Object.freeze(t)}})) } const message = $localize(_templateObject2()); function foo() { console.log($localize(_templateObject(), '\ufffd0\ufffd')); } `; const output = transformCode(input); expect(output).toContain('const message = ":escaped-colons:Welcome to the i18n app."'); expect(output).toContain('console.log(" Hello " + \'\ufffd0\ufffd\' + "! ");'); expect(output).not.toContain('templateObject'); expect(output).not.toContain('templateObject2'); }); it('should add diagnostic error with code-frame information if the arguments to `$localize` are missing', () => { const input = '$localize()'; const diagnostics = new Diagnostics(); transformCode(input, {}, {}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `${testPath}: \`$localize\` called without any arguments.\n` + '> 1 | $localize()\n' + ' | ^^^^^^^^^^^', }); }); it('should add diagnostic error with code-frame information if the arguments to `$localize` are invalid', () => { const input = '$localize(...x)'; const diagnostics = new Diagnostics(); transformCode(input, {}, {}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `${testPath}: Unexpected argument to \`$localize\` (expected an array).\n` + '> 1 | $localize(...x)\n' + ' | ^^^^', }); }); it('should add diagnostic error with code-frame information if the first argument to `$localize` is not an array', () => { const input = '$localize(null, [])'; const diagnostics = new Diagnostics(); transformCode(input, {}, {}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `${testPath}: Unexpected messageParts for \`$localize\` (expected an array of strings).\n` + '> 1 | $localize(null, [])\n' + ' | ^^^^', }); }); it('should add diagnostic error with code-frame information if raw message parts are not an expression', () => { const input = '$localize(__makeTemplateObject([], ...[]))'; const diagnostics = new Diagnostics(); transformCode(input, {}, {}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `${testPath}: Unexpected \`raw\` argument to the "makeTemplateObject()" function (expected an expression).\n` + '> 1 | $localize(__makeTemplateObject([], ...[]))\n' + ' | ^^^^^', }); });
{ "end_byte": 8731, "start_byte": 1000, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/source_files/es5_translate_plugin_spec.ts" }
angular/packages/localize/tools/test/translate/source_files/es5_translate_plugin_spec.ts_8739_13338
'should add diagnostic error with code-frame information if cooked message parts are not an expression', () => { const input = '$localize(__makeTemplateObject(...[], []))'; const diagnostics = new Diagnostics(); transformCode(input, {}, {}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `${testPath}: Unexpected \`cooked\` argument to the "makeTemplateObject()" function (expected an expression).\n` + '> 1 | $localize(__makeTemplateObject(...[], []))\n' + ' | ^^^^^', }); }); it('should add diagnostic error with code-frame information if not all cooked message parts are strings', () => { const input = '$localize(__makeTemplateObject(["a", 12, "b"], ["a", "12", "b"]))'; const diagnostics = new Diagnostics(); transformCode(input, {}, {}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `${testPath}: Unexpected messageParts for \`$localize\` (expected an array of strings).\n` + '> 1 | $localize(__makeTemplateObject(["a", 12, "b"], ["a", "12", "b"]))\n' + ' | ^^^^^^^^^^^^^^', }); }); it('should add diagnostic error with code-frame information if not all raw message parts are strings', () => { const input = '$localize(__makeTemplateObject(["a", "12", "b"], ["a", 12, "b"]))'; const diagnostics = new Diagnostics(); transformCode(input, {}, {}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `${testPath}: Unexpected messageParts for \`$localize\` (expected an array of strings).\n` + '> 1 | $localize(__makeTemplateObject(["a", "12", "b"], ["a", 12, "b"]))\n' + ' | ^^^^^^^^^^^^^^', }); }); it('should add diagnostic error with code-frame information if not all substitutions are expressions', () => { const input = '$localize(__makeTemplateObject(["a", "b"], ["a", "b"]), ...[])'; const diagnostics = new Diagnostics(); transformCode(input, {}, {}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `${testPath}: Invalid substitutions for \`$localize\` (expected all substitution arguments to be expressions).\n` + '> 1 | $localize(__makeTemplateObject(["a", "b"], ["a", "b"]), ...[])\n' + ' | ^^^^^', }); }); it('should add missing translation to diagnostic errors if missingTranslation is set to "error"', () => { const input = 'const b = 10;\n$localize(["try\\n", "\\n me"], 40 + b);'; const diagnostics = new Diagnostics(); transformCode(input, {}, {missingTranslation: 'error'}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `No translation found for "${ɵcomputeMsgId( 'try\n{$PH}\n me', )}" ("try\n{$PH}\n me").`, }); }); it('should add missing translation to diagnostic warnings if missingTranslation is set to "warning"', () => { const input = 'const b = 10;\n$localize(["try\\n", "\\n me"], 40 + b);'; const diagnostics = new Diagnostics(); transformCode(input, {}, {missingTranslation: 'warning'}, diagnostics); expect(diagnostics.hasErrors).toBe(false); expect(diagnostics.messages[0]).toEqual({ type: 'warning', message: `No translation found for "${ɵcomputeMsgId( 'try\n{$PH}\n me', )}" ("try\n{$PH}\n me").`, }); }); it('should ignore missing translations if missingTranslation is set to "ignore"', () => { const input = 'const b = 10;\n$localize(["try\\n", "\\n me"], 40 + b);'; const diagnostics = new Diagnostics(); transformCode(input, {}, {missingTranslation: 'ignore'}, diagnostics); expect(diagnostics.hasErrors).toBe(false); expect(diagnostics.messages).toEqual([]); }); }); }); d
{ "end_byte": 13338, "start_byte": 8739, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/source_files/es5_translate_plugin_spec.ts" }
angular/packages/localize/tools/test/translate/source_files/es5_translate_plugin_spec.ts_13342_17066
ibe('(with translations)', () => { it('should translate message parts (identity translations)', () => { const translations = { [ɵcomputeMsgId('abc')]: ɵparseTranslation('abc'), [ɵcomputeMsgId('abc{$PH}')]: ɵparseTranslation('abc{$PH}'), [ɵcomputeMsgId('abc{$PH}def')]: ɵparseTranslation('abc{$PH}def'), [ɵcomputeMsgId('abc{$PH}def{$PH_1}')]: ɵparseTranslation('abc{$PH}def{$PH_1}'), [ɵcomputeMsgId('Hello, {$PH}!')]: ɵparseTranslation('Hello, {$PH}!'), }; const input = '$localize(["abc"]);\n' + '$localize(["abc", ""], 1 + 2 + 3);\n' + '$localize(["abc", "def"], 1 + 2 + 3);\n' + '$localize(["abc", "def", ""], 1 + 2 + 3, 4 + 5 + 6);\n' + '$localize(["Hello, ", "!"], getName());'; const output = transformCode(input, translations); expect(output).toEqual( '"abc";\n' + '"abc" + (1 + 2 + 3) + "";\n' + '"abc" + (1 + 2 + 3) + "def";\n' + '"abc" + (1 + 2 + 3) + "def" + (4 + 5 + 6) + "";\n' + '"Hello, " + getName() + "!";', ); }); it('should translate message parts (uppercase translations)', () => { const translations = { [ɵcomputeMsgId('abc')]: ɵparseTranslation('ABC'), [ɵcomputeMsgId('abc{$PH}')]: ɵparseTranslation('ABC{$PH}'), [ɵcomputeMsgId('abc{$PH}def')]: ɵparseTranslation('ABC{$PH}DEF'), [ɵcomputeMsgId('abc{$PH}def{$PH_1}')]: ɵparseTranslation('ABC{$PH}DEF{$PH_1}'), [ɵcomputeMsgId('Hello, {$PH}!')]: ɵparseTranslation('HELLO, {$PH}!'), }; const input = '$localize(["abc"]);\n' + '$localize(["abc", ""], 1 + 2 + 3);\n' + '$localize(["abc", "def"], 1 + 2 + 3);\n' + '$localize(["abc", "def", ""], 1 + 2 + 3, 4 + 5 + 6);\n' + '$localize(["Hello, ", "!"], getName());'; const output = transformCode(input, translations); expect(output).toEqual( '"ABC";\n' + '"ABC" + (1 + 2 + 3) + "";\n' + '"ABC" + (1 + 2 + 3) + "DEF";\n' + '"ABC" + (1 + 2 + 3) + "DEF" + (4 + 5 + 6) + "";\n' + '"HELLO, " + getName() + "!";', ); }); it('should translate message parts (reversing placeholders)', () => { const translations = { [ɵcomputeMsgId('abc{$PH}def{$PH_1} - Hello, {$PH_2}!')]: ɵparseTranslation( 'abc{$PH_2}def{$PH_1} - Hello, {$PH}!', ), }; const input = '$localize(["abc", "def", " - Hello, ", "!"], 1 + 2 + 3, 4 + 5 + 6, getName());'; const output = transformCode(input, translations); expect(output).toEqual( '"abc" + getName() + "def" + (4 + 5 + 6) + " - Hello, " + (1 + 2 + 3) + "!";', ); }); it('should translate message parts (removing placeholders)', () => { const translations = { [ɵcomputeMsgId('abc{$PH}def{$PH_1} - Hello, {$PH_2}!')]: ɵparseTranslation( 'abc{$PH} - Hello, {$PH_2}!', ), }; const input = '$localize(["abc", "def", " - Hello, ", "!"], 1 + 2 + 3, 4 + 5 + 6, getName());'; const output = transformCode(input, translations); expect(output).toEqual('"abc" + (1 + 2 + 3) + " - Hello, " + getName() + "!";'); }); }); function transformCode( input: string, translations: Record<string, ɵParsedTranslation> = {}, pluginOptions?: TranslatePluginOptions, diagnostics = new Diagnostics(), ): string { const cwd = fs.resolve('/'); const filename = fs.resolve(cwd, testPath); return transformSync(input, { plugins: [makeEs5TranslatePlugin(diagnostics, translations, pluginOptions)], filename, cwd, })!.code!; } });
{ "end_byte": 17066, "start_byte": 13342, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/source_files/es5_translate_plugin_spec.ts" }
angular/packages/localize/tools/test/translate/source_files/es2015_translate_plugin_spec.ts_0_4745
/** * @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 {FileSystem, getFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system'; import {ɵcomputeMsgId, ɵparseTranslation} from '@angular/localize'; import {ɵParsedTranslation} from '@angular/localize/private'; import {transformSync} from '@babel/core'; import {Diagnostics} from '../../../src/diagnostics'; import {TranslatePluginOptions} from '../../../src/source_file_utils'; import {makeEs2015TranslatePlugin} from '../../../src/translate/source_files/es2015_translate_plugin'; import {runInNativeFileSystem} from '../../helpers'; runInNativeFileSystem(() => { let fs: FileSystem; beforeEach(() => { fs = getFileSystem(); }); describe('makeEs2015Plugin', () => { describe('(no translations)', () => { it('should transform `$localize` tags with binary expression', () => { const input = 'const b = 10;\n$localize`try\\n${40 + b}\\n me`;'; const output = transformCode(input); expect(output).toEqual('const b = 10;\n"try\\n" + (40 + b) + "\\n me";'); }); it('should strip meta blocks', () => { const input = 'const b = 10;\n$localize `:description:try\\n${40 + b}\\n me`;'; const output = transformCode(input); expect(output).toEqual('const b = 10;\n"try\\n" + (40 + b) + "\\n me";'); }); it('should not strip escaped meta blocks', () => { const input = 'const b = 10;\n$localize `\\:description:try\\n${40 + b}\\n me`;'; const output = transformCode(input); expect(output).toEqual('const b = 10;\n":description:try\\n" + (40 + b) + "\\n me";'); }); it('should transform nested `$localize` tags', () => { const input = '$localize`a${1}b${$localize`x${5}y${6}z`}c`;'; const output = transformCode(input); expect(output).toEqual('"a" + 1 + "b" + ("x" + 5 + "y" + 6 + "z") + "c";'); }); it('should transform tags inside functions', () => { const input = 'function foo() { $localize`a${1}b${2}c`; }'; const output = transformCode(input); expect(output).toEqual('function foo() {\n "a" + 1 + "b" + 2 + "c";\n}'); }); it('should ignore tags with the wrong name', () => { const input = 'other`a${1}b${2}c`;'; const output = transformCode(input); expect(output).toEqual('other`a${1}b${2}c`;'); }); it('should transform tags with different tag name configured', () => { const input = 'other`a${1}b${2}c`;'; const output = transformCode(input, {}, {localizeName: 'other'}); expect(output).toEqual('"a" + 1 + "b" + 2 + "c";'); }); it('should ignore tags if the identifier is not global', () => { const input = 'function foo($localize) { $localize`a${1}b${2}c`; }'; const output = transformCode(input); expect(output).toEqual('function foo($localize) {\n $localize`a${1}b${2}c`;\n}'); }); it('should add missing translation to diagnostic errors if missingTranslation is set to "error"', () => { const input = 'const b = 10;\n$localize `try\\n${40 + b}\\n me`;'; const diagnostics = new Diagnostics(); transformCode(input, {}, {missingTranslation: 'error'}, diagnostics); expect(diagnostics.hasErrors).toBe(true); expect(diagnostics.messages[0]).toEqual({ type: 'error', message: `No translation found for "${ɵcomputeMsgId( 'try\n{$PH}\n me', )}" ("try\n{$PH}\n me").`, }); }); it('should add missing translation to diagnostic errors if missingTranslation is set to "warning"', () => { const input = 'const b = 10;\n$localize `try\\n${40 + b}\\n me`;'; const diagnostics = new Diagnostics(); transformCode(input, {}, {missingTranslation: 'warning'}, diagnostics); expect(diagnostics.hasErrors).toBe(false); expect(diagnostics.messages[0]).toEqual({ type: 'warning', message: `No translation found for "${ɵcomputeMsgId( 'try\n{$PH}\n me', )}" ("try\n{$PH}\n me").`, }); }); it('should add missing translation to diagnostic errors if missingTranslation is set to "ignore"', () => { const input = 'const b = 10;\n$localize `try\\n${40 + b}\\n me`;'; const diagnostics = new Diagnostics(); transformCode(input, {}, {missingTranslation: 'ignore'}, diagnostics); expect(diagnostics.hasErrors).toBe(false); expect(diagnostics.messages).toEqual([]); }); });
{ "end_byte": 4745, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/source_files/es2015_translate_plugin_spec.ts" }
angular/packages/localize/tools/test/translate/source_files/es2015_translate_plugin_spec.ts_4751_8532
ibe('(with translations)', () => { it('should translate message parts (identity translations)', () => { const translations = { [ɵcomputeMsgId('abc')]: ɵparseTranslation('abc'), [ɵcomputeMsgId('abc{$PH}')]: ɵparseTranslation('abc{$PH}'), [ɵcomputeMsgId('abc{$PH}def')]: ɵparseTranslation('abc{$PH}def'), [ɵcomputeMsgId('abc{$PH}def{$PH_1}')]: ɵparseTranslation('abc{$PH}def{$PH_1}'), [ɵcomputeMsgId('Hello, {$PH}!')]: ɵparseTranslation('Hello, {$PH}!'), }; const input = '$localize `abc`;\n' + '$localize `abc${1 + 2 + 3}`;\n' + '$localize `abc${1 + 2 + 3}def`;\n' + '$localize `abc${1 + 2 + 3}def${4 + 5 + 6}`;\n' + '$localize `Hello, ${getName()}!`;'; const output = transformCode(input, translations); expect(output).toEqual( '"abc";\n' + '"abc" + (1 + 2 + 3) + "";\n' + '"abc" + (1 + 2 + 3) + "def";\n' + '"abc" + (1 + 2 + 3) + "def" + (4 + 5 + 6) + "";\n' + '"Hello, " + getName() + "!";', ); }); it('should translate message parts (uppercase translations)', () => { const translations = { [ɵcomputeMsgId('abc')]: ɵparseTranslation('ABC'), [ɵcomputeMsgId('abc{$PH}')]: ɵparseTranslation('ABC{$PH}'), [ɵcomputeMsgId('abc{$PH}def')]: ɵparseTranslation('ABC{$PH}DEF'), [ɵcomputeMsgId('abc{$PH}def{$PH_1}')]: ɵparseTranslation('ABC{$PH}DEF{$PH_1}'), [ɵcomputeMsgId('Hello, {$PH}!')]: ɵparseTranslation('HELLO, {$PH}!'), }; const input = '$localize `abc`;\n' + '$localize `abc${1 + 2 + 3}`;\n' + '$localize `abc${1 + 2 + 3}def`;\n' + '$localize `abc${1 + 2 + 3}def${4 + 5 + 6}`;\n' + '$localize `Hello, ${getName()}!`;'; const output = transformCode(input, translations); expect(output).toEqual( '"ABC";\n' + '"ABC" + (1 + 2 + 3) + "";\n' + '"ABC" + (1 + 2 + 3) + "DEF";\n' + '"ABC" + (1 + 2 + 3) + "DEF" + (4 + 5 + 6) + "";\n' + '"HELLO, " + getName() + "!";', ); }); it('should translate message parts (reversing placeholders)', () => { const translations = { [ɵcomputeMsgId('abc{$PH}def{$PH_1} - Hello, {$PH_2}!')]: ɵparseTranslation( 'abc{$PH_2}def{$PH_1} - Hello, {$PH}!', ), }; const input = '$localize `abc${1 + 2 + 3}def${4 + 5 + 6} - Hello, ${getName()}!`;'; const output = transformCode(input, translations); expect(output).toEqual( '"abc" + getName() + "def" + (4 + 5 + 6) + " - Hello, " + (1 + 2 + 3) + "!";', ); }); it('should translate message parts (removing placeholders)', () => { const translations = { [ɵcomputeMsgId('abc{$PH}def{$PH_1} - Hello, {$PH_2}!')]: ɵparseTranslation( 'abc{$PH} - Hello, {$PH_2}!', ), }; const input = '$localize `abc${1 + 2 + 3}def${4 + 5 + 6} - Hello, ${getName()}!`;'; const output = transformCode(input, translations); expect(output).toEqual('"abc" + (1 + 2 + 3) + " - Hello, " + getName() + "!";'); }); }); }); function transformCode( input: string, translations: Record<string, ɵParsedTranslation> = {}, pluginOptions?: TranslatePluginOptions, diagnostics = new Diagnostics(), ): string { const cwd = fs.resolve('/'); const filename = fs.resolve(cwd, 'app/dist/test.js'); return transformSync(input, { plugins: [makeEs2015TranslatePlugin(diagnostics, translations, pluginOptions)], filename, cwd, })!.code!; } });
{ "end_byte": 8532, "start_byte": 4751, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/source_files/es2015_translate_plugin_spec.ts" }
angular/packages/localize/tools/test/translate/source_files/locale_plugin_spec.ts_0_4444
/** * @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 {transformSync} from '@babel/core'; import {makeLocalePlugin} from '../../../src/translate/source_files/locale_plugin'; describe('makeLocalePlugin', () => { it('should replace $localize.locale with the locale string', () => { const input = '$localize.locale;'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('"fr";'); }); it('should replace $localize.locale with the locale string in the context of a variable assignment', () => { const input = 'const a = $localize.locale;'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('const a = "fr";'); }); it('should replace $localize.locale with the locale string in the context of a binary expression', () => { const input = '$localize.locale || "default";'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('"fr" || "default";'); }); it('should remove reference to `$localize` if used to guard the locale', () => { const input = 'typeof $localize !== "undefined" && $localize.locale;'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('"fr";'); }); it('should remove reference to `$localize` if used in a longer logical expression to guard the locale', () => { const input1 = 'x || y && typeof $localize !== "undefined" && $localize.locale;'; const output1 = transformSync(input1, {plugins: [makeLocalePlugin('fr')]})!; expect(output1.code).toEqual('x || y && "fr";'); const input2 = 'x || y && "undefined" !== typeof $localize && $localize.locale;'; const output2 = transformSync(input2, {plugins: [makeLocalePlugin('fr')]})!; expect(output2.code).toEqual('x || y && "fr";'); const input3 = 'x || y && typeof $localize != "undefined" && $localize.locale;'; const output3 = transformSync(input3, {plugins: [makeLocalePlugin('fr')]})!; expect(output3.code).toEqual('x || y && "fr";'); const input4 = 'x || y && "undefined" != typeof $localize && $localize.locale;'; const output4 = transformSync(input4, {plugins: [makeLocalePlugin('fr')]})!; expect(output4.code).toEqual('x || y && "fr";'); }); it('should ignore properties on $localize other than `locale`', () => { const input = '$localize.notLocale;'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('$localize.notLocale;'); }); it('should ignore indexed property on $localize', () => { const input = '$localize["locale"];'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('$localize["locale"];'); }); it('should ignore `locale` on objects other than $localize', () => { const input = '$notLocalize.locale;'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('$notLocalize.locale;'); }); it('should ignore `$localize.locale` if `$localize` is not global', () => { const input = 'const $localize = {};\n$localize.locale;'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('const $localize = {};\n$localize.locale;'); }); it('should ignore `locale` if it is not directly accessed from `$localize`', () => { const input = 'const {locale} = $localize;\nconst a = locale;'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('const {\n locale\n} = $localize;\nconst a = locale;'); }); it('should ignore `$localize.locale` on LHS of an assignment', () => { const input = 'let a;\na = $localize.locale = "de";'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('let a;\na = $localize.locale = "de";'); }); it('should handle `$localize.locale on RHS of an assignment', () => { const input = 'let a;\na = $localize.locale;'; const output = transformSync(input, {plugins: [makeLocalePlugin('fr')]})!; expect(output.code).toEqual('let a;\na = "fr";'); }); });
{ "end_byte": 4444, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/source_files/locale_plugin_spec.ts" }
angular/packages/localize/tools/test/translate/source_files/source_file_translation_handler_spec.ts_0_6518
/** * @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 { absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, PathSegment, relativeFrom, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {Diagnostics} from '../../../src/diagnostics'; import {SourceFileTranslationHandler} from '../../../src/translate/source_files/source_file_translation_handler'; import {TranslationBundle} from '../../../src/translate/translator'; runInEachFileSystem(() => { describe('SourceFileTranslationHandler', () => { let fs: FileSystem; let rootPath: AbsoluteFsPath; let filePath: PathSegment; let enTranslationPath: AbsoluteFsPath; let enUSTranslationPath: AbsoluteFsPath; let frTranslationPath: AbsoluteFsPath; beforeEach(() => { fs = getFileSystem(); rootPath = absoluteFrom('/src/path'); filePath = relativeFrom('relative/path.js'); enTranslationPath = absoluteFrom('/translations/en/relative/path.js'); enUSTranslationPath = absoluteFrom('/translations/en-US/relative/path.js'); frTranslationPath = absoluteFrom('/translations/fr/relative/path.js'); }); describe('canTranslate()', () => { it('should return true if the path ends in ".js"', () => { const handler = new SourceFileTranslationHandler(fs); expect(handler.canTranslate(relativeFrom('relative/path'), Buffer.from('contents'))).toBe( false, ); expect(handler.canTranslate(filePath, Buffer.from('contents'))).toBe(true); }); }); describe('translate()', () => { it('should copy files for each translation locale if they contain no reference to `$localize`', () => { const diagnostics = new Diagnostics(); const handler = new SourceFileTranslationHandler(fs); const translations = [ {locale: 'en', translations: {}}, {locale: 'fr', translations: {}}, ]; const contents = Buffer.from('contents'); handler.translate( diagnostics, rootPath, filePath, contents, mockOutputPathFn, translations, ); expect(fs.readFileBuffer(enTranslationPath)).toEqual(contents); expect(fs.readFileBuffer(frTranslationPath)).toEqual(contents); }); it('should copy files to the source locale if they contain no reference to `$localize` and `sourceLocale` is provided', () => { const diagnostics = new Diagnostics(); const handler = new SourceFileTranslationHandler(fs); const translations: TranslationBundle[] = []; const contents = Buffer.from('contents'); handler.translate( diagnostics, rootPath, filePath, contents, mockOutputPathFn, translations, 'en-US', ); expect(fs.readFileBuffer(enUSTranslationPath)).toEqual(contents); }); it('should transform each $localize template tag', () => { const diagnostics = new Diagnostics(); const handler = new SourceFileTranslationHandler(fs); const translations = [ {locale: 'en', translations: {}}, {locale: 'fr', translations: {}}, ]; const contents = Buffer.from( '$localize`a${1}b${2}c`;\n' + '$localize(__makeTemplateObject(["a", "b", "c"], ["a", "b", "c"]), 1, 2);', ); const output = '"a"+1+"b"+2+"c";"a"+1+"b"+2+"c";'; handler.translate( diagnostics, rootPath, filePath, contents, mockOutputPathFn, translations, ); expect(fs.readFile(enTranslationPath)).toEqual(output); expect(fs.readFile(frTranslationPath)).toEqual(output); }); it('should transform each $localize template tag and write it to the source locale if provided', () => { const diagnostics = new Diagnostics(); const handler = new SourceFileTranslationHandler(fs); const translations: TranslationBundle[] = []; const contents = Buffer.from( '$localize`a${1}b${2}c`;\n' + '$localize(__makeTemplateObject(["a", "b", "c"], ["a", "b", "c"]), 1, 2);', ); const output = '"a"+1+"b"+2+"c";"a"+1+"b"+2+"c";'; handler.translate( diagnostics, rootPath, filePath, contents, mockOutputPathFn, translations, 'en-US', ); expect(fs.readFile(enUSTranslationPath)).toEqual(output); }); it('should transform `$localize.locale` identifiers', () => { const diagnostics = new Diagnostics(); const handler = new SourceFileTranslationHandler(fs); const translations: TranslationBundle[] = [{locale: 'fr', translations: {}}]; const contents = Buffer.from( 'const x = $localize.locale;\n' + 'const y = typeof $localize !== "undefined" && $localize.locale;\n' + 'const z = "undefined" !== typeof $localize && $localize.locale || "default";', ); const getOutput = (locale: string) => `const x="${locale}";const y="${locale}";const z="${locale}"||"default";`; handler.translate( diagnostics, rootPath, filePath, contents, mockOutputPathFn, translations, 'en-US', ); expect(fs.readFile(frTranslationPath)).toEqual(getOutput('fr')); expect(fs.readFile(enUSTranslationPath)).toEqual(getOutput('en-US')); }); it('should error if the file is not valid JS', () => { const diagnostics = new Diagnostics(); const handler = new SourceFileTranslationHandler(fs); const translations = [{locale: 'en', translations: {}}]; const contents = Buffer.from('this is not a valid $localize file.'); expect(() => handler.translate( diagnostics, rootPath, filePath, contents, mockOutputPathFn, translations, ), ).toThrowError(); }); }); }); function mockOutputPathFn(locale: string, relativePath: string) { return `/translations/${locale}/${relativePath}`; } });
{ "end_byte": 6518, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/translate/source_files/source_file_translation_handler_spec.ts" }
angular/packages/localize/tools/test/migrate/migrate_spec.ts_0_4972
/** * @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 {migrateFile} from '../../src/migrate/migrate'; describe('migrateFile', () => { it('should migrate all of the legacy message IDs', () => { const source = ` <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="fr-FR" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="123hello-legacy" datatype="html"> <source>Hello</source> <target>Bonjour</target> </trans-unit> <trans-unit id="456goodbye-legacy" datatype="html"> <source>Goodbye</source> <target>Au revoir</target> </trans-unit> </body> </file> </xliff> `; const result = migrateFile(source, { '123hello-legacy': 'hello-migrated', '456goodbye-legacy': 'goodbye-migrated', }); expect(result).toContain('<trans-unit id="hello-migrated" datatype="html">'); expect(result).toContain('<trans-unit id="goodbye-migrated" datatype="html">'); }); it('should migrate messages whose ID contains special regex characters', () => { const source = ` <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="fr-FR" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="123hello(.*legacy" datatype="html"> <source>Hello</source> <target>Bonjour</target> </trans-unit> </body> </file> </xliff> `; const result = migrateFile(source, {'123hello(.*legacy': 'hello-migrated'}); expect(result).toContain('<trans-unit id="hello-migrated" datatype="html">'); }); it('should not migrate messages that are not in the mapping', () => { const source = ` <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="fr-FR" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="123hello-legacy" datatype="html"> <source>Hello</source> <target>Bonjour</target> </trans-unit> <trans-unit id="456goodbye" datatype="html"> <source>Goodbye</source> <target>Au revoir</target> </trans-unit> </body> </file> </xliff> `; const result = migrateFile(source, {'123hello-legacy': 'hello-migrated'}); expect(result).toContain('<trans-unit id="hello-migrated" datatype="html">'); expect(result).toContain('<trans-unit id="456goodbye" datatype="html">'); }); it('should not modify the file if none of the mappings match', () => { const source = ` <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="fr-FR" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="123hello-legacy" datatype="html"> <source>Hello</source> <target>Bonjour</target> </trans-unit> <trans-unit id="456goodbye-legacy" datatype="html"> <source>Goodbye</source> <target>Au revoir</target> </trans-unit> </body> </file> </xliff> `; const result = migrateFile(source, { 'does-not-match': 'migrated-does-not-match', 'also-does-not-match': 'migrated-also-does-not-match', }); expect(result).toBe(source); }); // Note: it shouldn't be possible for the ID to be repeated multiple times, but // this assertion is here to make sure that it behaves as expected if it does. it('should migrate if an ID appears in more than one place', () => { const source = ` <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="fr-FR" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="123hello-legacy" datatype="html"> <source>Hello</source> <target>Bonjour</target> </trans-unit> <made-up-tag datatype="html" belongs-to="123hello-legacy"> <source id="123hello-legacy">Hello</source> <target target-id="123hello-legacy">Bonjour</target> </mage-up-tag> </body> </file> </xliff> `; const result = migrateFile(source, {'123hello-legacy': 'hello-migrated'}); expect(result).toContain('<trans-unit id="hello-migrated" datatype="html">'); expect(result).toContain('<made-up-tag datatype="html" belongs-to="hello-migrated">'); expect(result).toContain('<source id="hello-migrated">'); expect(result).toContain('<target target-id="hello-migrated">Bonjour</target>'); }); });
{ "end_byte": 4972, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/migrate/migrate_spec.ts" }
angular/packages/localize/tools/test/migrate/integration/main_spec.ts_0_7147
/** * @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 { absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {MockLogger} from '@angular/compiler-cli/src/ngtsc/logging/testing'; import {loadTestDirectory} from '@angular/compiler-cli/src/ngtsc/testing'; import path from 'path'; import url from 'url'; import {migrateFiles} from '../../../src/migrate/index'; import {runInNativeFileSystem} from '../../helpers'; const currentDir = path.dirname(url.fileURLToPath(import.meta.url)); runInNativeFileSystem(() => { let fs: FileSystem; let logger: MockLogger; let rootPath: AbsoluteFsPath; let mappingFilePath: AbsoluteFsPath; beforeEach(() => { fs = getFileSystem(); logger = new MockLogger(); rootPath = absoluteFrom('/project'); mappingFilePath = fs.resolve(rootPath, 'test_files/mapping.json'); loadTestDirectory(fs, path.join(currentDir, 'test_files'), absoluteFrom('/project/test_files')); }); describe('migrateFiles()', () => { it('should log a warning if the migration file is empty', () => { const emptyMappingPath = fs.resolve(rootPath, 'test_files/empty-mapping.json'); migrateFiles({ rootPath, translationFilePaths: ['test_files/messages.json'], logger, mappingFilePath: emptyMappingPath, }); expect(logger.logs.warn).toEqual([ [ `Mapping file at ${emptyMappingPath} is empty. Either there are no messages ` + `that need to be migrated, or the extraction step failed to find them.`, ], ]); }); it('should migrate a json message file', () => { const filePath = 'test_files/messages.json'; migrateFiles({ rootPath, translationFilePaths: [filePath], logger, mappingFilePath, }); expect(readAndNormalize(fs.resolve(rootPath, filePath))).toEqual( [ `{`, ` "locale": "en-GB",`, ` "translations": {`, ` "9876543": "Hello",`, ` "custom-id": "Custom id message",`, ` "987654321098765": "Goodbye"`, ` }`, `}`, ].join('\n'), ); }); it('should migrate an arb message file', () => { const filePath = 'test_files/messages.arb'; migrateFiles({ rootPath, translationFilePaths: [filePath], logger, mappingFilePath, }); expect(readAndNormalize(fs.resolve(rootPath, filePath))).toEqual( [ `{`, ` "@@locale": "en-GB",`, ` "9876543": "Hello",`, ` "@9876543": {`, ` "x-locations": [`, ` {`, ` "file": "test.js",`, ` "start": { "line": "1", "column": "0" },`, ` "end": { "line": "1", "column": "0" }`, ` }`, ` ]`, ` },`, ` "custom-id": "Custom id message",`, ` "@custom-id": {`, ` "x-locations": [`, ` {`, ` "file": "test.js",`, ` "start": { "line": "2", "column": "0" },`, ` "end": { "line": "2", "column": "0" }`, ` }`, ` ]`, ` },`, ` "987654321098765": "Goodbye",`, ` "@987654321098765": {`, ` "x-locations": [`, ` {`, ` "file": "test.js",`, ` "start": { "line": "3", "column": "0" },`, ` "end": { "line": "3", "column": "0" }`, ` }`, ` ]`, ` }`, `}`, ].join('\n'), ); }); it('should migrate an xmb message file', () => { const filePath = 'test_files/messages.xmb'; migrateFiles({ rootPath, translationFilePaths: [filePath], logger, mappingFilePath, }); expect(readAndNormalize(fs.resolve(rootPath, filePath))).toEqual( [ `<?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="9876543"><source>test.js:1</source>Hello</msg>`, ` <msg id="custom-id"><source>test.js:2</source>Custom id message</msg>`, ` <msg id="987654321098765"><source>test.js:3</source>Goodbye</msg>`, `</messagebundle>`, ].join('\n'), ); }); it('should migrate an xlf message file', () => { const filePath = 'test_files/messages.xlf'; migrateFiles({ rootPath, translationFilePaths: [filePath], logger, mappingFilePath, }); expect(readAndNormalize(fs.resolve(rootPath, filePath))).toEqual( [ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en-GB">`, ` <file id="ngi18n" original="ng.template" xml:space="preserve">`, ` <unit id="9876543">`, ` <notes>`, ` <note category="location">test.js:1</note>`, ` </notes>`, ` <segment>`, ` <source>Hello</source>`, ` </segment>`, ` </unit>`, ` <unit id="custom-id">`, ` <notes>`, ` <note category="location">test.js:2</note>`, ` </notes>`, ` <segment>`, ` <source>Custom id message</source>`, ` </segment>`, ` </unit>`, ` <unit id="987654321098765">`, ` <notes>`, ` <note category="location">test.js:3</note>`, ` </notes>`, ` <segment>`, ` <source>Goodbye</source>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>`, ].join('\n'), ); }); /** Reads a path from the file system and normalizes the line endings. */ function readAndNormalize(path: AbsoluteFsPath): string { return fs.readFile(path).replace(/\r?\n/g, '\n'); } }); });
{ "end_byte": 7147, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/migrate/integration/main_spec.ts" }
angular/packages/localize/tools/test/migrate/integration/BUILD.bazel_0_1090
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*_spec.ts"], ), deps = [ "//packages:types", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/logging", "//packages/compiler-cli/src/ngtsc/logging/testing", "//packages/compiler-cli/src/ngtsc/testing", "//packages/localize/tools", "//packages/localize/tools/test:test_lib", "//packages/localize/tools/test/helpers", ], ) # Use copy_to_bin since filegroup doesn't seem to work on Windows. copy_to_bin( name = "test_files", srcs = glob(["test_files/**/*"]), ) jasmine_node_test( name = "integration", bootstrap = ["//tools/testing:node_no_angular"], data = [ ":test_files", ], deps = [ ":test_lib", "@npm//fast-glob", "@npm//yargs", ], )
{ "end_byte": 1090, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/migrate/integration/BUILD.bazel" }
angular/packages/localize/tools/test/migrate/integration/test_files/messages.arb_0_759
{ "@@locale": "en-GB", "12345678901234567890": "Hello", "@12345678901234567890": { "x-locations": [ { "file": "test.js", "start": { "line": "1", "column": "0" }, "end": { "line": "1", "column": "0" } } ] }, "custom-id": "Custom id message", "@custom-id": { "x-locations": [ { "file": "test.js", "start": { "line": "2", "column": "0" }, "end": { "line": "2", "column": "0" } } ] }, "1234567890123456789012345678901234567890": "Goodbye", "@1234567890123456789012345678901234567890": { "x-locations": [ { "file": "test.js", "start": { "line": "3", "column": "0" }, "end": { "line": "3", "column": "0" } } ] } }
{ "end_byte": 759, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/migrate/integration/test_files/messages.arb" }
angular/packages/localize/tools/test/migrate/integration/test_files/messages.xlf_0_809
<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en-GB"> <file id="ngi18n" original="ng.template" xml:space="preserve"> <unit id="12345678901234567890"> <notes> <note category="location">test.js:1</note> </notes> <segment> <source>Hello</source> </segment> </unit> <unit id="custom-id"> <notes> <note category="location">test.js:2</note> </notes> <segment> <source>Custom id message</source> </segment> </unit> <unit id="1234567890123456789012345678901234567890"> <notes> <note category="location">test.js:3</note> </notes> <segment> <source>Goodbye</source> </segment> </unit> </file> </xliff>
{ "end_byte": 809, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/migrate/integration/test_files/messages.xlf" }
angular/packages/localize/tools/test/migrate/integration/test_files/messages.xmb_0_901
<?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="12345678901234567890"><source>test.js:1</source>Hello</msg> <msg id="custom-id"><source>test.js:2</source>Custom id message</msg> <msg id="1234567890123456789012345678901234567890"><source>test.js:3</source>Goodbye</msg> </messagebundle>
{ "end_byte": 901, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/migrate/integration/test_files/messages.xmb" }
angular/packages/localize/tools/test/extract/extractor_spec.ts_0_5312
/** * @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 {absoluteFrom, getFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system'; import {MockLogger} from '@angular/compiler-cli/src/ngtsc/logging/testing'; import {MessageExtractor} from '../../src/extract/extraction'; import {runInNativeFileSystem} from '../helpers'; runInNativeFileSystem(() => { describe('extractMessages', () => { it('should extract a message for each $localize template tag', () => { const fs = getFileSystem(); const logger = new MockLogger(); const basePath = absoluteFrom('/root/path/'); const filename = 'relative/path.js'; const file = fs.resolve(basePath, filename); const extractor = new MessageExtractor(fs, logger, {basePath}); fs.ensureDir(fs.dirname(file)); fs.writeFile( file, [ '$localize`:meaning|description:a${1}b${2}:ICU@@associated-id:c`;', '$localize(__makeTemplateObject(["a", ":custom-placeholder:b", "c"], ["a", ":custom-placeholder:b", "c"]), 1, 2);', '$localize`:@@custom-id:a${1}b${2}c`;', ].join('\n'), ); const messages = extractor.extractMessages(filename); expect(messages.length).toEqual(3); expect(messages[0]).toEqual({ id: '8550342801935228331', customId: undefined, description: 'description', meaning: 'meaning', messageParts: ['a', 'b', 'c'], messagePartLocations: [ { start: {line: 0, column: 10}, end: {line: 0, column: 32}, file, text: ':meaning|description:a', }, { start: {line: 0, column: 36}, end: {line: 0, column: 37}, file, text: 'b', }, { start: {line: 0, column: 41}, end: {line: 0, column: 62}, file, text: ':ICU@@associated-id:c', }, ], text: 'a{$PH}b{$ICU}c', placeholderNames: ['PH', 'ICU'], associatedMessageIds: {ICU: 'associated-id'}, substitutions: jasmine.any(Object), substitutionLocations: { PH: {start: {line: 0, column: 34}, end: {line: 0, column: 35}, file, text: '1'}, ICU: {start: {line: 0, column: 39}, end: {line: 0, column: 40}, file, text: '2'}, }, legacyIds: [], location: { start: {line: 0, column: 9}, end: {line: 0, column: 63}, file, text: '`:meaning|description:a${1}b${2}:ICU@@associated-id:c`', }, }); expect(messages[1]).toEqual({ id: '5692770902395945649', customId: undefined, description: '', meaning: '', messageParts: ['a', 'b', 'c'], messagePartLocations: [ { start: {line: 1, column: 69}, end: {line: 1, column: 72}, file, text: '"a"', }, { start: {line: 1, column: 74}, end: {line: 1, column: 97}, file, text: '":custom-placeholder:b"', }, { start: {line: 1, column: 99}, end: {line: 1, column: 102}, file, text: '"c"', }, ], text: 'a{$custom-placeholder}b{$PH_1}c', placeholderNames: ['custom-placeholder', 'PH_1'], associatedMessageIds: {}, substitutions: jasmine.any(Object), substitutionLocations: { 'custom-placeholder': { start: {line: 1, column: 106}, end: {line: 1, column: 107}, file, text: '1', }, PH_1: {start: {line: 1, column: 109}, end: {line: 1, column: 110}, file, text: '2'}, }, legacyIds: [], location: { start: {line: 1, column: 10}, end: {line: 1, column: 107}, file, text: '__makeTemplateObject(["a", ":custom-placeholder:b", "c"], ["a", ":custom-placeholder:b", "c"])', }, }); expect(messages[2]).toEqual({ id: 'custom-id', customId: 'custom-id', description: '', meaning: '', messageParts: ['a', 'b', 'c'], text: 'a{$PH}b{$PH_1}c', placeholderNames: ['PH', 'PH_1'], associatedMessageIds: {}, substitutions: jasmine.any(Object), substitutionLocations: { PH: {start: {line: 2, column: 26}, end: {line: 2, column: 27}, file, text: '1'}, PH_1: {start: {line: 2, column: 31}, end: {line: 2, column: 32}, file, text: '2'}, }, messagePartLocations: [ {start: {line: 2, column: 10}, end: {line: 2, column: 24}, file, text: ':@@custom-id:a'}, {start: {line: 2, column: 28}, end: {line: 2, column: 29}, file, text: 'b'}, {start: {line: 2, column: 33}, end: {line: 2, column: 34}, file, text: 'c'}, ], legacyIds: [], location: { start: {line: 2, column: 9}, end: {line: 2, column: 35}, file, text: '`:@@custom-id:a${1}b${2}c`', }, }); }); }); });
{ "end_byte": 5312, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/extractor_spec.ts" }
angular/packages/localize/tools/test/extract/integration/main_spec.ts_0_1802
/** * @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 { absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, setFileSystem, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {InvalidFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/src/invalid_file_system'; import {MockLogger} from '@angular/compiler-cli/src/ngtsc/logging/testing'; import {loadTestDirectory} from '@angular/compiler-cli/src/ngtsc/testing'; import path from 'path'; import url from 'url'; import {extractTranslations} from '../../../src/extract/index'; import {FormatOptions} from '../../../src/extract/translation_files/format_options'; import {runInNativeFileSystem} from '../../helpers'; import {toAttributes} from '../translation_files/utils'; const currentDir = path.dirname(url.fileURLToPath(import.meta.url)); runInNativeFileSystem(() => { let fs: FileSystem; let logger: MockLogger; let rootPath: AbsoluteFsPath; let outputPath: AbsoluteFsPath; let sourceFilePath: AbsoluteFsPath; let textFile1: AbsoluteFsPath; let textFile2: AbsoluteFsPath; beforeEach(() => { fs = getFileSystem(); logger = new MockLogger(); rootPath = absoluteFrom('/project'); outputPath = fs.resolve(rootPath, 'extracted-message-file'); sourceFilePath = fs.resolve(rootPath, 'test_files/test.js'); textFile1 = fs.resolve(rootPath, 'test_files/test-1.txt'); textFile2 = fs.resolve(rootPath, 'test_files/test-2.txt'); fs.ensureDir(fs.dirname(sourceFilePath)); loadTestDirectory(fs, path.join(currentDir, 'test_files'), absoluteFrom('/project/test_files')); setFileSystem(new InvalidFileSystem()); });
{ "end_byte": 1802, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/main_spec.ts" }
angular/packages/localize/tools/test/extract/integration/main_spec.ts_1806_9394
describe('extractTranslations()', () => { it('should ignore non-code files', () => { extractTranslations({ rootPath, sourceLocale: 'en', sourceFilePaths: [textFile1, textFile2], format: 'json', outputPath, logger, useSourceMaps: false, useLegacyIds: false, duplicateMessageHandling: 'ignore', fileSystem: fs, }); expect(fs.readFile(outputPath)).toEqual( [`{`, ` "locale": "en",`, ` "translations": {}`, `}`].join('\n'), ); }); for (const useLegacyIds of [true, false]) { describe(useLegacyIds ? '[using legacy ids]' : '', () => { it('should extract translations from source code, and write as simple JSON format', () => { extractTranslations({ rootPath, sourceLocale: 'en-GB', sourceFilePaths: [sourceFilePath], format: 'json', outputPath, logger, useSourceMaps: false, useLegacyIds, duplicateMessageHandling: 'ignore', fileSystem: fs, }); expect(fs.readFile(outputPath)).toEqual( [ `{`, ` "locale": "en-GB",`, ` "translations": {`, ` "3291030485717846467": "Hello, {$PH}!",`, ` "8669027859022295761": "try{$PH}me",`, ` "custom-id": "Custom id message",`, ` "273296103957933077": "Legacy id message",`, ` "custom-id-2": "Custom and legacy message",`, ` "2932901491976224757": "pre{$START_TAG_SPAN}inner-pre{$START_BOLD_TEXT}bold{$CLOSE_BOLD_TEXT}inner-post{$CLOSE_TAG_SPAN}post"`, ` }`, `}`, ].join('\n'), ); }); it('should extract translations from source code, and write as ARB format', () => { extractTranslations({ rootPath, sourceLocale: 'en-GB', sourceFilePaths: [sourceFilePath], format: 'arb', outputPath, logger, useSourceMaps: false, useLegacyIds, duplicateMessageHandling: 'ignore', fileSystem: fs, }); expect(fs.readFile(outputPath)).toEqual( [ '{', ' "@@locale": "en-GB",', ' "3291030485717846467": "Hello, {$PH}!",', ' "@3291030485717846467": {', ' "x-locations": [', ' {', ' "file": "test_files/test.js",', ' "start": { "line": "1", "column": "23" },', ' "end": { "line": "1", "column": "40" }', ' }', ' ]', ' },', ' "8669027859022295761": "try{$PH}me",', ' "@8669027859022295761": {', ' "x-locations": [', ' {', ' "file": "test_files/test.js",', ' "start": { "line": "2", "column": "22" },', ' "end": { "line": "2", "column": "80" }', ' }', ' ]', ' },', ' "custom-id": "Custom id message",', ' "@custom-id": {', ' "x-locations": [', ' {', ' "file": "test_files/test.js",', ' "start": { "line": "3", "column": "29" },', ' "end": { "line": "3", "column": "61" }', ' }', ' ]', ' },', ' "273296103957933077": "Legacy id message",', ' "@273296103957933077": {', ' "x-locations": [', ' {', ' "file": "test_files/test.js",', ' "start": { "line": "4", "column": "29" },', ' "end": { "line": "4", "column": "112" }', ' }', ' ]', ' },', ' "custom-id-2": "Custom and legacy message",', ' "@custom-id-2": {', ' "x-locations": [', ' {', ' "file": "test_files/test.js",', ' "start": { "line": "5", "column": "38" },', ' "end": { "line": "5", "column": "142" }', ' }', ' ]', ' },', ' "2932901491976224757": "pre{$START_TAG_SPAN}inner-pre{$START_BOLD_TEXT}bold{$CLOSE_BOLD_TEXT}inner-post{$CLOSE_TAG_SPAN}post",', ' "@2932901491976224757": {', ' "x-locations": [', ' {', ' "file": "test_files/test.js",', ' "start": { "line": "6", "column": "26" },', ' "end": { "line": "6", "column": "164" }', ' }', ' ]', ' }', '}', ].join('\n'), ); }); it('should extract translations from source code, and write as xmb format', () => { extractTranslations({ rootPath, sourceLocale: 'en', sourceFilePaths: [sourceFilePath], format: 'xmb', outputPath, logger, useSourceMaps: false, useLegacyIds, duplicateMessageHandling: 'ignore', fileSystem: fs, }); expect(fs.readFile(outputPath)).toEqual( [ `<?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="3291030485717846467"><source>test_files/test.js:1</source>Hello, <ph name="PH"/>!</msg>`, ` <msg id="8669027859022295761"><source>test_files/test.js:2</source>try<ph name="PH"/>me</msg>`, ` <msg id="custom-id"><source>test_files/test.js:3</source>Custom id message</msg>`, ` <msg id="${ useLegacyIds ? '12345678901234567890' : '273296103957933077' }"><source>test_files/test.js:4</source>Legacy id message</msg>`, ` <msg id="custom-id-2"><source>test_files/test.js:5</source>Custom and legacy message</msg>`, ` <msg id="2932901491976224757"><source>test_files/test.js:6</source>pre<ph name="START_TAG_SPAN"/>` + `inner-pre<ph name="START_BOLD_TEXT"/>bold<ph name="CLOSE_BOLD_TEXT"/>inner-post<ph name="CLOSE_TAG_SPAN"/>post</msg>`, `</messagebundle>\n`, ].join('\n'), ); });
{ "end_byte": 9394, "start_byte": 1806, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/main_spec.ts" }
angular/packages/localize/tools/test/extract/integration/main_spec.ts_9404_17492
for (const formatOptions of [{}, {'xml:space': 'preserve'}] as FormatOptions[]) { it(`should extract translations from source code, and write as XLIFF 1.2 format${ formatOptions['xml:space'] ? '[with xml:space attribute]' : '' }`, () => { extractTranslations({ rootPath, sourceLocale: 'en-CA', sourceFilePaths: [sourceFilePath], format: 'xliff', outputPath, logger, useSourceMaps: false, useLegacyIds, duplicateMessageHandling: 'ignore', formatOptions, fileSystem: fs, }); expect(fs.readFile(outputPath)).toEqual( [ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">`, ` <file source-language="en-CA" datatype="plaintext" original="ng2.template"${toAttributes( formatOptions, )}>`, ` <body>`, ` <trans-unit id="3291030485717846467" datatype="html">`, ` <source>Hello, <x id="PH" equiv-text="name"/>!</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">test_files/test.js</context>`, ` <context context-type="linenumber">2</context>`, ` </context-group>`, ` </trans-unit>`, ` <trans-unit id="8669027859022295761" datatype="html">`, ` <source>try<x id="PH" equiv-text="40 + 2"/>me</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">test_files/test.js</context>`, ` <context context-type="linenumber">3</context>`, ` </context-group>`, ` </trans-unit>`, ` <trans-unit id="custom-id" datatype="html">`, ` <source>Custom id message</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">test_files/test.js</context>`, ` <context context-type="linenumber">4</context>`, ` </context-group>`, ` </trans-unit>`, ` <trans-unit id="${ useLegacyIds ? '1234567890123456789012345678901234567890' : '273296103957933077' }" datatype="html">`, ` <source>Legacy id message</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">test_files/test.js</context>`, ` <context context-type="linenumber">5</context>`, ` </context-group>`, ` </trans-unit>`, ` <trans-unit id="custom-id-2" datatype="html">`, ` <source>Custom and legacy message</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">test_files/test.js</context>`, ` <context context-type="linenumber">6</context>`, ` </context-group>`, ` </trans-unit>`, ` <trans-unit id="2932901491976224757" datatype="html">`, ` <source>pre<x id="START_TAG_SPAN" ctype="x-span" equiv-text="&apos;&lt;span&gt;&apos;"/>` + `inner-pre<x id="START_BOLD_TEXT" ctype="x-b" equiv-text="&apos;&lt;b&gt;&apos;"/>bold<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="&apos;&lt;/b&gt;&apos;"/>` + `inner-post<x id="CLOSE_TAG_SPAN" ctype="x-span" equiv-text="&apos;&lt;/span&gt;&apos;"/>post</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">test_files/test.js</context>`, ` <context context-type="linenumber">7</context>`, ` </context-group>`, ` </trans-unit>`, ` </body>`, ` </file>`, `</xliff>\n`, ].join('\n'), ); }); it('should extract translations from source code, and write as XLIFF 2 format', () => { extractTranslations({ rootPath, sourceLocale: 'en-AU', sourceFilePaths: [sourceFilePath], format: 'xliff2', outputPath, logger, useSourceMaps: false, useLegacyIds, duplicateMessageHandling: 'ignore', formatOptions, fileSystem: fs, }); expect(fs.readFile(outputPath)).toEqual( [ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en-AU">`, ` <file id="ngi18n" original="ng.template"${toAttributes(formatOptions)}>`, ` <unit id="3291030485717846467">`, ` <notes>`, ` <note category="location">test_files/test.js:2</note>`, ` </notes>`, ` <segment>`, ` <source>Hello, <ph id="0" equiv="PH" disp="name"/>!</source>`, ` </segment>`, ` </unit>`, ` <unit id="8669027859022295761">`, ` <notes>`, ` <note category="location">test_files/test.js:3</note>`, ` </notes>`, ` <segment>`, ` <source>try<ph id="0" equiv="PH" disp="40 + 2"/>me</source>`, ` </segment>`, ` </unit>`, ` <unit id="custom-id">`, ` <notes>`, ` <note category="location">test_files/test.js:4</note>`, ` </notes>`, ` <segment>`, ` <source>Custom id message</source>`, ` </segment>`, ` </unit>`, ` <unit id="${useLegacyIds ? '12345678901234567890' : '273296103957933077'}">`, ` <notes>`, ` <note category="location">test_files/test.js:5</note>`, ` </notes>`, ` <segment>`, ` <source>Legacy id message</source>`, ` </segment>`, ` </unit>`, ` <unit id="custom-id-2">`, ` <notes>`, ` <note category="location">test_files/test.js:6</note>`, ` </notes>`, ` <segment>`, ` <source>Custom and legacy message</source>`, ` </segment>`, ` </unit>`, ` <unit id="2932901491976224757">`, ` <notes>`, ` <note category="location">test_files/test.js:7</note>`, ` </notes>`, ` <segment>`, ` <source>pre<pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other" dispStart="&apos;&lt;span&gt;&apos;" dispEnd="&apos;&lt;/span&gt;&apos;">` + `inner-pre<pc id="1" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&apos;&lt;b&gt;&apos;" dispEnd="&apos;&lt;/b&gt;&apos;">bold</pc>` + `inner-post</pc>post</source>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>\n`, ].join('\n'), ); }); } }); }
{ "end_byte": 17492, "start_byte": 9404, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/main_spec.ts" }
angular/packages/localize/tools/test/extract/integration/main_spec.ts_17498_24010
for (const target of ['es2015', 'es5']) { it(`should render the original location of translations, when processing an ${target} bundle with source-maps`, () => { extractTranslations({ rootPath, sourceLocale: 'en-CA', sourceFilePaths: [fs.resolve(rootPath, `test_files/dist_${target}/index.js`)], format: 'xliff', outputPath, logger, useSourceMaps: true, useLegacyIds: false, duplicateMessageHandling: 'ignore', fileSystem: fs, }); expect(fs.readFile(outputPath)).toEqual( [ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">`, ` <file source-language="en-CA" datatype="plaintext" original="ng2.template">`, ` <body>`, ` <trans-unit id="157258427077572998" datatype="html">`, ` <source>Message in <x id="a-file" equiv-text="file"/>!</source>`, ` <context-group purpose="location">`, // These source file paths are due to how Bazel TypeScript compilation source-maps // work ` <context context-type="sourcefile">../packages/localize/tools/test/extract/integration/test_files/src/a.ts</context>`, ` <context context-type="linenumber">3</context>`, ` </context-group>`, ` </trans-unit>`, ` <trans-unit id="7829869508202074508" datatype="html">`, ` <source>Message in <x id="b-file" equiv-text="file"/>!</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">../packages/localize/tools/test/extract/integration/test_files/src/b.ts</context>`, ` <context context-type="linenumber">3</context>`, ` </context-group>`, ` </trans-unit>`, ` </body>`, ` </file>`, `</xliff>\n`, ].join('\n'), ); }); } describe('[duplicateMessageHandling]', () => { it('should throw if set to "error"', () => { expect(() => extractTranslations({ rootPath, sourceLocale: 'en-GB', sourceFilePaths: [fs.resolve(rootPath, 'test_files/duplicate.js')], format: 'json', outputPath, logger, useSourceMaps: false, useLegacyIds: false, duplicateMessageHandling: 'error', fileSystem: fs, }), ).toThrowError( `Failed to extract messages\n` + `ERRORS:\n` + ` - Duplicate messages with id "message-2":\n` + ` - "message contents" : test_files/duplicate.js:6\n` + ` - "different message contents" : test_files/duplicate.js:7`, ); expect(fs.exists(outputPath)).toBe(false); }); it('should log to the logger if set to "warning"', () => { extractTranslations({ rootPath, sourceLocale: 'en-GB', sourceFilePaths: [fs.resolve(rootPath, 'test_files/duplicate.js')], format: 'json', outputPath, logger, useSourceMaps: false, useLegacyIds: false, duplicateMessageHandling: 'warning', fileSystem: fs, }); expect(logger.logs.warn).toEqual([ [ 'Messages extracted with warnings\n' + `WARNINGS:\n` + ` - Duplicate messages with id "message-2":\n` + ` - "message contents" : test_files/duplicate.js:6\n` + ` - "different message contents" : test_files/duplicate.js:7`, ], ]); expect(fs.readFile(outputPath)).toEqual( [ `{`, ` "locale": "en-GB",`, ` "translations": {`, ` "message-1": "message {$PH} contents",`, ` "message-2": "message contents"`, ` }`, `}`, ].join('\n'), ); }); it('should not log to the logger if set to "ignore"', () => { extractTranslations({ rootPath, sourceLocale: 'en-GB', sourceFilePaths: [fs.resolve(rootPath, 'test_files/duplicate.js')], format: 'json', outputPath, logger, useSourceMaps: false, useLegacyIds: false, duplicateMessageHandling: 'ignore', fileSystem: fs, }); expect(logger.logs.warn).toEqual([]); expect(fs.readFile(outputPath)).toEqual( [ `{`, ` "locale": "en-GB",`, ` "translations": {`, ` "message-1": "message {$PH} contents",`, ` "message-2": "message contents"`, ` }`, `}`, ].join('\n'), ); }); it('should generate the migration map file, if requested', () => { extractTranslations({ rootPath, sourceLocale: 'en', sourceFilePaths: [sourceFilePath], format: 'legacy-migrate', outputPath, logger, useSourceMaps: false, useLegacyIds: true, duplicateMessageHandling: 'ignore', fileSystem: fs, }); expect(fs.readFile(outputPath)).toEqual( [ `{`, ` "1234567890123456789012345678901234567890": "273296103957933077",`, ` "12345678901234567890": "273296103957933077"`, `}`, ].join('\n'), ); }); it('should log a warning if there are no legacy message IDs to migrate', () => { extractTranslations({ rootPath, sourceLocale: 'en', sourceFilePaths: [textFile1], format: 'legacy-migrate', outputPath, logger, useSourceMaps: false, useLegacyIds: true, duplicateMessageHandling: 'ignore', fileSystem: fs, }); expect(fs.readFile(outputPath)).toBe('{}'); expect(logger.logs.warn).toEqual([ [ 'Messages extracted with warnings\n' + 'WARNINGS:\n' + ' - Could not find any legacy message IDs in source files while generating the legacy message migration file.', ], ]); }); }); }); });
{ "end_byte": 24010, "start_byte": 17498, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/main_spec.ts" }
angular/packages/localize/tools/test/extract/integration/BUILD.bazel_0_1106
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*_spec.ts"], ), deps = [ "//packages:types", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/logging", "//packages/compiler-cli/src/ngtsc/logging/testing", "//packages/compiler-cli/src/ngtsc/testing", "//packages/localize/tools", "//packages/localize/tools/test:test_lib", "//packages/localize/tools/test/helpers", ], ) jasmine_node_test( name = "integration", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/localize/tools/test/extract/integration/test_files", "//packages/localize/tools/test/extract/integration/test_files:compile_es2015", "//packages/localize/tools/test/extract/integration/test_files:compile_es5", ], deps = [ ":test_lib", "@npm//fast-glob", "@npm//yargs", ], )
{ "end_byte": 1106, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/BUILD.bazel" }
angular/packages/localize/tools/test/extract/integration/test_files/test.js_0_640
var name = 'World'; var message = $localize`Hello, ${name}!`; var other = $localize(__makeTemplateObject(['try', 'me'], ['try', 'me']), 40 + 2); var customMessage = $localize`:@@custom-id:Custom id message`; var legacyMessage = $localize`:␟1234567890123456789012345678901234567890␟12345678901234567890:Legacy id message`; var customAndLegacyMessage = $localize`:@@custom-id-2␟1234567890123456789012345678901234567890␟12345678901234567890:Custom and legacy message`; var containers = $localize`pre${'<span>'}:START_TAG_SPAN:inner-pre${'<b>'}:START_BOLD_TEXT:bold${'</b>'}:CLOSE_BOLD_TEXT:inner-post${'</span>'}:CLOSE_TAG_SPAN:post`;
{ "end_byte": 640, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/test_files/test.js" }
angular/packages/localize/tools/test/extract/integration/test_files/BUILD.bazel_0_1226
load("@npm//typescript:index.bzl", "tsc") load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") package(default_visibility = ["//packages/localize/tools/test/extract/integration:__pkg__"]) tsc( name = "compile_es5", outs = [ "dist_es5/index.js", "dist_es5/index.js.map", ], args = [ "--target", "es5", "--module", "amd", "--outFile", "$(execpath dist_es5/index.js)", "--skipLibCheck", "--sourceMap", "--inlineSources", "$(execpath src/index.ts)", ], data = glob(["src/*.ts"]), ) tsc( name = "compile_es2015", outs = [ "dist_es2015/index.js", "dist_es2015/index.js.map", ], args = [ "--target", "es2015", "--module", "amd", "--outFile", "$(execpath dist_es2015/index.js)", "--skipLibCheck", "--sourceMap", "--inlineSources", "$(execpath src/index.ts)", ], data = glob(["src/*.ts"]), ) # Use copy_to_bin since filegroup doesn't seem to work on Windows. copy_to_bin( name = "test_files", srcs = glob([ "**/*.js", "**/*.txt", "**/*.ts", ]), )
{ "end_byte": 1226, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/test_files/BUILD.bazel" }
angular/packages/localize/tools/test/extract/integration/test_files/duplicate.js_0_336
// Different interpolation values will not affect message text const a = $localize`:@@message-1:message ${10} contents`; const b = $localize`:@@message-1:message ${20} contents`; // But different actual text content will const c = $localize`:@@message-2:message contents`; const d = $localize`:@@message-2:different message contents`;
{ "end_byte": 336, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/test_files/duplicate.js" }
angular/packages/localize/tools/test/extract/integration/test_files/test-1.txt_0_22
Contents of test-1.txt
{ "end_byte": 22, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/test_files/test-1.txt" }
angular/packages/localize/tools/test/extract/integration/test_files/test-2.txt_0_22
Contents of test-2.txt
{ "end_byte": 22, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/test_files/test-2.txt" }
angular/packages/localize/tools/test/extract/integration/test_files/src/b.ts_0_115
declare const $localize: any; const file = 'b.ts'; export const messageB = $localize`Message in ${file}:b-file:!`;
{ "end_byte": 115, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/test_files/src/b.ts" }
angular/packages/localize/tools/test/extract/integration/test_files/src/a.ts_0_115
declare const $localize: any; const file = 'a.ts'; export const messageA = $localize`Message in ${file}:a-file:!`;
{ "end_byte": 115, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/test_files/src/a.ts" }
angular/packages/localize/tools/test/extract/integration/test_files/src/index.ts_0_42
export * from './a'; export * from './b';
{ "end_byte": 42, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/integration/test_files/src/index.ts" }
angular/packages/localize/tools/test/extract/translation_files/xliff1_translation_serializer_spec.ts_0_8096
/** * @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 {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize'; import {FormatOptions} from '../../../src/extract/translation_files/format_options'; import {Xliff1TranslationSerializer} from '../../../src/extract/translation_files/xliff1_translation_serializer'; import {location, mockMessage} from './mock_message'; import {toAttributes} from './utils'; runInEachFileSystem(() => { describe('Xliff1TranslationSerializer', () => { ([{}, {'xml:space': 'preserve'}] as FormatOptions[]).forEach((options) => { [false, true].forEach((useLegacyIds) => { describe(`renderFile() [using ${useLegacyIds ? 'legacy' : 'canonical'} ids]`, () => { it('should convert a set of parsed messages into an XML string', () => { const phLocation: ɵSourceLocation = { start: {line: 0, column: 10}, end: {line: 1, column: 15}, file: absoluteFrom('/project/file.ts'), text: 'placeholder + 1', }; const messagePartLocation: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file.ts'), text: 'message part', }; const messages: ɵParsedMessage[] = [ mockMessage('12345', ['a', 'b', 'c'], ['PH', 'PH_1'], { meaning: 'some meaning', location: { file: absoluteFrom('/project/file.ts'), start: {line: 5, column: 10}, end: {line: 5, column: 12}, }, legacyIds: ['1234567890ABCDEF1234567890ABCDEF12345678', '615790887472569365'], }), mockMessage('54321', ['a', 'b', 'c'], ['PH', 'PH_1'], { customId: 'someId', legacyIds: ['87654321FEDCBA0987654321FEDCBA0987654321', '563965274788097516'], messagePartLocations: [undefined, messagePartLocation, undefined], substitutionLocations: {'PH': phLocation, 'PH_1': undefined}, }), mockMessage('67890', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { description: 'some description', }), mockMessage('38705', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { location: { file: absoluteFrom('/project/file.ts'), start: {line: 2, column: 7}, end: {line: 3, column: 2}, }, }), mockMessage('13579', ['', 'b', ''], ['START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], {}), mockMessage('24680', ['a'], [], {meaning: 'meaning', description: 'and description'}), mockMessage('80808', ['multi\nlines'], [], {}), mockMessage('90000', ['<escape', 'me>'], ['double-quotes-"'], {}), mockMessage('100000', ['pre-ICU ', ' post-ICU'], ['ICU'], { associatedMessageIds: {ICU: 'SOME_ICU_ID'}, }), mockMessage( 'SOME_ICU_ID', ['{VAR_SELECT, select, a {a} b {{INTERPOLATION}} c {pre {INTERPOLATION_1} post}}'], [], {}, ), mockMessage( '100001', [ '{VAR_PLURAL, plural, one {{START_BOLD_TEXT}something bold{CLOSE_BOLD_TEXT}} other {pre {START_TAG_SPAN}middle{CLOSE_TAG_SPAN} post}}', ], [], {}, ), ]; const serializer = new Xliff1TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize(messages); expect(output).toEqual( [ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">`, ` <file source-language="xx" datatype="plaintext" original="ng2.template"${toAttributes( options, )}>`, ` <body>`, ` <trans-unit id="someId" datatype="html">`, ` <source>a<x id="PH" equiv-text="placeholder + 1"/>b<x id="PH_1"/>c</source>`, ` </trans-unit>`, ` <trans-unit id="67890" datatype="html">`, ` <source>a<x id="START_TAG_SPAN" ctype="x-span"/><x id="CLOSE_TAG_SPAN" ctype="x-span"/>c</source>`, ` <note priority="1" from="description">some description</note>`, ` </trans-unit>`, ` <trans-unit id="13579" datatype="html">`, ` <source><x id="START_BOLD_TEXT" ctype="x-b"/>b<x id="CLOSE_BOLD_TEXT" ctype="x-b"/></source>`, ` </trans-unit>`, ` <trans-unit id="24680" datatype="html">`, ` <source>a</source>`, ` <note priority="1" from="description">and description</note>`, ` <note priority="1" from="meaning">meaning</note>`, ` </trans-unit>`, ` <trans-unit id="80808" datatype="html">`, ` <source>multi`, `lines</source>`, ` </trans-unit>`, ` <trans-unit id="90000" datatype="html">`, ` <source>&lt;escape<x id="double-quotes-&quot;"/>me&gt;</source>`, ` </trans-unit>`, ` <trans-unit id="100000" datatype="html">`, ` <source>pre-ICU <x id="ICU" xid="SOME_ICU_ID"/> post-ICU</source>`, ` </trans-unit>`, ` <trans-unit id="SOME_ICU_ID" datatype="html">`, ` <source>{VAR_SELECT, select, a {a} b {<x id="INTERPOLATION"/>} c {pre <x id="INTERPOLATION_1"/> post}}</source>`, ` </trans-unit>`, ` <trans-unit id="100001" datatype="html">`, ` <source>{VAR_PLURAL, plural, one {<x id="START_BOLD_TEXT" ctype="x-b"/>something bold<x id="CLOSE_BOLD_TEXT" ctype="x-b"/>} other {pre <x id="START_TAG_SPAN" ctype="x-span"/>middle<x id="CLOSE_TAG_SPAN" ctype="x-span"/> post}}</source>`, ` </trans-unit>`, ` <trans-unit id="38705" datatype="html">`, ` <source>a<x id="START_TAG_SPAN" ctype="x-span"/><x id="CLOSE_TAG_SPAN" ctype="x-span"/>c</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">file.ts</context>`, ` <context context-type="linenumber">3,4</context>`, ` </context-group>`, ` </trans-unit>`, ` <trans-unit id="${ useLegacyIds ? '1234567890ABCDEF1234567890ABCDEF12345678' : '12345' }" datatype="html">`, ` <source>a<x id="PH"/>b<x id="PH_1"/>c</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">file.ts</context>`, ` <context context-type="linenumber">6</context>`, ` </context-group>`, ` <note priority="1" from="meaning">some meaning</note>`, ` </trans-unit>`, ` </body>`, ` </file>`, `</xliff>\n`, ].join('\n'), ); });
{ "end_byte": 8096, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/xliff1_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/xliff1_translation_serializer_spec.ts_8108_16293
hould convert a set of parsed messages into an XML string', () => { const messageLocation1: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file-1.ts'), text: 'message text', }; const messageLocation2: ɵSourceLocation = { start: {line: 3, column: 2}, end: {line: 4, column: 7}, file: absoluteFrom('/project/file-2.ts'), text: 'message text', }; const messageLocation3: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file-3.ts'), text: 'message text', }; const messageLocation4: ɵSourceLocation = { start: {line: 3, column: 2}, end: {line: 4, column: 7}, file: absoluteFrom('/project/file-4.ts'), text: 'message text', }; const messages: ɵParsedMessage[] = [ mockMessage('1234', ['message text'], [], {location: messageLocation1}), mockMessage('1234', ['message text'], [], {location: messageLocation2}), mockMessage('1234', ['message text'], [], { location: messageLocation3, legacyIds: ['87654321FEDCBA0987654321FEDCBA0987654321', '563965274788097516'], }), mockMessage('1234', ['message text'], [], { location: messageLocation4, customId: 'other', }), ]; const serializer = new Xliff1TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize(messages); // Note that in this test the third message will match the first two if legacyIds is // false. Otherwise it will be a separate message on its own. expect(output).toEqual( [ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">`, ` <file source-language="xx" datatype="plaintext" original="ng2.template"${toAttributes( options, )}>`, ` <body>`, ` <trans-unit id="1234" datatype="html">`, ` <source>message text</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">file-1.ts</context>`, ` <context context-type="linenumber">1</context>`, ` </context-group>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">file-2.ts</context>`, ` <context context-type="linenumber">4,5</context>`, ` </context-group>`, ...(useLegacyIds ? [] : [ ` <context-group purpose="location">`, ` <context context-type="sourcefile">file-3.ts</context>`, ` <context context-type="linenumber">1</context>`, ` </context-group>`, ]), ` </trans-unit>`, ...(useLegacyIds ? [ ` <trans-unit id="87654321FEDCBA0987654321FEDCBA0987654321" datatype="html">`, ` <source>message text</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">file-3.ts</context>`, ` <context context-type="linenumber">1</context>`, ` </context-group>`, ` </trans-unit>`, ] : []), ` <trans-unit id="other" datatype="html">`, ` <source>message text</source>`, ` <context-group purpose="location">`, ` <context context-type="sourcefile">file-4.ts</context>`, ` <context context-type="linenumber">4,5</context>`, ` </context-group>`, ` </trans-unit>`, ` </body>`, ` </file>`, `</xliff>\n`, ].join('\n'), ); }); it('should render the "ctype" for line breaks', () => { const serializer = new Xliff1TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([mockMessage('1', ['a', 'b'], ['LINE_BREAK'], {})]); expect(output).toContain('<source>a<x id="LINE_BREAK" ctype="lb"/>b</source>'); }); it('should render the "ctype" for images', () => { const serializer = new Xliff1TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([mockMessage('2', ['a', 'b'], ['TAG_IMG'], {})]); expect(output).toContain('<source>a<x id="TAG_IMG" ctype="image"/>b</source>'); }); it('should render the "ctype" for bold elements', () => { const serializer = new Xliff1TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage('3', ['a', 'b', 'c'], ['START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], {}), ]); expect(output).toContain( '<source>a<x id="START_BOLD_TEXT" ctype="x-b"/>b<x id="CLOSE_BOLD_TEXT" ctype="x-b"/>c</source>', ); }); it('should render the "ctype" for headings', () => { const serializer = new Xliff1TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage( '4', ['a', 'b', 'c'], ['START_HEADING_LEVEL1', 'CLOSE_HEADING_LEVEL1'], {}, ), ]); expect(output).toContain( '<source>a<x id="START_HEADING_LEVEL1" ctype="x-h1"/>b<x id="CLOSE_HEADING_LEVEL1" ctype="x-h1"/>c</source>', ); }); it('should render the "ctype" for span elements', () => { const serializer = new Xliff1TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage('5', ['a', 'b', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], {}), ]); expect(output).toContain( '<source>a<x id="START_TAG_SPAN" ctype="x-span"/>b<x id="CLOSE_TAG_SPAN" ctype="x-span"/>c</source>', ); }); it('should render the "ctype" for div elements', () => { const serializer = new Xliff1TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage('6', ['a', 'b', 'c'], ['START_TAG_DIV', 'CLOSE_TAG_DIV'], {}), ]); expect(output).toContain( '<source>a<x id="START_TAG_DIV" ctype="x-div"/>b<x id="CLOSE_TAG_DIV" ctype="x-div"/>c</source>', ); }); }); }); }); desc
{ "end_byte": 16293, "start_byte": 8108, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/xliff1_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/xliff1_translation_serializer_spec.ts_16299_20694
renderFile()', () => { it('should consistently order serialized messages by location', () => { const messages: ɵParsedMessage[] = [ mockMessage('1', ['message-1'], [], {location: location('/root/c-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/c-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 8, 0, 10, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 8, 0, 10, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/a-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/a-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 20, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 20, 5, 12)}), ]; const serializer = new Xliff1TranslationSerializer('xx', absoluteFrom('/root'), false, {}); const output = serializer.serialize(messages); expect(output.split('\n')).toEqual([ '<?xml version="1.0" encoding="UTF-8" ?>', '<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">', ' <file source-language="xx" datatype="plaintext" original="ng2.template">', ' <body>', ' <trans-unit id="1" datatype="html">', ' <source>message-1</source>', ' <context-group purpose="location">', ' <context context-type="sourcefile">a-1.ts</context>', ' <context context-type="linenumber">6</context>', ' </context-group>', ' <context-group purpose="location">', ' <context context-type="sourcefile">b-1.ts</context>', ' <context context-type="linenumber">6</context>', ' </context-group>', ' <context-group purpose="location">', ' <context context-type="sourcefile">b-1.ts</context>', ' <context context-type="linenumber">6</context>', ' </context-group>', ' <context-group purpose="location">', ' <context context-type="sourcefile">b-1.ts</context>', ' <context context-type="linenumber">9,11</context>', ' </context-group>', ' <context-group purpose="location">', ' <context context-type="sourcefile">c-1.ts</context>', ' <context context-type="linenumber">6</context>', ' </context-group>', ' </trans-unit>', ' <trans-unit id="2" datatype="html">', ' <source>message-1</source>', ' <context-group purpose="location">', ' <context context-type="sourcefile">a-2.ts</context>', ' <context context-type="linenumber">6</context>', ' </context-group>', ' <context-group purpose="location">', ' <context context-type="sourcefile">b-2.ts</context>', ' <context context-type="linenumber">6</context>', ' </context-group>', ' <context-group purpose="location">', ' <context context-type="sourcefile">b-2.ts</context>', ' <context context-type="linenumber">6</context>', ' </context-group>', ' <context-group purpose="location">', ' <context context-type="sourcefile">b-2.ts</context>', ' <context context-type="linenumber">9,11</context>', ' </context-group>', ' <context-group purpose="location">', ' <context context-type="sourcefile">c-2.ts</context>', ' <context context-type="linenumber">6</context>', ' </context-group>', ' </trans-unit>', ' </body>', ' </file>', '</xliff>', '', ]); }); }); }); });
{ "end_byte": 20694, "start_byte": 16299, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/xliff1_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/legacy_message_id_migration_serializer_spec.ts_0_2888
/** * @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 {ɵParsedMessage} from '@angular/localize'; import {Diagnostics} from '../../../src/diagnostics'; import {LegacyMessageIdMigrationSerializer} from '../../../src/extract/translation_files/legacy_message_id_migration_serializer'; import {mockMessage} from './mock_message'; // Doesn't need to run in each file system since it doesn't interact with the file system. describe('LegacyMessageIdMigrationSerializer', () => { let serializer: LegacyMessageIdMigrationSerializer; beforeEach(() => { serializer = new LegacyMessageIdMigrationSerializer(new Diagnostics()); }); it('should convert a set of parsed messages into a migration mapping file', () => { const messages: ɵParsedMessage[] = [ mockMessage('one', [], [], {legacyIds: ['legacy-one', 'other-legacy-one']}), mockMessage('two', [], [], {legacyIds: ['legacy-two']}), mockMessage('three', [], [], {legacyIds: ['legacy-three', 'other-legacy-three']}), ]; const output = serializer.serialize(messages); expect(output.split('\n')).toEqual([ '{', ' "legacy-one": "one",', ' "other-legacy-one": "one",', ' "legacy-two": "two",', ' "legacy-three": "three",', ' "other-legacy-three": "three"', '}', ]); }); it('should not include messages that have a custom ID', () => { const messages: ɵParsedMessage[] = [ mockMessage('one', [], [], {legacyIds: ['legacy-one']}), mockMessage('two', [], [], {legacyIds: ['legacy-two'], customId: 'custom-two'}), mockMessage('three', [], [], {legacyIds: ['legacy-three']}), ]; const output = serializer.serialize(messages); expect(output.split('\n')).toEqual([ '{', ' "legacy-one": "one",', ' "legacy-three": "three"', '}', ]); }); it('should not include messages that do not have legacy IDs', () => { const messages: ɵParsedMessage[] = [ mockMessage('one', [], [], {legacyIds: ['legacy-one']}), mockMessage('two', [], [], {}), mockMessage('three', [], [], {legacyIds: ['legacy-three']}), ]; const output = serializer.serialize(messages); expect(output.split('\n')).toEqual([ '{', ' "legacy-one": "one",', ' "legacy-three": "three"', '}', ]); }); it('should produce an empty file if none of the messages need to be migrated', () => { const messages: ɵParsedMessage[] = [ mockMessage('one', [], [], {legacyIds: ['legacy-one'], customId: 'custom-one'}), mockMessage('two', [], [], {}), mockMessage('three', [], [], {legacyIds: []}), ]; const output = serializer.serialize(messages); expect(output).toBe('{}'); }); });
{ "end_byte": 2888, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/legacy_message_id_migration_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/xmb_translation_serializer_spec.ts_0_7077
/** * @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 { absoluteFrom, getFileSystem, PathManipulation, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize'; import {XmbTranslationSerializer} from '../../../src/extract/translation_files/xmb_translation_serializer'; import {location, mockMessage} from './mock_message'; runInEachFileSystem(() => { let fs: PathManipulation; beforeEach(() => (fs = getFileSystem())); describe('XmbTranslationSerializer', () => { [false, true].forEach((useLegacyIds) => { describe(`renderFile() [using ${useLegacyIds ? 'legacy' : 'canonical'} ids]`, () => { it('should convert a set of parsed messages into an XML string', () => { const phLocation: ɵSourceLocation = { start: {line: 0, column: 10}, end: {line: 1, column: 15}, file: absoluteFrom('/project/file.ts'), text: 'placeholder + 1', }; const messagePartLocation: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file.ts'), text: 'message part', }; const messages: ɵParsedMessage[] = [ mockMessage('12345', ['a', 'b', 'c'], ['PH', 'PH_1'], { meaning: 'some meaning', legacyIds: ['1234567890ABCDEF1234567890ABCDEF12345678', '615790887472569365'], }), mockMessage('54321', ['a', 'b', 'c'], ['PH', 'PH_1'], { customId: 'someId', legacyIds: ['87654321FEDCBA0987654321FEDCBA0987654321', '563965274788097516'], messagePartLocations: [undefined, messagePartLocation, undefined], substitutionLocations: {'PH': phLocation, 'PH_1': undefined}, }), mockMessage('67890', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { description: 'some description', }), mockMessage('13579', ['', 'b', ''], ['START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], {}), mockMessage('24680', ['a'], [], {meaning: 'meaning', description: 'and description'}), mockMessage('80808', ['multi\nlines'], [], {}), mockMessage('90000', ['<escape', 'me>'], ['double-quotes-"'], {}), mockMessage( '100000', [ 'pre-ICU {VAR_SELECT, select, a {a} b {{INTERPOLATION}} c {pre {INTERPOLATION_1} post}} post-ICU', ], [], {}, ), mockMessage( '100001', [ '{VAR_PLURAL, plural, one {{START_BOLD_TEXT}something bold{CLOSE_BOLD_TEXT}} other {pre {START_TAG_SPAN}middle{CLOSE_TAG_SPAN} post}}', ], [], {}, ), ]; const serializer = new XmbTranslationSerializer( absoluteFrom('/project'), useLegacyIds, fs, ); const output = serializer.serialize(messages); expect(output).toContain( [ `<messagebundle handler="angular">`, ` <msg id="${ useLegacyIds ? '615790887472569365' : '12345' }" meaning="some meaning">a<ph name="PH"/>b<ph name="PH_1"/>c</msg>`, ` <msg id="someId">a<ph name="PH"/>b<ph name="PH_1"/>c</msg>`, ` <msg id="67890" desc="some description">a<ph name="START_TAG_SPAN"/><ph name="CLOSE_TAG_SPAN"/>c</msg>`, ` <msg id="13579"><ph name="START_BOLD_TEXT"/>b<ph name="CLOSE_BOLD_TEXT"/></msg>`, ` <msg id="24680" desc="and description" meaning="meaning">a</msg>`, ` <msg id="80808">multi`, `lines</msg>`, ` <msg id="90000">&lt;escape<ph name="double-quotes-&quot;"/>me&gt;</msg>`, ` <msg id="100000">pre-ICU {VAR_SELECT, select, a {a} b {<ph name="INTERPOLATION"/>} c {pre <ph name="INTERPOLATION_1"/> post}} post-ICU</msg>`, ` <msg id="100001">{VAR_PLURAL, plural, one {<ph name="START_BOLD_TEXT"/>something bold<ph name="CLOSE_BOLD_TEXT"/>} other {pre <ph name="START_TAG_SPAN"/>middle<ph name="CLOSE_TAG_SPAN"/> post}}</msg>`, `</messagebundle>\n`, ].join('\n'), ); }); }); }); }); describe('renderFile()', () => { it('should consistently order serialized messages by location', () => { const messages: ɵParsedMessage[] = [ mockMessage('1', ['message-1'], [], {location: location('/root/c-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/c-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 8, 0, 10, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 8, 0, 10, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/a-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/a-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 20, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 20, 5, 12)}), ]; const serializer = new XmbTranslationSerializer(absoluteFrom('/root'), false); const output = serializer.serialize(messages); expect(output.split('\n')).toEqual([ '<?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="1"><source>a-1.ts:5</source>message-1</msg>', ' <msg id="2"><source>a-2.ts:5</source>message-1</msg>', '</messagebundle>', '', ]); }); }); });
{ "end_byte": 7077, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/xmb_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/utils.ts_0_470
/** * @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 {FormatOptions} from '../../../src/extract/translation_files/format_options'; export function toAttributes(options: FormatOptions) { let result = ''; for (const option in options) { result += ` ${option}="${options[option]}"`; } return result; }
{ "end_byte": 470, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/utils.ts" }
angular/packages/localize/tools/test/extract/translation_files/arb_translation_serializer_spec.ts_0_4454
/** * @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 { absoluteFrom, getFileSystem, PathManipulation, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {ɵParsedMessage} from '@angular/localize'; import {ArbTranslationSerializer} from '../../../src/extract/translation_files/arb_translation_serializer'; import {location, mockMessage} from './mock_message'; runInEachFileSystem(() => { let fs: PathManipulation; describe('ArbTranslationSerializer', () => { beforeEach(() => { fs = getFileSystem(); }); describe('renderFile()', () => { it('should convert a set of parsed messages into a JSON string', () => { const messages: ɵParsedMessage[] = [ mockMessage('12345', ['a', 'b', 'c'], ['PH', 'PH_1'], { meaning: 'some meaning', location: location('/project/file.ts', 5, 10, 5, 12), }), mockMessage('54321', ['a', 'b', 'c'], ['PH', 'PH_1'], { customId: 'someId', }), mockMessage('67890', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { description: 'some description', location: location('/project/file.ts', 5, 10, 5, 12), }), mockMessage('67890', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { description: 'some description', location: location('/project/other.ts', 2, 10, 3, 12), }), mockMessage('13579', ['', 'b', ''], ['START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], {}), mockMessage('24680', ['a'], [], {meaning: 'meaning', description: 'and description'}), mockMessage('80808', ['multi\nlines'], [], {}), mockMessage('90000', ['<escape', 'me>'], ['double-quotes-"'], {}), mockMessage( '100000', [ 'pre-ICU {VAR_SELECT, select, a {a} b {{INTERPOLATION}} c {pre {INTERPOLATION_1} post}} post-ICU', ], [], {}, ), mockMessage( '100001', [ '{VAR_PLURAL, plural, one {{START_BOLD_TEXT}something bold{CLOSE_BOLD_TEXT}} other {pre {START_TAG_SPAN}middle{CLOSE_TAG_SPAN} post}}', ], [], {}, ), ]; const serializer = new ArbTranslationSerializer('xx', fs.resolve('/project'), fs); const output = serializer.serialize(messages); expect(output.split('\n')).toEqual([ '{', ' "@@locale": "xx",', ' "someId": "a{$PH}b{$PH_1}c",', ' "13579": "{$START_BOLD_TEXT}b{$CLOSE_BOLD_TEXT}",', ' "24680": "a",', ' "@24680": {', ' "description": "and description",', ' "x-meaning": "meaning"', ' },', ' "80808": "multi\\nlines",', ' "90000": "<escape{$double-quotes-\\"}me>",', ' "100000": "pre-ICU {VAR_SELECT, select, a {a} b {{INTERPOLATION}} c {pre {INTERPOLATION_1} post}} post-ICU",', ' "100001": "{VAR_PLURAL, plural, one {{START_BOLD_TEXT}something bold{CLOSE_BOLD_TEXT}} other {pre {START_TAG_SPAN}middle{CLOSE_TAG_SPAN} post}}",', ' "12345": "a{$PH}b{$PH_1}c",', ' "@12345": {', ' "x-meaning": "some meaning",', ' "x-locations": [', ' {', ' "file": "file.ts",', ' "start": { "line": "5", "column": "10" },', ' "end": { "line": "5", "column": "12" }', ' }', ' ]', ' },', ' "67890": "a{$START_TAG_SPAN}{$CLOSE_TAG_SPAN}c",', ' "@67890": {', ' "description": "some description",', ' "x-locations": [', ' {', ' "file": "file.ts",', ' "start": { "line": "5", "column": "10" },', ' "end": { "line": "5", "column": "12" }', ' },', ' {', ' "file": "other.ts",', ' "start": { "line": "2", "column": "10" },', ' "end": { "line": "3", "column": "12" }', ' }', ' ]', ' }', '}', ]); });
{ "end_byte": 4454, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/arb_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/arb_translation_serializer_spec.ts_4462_8172
('should consistently order serialized messages by location', () => { const messages: ɵParsedMessage[] = [ mockMessage('1', ['message-1'], [], {location: location('/root/c-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/c-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 8, 0, 10, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 8, 0, 10, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/a-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/a-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 20, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 20, 5, 12)}), ]; const serializer = new ArbTranslationSerializer('xx', fs.resolve('/root'), fs); const output = serializer.serialize(messages); expect(output.split('\n')).toEqual([ '{', ' "@@locale": "xx",', ' "1": "message-1",', ' "@1": {', ' "x-locations": [', ' {', ' "file": "a-1.ts",', ' "start": { "line": "5", "column": "10" },', ' "end": { "line": "5", "column": "12" }', ' },', ' {', ' "file": "b-1.ts",', ' "start": { "line": "5", "column": "10" },', ' "end": { "line": "5", "column": "12" }', ' },', ' {', ' "file": "b-1.ts",', ' "start": { "line": "5", "column": "20" },', ' "end": { "line": "5", "column": "12" }', ' },', ' {', ' "file": "b-1.ts",', ' "start": { "line": "8", "column": "0" },', ' "end": { "line": "10", "column": "12" }', ' },', ' {', ' "file": "c-1.ts",', ' "start": { "line": "5", "column": "10" },', ' "end": { "line": "5", "column": "12" }', ' }', ' ]', ' },', ' "2": "message-1",', ' "@2": {', ' "x-locations": [', ' {', ' "file": "a-2.ts",', ' "start": { "line": "5", "column": "10" },', ' "end": { "line": "5", "column": "12" }', ' },', ' {', ' "file": "b-2.ts",', ' "start": { "line": "5", "column": "10" },', ' "end": { "line": "5", "column": "12" }', ' },', ' {', ' "file": "b-2.ts",', ' "start": { "line": "5", "column": "20" },', ' "end": { "line": "5", "column": "12" }', ' },', ' {', ' "file": "b-2.ts",', ' "start": { "line": "8", "column": "0" },', ' "end": { "line": "10", "column": "12" }', ' },', ' {', ' "file": "c-2.ts",', ' "start": { "line": "5", "column": "10" },', ' "end": { "line": "5", "column": "12" }', ' }', ' ]', ' }', '}', ]); }); }); }); });
{ "end_byte": 8172, "start_byte": 4462, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/arb_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/json_translation_serializer_spec.ts_0_2715
/** * @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 {ɵParsedMessage} from '@angular/localize'; import {SimpleJsonTranslationSerializer} from '../../../src/extract/translation_files/json_translation_serializer'; import {mockMessage} from './mock_message'; describe('JsonTranslationSerializer', () => { describe('renderFile()', () => { it('should convert a set of parsed messages into a JSON string', () => { const messages: ɵParsedMessage[] = [ mockMessage('12345', ['a', 'b', 'c'], ['PH', 'PH_1'], {meaning: 'some meaning'}), mockMessage('54321', ['a', 'b', 'c'], ['PH', 'PH_1'], { customId: 'someId', }), mockMessage('67890', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { description: 'some description', }), mockMessage('13579', ['', 'b', ''], ['START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], {}), mockMessage('24680', ['a'], [], {meaning: 'meaning', description: 'and description'}), mockMessage('80808', ['multi\nlines'], [], {}), mockMessage('90000', ['<escape', 'me>'], ['double-quotes-"'], {}), mockMessage( '100000', [ 'pre-ICU {VAR_SELECT, select, a {a} b {{INTERPOLATION}} c {pre {INTERPOLATION_1} post}} post-ICU', ], [], {}, ), mockMessage( '100001', [ '{VAR_PLURAL, plural, one {{START_BOLD_TEXT}something bold{CLOSE_BOLD_TEXT}} other {pre {START_TAG_SPAN}middle{CLOSE_TAG_SPAN} post}}', ], [], {}, ), ]; const serializer = new SimpleJsonTranslationSerializer('xx'); const output = serializer.serialize(messages); expect(output).toEqual( [ `{`, ` "locale": "xx",`, ` "translations": {`, ` "12345": "a{$PH}b{$PH_1}c",`, ` "13579": "{$START_BOLD_TEXT}b{$CLOSE_BOLD_TEXT}",`, ` "24680": "a",`, ` "67890": "a{$START_TAG_SPAN}{$CLOSE_TAG_SPAN}c",`, ` "80808": "multi\\nlines",`, ` "90000": "<escape{$double-quotes-\\"}me>",`, ` "100000": "pre-ICU {VAR_SELECT, select, a {a} b {{INTERPOLATION}} c {pre {INTERPOLATION_1} post}} post-ICU",`, ` "100001": "{VAR_PLURAL, plural, one {{START_BOLD_TEXT}something bold{CLOSE_BOLD_TEXT}} other {pre {START_TAG_SPAN}middle{CLOSE_TAG_SPAN} post}}",`, ` "someId": "a{$PH}b{$PH_1}c"`, ` }`, `}`, ].join('\n'), ); }); }); });
{ "end_byte": 2715, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/json_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/mock_message.ts_0_1597
/** * @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 {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system'; import {ɵParsedMessage} from '@angular/localize'; import {MessageId, SourceLocation} from '@angular/localize/src/utils'; export interface MockMessageOptions { customId?: string; meaning?: string; description?: string; location?: SourceLocation; legacyIds?: string[]; messagePartLocations?: (SourceLocation | undefined)[]; associatedMessageIds?: Record<string, string>; substitutionLocations?: Record<string, SourceLocation | undefined>; } /** * This helper is used to create `ParsedMessage` objects to be rendered in the * `TranslationSerializer` tests. */ export function mockMessage( id: MessageId, messageParts: string[], placeholderNames: string[], options: MockMessageOptions, ): ɵParsedMessage { let text = messageParts[0]; for (let i = 1; i < messageParts.length; i++) { text += `{$${placeholderNames[i - 1]}}${messageParts[i]}`; } return { substitutions: [], ...options, id: options.customId || id, // customId trumps id text, messageParts, placeholderNames, }; } export function location( file: string, startLine: number, startCol: number, endLine: number, endCol: number, ): SourceLocation { return { file: absoluteFrom(file), start: {line: startLine, column: startCol}, end: {line: endLine, column: endCol}, }; }
{ "end_byte": 1597, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/mock_message.ts" }
angular/packages/localize/tools/test/extract/translation_files/icu_parsing_spec.ts_0_2703
/** * @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 {extractIcuPlaceholders} from '../../../src/extract/translation_files/icu_parsing'; describe('extractIcuPlaceholders()', () => { it('should return a single string if there is no ICU', () => { expect(extractIcuPlaceholders('')).toEqual(['']); expect(extractIcuPlaceholders('some text')).toEqual(['some text']); expect(extractIcuPlaceholders('some } text')).toEqual(['some } text']); expect(extractIcuPlaceholders('this is {not an ICU}')).toEqual(['this is {not an ICU}']); }); it('should return a single string if there are no ICU placeholders', () => { expect( extractIcuPlaceholders('{VAR_PLURAL, plural, one {SOME} few {FEW} other {OTHER}}'), ).toEqual(['{VAR_PLURAL, plural, one {SOME} few {FEW} other {OTHER}}']); expect( extractIcuPlaceholders('{VAR_SELECT, select, male {HE} female {SHE} other {XE}}'), ).toEqual(['{VAR_SELECT, select, male {HE} female {SHE} other {XE}}']); }); it('should split out simple interpolation placeholders', () => { expect( extractIcuPlaceholders( '{VAR_PLURAL, plural, one {{INTERPOLATION}} few {pre {INTERPOLATION_1}} other {{INTERPOLATION_2} post}}', ), ).toEqual([ '{VAR_PLURAL, plural, one {', 'INTERPOLATION', '} few {pre ', 'INTERPOLATION_1', '} other {', 'INTERPOLATION_2', ' post}}', ]); }); it('should split out element placeholders', () => { expect( extractIcuPlaceholders( '{VAR_PLURAL, plural, one {{START_BOLD_TEXT}something bold{CLOSE_BOLD_TEXT}} other {pre {START_TAG_SPAN}middle{CLOSE_TAG_SPAN} post}}', ), ).toEqual([ '{VAR_PLURAL, plural, one {', 'START_BOLD_TEXT', 'something bold', 'CLOSE_BOLD_TEXT', '} other {pre ', 'START_TAG_SPAN', 'middle', 'CLOSE_TAG_SPAN', ' post}}', ]); }); it('should handle nested ICUs', () => { expect( extractIcuPlaceholders( [ '{VAR_SELECT_1, select,', ' invoice {Invoice for {INTERPOLATION}}', ' payment {{VAR_SELECT, select,', ' processor {Payment gateway}', ' other {{INTERPOLATION_1}}', ' }}', '}', ].join('\n'), ), ).toEqual([ '{VAR_SELECT_1, select,\n invoice {Invoice for ', 'INTERPOLATION', '}\n payment {{VAR_SELECT, select,\n processor {Payment gateway}\n other {', 'INTERPOLATION_1', '}\n }}\n}', ]); }); });
{ "end_byte": 2703, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/icu_parsing_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/format_options_spec.ts_0_1801
/** * @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 { parseFormatOptions, validateOptions, } from '../../../src/extract/translation_files/format_options'; describe('format_options', () => { describe('validateOptions()', () => { it('should do nothing if there are no options', () => { expect(() => validateOptions('TestSerializer', [['key', ['value1', 'value2']]], {}), ).not.toThrow(); }); it('should do nothing if the options are valid', () => { expect(() => validateOptions('TestSerializer', [['key', ['value1', 'value2']]], {key: 'value1'}), ).not.toThrow(); }); it('should error if there is an unexpected option', () => { expect(() => validateOptions('TestSerializer', [['key', ['value1', 'value2']]], {wrong: 'xxx'}), ).toThrowError( 'Invalid format option for TestSerializer: "wrong".\n' + 'Allowed options are ["key"].', ); }); it('should error if there is an unexpected option value', () => { expect(() => validateOptions('TestSerializer', [['key', ['value1', 'value2']]], {key: 'other'}), ).toThrowError( 'Invalid format option value for TestSerializer: "key".\n' + 'Allowed option values are ["value1","value2"] but received "other".', ); }); }); describe('parseFormatOptions()', () => { it('should parse the string as JSON', () => { expect(parseFormatOptions('{"a": "1", "b": "2"}')).toEqual({a: '1', b: '2'}); }); it('should parse undefined into an empty object', () => { expect(parseFormatOptions(undefined)).toEqual({}); }); }); });
{ "end_byte": 1801, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/format_options_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/xliff2_translation_serializer_spec.ts_0_727
/** * @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 {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize'; import {FormatOptions} from '../../../src/extract/translation_files/format_options'; import {Xliff2TranslationSerializer} from '../../../src/extract/translation_files/xliff2_translation_serializer'; import {location, mockMessage} from './mock_message'; import {toAttributes} from './utils';
{ "end_byte": 727, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/xliff2_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/xliff2_translation_serializer_spec.ts_729_8435
nInEachFileSystem(() => { describe('Xliff2TranslationSerializer', () => { ([{}, {'xml:space': 'preserve'}] as FormatOptions[]).forEach((options) => { [false, true].forEach((useLegacyIds) => { describe(`renderFile() [using ${useLegacyIds ? 'legacy' : 'canonical'} ids]`, () => { it('should convert a set of parsed messages into an XML string', () => { const phLocation: ɵSourceLocation = { start: {line: 0, column: 10}, end: {line: 1, column: 15}, file: absoluteFrom('/project/file.ts'), text: 'placeholder + 1', }; const messagePartLocation: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file.ts'), text: 'message part', }; const messages: ɵParsedMessage[] = [ mockMessage('12345', ['a', 'b', 'c'], ['PH', 'PH_1'], { meaning: 'some meaning', location: { file: absoluteFrom('/project/file.ts'), start: {line: 5, column: 0}, end: {line: 5, column: 3}, }, legacyIds: ['1234567890ABCDEF1234567890ABCDEF12345678', '615790887472569365'], }), mockMessage('54321', ['a', 'b', 'c'], ['PH', 'PH_1'], { customId: 'someId', legacyIds: ['87654321FEDCBA0987654321FEDCBA0987654321', '563965274788097516'], messagePartLocations: [undefined, messagePartLocation, undefined], substitutionLocations: {'PH': phLocation, 'PH_1': undefined}, }), mockMessage('67890', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { description: 'some description', location: { file: absoluteFrom('/project/file.ts'), start: {line: 2, column: 7}, end: {line: 3, column: 2}, }, }), mockMessage('location-only', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { location: { file: absoluteFrom('/project/file.ts'), start: {line: 2, column: 7}, end: {line: 3, column: 2}, }, }), mockMessage('13579', ['', 'b', ''], ['START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], {}), mockMessage('24680', ['a'], [], {meaning: 'meaning', description: 'and description'}), mockMessage('80808', ['multi\nlines'], [], {}), mockMessage('90000', ['<escape', 'me>'], ['double-quotes-"'], {}), mockMessage('100000', ['pre-ICU ', ' post-ICU'], ['ICU'], { associatedMessageIds: {ICU: 'SOME_ICU_ID'}, }), mockMessage( 'SOME_ICU_ID', ['{VAR_SELECT, select, a {a} b {{INTERPOLATION}} c {pre {INTERPOLATION_1} post}}'], [], {}, ), mockMessage( '100001', [ '{VAR_PLURAL, plural, one {{START_BOLD_TEXT}something bold{CLOSE_BOLD_TEXT}} other {pre {START_TAG_SPAN}middle{CLOSE_TAG_SPAN} post}}', ], [], {}, ), ]; const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize(messages); expect(output.split(/\r?\n/)).toEqual([ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="xx">`, ` <file id="ngi18n" original="ng.template"${toAttributes(options)}>`, ` <unit id="someId">`, ` <segment>`, ` <source>a<ph id="0" equiv="PH" disp="placeholder + 1"/>b<ph id="1" equiv="PH_1"/>c</source>`, ` </segment>`, ` </unit>`, ` <unit id="13579">`, ` <segment>`, ` <source><pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt">b</pc></source>`, ` </segment>`, ` </unit>`, ` <unit id="24680">`, ` <notes>`, ` <note category="description">and description</note>`, ` <note category="meaning">meaning</note>`, ` </notes>`, ` <segment>`, ` <source>a</source>`, ` </segment>`, ` </unit>`, ` <unit id="80808">`, ` <segment>`, ` <source>multi`, `lines</source>`, ` </segment>`, ` </unit>`, ` <unit id="90000">`, ` <segment>`, ` <source>&lt;escape<ph id="0" equiv="double-quotes-&quot;"/>me&gt;</source>`, ` </segment>`, ` </unit>`, ` <unit id="100000">`, ` <segment>`, ` <source>pre-ICU <ph id="0" equiv="ICU" subFlows="SOME_ICU_ID"/> post-ICU</source>`, ` </segment>`, ` </unit>`, ` <unit id="SOME_ICU_ID">`, ` <segment>`, ` <source>{VAR_SELECT, select, a {a} b {<ph id="0" equiv="INTERPOLATION"/>} c {pre <ph id="1" equiv="INTERPOLATION_1"/> post}}</source>`, ` </segment>`, ` </unit>`, ` <unit id="100001">`, ` <segment>`, ` <source>{VAR_PLURAL, plural, one {<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt">something bold</pc>} other {pre <pc id="1" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other">middle</pc> post}}</source>`, ` </segment>`, ` </unit>`, ` <unit id="67890">`, ` <notes>`, ` <note category="location">file.ts:3,4</note>`, ` <note category="description">some description</note>`, ` </notes>`, ` <segment>`, ` <source>a<pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other"></pc>c</source>`, ` </segment>`, ` </unit>`, ` <unit id="location-only">`, ` <notes>`, ` <note category="location">file.ts:3,4</note>`, ` </notes>`, ` <segment>`, ` <source>a<pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other"></pc>c</source>`, ` </segment>`, ` </unit>`, ` <unit id="${useLegacyIds ? '615790887472569365' : '12345'}">`, ` <notes>`, ` <note category="location">file.ts:6</note>`, ` <note category="meaning">some meaning</note>`, ` </notes>`, ` <segment>`, ` <source>a<ph id="0" equiv="PH"/>b<ph id="1" equiv="PH_1"/>c</source>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>`, ``, ]); });
{ "end_byte": 8435, "start_byte": 729, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/xliff2_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/xliff2_translation_serializer_spec.ts_8447_17257
hould convert a set of parsed messages into an XML string', () => { const messageLocation1: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file-1.ts'), text: 'message text', }; const messageLocation2: ɵSourceLocation = { start: {line: 3, column: 2}, end: {line: 4, column: 7}, file: absoluteFrom('/project/file-2.ts'), text: 'message text', }; const messageLocation3: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file-3.ts'), text: 'message text', }; const messageLocation4: ɵSourceLocation = { start: {line: 3, column: 2}, end: {line: 4, column: 7}, file: absoluteFrom('/project/file-4.ts'), text: 'message text', }; const messages: ɵParsedMessage[] = [ mockMessage('1234', ['message text'], [], {location: messageLocation1}), mockMessage('1234', ['message text'], [], {location: messageLocation2}), mockMessage('1234', ['message text'], [], { location: messageLocation3, legacyIds: ['87654321FEDCBA0987654321FEDCBA0987654321', '563965274788097516'], }), mockMessage('1234', ['message text'], [], { location: messageLocation4, customId: 'other', }), ]; const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize(messages); // Note that in this test the third message will match the first two if legacyIds is // false. Otherwise it will be a separate message on its own. expect(output).toEqual( [ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="xx">`, ` <file id="ngi18n" original="ng.template"${toAttributes(options)}>`, ` <unit id="1234">`, ` <notes>`, ` <note category="location">file-1.ts:1</note>`, ` <note category="location">file-2.ts:4,5</note>`, ...(useLegacyIds ? [] : [' <note category="location">file-3.ts:1</note>']), ` </notes>`, ` <segment>`, ` <source>message text</source>`, ` </segment>`, ` </unit>`, ...(useLegacyIds ? [ ` <unit id="563965274788097516">`, ` <notes>`, ` <note category="location">file-3.ts:1</note>`, ` </notes>`, ` <segment>`, ` <source>message text</source>`, ` </segment>`, ` </unit>`, ] : []), ` <unit id="other">`, ` <notes>`, ` <note category="location">file-4.ts:4,5</note>`, ` </notes>`, ` <segment>`, ` <source>message text</source>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>\n`, ].join('\n'), ); }); it('should render the "type" for line breaks', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([mockMessage('1', ['a', 'b'], ['LINE_BREAK'], {})]); expect(output).toContain( '<source>a<ph id="0" equiv="LINE_BREAK" type="fmt"/>b</source>', ); }); it('should render the "type" for images', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([mockMessage('2', ['a', 'b'], ['TAG_IMG'], {})]); expect(output).toContain( '<source>a<ph id="0" equiv="TAG_IMG" type="image"/>b</source>', ); }); it('should render the "type" for bold elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage('3', ['a', 'b', 'c'], ['START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], {}), ]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt">b</pc>c</source>', ); }); it('should render the "type" for heading elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage( '4', ['a', 'b', 'c'], ['START_HEADING_LEVEL1', 'CLOSE_HEADING_LEVEL1'], {}, ), ]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_HEADING_LEVEL1" equivEnd="CLOSE_HEADING_LEVEL1" type="other">b</pc>c</source>', ); }); it('should render the "type" for span elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage('5', ['a', 'b', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], {}), ]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other">b</pc>c</source>', ); }); it('should render the "type" for div elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage('6', ['a', 'b', 'c'], ['START_TAG_DIV', 'CLOSE_TAG_DIV'], {}), ]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other">b</pc>c</source>', ); }); it('should render the "type" for link elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage('6', ['a', 'b', 'c'], ['START_LINK', 'CLOSE_LINK'], {}), ]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_LINK" equivEnd="CLOSE_LINK" type="link">b</pc>c</source>', ); }); it('should render generic close tag placeholders for additional elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options, ); const output = serializer.serialize([ mockMessage( '6', ['a', 'b', 'c', 'd', 'e'], ['START_LINK', 'CLOSE_LINK', 'START_LINK_1', 'CLOSE_LINK'], {}, ), ]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_LINK" equivEnd="CLOSE_LINK" type="link">b</pc>c<pc id="1" equivStart="START_LINK_1" equivEnd="CLOSE_LINK" type="link">d</pc>e</source>', ); }); }); }); }); desc
{ "end_byte": 17257, "start_byte": 8447, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/xliff2_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/translation_files/xliff2_translation_serializer_spec.ts_17263_19995
renderFile()', () => { it('should consistently order serialized messages by location', () => { const messages: ɵParsedMessage[] = [ mockMessage('1', ['message-1'], [], {location: location('/root/c-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/c-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 8, 0, 10, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 8, 0, 10, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/a-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/a-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 20, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 20, 5, 12)}), ]; const serializer = new Xliff2TranslationSerializer('xx', absoluteFrom('/root'), false, {}); const output = serializer.serialize(messages); expect(output.split('\n')).toEqual([ '<?xml version="1.0" encoding="UTF-8" ?>', '<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="xx">', ' <file id="ngi18n" original="ng.template">', ' <unit id="1">', ' <notes>', ' <note category="location">a-1.ts:6</note>', ' <note category="location">b-1.ts:6</note>', ' <note category="location">b-1.ts:6</note>', ' <note category="location">b-1.ts:9,11</note>', ' <note category="location">c-1.ts:6</note>', ' </notes>', ' <segment>', ' <source>message-1</source>', ' </segment>', ' </unit>', ' <unit id="2">', ' <notes>', ' <note category="location">a-2.ts:6</note>', ' <note category="location">b-2.ts:6</note>', ' <note category="location">b-2.ts:6</note>', ' <note category="location">b-2.ts:9,11</note>', ' <note category="location">c-2.ts:6</note>', ' </notes>', ' <segment>', ' <source>message-1</source>', ' </segment>', ' </unit>', ' </file>', '</xliff>', '', ]); }); }); }); });
{ "end_byte": 19995, "start_byte": 17263, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/translation_files/xliff2_translation_serializer_spec.ts" }
angular/packages/localize/tools/test/extract/source_files/es5_extract_plugin_spec.ts_0_1647
/** * @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 { FileSystem, getFileSystem, PathSegment, relativeFrom, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {ɵParsedMessage} from '@angular/localize/private'; import {transformSync} from '@babel/core'; import {makeEs5ExtractPlugin} from '../../../src/extract/source_files/es5_extract_plugin'; import {runInNativeFileSystem} from '../../helpers'; runInNativeFileSystem(() => { let fs: FileSystem; let testPath: PathSegment; beforeEach(() => { fs = getFileSystem(); testPath = relativeFrom('app/dist/test.js'); }); describe('makeEs5ExtractPlugin()', () => { it('should error with code-frame information if the first argument to `$localize` is not an array', () => { const input = '$localize(null, [])'; expect(() => transformCode(input)).toThrowError( `Cannot create property 'message' on string '${testPath}: ` + 'Unexpected messageParts for `$localize` (expected an array of strings).\n' + '> 1 | $localize(null, [])\n' + " | ^^^^'", ); }); function transformCode(input: string): ɵParsedMessage[] { const messages: ɵParsedMessage[] = []; const cwd = fs.resolve('/'); const filename = fs.resolve(cwd, testPath); transformSync(input, { plugins: [makeEs5ExtractPlugin(getFileSystem(), messages)], filename, cwd, })!.code!; return messages; } }); });
{ "end_byte": 1647, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/extract/source_files/es5_extract_plugin_spec.ts" }
angular/packages/localize/tools/test/helpers/BUILD.bazel_0_357
load("//tools:defaults.bzl", "ts_library") ts_library( name = "helpers", testonly = True, srcs = glob( ["**/*.ts"], ), visibility = ["//packages/localize/tools/test:__subpackages__"], deps = [ "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", ], )
{ "end_byte": 357, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/helpers/BUILD.bazel" }
angular/packages/localize/tools/test/helpers/index.ts_0_1008
/** * @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 {setFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system'; import {InvalidFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/src/invalid_file_system'; import {MockFileSystemNative} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; /** * Only run these tests on the "native" file-system. * * Babel uses the `path.resolve()` function internally, which makes it very hard to mock out the * file-system from the outside. We run these tests on Unix and Windows in our CI jobs, so there is * test coverage. */ export function runInNativeFileSystem(callback: () => void) { describe(`<<FileSystem: Native>>`, () => { beforeEach(() => setFileSystem(new MockFileSystemNative())); afterEach(() => setFileSystem(new InvalidFileSystem())); callback(); }); }
{ "end_byte": 1008, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/test/helpers/index.ts" }
angular/packages/localize/tools/src/diagnostics.ts_0_1504
/** * @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 */ /** * How to handle potential diagnostics. */ export type DiagnosticHandlingStrategy = 'error' | 'warning' | 'ignore'; /** * This class is used to collect and then report warnings and errors that occur during the execution * of the tools. * * @publicApi used by CLI */ export class Diagnostics { readonly messages: {type: 'warning' | 'error'; message: string}[] = []; get hasErrors() { return this.messages.some((m) => m.type === 'error'); } add(type: DiagnosticHandlingStrategy, message: string) { if (type !== 'ignore') { this.messages.push({type, message}); } } warn(message: string) { this.messages.push({type: 'warning', message}); } error(message: string) { this.messages.push({type: 'error', message}); } merge(other: Diagnostics) { this.messages.push(...other.messages); } formatDiagnostics(message: string): string { const errors = this.messages.filter((d) => d.type === 'error').map((d) => ' - ' + d.message); const warnings = this.messages .filter((d) => d.type === 'warning') .map((d) => ' - ' + d.message); if (errors.length) { message += '\nERRORS:\n' + errors.join('\n'); } if (warnings.length) { message += '\nWARNINGS:\n' + warnings.join('\n'); } return message; } }
{ "end_byte": 1504, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/diagnostics.ts" }
angular/packages/localize/tools/src/source_file_utils.ts_0_8646
/** * @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 { AbsoluteFsPath, getFileSystem, PathManipulation, } from '@angular/compiler-cli/private/localize'; import { ɵisMissingTranslationError, ɵmakeTemplateObject, ɵParsedTranslation, ɵSourceLocation, ɵtranslate, } from '@angular/localize'; import {BabelFile, NodePath, types as t} from '@babel/core'; import {DiagnosticHandlingStrategy, Diagnostics} from './diagnostics'; /** * Is the given `expression` the global `$localize` identifier? * * @param expression The expression to check. * @param localizeName The configured name of `$localize`. */ export function isLocalize( expression: NodePath, localizeName: string, ): expression is NodePath<t.Identifier> { return isNamedIdentifier(expression, localizeName) && isGlobalIdentifier(expression); } /** * Is the given `expression` an identifier with the correct `name`? * * @param expression The expression to check. * @param name The name of the identifier we are looking for. */ export function isNamedIdentifier( expression: NodePath, name: string, ): expression is NodePath<t.Identifier> { return expression.isIdentifier() && expression.node.name === name; } /** * Is the given `identifier` declared globally. * * @param identifier The identifier to check. * @publicApi used by CLI */ export function isGlobalIdentifier(identifier: NodePath<t.Identifier>) { return !identifier.scope || !identifier.scope.hasBinding(identifier.node.name); } /** * Build a translated expression to replace the call to `$localize`. * @param messageParts The static parts of the message. * @param substitutions The expressions to substitute into the message. * @publicApi used by CLI */ export function buildLocalizeReplacement( messageParts: TemplateStringsArray, substitutions: readonly t.Expression[], ): t.Expression { let mappedString: t.Expression = t.stringLiteral(messageParts[0]); for (let i = 1; i < messageParts.length; i++) { mappedString = t.binaryExpression( '+', mappedString, wrapInParensIfNecessary(substitutions[i - 1]), ); mappedString = t.binaryExpression('+', mappedString, t.stringLiteral(messageParts[i])); } return mappedString; } /** * Extract the message parts from the given `call` (to `$localize`). * * The message parts will either by the first argument to the `call` or it will be wrapped in call * to a helper function like `__makeTemplateObject`. * * @param call The AST node of the call to process. * @param fs The file system to use when computing source-map paths. If not provided then it uses * the "current" FileSystem. * @publicApi used by CLI */ export function unwrapMessagePartsFromLocalizeCall( call: NodePath<t.CallExpression>, fs: PathManipulation = getFileSystem(), ): [TemplateStringsArray, (ɵSourceLocation | undefined)[]] { let cooked = call.get('arguments')[0]; if (cooked === undefined) { throw new BabelParseError(call.node, '`$localize` called without any arguments.'); } if (!cooked.isExpression()) { throw new BabelParseError( cooked.node, 'Unexpected argument to `$localize` (expected an array).', ); } // If there is no call to `__makeTemplateObject(...)`, then `raw` must be the same as `cooked`. let raw = cooked; // Check for a memoized form: `x || x = ...` if ( cooked.isLogicalExpression() && cooked.node.operator === '||' && cooked.get('left').isIdentifier() ) { const right = cooked.get('right'); if (right.isAssignmentExpression()) { cooked = right.get('right'); if (!cooked.isExpression()) { throw new BabelParseError( cooked.node, 'Unexpected "makeTemplateObject()" function (expected an expression).', ); } } else if (right.isSequenceExpression()) { const expressions = right.get('expressions'); if (expressions.length > 2) { // This is a minified sequence expression, where the first two expressions in the sequence // are assignments of the cooked and raw arrays respectively. const [first, second] = expressions; if (first.isAssignmentExpression()) { cooked = first.get('right'); if (!cooked.isExpression()) { throw new BabelParseError( first.node, 'Unexpected cooked value, expected an expression.', ); } if (second.isAssignmentExpression()) { raw = second.get('right'); if (!raw.isExpression()) { throw new BabelParseError( second.node, 'Unexpected raw value, expected an expression.', ); } } else { // If the second expression is not an assignment then it is probably code to take a copy // of the cooked array. For example: `raw || (raw=cooked.slice(0))`. raw = cooked; } } } } } // Check for `__makeTemplateObject(cooked, raw)` or `__templateObject()` calls. if (cooked.isCallExpression()) { let call = cooked; if (call.get('arguments').length === 0) { // No arguments so perhaps it is a `__templateObject()` call. // Unwrap this to get the `_taggedTemplateLiteral(cooked, raw)` call. call = unwrapLazyLoadHelperCall(call); } cooked = call.get('arguments')[0]; if (!cooked.isExpression()) { throw new BabelParseError( cooked.node, 'Unexpected `cooked` argument to the "makeTemplateObject()" function (expected an expression).', ); } const arg2 = call.get('arguments')[1]; if (arg2 && !arg2.isExpression()) { throw new BabelParseError( arg2.node, 'Unexpected `raw` argument to the "makeTemplateObject()" function (expected an expression).', ); } // If there is no second argument then assume that raw and cooked are the same raw = arg2 !== undefined ? arg2 : cooked; } const [cookedStrings] = unwrapStringLiteralArray(cooked, fs); const [rawStrings, rawLocations] = unwrapStringLiteralArray(raw, fs); return [ɵmakeTemplateObject(cookedStrings, rawStrings), rawLocations]; } /** * Parse the localize call expression to extract the arguments that hold the substitution * expressions. * * @param call The AST node of the call to process. * @param fs The file system to use when computing source-map paths. If not provided then it uses * the "current" FileSystem. * @publicApi used by CLI */ export function unwrapSubstitutionsFromLocalizeCall( call: NodePath<t.CallExpression>, fs: PathManipulation = getFileSystem(), ): [t.Expression[], (ɵSourceLocation | undefined)[]] { const expressions = call.get('arguments').splice(1); if (!isArrayOfExpressions(expressions)) { const badExpression = expressions.find((expression) => !expression.isExpression())!; throw new BabelParseError( badExpression.node, 'Invalid substitutions for `$localize` (expected all substitution arguments to be expressions).', ); } return [ expressions.map((path) => path.node), expressions.map((expression) => getLocation(fs, expression)), ]; } /** * Parse the tagged template literal to extract the message parts. * * @param elements The elements of the template literal to process. * @param fs The file system to use when computing source-map paths. If not provided then it uses * the "current" FileSystem. * @publicApi used by CLI */ export function unwrapMessagePartsFromTemplateLiteral( elements: NodePath<t.TemplateElement>[], fs: PathManipulation = getFileSystem(), ): [TemplateStringsArray, (ɵSourceLocation | undefined)[]] { const cooked = elements.map((q) => { if (q.node.value.cooked === undefined) { throw new BabelParseError( q.node, `Unexpected undefined message part in "${elements.map((q) => q.node.value.cooked)}"`, ); } return q.node.value.cooked; }); const raw = elements.map((q) => q.node.value.raw); const locations = elements.map((q) => getLocation(fs, q)); return [ɵmakeTemplateObject(cooked, raw), locations]; } /** * Parse the tagged template literal to extract the interpolation expressions. * * @param quasi The AST node of the template literal to process. * @param fs The file system to use when computing source-map paths. If not provided then it uses * the "current" FileSystem. * @publicApi used by CLI */ export fu
{ "end_byte": 8646, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/source_file_utils.ts" }
angular/packages/localize/tools/src/source_file_utils.ts_8647_17234
ction unwrapExpressionsFromTemplateLiteral( quasi: NodePath<t.TemplateLiteral>, fs: PathManipulation = getFileSystem(), ): [t.Expression[], (ɵSourceLocation | undefined)[]] { return [ quasi.node.expressions as t.Expression[], quasi.get('expressions').map((e) => getLocation(fs, e)), ]; } /** * Wrap the given `expression` in parentheses if it is a binary expression. * * This ensures that this expression is evaluated correctly if it is embedded in another expression. * * @param expression The expression to potentially wrap. */ export function wrapInParensIfNecessary(expression: t.Expression): t.Expression { if (t.isBinaryExpression(expression)) { return t.parenthesizedExpression(expression); } else { return expression; } } /** * Extract the string values from an `array` of string literals. * * @param array The array to unwrap. * @param fs The file system to use when computing source-map paths. If not provided then it uses * the "current" FileSystem. */ export function unwrapStringLiteralArray( array: NodePath<t.Expression>, fs: PathManipulation = getFileSystem(), ): [string[], (ɵSourceLocation | undefined)[]] { if (!isStringLiteralArray(array.node)) { throw new BabelParseError( array.node, 'Unexpected messageParts for `$localize` (expected an array of strings).', ); } const elements = array.get('elements') as NodePath<t.StringLiteral>[]; return [elements.map((str) => str.node.value), elements.map((str) => getLocation(fs, str))]; } /** * This expression is believed to be a call to a "lazy-load" template object helper function. * This is expected to be of the form: * * ```ts * function _templateObject() { * var e = _taggedTemplateLiteral(['cooked string', 'raw string']); * return _templateObject = function() { return e }, e * } * ``` * * We unwrap this to return the call to `_taggedTemplateLiteral()`. * * @param call the call expression to unwrap * @returns the call expression */ export function unwrapLazyLoadHelperCall( call: NodePath<t.CallExpression>, ): NodePath<t.CallExpression> { const callee = call.get('callee'); if (!callee.isIdentifier()) { throw new BabelParseError( callee.node, 'Unexpected lazy-load helper call (expected a call of the form `_templateObject()`).', ); } const lazyLoadBinding = call.scope.getBinding(callee.node.name); if (!lazyLoadBinding) { throw new BabelParseError(callee.node, 'Missing declaration for lazy-load helper function'); } const lazyLoadFn = lazyLoadBinding.path; if (!lazyLoadFn.isFunctionDeclaration()) { throw new BabelParseError( lazyLoadFn.node, 'Unexpected expression (expected a function declaration', ); } const returnedNode = getReturnedExpression(lazyLoadFn); if (returnedNode.isCallExpression()) { return returnedNode; } if (returnedNode.isIdentifier()) { const identifierName = returnedNode.node.name; const declaration = returnedNode.scope.getBinding(identifierName); if (declaration === undefined) { throw new BabelParseError( returnedNode.node, 'Missing declaration for return value from helper.', ); } if (!declaration.path.isVariableDeclarator()) { throw new BabelParseError( declaration.path.node, 'Unexpected helper return value declaration (expected a variable declaration).', ); } const initializer = declaration.path.get('init'); if (!initializer.isCallExpression()) { throw new BabelParseError( declaration.path.node, 'Unexpected return value from helper (expected a call expression).', ); } // Remove the lazy load helper if this is the only reference to it. if (lazyLoadBinding.references === 1) { lazyLoadFn.remove(); } return initializer; } return call; } function getReturnedExpression(fn: NodePath<t.FunctionDeclaration>): NodePath<t.Expression> { const bodyStatements = fn.get('body').get('body'); for (const statement of bodyStatements) { if (statement.isReturnStatement()) { const argument = statement.get('argument'); if (argument.isSequenceExpression()) { const expressions = argument.get('expressions'); return Array.isArray(expressions) ? expressions[expressions.length - 1] : expressions; } else if (argument.isExpression()) { return argument; } else { throw new BabelParseError( statement.node, 'Invalid return argument in helper function (expected an expression).', ); } } } throw new BabelParseError(fn.node, 'Missing return statement in helper function.'); } /** * Is the given `node` an array of literal strings? * * @param node The node to test. */ export function isStringLiteralArray( node: t.Node, ): node is t.Expression & {elements: t.StringLiteral[]} { return t.isArrayExpression(node) && node.elements.every((element) => t.isStringLiteral(element)); } /** * Are all the given `nodes` expressions? * @param nodes The nodes to test. */ export function isArrayOfExpressions(paths: NodePath<t.Node>[]): paths is NodePath<t.Expression>[] { return paths.every((element) => element.isExpression()); } /** Options that affect how the `makeEsXXXTranslatePlugin()` functions work. */ export interface TranslatePluginOptions { missingTranslation?: DiagnosticHandlingStrategy; localizeName?: string; } /** * Translate the text of the given message, using the given translations. * * Logs as warning if the translation is not available * @publicApi used by CLI */ export function translate( diagnostics: Diagnostics, translations: Record<string, ɵParsedTranslation>, messageParts: TemplateStringsArray, substitutions: readonly any[], missingTranslation: DiagnosticHandlingStrategy, ): [TemplateStringsArray, readonly any[]] { try { return ɵtranslate(translations, messageParts, substitutions); } catch (e: any) { if (ɵisMissingTranslationError(e)) { diagnostics.add(missingTranslation, e.message); // Return the parsed message because this will have the meta blocks stripped return [ ɵmakeTemplateObject(e.parsedMessage.messageParts, e.parsedMessage.messageParts), substitutions, ]; } else { diagnostics.error(e.message); return [messageParts, substitutions]; } } } export class BabelParseError extends Error { private readonly type = 'BabelParseError'; constructor( public node: t.Node, message: string, ) { super(message); } } export function isBabelParseError(e: any): e is BabelParseError { return e.type === 'BabelParseError'; } export function buildCodeFrameError( fs: PathManipulation, path: NodePath, file: BabelFile, e: BabelParseError, ): string { let filename = file.opts.filename; if (filename) { filename = fs.resolve(filename); let cwd = file.opts.cwd; if (cwd) { cwd = fs.resolve(cwd); filename = fs.relative(cwd, filename); } } else { filename = '(unknown file)'; } const {message} = file.hub.buildError(e.node, e.message); return `${filename}: ${message}`; } export function getLocation( fs: PathManipulation, startPath: NodePath, endPath?: NodePath, ): ɵSourceLocation | undefined { const startLocation = startPath.node.loc; const file = getFileFromPath(fs, startPath); if (!startLocation || !file) { return undefined; } const endLocation = (endPath && getFileFromPath(fs, endPath) === file && endPath.node.loc) || startLocation; return { start: getLineAndColumn(startLocation.start), end: getLineAndColumn(endLocation.end), file, text: startPath.getSource() || undefined, }; } export function serializeLocationPosition(location: ɵSourceLocation): string { const endLineString = location.end !== undefined && location.end.line !== location.start.line ? `,${location.end.line + 1}` : ''; return `${location.start.line + 1}${endLineString}`; } function getFileFromPath(fs: PathManipulation, path: NodePath | undefined): AbsoluteFsPath | null { // The file field is not guaranteed to be present for all node paths const opts = (path?.hub as {file?: BabelFile}).file?.opts; const filename = opts?.filename; if (!filename || !opts.cwd) { return null; } const relativePath = fs.relative(opts.cwd, filename); const root = opts.generatorOpts?.sourceRoot ?? opts.cwd; const absPath = fs.resolve(root, relativePath); return absPath; } function getLine
{ "end_byte": 17234, "start_byte": 8647, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/source_file_utils.ts" }
angular/packages/localize/tools/src/source_file_utils.ts_17236_17451
dColumn(loc: {line: number; column: number}): {line: number; column: number} { // Note we want 0-based line numbers but Babel returns 1-based. return {line: loc.line - 1, column: loc.column}; }
{ "end_byte": 17451, "start_byte": 17236, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/source_file_utils.ts" }
angular/packages/localize/tools/src/translate/translator.ts_0_3835
/** * @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 { AbsoluteFsPath, PathSegment, ReadonlyFileSystem, } from '@angular/compiler-cli/private/localize'; import {MessageId, ɵParsedTranslation} from '@angular/localize'; import {Diagnostics} from '../diagnostics'; import {OutputPathFn} from './output_path'; /** * An object that holds information to be used to translate files. */ export interface TranslationBundle { locale: string; translations: Record<MessageId, ɵParsedTranslation>; diagnostics?: Diagnostics; } /** * Implement this interface to provide a class that can handle translation for the given resource in * an appropriate manner. * * For example, source code files will need to be transformed if they contain `$localize` tagged * template strings, while most static assets will just need to be copied. */ export interface TranslationHandler { /** * Returns true if the given file can be translated by this handler. * * @param relativeFilePath A relative path from the sourceRoot to the resource file to handle. * @param contents The contents of the file to handle. */ canTranslate(relativeFilePath: PathSegment | AbsoluteFsPath, contents: Uint8Array): boolean; /** * Translate the file at `relativeFilePath` containing `contents`, using the given `translations`, * and write the translated content to the path computed by calling `outputPathFn()`. * * @param diagnostics An object for collecting translation diagnostic messages. * @param sourceRoot An absolute path to the root of the files being translated. * @param relativeFilePath A relative path from the sourceRoot to the file to translate. * @param contents The contents of the file to translate. * @param outputPathFn A function that returns an absolute path where the output file should be * written. * @param translations A collection of translations to apply to this file. * @param sourceLocale The locale of the original application source. If provided then an * additional copy of the application is created under this locale just with the `$localize` calls * stripped out. */ translate( diagnostics: Diagnostics, sourceRoot: AbsoluteFsPath, relativeFilePath: PathSegment | AbsoluteFsPath, contents: Uint8Array, outputPathFn: OutputPathFn, translations: TranslationBundle[], sourceLocale?: string, ): void; } /** * Translate each file (e.g. source file or static asset) using the given `TranslationHandler`s. * The file will be translated by the first handler that returns true for `canTranslate()`. */ export class Translator { constructor( private fs: ReadonlyFileSystem, private resourceHandlers: TranslationHandler[], private diagnostics: Diagnostics, ) {} translateFiles( inputPaths: PathSegment[], rootPath: AbsoluteFsPath, outputPathFn: OutputPathFn, translations: TranslationBundle[], sourceLocale?: string, ): void { inputPaths.forEach((inputPath) => { const absInputPath = this.fs.resolve(rootPath, inputPath); const contents = this.fs.readFileBuffer(absInputPath); const relativePath = this.fs.relative(rootPath, absInputPath); for (const resourceHandler of this.resourceHandlers) { if (resourceHandler.canTranslate(relativePath, contents)) { return resourceHandler.translate( this.diagnostics, rootPath, relativePath, contents, outputPathFn, translations, sourceLocale, ); } } this.diagnostics.error(`Unable to handle resource file: ${inputPath}`); }); } }
{ "end_byte": 3835, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translator.ts" }
angular/packages/localize/tools/src/translate/cli.ts_0_4605
#!/usr/bin/env node /** * @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 {NodeJSFileSystem, setFileSystem} from '@angular/compiler-cli/private/localize'; import glob from 'fast-glob'; import yargs from 'yargs'; import {DiagnosticHandlingStrategy, Diagnostics} from '../diagnostics'; import {getOutputPathFn} from './output_path'; import {translateFiles} from './index'; process.title = 'Angular Localization Message Translator (localize-translate)'; const args = process.argv.slice(2); const options = yargs(args) .option('r', { alias: 'root', required: true, describe: 'The root path of the files to translate, either absolute or relative to the current working directory. E.g. `dist/en`.', type: 'string', }) .option('s', { alias: 'source', required: true, describe: 'A glob pattern indicating what files to translate, relative to the `root` path. E.g. `bundles/**/*`.', type: 'string', }) .option('l', { alias: 'source-locale', describe: 'The source locale of the application. If this is provided then a copy of the application will be created with no translation but just the `$localize` calls stripped out.', type: 'string', }) .option('t', { alias: 'translations', required: true, array: true, describe: 'A list of paths to the translation files to load, either absolute or relative to the current working directory.\n' + 'E.g. `-t src/locale/messages.en.xlf src/locale/messages.fr.xlf src/locale/messages.de.xlf`.\n' + 'If you want to merge multiple translation files for each locale, then provide the list of files in an array.\n' + 'Note that the arrays must be in double quotes if you include any whitespace within the array.\n' + 'E.g. `-t "[src/locale/messages.en.xlf, src/locale/messages-2.en.xlf]" [src/locale/messages.fr.xlf,src/locale/messages-2.fr.xlf]`', type: 'string', }) .option('target-locales', { array: true, describe: 'A list of target locales for the translation files, which will override any target locale parsed from the translation file.\n' + 'E.g. "-t en fr de".', type: 'string', }) .option('o', { alias: 'outputPath', required: true, describe: 'A output path pattern to where the translated files will be written.\n' + 'The path must be either absolute or relative to the current working directory.\n' + 'The marker `{{LOCALE}}` will be replaced with the target locale. E.g. `dist/{{LOCALE}}`.', type: 'string', }) .option('m', { alias: 'missingTranslation', describe: 'How to handle missing translations.', choices: ['error', 'warning', 'ignore'], default: 'warning', type: 'string', }) .option('d', { alias: 'duplicateTranslation', describe: 'How to handle duplicate translations.', choices: ['error', 'warning', 'ignore'], default: 'warning', type: 'string', }) .strict() .help() .parseSync(); const fs = new NodeJSFileSystem(); setFileSystem(fs); const sourceRootPath = options.r; const sourceFilePaths = glob.sync(options.s, {cwd: sourceRootPath, onlyFiles: true}); const translationFilePaths: (string | string[])[] = convertArraysFromArgs(options.t); const outputPathFn = getOutputPathFn(fs, fs.resolve(options.o)); const diagnostics = new Diagnostics(); const missingTranslation = options.m as DiagnosticHandlingStrategy; const duplicateTranslation = options.d as DiagnosticHandlingStrategy; const sourceLocale: string | undefined = options.l; const translationFileLocales: string[] = options['target-locales'] || []; translateFiles({ sourceRootPath, sourceFilePaths, translationFilePaths, translationFileLocales, outputPathFn, diagnostics, missingTranslation, duplicateTranslation, sourceLocale, }); diagnostics.messages.forEach((m) => console.warn(`${m.type}: ${m.message}`)); process.exit(diagnostics.hasErrors ? 1 : 0); /** * Parse each of the given string `args` and convert it to an array if it is of the form * `[abc, def, ghi]`, i.e. it is enclosed in square brackets with comma delimited items. * @param args The string to potentially convert to arrays. */ function convertArraysFromArgs(args: string[]): (string | string[])[] { return args.map((arg) => arg.startsWith('[') && arg.endsWith(']') ? arg .slice(1, -1) .split(',') .map((arg) => arg.trim()) : arg, ); }
{ "end_byte": 4605, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/cli.ts" }
angular/packages/localize/tools/src/translate/output_path.ts_0_1138
/** * @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 {AbsoluteFsPath, PathManipulation} from '@angular/compiler-cli/private/localize'; /** * A function that will return an absolute path to where a file is to be written, given a locale and * a relative path. */ export interface OutputPathFn { (locale: string, relativePath: string): string; } /** * Create a function that will compute the absolute path to where a translated file should be * written. * * The special `{{LOCALE}}` marker will be replaced with the locale code of the current translation. * @param outputFolder An absolute path to the folder containing this set of translations. */ export function getOutputPathFn(fs: PathManipulation, outputFolder: AbsoluteFsPath): OutputPathFn { const [pre, post] = outputFolder.split('{{LOCALE}}'); return post === undefined ? (_locale, relativePath) => fs.join(pre, relativePath) : (locale, relativePath) => fs.join(pre + locale + post, relativePath); }
{ "end_byte": 1138, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/output_path.ts" }