-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
arb_translation_parser.ts
96 lines (87 loc) 路 2.77 KB
/
arb_translation_parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* @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.io/license
*/
import {MessageId, 傻parseTranslation, 傻SourceMessage} from '@angular/localize';
import {Diagnostics} from '../../../diagnostics';
import {ParseAnalysis, ParsedTranslationBundle, TranslationParser} from './translation_parser';
export interface ArbJsonObject extends Record<MessageId, 傻SourceMessage|ArbMetadata> {
'@@locale': string;
}
export interface ArbMetadata {
type?: 'text'|'image'|'css';
description?: string;
['x-locations']?: ArbLocation[];
}
export interface ArbLocation {
start: {line: number; column: number};
end: {line: number; column: number};
file: string;
}
/**
* A translation parser that can parse JSON formatted as an Application Resource Bundle (ARB).
*
* See https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification
*
* ```
* {
* "@@locale": "en-US",
* "message-id": "Target message string",
* "@message-id": {
* "type": "text",
* "description": "Some description text",
* "x-locations": [
* {
* "start": {"line": 23, "column": 145},
* "end": {"line": 24, "column": 53},
* "file": "some/file.ts"
* },
* ...
* ]
* },
* ...
* }
* ```
*/
export class ArbTranslationParser implements TranslationParser<ArbJsonObject> {
analyze(_filePath: string, contents: string): ParseAnalysis<ArbJsonObject> {
const diagnostics = new Diagnostics();
if (!contents.includes('"@@locale"')) {
return {canParse: false, diagnostics};
}
try {
// We can parse this file if it is valid JSON and contains the `"@@locale"` property.
return {canParse: true, diagnostics, hint: this.tryParseArbFormat(contents)};
} catch {
diagnostics.warn('File is not valid JSON.');
return {canParse: false, diagnostics};
}
}
parse(_filePath: string, contents: string, arb: ArbJsonObject = this.tryParseArbFormat(contents)):
ParsedTranslationBundle {
const bundle: ParsedTranslationBundle = {
locale: arb['@@locale'],
translations: {},
diagnostics: new Diagnostics(),
};
for (const messageId of Object.keys(arb)) {
if (messageId.startsWith('@')) {
// Skip metadata keys
continue;
}
const targetMessage = arb[messageId] as string;
bundle.translations[messageId] = 傻parseTranslation(targetMessage);
}
return bundle;
}
private tryParseArbFormat(contents: string): ArbJsonObject {
const json = JSON.parse(contents) as ArbJsonObject;
if (typeof json['@@locale'] !== 'string') {
throw new Error('Missing @@locale property.');
}
return json;
}
}