-
Notifications
You must be signed in to change notification settings - Fork 0
/
JavaScriptFile.js
352 lines (307 loc) · 13.4 KB
/
JavaScriptFile.js
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
* JavaScriptFile.js - plugin to extract resources from a JavaScript source code file
*
* Copyright (c) 2019-2022, JEDLSoft
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require("fs");
var path = require("path");
/**
* Create a new JavaScript file with the given path name and within
* the given project.
*
* @param {Project} project the project object
* @param {String} pathName path to the file relative to the root
* of the project file
* @param {FileType} type the file type of this instance
*/
var JavaScriptFile = function(props) {
this.project = props.project;
this.pathName = props.pathName;
this.type = props.type;
this.API = props.project.getAPI();
this.logger = this.API.getLogger("loctool.plugin.webOSJSFile");
this.set = this.API.newTranslationSet(this.project ? this.project.sourceLocale : "zxx-XX");
};
/**
* Unescape the string to make the same string that would be
* in memory in the target programming language.
*
* @static
* @param {String} string the string to unescape
* @returns {String} the unescaped string
*/
JavaScriptFile.unescapeString = function(string) {
var unescaped = string;
unescaped = unescaped.
replace(/^\\\\/, "\\"). // unescape backslashes
replace(/([^\\])\\\\/g, "$1\\").
replace(/^\\'/, "'"). // unescape quotes
replace(/([^\\])\\'/g, "$1'").
replace(/^\\"/, '"').
replace(/([^\\])\\"/g, '$1"');
return unescaped;
};
/**
* Clean the string to make a resource name string. This means
* removing leading and trailing white space, compressing
* whitespaces, and unescaping characters. This changes
* the string from what it looks like in the source
* code but increases matching.
*
* @static
* @param {String} string the string to clean
* @returns {String} the cleaned string
*/
JavaScriptFile.cleanString = function(string) {
var unescaped = JavaScriptFile.unescapeString(string);
unescaped = unescaped.
replace(/\\[btnfr]/g, " ").
replace(/[ \n\t\r\f]+/g, " ").
trim();
return unescaped;
};
/**
* Remove single and multi-lines comments except for i18n comment style.
*
* @private
* @param {String} string the string to clean
* @returns {String} the cleaned string
*/
JavaScriptFile.trimComments = function(data) {
if (!data) return;
// comment style: // , /* */ single, multi line
var trimData = data.replace(/\/\/\s*((?!i18n).)*[$/\n]/g, "").
replace(/\/\*+([^*]|\*(?!\/))*\*+\//g, "").
replace(/\/\*(.*)\*\//g, "");
return trimData;
};
/**
* Make a new key for the given string. This must correspond
* exactly with the code in htglob jar file so that the
* resources match up. See the class IResourceBundle in
* this project under the JavaScript directory for the corresponding
* code.
*
* @private
* @param {String} source the source string to make a resource
* key for
* @returns {String} a unique key for this string
*/
JavaScriptFile.prototype.makeKey = function(source) {
return JavaScriptFile.unescapeString(source).replace(/\s+/gm, ' ');
};
var reGetStringBogusConcatenation1 = new RegExp(/\.getString(JS)?\s*\(\s*("[^"]*"|'[^']*')\s*\+/g);
var reGetStringBogusConcatenation2 = new RegExp(/\.getString(JS)?\s*\([^\)]*\+\s*("[^"]*"|'[^']*')\s*\)/g);
var reGetStringBogusParam = new RegExp(/\.getString(JS)?\s*\([^"'\)]*\)/g);
var reGetString = new RegExp(/\.getString(JS)?\s*\(\s*("((\\"|[^"])*)"|'((\\'|[^'])*)')\s*\)/g);
var reGetStringSymbol = new RegExp(/(^\$|\W\$)L?\s*\(\s*("((\\"|[^"])*)"|'((\\'|[^'])*)')\s*\)/g);
var reGetStringSymbolKeyValuePattern = new RegExp(/(?:^\$|\W\$)L?\s*\(\s*{\s*(key|value)\:\s*("((\\"|[^"])*)"|'((\\'|[^'])*)')\,\s*(key|value)\:\s*("((\\"|[^"])*)"|'((\\'|[^'])*)')\s*\}\s*\)/g);
var reGetStringWithId = new RegExp(/\.getString(JS)?\s*\(\s*("((\\"|[^"])*)"|'((\\'|[^'])*)')\s*,\s*("((\\"|[^"])*)"|'((\\'|[^'])*)')\s*\)/g);
var reI18nComment = new RegExp("//\\s*i18n\\s*:\\s*(.*)$");
/**
* Parse the data string looking for the localizable strings and add them to the
* project's translation set.
* @param {String} data the string to parse
*/
JavaScriptFile.prototype.parse = function(data) {
this.logger.debug("Extracting strings from " + this.pathName);
data = JavaScriptFile.trimComments(data);
this.resourceIndex = 0;
var comment, match, key;
reGetString.lastIndex = 0; // just to be safe
var result = reGetString.exec(data);
while (result && result.length > 1 && result[2]) {
// different matches for single and double quotes
match = (result[2][0] === '"') ? result[3] : result[5];
if (match && match.length) {
this.logger.trace("Found string key: " + this.makeKey(match) + ", string: '" + match + "'");
var last = data.indexOf('\n', reGetString.lastIndex);
last = (last === -1) ? data.length : last;
var line = data.substring(reGetString.lastIndex, last);
var commentResult = reI18nComment.exec(line);
comment = (commentResult && commentResult.length > 1) ? commentResult[1] : undefined;
var r = this.API.newResource({
resType: "string",
project: this.project.getProjectId(),
key: this.makeKey(match),
sourceLocale: this.project.sourceLocale,
source: JavaScriptFile.unescapeString(match),
autoKey: true,
pathName: this.pathName,
state: "new",
comment: comment,
datatype: this.type.datatype,
index: this.resourceIndex++
});
this.set.add(r);
} else {
this.logger.debug("Warning: Bogus empty string in get string call: ");
this.logger.debug("... " + data.substring(result.index, reGetString.lastIndex) + " ...");
}
result = reGetString.exec(data);
}
// just to be safe
reI18nComment.lastIndex = 0;
reGetStringWithId.lastIndex = 0;
result = reGetStringWithId.exec(data);
while (result && result.length > 2 && result[2] && result[7]) {
// different matches for single and double quotes
match = (result[2][0] === '"') ? result[3] : result[5];
key = (result[7][0] === '"') ? result[8] : result[10];
if (match && key && match.length && key.length) {
var last = data.indexOf('\n', reGetStringWithId.lastIndex);
last = (last === -1) ? data.length : last;
var line = data.substring(reGetStringWithId.lastIndex, last);
var commentResult = reI18nComment.exec(line);
comment = (commentResult && commentResult.length > 1) ? commentResult[1] : undefined;
this.logger.trace("Found string '" + match + "' with unique key " + key + ", comment: " + comment);
var r = this.API.newResource({
resType: "string",
project: this.project.getProjectId(),
key: this.makeKey(key),
sourceLocale: this.project.sourceLocale,
source: JavaScriptFile.unescapeString(match),
pathName: this.pathName,
state: "new",
comment: comment,
datatype: this.type.datatype,
index: this.resourceIndex++
});
this.set.add(r);
} else {
this.logger.debug("Warning: Bogus empty string in get string call: ");
this.logger.debug("... " + data.substring(result.index, reGetString.lastIndex) + " ...");
}
result = reGetStringWithId.exec(data);
}
// just to be safe
// In order to parse Enyo/Enact style. ex)$L("hello");
reI18nComment.lastIndex = 0;
reGetStringSymbol.lastIndex = 0; // just to be safe
var result = reGetStringSymbol.exec(data);
while (result && result.length > 1 && result[2]) {
// different matches for single and double quotes
match = (result[2][0] === '"') ? result[3] : result[5];
if (match && match.length) {
this.logger.trace("Found string key: " + this.makeKey(match) + ", string: '" + match + "'");
var last = data.indexOf('\n', reGetStringSymbol.lastIndex);
last = (last === -1) ? data.length : last;
var line = data.substring(reGetStringSymbol.lastIndex, last);
var commentResult = reI18nComment.exec(line);
comment = (commentResult && commentResult.length > 1) ? commentResult[1] : undefined;
var r = this.API.newResource({
project: this.project.getProjectId(),
key: this.makeKey(match),
sourceLocale: this.project.sourceLocale,
source: JavaScriptFile.unescapeString(match),
autoKey: true,
pathName: this.pathName,
state: "new",
comment: comment,
datatype: "javascript",
index: this.resourceIndex++
});
this.set.add(r);
} else {
this.logger.debug("Warning: Bogus empty string in get string call: ");
this.logger.debug("... " + data.substring(result.index, reGetStringSymbol.lastIndex) + " ...");
}
result = reGetStringSymbol.exec(data);
}
// In order to parse Enyo/Enact style. $L({key:'speaker_channel', value:'Channel'})
reI18nComment.lastIndex = 0;
reGetStringSymbolKeyValuePattern.lastIndex = 0; // just to be safe
var result = reGetStringSymbolKeyValuePattern.exec(data);
while (result && result.length > 1 && result[2]) {
// different matches for single and double quotes
if (result[1] === "key") {
key = (result[2][0] === '"') ? result[3] : result[5];
match = (result[8][0] === '"') ? result[9] : result[11];
} else if (result[7] === "key") {
key = (result[8][0] === '"') ? result[9] : result[11];
match = (result[2][0] === '"') ? result[3] : result[5];
}
if (match && match.length) {
this.logger.trace("Found string key: " + key + ", string: '" + match + "'");
var last = data.indexOf('\n', reGetStringSymbolKeyValuePattern.lastIndex);
last = (last === -1) ? data.length : last;
var line = data.substring(reGetStringSymbolKeyValuePattern.lastIndex, last);
var commentResult = reI18nComment.exec(line);
comment = (commentResult && commentResult.length > 1) ? commentResult[1] : undefined;
var r = this.API.newResource({
project: this.project.getProjectId(),
key: this.makeKey(key),
sourceLocale: this.project.sourceLocale,
source: JavaScriptFile.unescapeString(match),
autoKey: true,
pathName: this.pathName,
state: "new",
comment: comment,
datatype: "javascript",
index: this.resourceIndex++
});
this.set.add(r);
} else {
this.logger.debug("Warning: Bogus empty string in get string call: ");
this.logger.debug("... " + data.substring(result.index, reGetStringSymbolKeyValuePattern.lastIndex) + " ...");
}
result = reGetStringSymbolKeyValuePattern.exec(data);
}
// now check for and report on errors in the source
this.API.utils.generateWarnings(data, reGetStringBogusConcatenation1,
"Warning: string concatenation is not allowed in the .getString() parameters:",
this.logger,
this.pathName);
this.API.utils.generateWarnings(data, reGetStringBogusConcatenation2,
"Warning: string concatenation is not allowed in the .getString() parameters:",
this.logger,
this.pathName);
this.API.utils.generateWarnings(data, reGetStringBogusParam,
"Warning: non-string arguments are not allowed in the .getString() parameters:",
this.logger,
this.pathName);
};
/**
* Extract all the localizable strings from the JavaScript file and add them to the
* project's translation set.
*/
JavaScriptFile.prototype.extract = function() {
this.logger.debug("Extracting strings from " + this.pathName);
if (this.pathName) {
var p = path.join(this.project.root, this.pathName);
try {
var data = fs.readFileSync(p, "utf8");
if (data) {
this.parse(data);
}
} catch (e) {
this.logger.warn("Could not read file: " + p);
}
}
};
/**
* Return the set of resources found in the current JavaScript file.
*
* @returns {TranslationSet} The set of resources found in the
* current JavaScript file.
*/
JavaScriptFile.prototype.getTranslationSet = function() {
return this.set;
}
// we don't localize or write javascript source files
JavaScriptFile.prototype.localize = function() {};
JavaScriptFile.prototype.write = function() {};
module.exports = JavaScriptFile;