Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80635 views
1
/**
2
* lodash 3.6.1 (Custom Build) <https://lodash.com/>
3
* Build: `lodash modern modularize exports="npm" -o ./`
4
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
5
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
6
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
7
* Available under MIT license <https://lodash.com/license>
8
*/
9
var baseCopy = require('lodash._basecopy'),
10
baseToString = require('lodash._basetostring'),
11
baseValues = require('lodash._basevalues'),
12
isIterateeCall = require('lodash._isiterateecall'),
13
reInterpolate = require('lodash._reinterpolate'),
14
keys = require('lodash.keys'),
15
restParam = require('lodash.restparam'),
16
templateSettings = require('lodash.templatesettings');
17
18
/** `Object#toString` result references. */
19
var errorTag = '[object Error]';
20
21
/** Used to match empty string literals in compiled template source. */
22
var reEmptyStringLeading = /\b__p \+= '';/g,
23
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
24
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
25
26
/** Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components). */
27
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
28
29
/** Used to ensure capturing order of template delimiters. */
30
var reNoMatch = /($^)/;
31
32
/** Used to match unescaped characters in compiled string literals. */
33
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
34
35
/** Used to escape characters for inclusion in compiled string literals. */
36
var stringEscapes = {
37
'\\': '\\',
38
"'": "'",
39
'\n': 'n',
40
'\r': 'r',
41
'\u2028': 'u2028',
42
'\u2029': 'u2029'
43
};
44
45
/**
46
* Used by `_.template` to escape characters for inclusion in compiled
47
* string literals.
48
*
49
* @private
50
* @param {string} chr The matched character to escape.
51
* @returns {string} Returns the escaped character.
52
*/
53
function escapeStringChar(chr) {
54
return '\\' + stringEscapes[chr];
55
}
56
57
/**
58
* Checks if `value` is object-like.
59
*
60
* @private
61
* @param {*} value The value to check.
62
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
63
*/
64
function isObjectLike(value) {
65
return !!value && typeof value == 'object';
66
}
67
68
/** Used for native method references. */
69
var objectProto = Object.prototype;
70
71
/** Used to check objects for own properties. */
72
var hasOwnProperty = objectProto.hasOwnProperty;
73
74
/**
75
* Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
76
* of values.
77
*/
78
var objToString = objectProto.toString;
79
80
/**
81
* Used by `_.template` to customize its `_.assign` use.
82
*
83
* **Note:** This function is like `assignDefaults` except that it ignores
84
* inherited property values when checking if a property is `undefined`.
85
*
86
* @private
87
* @param {*} objectValue The destination object property value.
88
* @param {*} sourceValue The source object property value.
89
* @param {string} key The key associated with the object and source values.
90
* @param {Object} object The destination object.
91
* @returns {*} Returns the value to assign to the destination object.
92
*/
93
function assignOwnDefaults(objectValue, sourceValue, key, object) {
94
return (objectValue === undefined || !hasOwnProperty.call(object, key))
95
? sourceValue
96
: objectValue;
97
}
98
99
/**
100
* A specialized version of `_.assign` for customizing assigned values without
101
* support for argument juggling, multiple sources, and `this` binding `customizer`
102
* functions.
103
*
104
* @private
105
* @param {Object} object The destination object.
106
* @param {Object} source The source object.
107
* @param {Function} customizer The function to customize assigned values.
108
* @returns {Object} Returns `object`.
109
*/
110
function assignWith(object, source, customizer) {
111
var index = -1,
112
props = keys(source),
113
length = props.length;
114
115
while (++index < length) {
116
var key = props[index],
117
value = object[key],
118
result = customizer(value, source[key], key, object, source);
119
120
if ((result === result ? (result !== value) : (value === value)) ||
121
(value === undefined && !(key in object))) {
122
object[key] = result;
123
}
124
}
125
return object;
126
}
127
128
/**
129
* The base implementation of `_.assign` without support for argument juggling,
130
* multiple sources, and `customizer` functions.
131
*
132
* @private
133
* @param {Object} object The destination object.
134
* @param {Object} source The source object.
135
* @returns {Object} Returns `object`.
136
*/
137
function baseAssign(object, source) {
138
return source == null
139
? object
140
: baseCopy(source, keys(source), object);
141
}
142
143
/**
144
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
145
* `SyntaxError`, `TypeError`, or `URIError` object.
146
*
147
* @static
148
* @memberOf _
149
* @category Lang
150
* @param {*} value The value to check.
151
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
152
* @example
153
*
154
* _.isError(new Error);
155
* // => true
156
*
157
* _.isError(Error);
158
* // => false
159
*/
160
function isError(value) {
161
return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
162
}
163
164
/**
165
* Creates a compiled template function that can interpolate data properties
166
* in "interpolate" delimiters, HTML-escape interpolated data properties in
167
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
168
* properties may be accessed as free variables in the template. If a setting
169
* object is provided it takes precedence over `_.templateSettings` values.
170
*
171
* **Note:** In the development build `_.template` utilizes
172
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
173
* for easier debugging.
174
*
175
* For more information on precompiling templates see
176
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
177
*
178
* For more information on Chrome extension sandboxes see
179
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
180
*
181
* @static
182
* @memberOf _
183
* @category String
184
* @param {string} [string=''] The template string.
185
* @param {Object} [options] The options object.
186
* @param {RegExp} [options.escape] The HTML "escape" delimiter.
187
* @param {RegExp} [options.evaluate] The "evaluate" delimiter.
188
* @param {Object} [options.imports] An object to import into the template as free variables.
189
* @param {RegExp} [options.interpolate] The "interpolate" delimiter.
190
* @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
191
* @param {string} [options.variable] The data object variable name.
192
* @param- {Object} [otherOptions] Enables the legacy `options` param signature.
193
* @returns {Function} Returns the compiled template function.
194
* @example
195
*
196
* // using the "interpolate" delimiter to create a compiled template
197
* var compiled = _.template('hello <%= user %>!');
198
* compiled({ 'user': 'fred' });
199
* // => 'hello fred!'
200
*
201
* // using the HTML "escape" delimiter to escape data property values
202
* var compiled = _.template('<b><%- value %></b>');
203
* compiled({ 'value': '<script>' });
204
* // => '<b>&lt;script&gt;</b>'
205
*
206
* // using the "evaluate" delimiter to execute JavaScript and generate HTML
207
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
208
* compiled({ 'users': ['fred', 'barney'] });
209
* // => '<li>fred</li><li>barney</li>'
210
*
211
* // using the internal `print` function in "evaluate" delimiters
212
* var compiled = _.template('<% print("hello " + user); %>!');
213
* compiled({ 'user': 'barney' });
214
* // => 'hello barney!'
215
*
216
* // using the ES delimiter as an alternative to the default "interpolate" delimiter
217
* var compiled = _.template('hello ${ user }!');
218
* compiled({ 'user': 'pebbles' });
219
* // => 'hello pebbles!'
220
*
221
* // using custom template delimiters
222
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
223
* var compiled = _.template('hello {{ user }}!');
224
* compiled({ 'user': 'mustache' });
225
* // => 'hello mustache!'
226
*
227
* // using backslashes to treat delimiters as plain text
228
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
229
* compiled({ 'value': 'ignored' });
230
* // => '<%- value %>'
231
*
232
* // using the `imports` option to import `jQuery` as `jq`
233
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
234
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
235
* compiled({ 'users': ['fred', 'barney'] });
236
* // => '<li>fred</li><li>barney</li>'
237
*
238
* // using the `sourceURL` option to specify a custom sourceURL for the template
239
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
240
* compiled(data);
241
* // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
242
*
243
* // using the `variable` option to ensure a with-statement isn't used in the compiled template
244
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
245
* compiled.source;
246
* // => function(data) {
247
* // var __t, __p = '';
248
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
249
* // return __p;
250
* // }
251
*
252
* // using the `source` property to inline compiled templates for meaningful
253
* // line numbers in error messages and a stack trace
254
* fs.writeFileSync(path.join(cwd, 'jst.js'), '\
255
* var JST = {\
256
* "main": ' + _.template(mainText).source + '\
257
* };\
258
* ');
259
*/
260
function template(string, options, otherOptions) {
261
// Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
262
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
263
var settings = templateSettings.imports._.templateSettings || templateSettings;
264
265
if (otherOptions && isIterateeCall(string, options, otherOptions)) {
266
options = otherOptions = null;
267
}
268
string = baseToString(string);
269
options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
270
271
var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
272
importsKeys = keys(imports),
273
importsValues = baseValues(imports, importsKeys);
274
275
var isEscaping,
276
isEvaluating,
277
index = 0,
278
interpolate = options.interpolate || reNoMatch,
279
source = "__p += '";
280
281
// Compile the regexp to match each delimiter.
282
var reDelimiters = RegExp(
283
(options.escape || reNoMatch).source + '|' +
284
interpolate.source + '|' +
285
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
286
(options.evaluate || reNoMatch).source + '|$'
287
, 'g');
288
289
// Use a sourceURL for easier debugging.
290
var sourceURL = 'sourceURL' in options ? '//# sourceURL=' + options.sourceURL + '\n' : '';
291
292
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
293
interpolateValue || (interpolateValue = esTemplateValue);
294
295
// Escape characters that can't be included in string literals.
296
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
297
298
// Replace delimiters with snippets.
299
if (escapeValue) {
300
isEscaping = true;
301
source += "' +\n__e(" + escapeValue + ") +\n'";
302
}
303
if (evaluateValue) {
304
isEvaluating = true;
305
source += "';\n" + evaluateValue + ";\n__p += '";
306
}
307
if (interpolateValue) {
308
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
309
}
310
index = offset + match.length;
311
312
// The JS engine embedded in Adobe products requires returning the `match`
313
// string in order to produce the correct `offset` value.
314
return match;
315
});
316
317
source += "';\n";
318
319
// If `variable` is not specified wrap a with-statement around the generated
320
// code to add the data object to the top of the scope chain.
321
var variable = options.variable;
322
if (!variable) {
323
source = 'with (obj) {\n' + source + '\n}\n';
324
}
325
// Cleanup code by stripping empty strings.
326
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
327
.replace(reEmptyStringMiddle, '$1')
328
.replace(reEmptyStringTrailing, '$1;');
329
330
// Frame code as the function body.
331
source = 'function(' + (variable || 'obj') + ') {\n' +
332
(variable
333
? ''
334
: 'obj || (obj = {});\n'
335
) +
336
"var __t, __p = ''" +
337
(isEscaping
338
? ', __e = _.escape'
339
: ''
340
) +
341
(isEvaluating
342
? ', __j = Array.prototype.join;\n' +
343
"function print() { __p += __j.call(arguments, '') }\n"
344
: ';\n'
345
) +
346
source +
347
'return __p\n}';
348
349
var result = attempt(function() {
350
return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
351
});
352
353
// Provide the compiled function's source by its `toString` method or
354
// the `source` property as a convenience for inlining compiled templates.
355
result.source = source;
356
if (isError(result)) {
357
throw result;
358
}
359
return result;
360
}
361
362
/**
363
* Attempts to invoke `func`, returning either the result or the caught error
364
* object. Any additional arguments are provided to `func` when it is invoked.
365
*
366
* @static
367
* @memberOf _
368
* @category Utility
369
* @param {Function} func The function to attempt.
370
* @returns {*} Returns the `func` result or error object.
371
* @example
372
*
373
* // avoid throwing errors for invalid selectors
374
* var elements = _.attempt(function(selector) {
375
* return document.querySelectorAll(selector);
376
* }, '>_>');
377
*
378
* if (_.isError(elements)) {
379
* elements = [];
380
* }
381
*/
382
var attempt = restParam(function(func, args) {
383
try {
384
return func.apply(undefined, args);
385
} catch(e) {
386
return isError(e) ? e : new Error(e);
387
}
388
});
389
390
module.exports = template;
391
392