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