This repository has been archived by the owner on Apr 11, 2018. It is now read-only.
/
helpers.js
188 lines (152 loc) · 6.58 KB
/
helpers.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
var _ = require('underscore'),
filters = require('./filters'),
// Checks if there are unescaped single quotes (the string needs to be reversed first)
UNESCAPED_QUOTE = /'(?!\\)/,
// Checks if there are unescaped double quotes (the string needs to be reversed first)
UNESCAPED_DQUOTE = /"(?!\\)/,
// Javascript keywords can't be a name: 'for.is_invalid' as well as 'for' but not 'for_' or '_for'
KEYWORDS = /^(Array|ArrayBuffer|Boolean|Date|Error|eval|EvalError|Function|Infinity|Iterator|JSON|Math|Namespace|NaN|Number|Object|QName|RangeError|ReferenceError|RegExp|StopIteration|String|SyntaxError|TypeError|undefined|uneval|URIError|XML|XMLList|break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|this|throw|try|typeof|var|void|while|with)(?=(\.|$))/;
// Returns TRUE if the passed string is a valid javascript number or string literal
function isLiteral(string) {
var literal = false,
teststr;
// Check if it's a number literal
if ((/^\d+([.]\d+)?$/).test(string)) {
literal = true;
} else if ((string[0] === string[string.length - 1]) && (string[0] === "'" || string[0] === '"')) {
// Check if it's a valid string literal (throw exception otherwise)
teststr = string.substr(1, string.length - 2).split('').reverse().join('');
if ((string[0] === "'" && UNESCAPED_QUOTE.test(teststr)) || (string[1] === '"' && UNESCAPED_DQUOTE.test(teststr))) {
throw new Error('Invalid string literal. Unescaped quote (' + string[0] + ') found.');
}
literal = true;
}
return literal;
}
exports.isLiteral = isLiteral;
// Returns TRUE if the passed string is a valid javascript string literal
function isStringLiteral(string) {
// Check if it's a valid string literal (throw exception otherwise)
if ((string[0] === string[string.length - 1]) && (string[0] === "'" || string[0] === '"')) {
var teststr = string.substr(1, string.length - 2).split('').reverse().join('');
if ((string[0] === "'" && UNESCAPED_QUOTE.test(teststr)) || (string[1] === '"' && UNESCAPED_DQUOTE.test(teststr))) {
throw new Error('Invalid string literal. Unescaped quote (' + string[0] + ') found.');
}
return true;
}
return false;
}
exports.isStringLiteral = isStringLiteral;
// Variable names starting with __ are reserved.
function isValidName(string) {
return string.substr(0, 2) !== '__' && (/^([$A-Za-z_]+[$A-Za-z_0-9]*)(\.?([$A-Za-z_]+[$A-Za-z_0-9]*))*$/).test(string) && !KEYWORDS.test(string);
}
exports.isValidName = isValidName;
// Variable names starting with __ are reserved.
function isValidShortName(string) {
return string.substr(0, 2) !== '__' && (/^[$A-Za-z_]+[$A-Za-z_0-9]*$/).test(string) && !KEYWORDS.test(string);
}
exports.isValidShortName = isValidShortName;
// Checks if a name is a vlaid block name
function isValidBlockName(string) {
return (/^[A-Za-z]+[A-Za-z_0-9]*$/).test(string);
}
exports.isValidBlockName = isValidBlockName;
/**
* Returns a valid javascript code that will
* check if a variable (or property chain) exists
* in the evaled context. For example:
* check('foo.bar.baz')
* will return the following string:
* typeof foo !== 'undefined' && typeof foo.bar !== 'undefined' && typeof foo.bar.baz !== 'undefined'
*/
function check(variable, context) {
if (Array.isArray(variable)) {
return '(true)';
}
variable = variable.replace(/^this/, '__this.__currentContext');
if (isLiteral(variable)) {
return '(true)';
}
var props = variable.split(/(\.|\[|\])/),
chain = '',
output = [];
if (typeof context === 'string' && context.length) {
props.unshift(context);
}
props = _.reject(props, function (val) {
return val === '' || val === '.' || val === '[' || val === ']';
});
props.forEach(function (prop) {
chain += chain ? (isNaN(prop) && prop[0] !== '"' && prop[0] !== "'" ? '.' + prop : '[' + prop + ']') : prop;
output.push('typeof ' + chain + ' !== "undefined"');
});
return '(' + output.join(' && ') + ')';
}
exports.check = check;
/**
* Returns an escaped string (safe for evaling). If context is passed
* then returns a concatenation of context and the escaped variable name.
*/
exports.escape = function (variable, context) {
if (Array.isArray(variable)) {
_.each(variable, function (val, key) {
variable[key] = exports.escape(val, context);
});
return variable;
}
variable = variable.replace(/^this/, '__this.__currentContext');
if (isLiteral(variable)) {
return variable;
} else if (typeof context === 'string' && context.length) {
variable = context + '.' + variable;
}
var chain = '', props = variable.split('.');
props.forEach(function (prop) {
chain += (chain ? (isNaN(prop) ? '.' + prop : '[' + prop + ']') : prop);
});
return chain.replace(/\n/g, '\\n').replace(/\r/g, '\\r');
};
exports.escaper = function (input) {
if (typeof input === 'string') {
return input.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
} else {
return input;
}
};
exports.wrapFilter = function (variable, filter) {
var output = variable,
args;
if (!filter) {
return variable;
}
if (filters.hasOwnProperty(filter.name)) {
args = [variable];
filter.args.forEach(function (f) {
args.push('\'' + f.replace(/\\/g, '\\\\').replace(/^\"|\"$/g, '') + '\'');
});
output = '__filters.' + filter.name + '.apply(this, [' + args.toString() + '])';
}
return output;
};
exports.wrapFilters = function (variable, filters, context, escape) {
var output = exports.escape(variable, context);
if (filters && filters.length > 0) {
filters.forEach(function (filter) {
output = exports.wrapFilter(output, filter);
});
}
if (escape) {
output = '__escape.apply(this, [' + output + '])';
}
return output;
};
exports.setVar = function (varName, argument) {
var out = 'var ' + varName + ' = "";' +
'if (' + check(argument.name) + ') {' +
' ' + varName + ' = ' + exports.wrapFilters(exports.escape(argument.name), argument.filters, null, argument.escape) + ';' +
'} else if (' + check(argument.name, '__context') + ') {' +
' ' + varName + ' = ' + exports.wrapFilters(exports.escape(argument.name), argument.filters, '__context', argument.escape) + ';' +
'}';
return out;
};