nunjucks
Version:
A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
1,691 lines (1,624 loc) • 107 kB
JavaScript
/*! Browser bundle of nunjucks 3.2.4 (slim, only works with precompiled templates) */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["nunjucks"] = factory();
else
root["nunjucks"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 6);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ArrayProto = Array.prototype;
var ObjProto = Object.prototype;
var escapeMap = {
'&': '&',
'"': '"',
'\'': ''',
'<': '<',
'>': '>',
'\\': '\'
};
var escapeRegex = /[&"'<>\\]/g;
var exports = module.exports = {};
function hasOwnProp(obj, k) {
return ObjProto.hasOwnProperty.call(obj, k);
}
exports.hasOwnProp = hasOwnProp;
function lookupEscape(ch) {
return escapeMap[ch];
}
function _prettifyError(path, withInternals, err) {
if (!err.Update) {
// not one of ours, cast it
err = new exports.TemplateError(err);
}
err.Update(path);
// Unless they marked the dev flag, show them a trace from here
if (!withInternals) {
var old = err;
err = new Error(old.message);
err.name = old.name;
}
return err;
}
exports._prettifyError = _prettifyError;
function TemplateError(message, lineno, colno) {
var err;
var cause;
if (message instanceof Error) {
cause = message;
message = cause.name + ": " + cause.message;
}
if (Object.setPrototypeOf) {
err = new Error(message);
Object.setPrototypeOf(err, TemplateError.prototype);
} else {
err = this;
Object.defineProperty(err, 'message', {
enumerable: false,
writable: true,
value: message
});
}
Object.defineProperty(err, 'name', {
value: 'Template render error'
});
if (Error.captureStackTrace) {
Error.captureStackTrace(err, this.constructor);
}
var getStack;
if (cause) {
var stackDescriptor = Object.getOwnPropertyDescriptor(cause, 'stack');
getStack = stackDescriptor && (stackDescriptor.get || function () {
return stackDescriptor.value;
});
if (!getStack) {
getStack = function getStack() {
return cause.stack;
};
}
} else {
var stack = new Error(message).stack;
getStack = function getStack() {
return stack;
};
}
Object.defineProperty(err, 'stack', {
get: function get() {
return getStack.call(err);
}
});
Object.defineProperty(err, 'cause', {
value: cause
});
err.lineno = lineno;
err.colno = colno;
err.firstUpdate = true;
err.Update = function Update(path) {
var msg = '(' + (path || 'unknown path') + ')';
// only show lineno + colno next to path of template
// where error occurred
if (this.firstUpdate) {
if (this.lineno && this.colno) {
msg += " [Line " + this.lineno + ", Column " + this.colno + "]";
} else if (this.lineno) {
msg += " [Line " + this.lineno + "]";
}
}
msg += '\n ';
if (this.firstUpdate) {
msg += ' ';
}
this.message = msg + (this.message || '');
this.firstUpdate = false;
return this;
};
return err;
}
if (Object.setPrototypeOf) {
Object.setPrototypeOf(TemplateError.prototype, Error.prototype);
} else {
TemplateError.prototype = Object.create(Error.prototype, {
constructor: {
value: TemplateError
}
});
}
exports.TemplateError = TemplateError;
function escape(val) {
return val.replace(escapeRegex, lookupEscape);
}
exports.escape = escape;
function isFunction(obj) {
return ObjProto.toString.call(obj) === '[object Function]';
}
exports.isFunction = isFunction;
function isArray(obj) {
return ObjProto.toString.call(obj) === '[object Array]';
}
exports.isArray = isArray;
function isString(obj) {
return ObjProto.toString.call(obj) === '[object String]';
}
exports.isString = isString;
function isObject(obj) {
return ObjProto.toString.call(obj) === '[object Object]';
}
exports.isObject = isObject;
/**
* @param {string|number} attr
* @returns {(string|number)[]}
* @private
*/
function _prepareAttributeParts(attr) {
if (!attr) {
return [];
}
if (typeof attr === 'string') {
return attr.split('.');
}
return [attr];
}
/**
* @param {string} attribute Attribute value. Dots allowed.
* @returns {function(Object): *}
*/
function getAttrGetter(attribute) {
var parts = _prepareAttributeParts(attribute);
return function attrGetter(item) {
var _item = item;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
// If item is not an object, and we still got parts to handle, it means
// that something goes wrong. Just roll out to undefined in that case.
if (hasOwnProp(_item, part)) {
_item = _item[part];
} else {
return undefined;
}
}
return _item;
};
}
exports.getAttrGetter = getAttrGetter;
function groupBy(obj, val, throwOnUndefined) {
var result = {};
var iterator = isFunction(val) ? val : getAttrGetter(val);
for (var i = 0; i < obj.length; i++) {
var value = obj[i];
var key = iterator(value, i);
if (key === undefined && throwOnUndefined === true) {
throw new TypeError("groupby: attribute \"" + val + "\" resolved to undefined");
}
(result[key] || (result[key] = [])).push(value);
}
return result;
}
exports.groupBy = groupBy;
function toArray(obj) {
return Array.prototype.slice.call(obj);
}
exports.toArray = toArray;
function without(array) {
var result = [];
if (!array) {
return result;
}
var length = array.length;
var contains = toArray(arguments).slice(1);
var index = -1;
while (++index < length) {
if (indexOf(contains, array[index]) === -1) {
result.push(array[index]);
}
}
return result;
}
exports.without = without;
function repeat(char_, n) {
var str = '';
for (var i = 0; i < n; i++) {
str += char_;
}
return str;
}
exports.repeat = repeat;
function each(obj, func, context) {
if (obj == null) {
return;
}
if (ArrayProto.forEach && obj.forEach === ArrayProto.forEach) {
obj.forEach(func, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
func.call(context, obj[i], i, obj);
}
}
}
exports.each = each;
function map(obj, func) {
var results = [];
if (obj == null) {
return results;
}
if (ArrayProto.map && obj.map === ArrayProto.map) {
return obj.map(func);
}
for (var i = 0; i < obj.length; i++) {
results[results.length] = func(obj[i], i);
}
if (obj.length === +obj.length) {
results.length = obj.length;
}
return results;
}
exports.map = map;
function asyncIter(arr, iter, cb) {
var i = -1;
function next() {
i++;
if (i < arr.length) {
iter(arr[i], i, next, cb);
} else {
cb();
}
}
next();
}
exports.asyncIter = asyncIter;
function asyncFor(obj, iter, cb) {
var keys = keys_(obj || {});
var len = keys.length;
var i = -1;
function next() {
i++;
var k = keys[i];
if (i < len) {
iter(k, obj[k], i, len, next);
} else {
cb();
}
}
next();
}
exports.asyncFor = asyncFor;
function indexOf(arr, searchElement, fromIndex) {
return Array.prototype.indexOf.call(arr || [], searchElement, fromIndex);
}
exports.indexOf = indexOf;
function keys_(obj) {
/* eslint-disable no-restricted-syntax */
var arr = [];
for (var k in obj) {
if (hasOwnProp(obj, k)) {
arr.push(k);
}
}
return arr;
}
exports.keys = keys_;
function _entries(obj) {
return keys_(obj).map(function (k) {
return [k, obj[k]];
});
}
exports._entries = _entries;
function _values(obj) {
return keys_(obj).map(function (k) {
return obj[k];
});
}
exports._values = _values;
function extend(obj1, obj2) {
obj1 = obj1 || {};
keys_(obj2).forEach(function (k) {
obj1[k] = obj2[k];
});
return obj1;
}
exports._assign = exports.extend = extend;
function inOperator(key, val) {
if (isArray(val) || isString(val)) {
return val.indexOf(key) !== -1;
} else if (isObject(val)) {
return key in val;
}
throw new Error('Cannot use "in" operator to search for "' + key + '" in unexpected types.');
}
exports.inOperator = inOperator;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var lib = __webpack_require__(1);
var arrayFrom = Array.from;
var supportsIterators = typeof Symbol === 'function' && Symbol.iterator && typeof arrayFrom === 'function';
// Frames keep track of scoping both at compile-time and run-time so
// we know how to access variables. Block tags can introduce special
// variables, for example.
var Frame = /*#__PURE__*/function () {
function Frame(parent, isolateWrites) {
this.variables = Object.create(null);
this.parent = parent;
this.topLevel = false;
// if this is true, writes (set) should never propagate upwards past
// this frame to its parent (though reads may).
this.isolateWrites = isolateWrites;
}
var _proto = Frame.prototype;
_proto.set = function set(name, val, resolveUp) {
// Allow variables with dots by automatically creating the
// nested structure
var parts = name.split('.');
var obj = this.variables;
var frame = this;
if (resolveUp) {
if (frame = this.resolve(parts[0], true)) {
frame.set(name, val);
return;
}
}
for (var i = 0; i < parts.length - 1; i++) {
var id = parts[i];
if (!obj[id]) {
obj[id] = {};
}
obj = obj[id];
}
obj[parts[parts.length - 1]] = val;
};
_proto.get = function get(name) {
var val = this.variables[name];
if (val !== undefined) {
return val;
}
return null;
};
_proto.lookup = function lookup(name) {
var p = this.parent;
var val = this.variables[name];
if (val !== undefined) {
return val;
}
return p && p.lookup(name);
};
_proto.resolve = function resolve(name, forWrite) {
var p = forWrite && this.isolateWrites ? undefined : this.parent;
var val = this.variables[name];
if (val !== undefined) {
return this;
}
return p && p.resolve(name);
};
_proto.push = function push(isolateWrites) {
return new Frame(this, isolateWrites);
};
_proto.pop = function pop() {
return this.parent;
};
return Frame;
}();
function makeMacro(argNames, kwargNames, func) {
return function macro() {
for (var _len = arguments.length, macroArgs = new Array(_len), _key = 0; _key < _len; _key++) {
macroArgs[_key] = arguments[_key];
}
var argCount = numArgs(macroArgs);
var args;
var kwargs = getKeywordArgs(macroArgs);
if (argCount > argNames.length) {
args = macroArgs.slice(0, argNames.length);
// Positional arguments that should be passed in as
// keyword arguments (essentially default values)
macroArgs.slice(args.length, argCount).forEach(function (val, i) {
if (i < kwargNames.length) {
kwargs[kwargNames[i]] = val;
}
});
args.push(kwargs);
} else if (argCount < argNames.length) {
args = macroArgs.slice(0, argCount);
for (var i = argCount; i < argNames.length; i++) {
var arg = argNames[i];
// Keyword arguments that should be passed as
// positional arguments, i.e. the caller explicitly
// used the name of a positional arg
args.push(kwargs[arg]);
delete kwargs[arg];
}
args.push(kwargs);
} else {
args = macroArgs;
}
return func.apply(this, args);
};
}
function makeKeywordArgs(obj) {
obj.__keywords = true;
return obj;
}
function isKeywordArgs(obj) {
return obj && Object.prototype.hasOwnProperty.call(obj, '__keywords');
}
function getKeywordArgs(args) {
var len = args.length;
if (len) {
var lastArg = args[len - 1];
if (isKeywordArgs(lastArg)) {
return lastArg;
}
}
return {};
}
function numArgs(args) {
var len = args.length;
if (len === 0) {
return 0;
}
var lastArg = args[len - 1];
if (isKeywordArgs(lastArg)) {
return len - 1;
} else {
return len;
}
}
// A SafeString object indicates that the string should not be
// autoescaped. This happens magically because autoescaping only
// occurs on primitive string objects.
function SafeString(val) {
if (typeof val !== 'string') {
return val;
}
this.val = val;
this.length = val.length;
}
SafeString.prototype = Object.create(String.prototype, {
length: {
writable: true,
configurable: true,
value: 0
}
});
SafeString.prototype.valueOf = function valueOf() {
return this.val;
};
SafeString.prototype.toString = function toString() {
return this.val;
};
function copySafeness(dest, target) {
if (dest instanceof SafeString) {
return new SafeString(target);
}
return target.toString();
}
function markSafe(val) {
var type = typeof val;
if (type === 'string') {
return new SafeString(val);
} else if (type !== 'function') {
return val;
} else {
return function wrapSafe(args) {
var ret = val.apply(this, arguments);
if (typeof ret === 'string') {
return new SafeString(ret);
}
return ret;
};
}
}
function suppressValue(val, autoescape) {
val = val !== undefined && val !== null ? val : '';
if (autoescape && !(val instanceof SafeString)) {
val = lib.escape(val.toString());
}
return val;
}
function ensureDefined(val, lineno, colno) {
if (val === null || val === undefined) {
throw new lib.TemplateError('attempted to output null or undefined value', lineno + 1, colno + 1);
}
return val;
}
function memberLookup(obj, val) {
if (obj === undefined || obj === null) {
return undefined;
}
if (typeof obj[val] === 'function') {
return function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return obj[val].apply(obj, args);
};
}
return obj[val];
}
function callWrap(obj, name, context, args) {
if (!obj) {
throw new Error('Unable to call `' + name + '`, which is undefined or falsey');
} else if (typeof obj !== 'function') {
throw new Error('Unable to call `' + name + '`, which is not a function');
}
return obj.apply(context, args);
}
function contextOrFrameLookup(context, frame, name) {
var val = frame.lookup(name);
return val !== undefined ? val : context.lookup(name);
}
function handleError(error, lineno, colno) {
if (error.lineno) {
return error;
} else {
return new lib.TemplateError(error, lineno, colno);
}
}
function asyncEach(arr, dimen, iter, cb) {
if (lib.isArray(arr)) {
var len = arr.length;
lib.asyncIter(arr, function iterCallback(item, i, next) {
switch (dimen) {
case 1:
iter(item, i, len, next);
break;
case 2:
iter(item[0], item[1], i, len, next);
break;
case 3:
iter(item[0], item[1], item[2], i, len, next);
break;
default:
item.push(i, len, next);
iter.apply(this, item);
}
}, cb);
} else {
lib.asyncFor(arr, function iterCallback(key, val, i, len, next) {
iter(key, val, i, len, next);
}, cb);
}
}
function asyncAll(arr, dimen, func, cb) {
var finished = 0;
var len;
var outputArr;
function done(i, output) {
finished++;
outputArr[i] = output;
if (finished === len) {
cb(null, outputArr.join(''));
}
}
if (lib.isArray(arr)) {
len = arr.length;
outputArr = new Array(len);
if (len === 0) {
cb(null, '');
} else {
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
switch (dimen) {
case 1:
func(item, i, len, done);
break;
case 2:
func(item[0], item[1], i, len, done);
break;
case 3:
func(item[0], item[1], item[2], i, len, done);
break;
default:
item.push(i, len, done);
func.apply(this, item);
}
}
}
} else {
var keys = lib.keys(arr || {});
len = keys.length;
outputArr = new Array(len);
if (len === 0) {
cb(null, '');
} else {
for (var _i = 0; _i < keys.length; _i++) {
var k = keys[_i];
func(k, arr[k], _i, len, done);
}
}
}
}
function fromIterator(arr) {
if (typeof arr !== 'object' || arr === null || lib.isArray(arr)) {
return arr;
} else if (supportsIterators && Symbol.iterator in arr) {
return arrayFrom(arr);
} else {
return arr;
}
}
module.exports = {
Frame: Frame,
makeMacro: makeMacro,
makeKeywordArgs: makeKeywordArgs,
numArgs: numArgs,
suppressValue: suppressValue,
ensureDefined: ensureDefined,
memberLookup: memberLookup,
contextOrFrameLookup: contextOrFrameLookup,
callWrap: callWrap,
handleError: handleError,
isArray: lib.isArray,
keys: lib.keys,
SafeString: SafeString,
copySafeness: copySafeness,
markSafe: markSafe,
asyncEach: asyncEach,
asyncAll: asyncAll,
inOperator: lib.inOperator,
fromIterator: fromIterator
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Loader = __webpack_require__(4);
var PrecompiledLoader = /*#__PURE__*/function (_Loader) {
_inheritsLoose(PrecompiledLoader, _Loader);
function PrecompiledLoader(compiledTemplates) {
var _this;
_this = _Loader.call(this) || this;
_this.precompiled = compiledTemplates || {};
return _this;
}
var _proto = PrecompiledLoader.prototype;
_proto.getSource = function getSource(name) {
if (this.precompiled[name]) {
return {
src: {
type: 'code',
obj: this.precompiled[name]
},
path: name
};
}
return null;
};
return PrecompiledLoader;
}(Loader);
module.exports = {
PrecompiledLoader: PrecompiledLoader
};
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var path = __webpack_require__(0);
var _require = __webpack_require__(5),
EmitterObj = _require.EmitterObj;
module.exports = /*#__PURE__*/function (_EmitterObj) {
_inheritsLoose(Loader, _EmitterObj);
function Loader() {
return _EmitterObj.apply(this, arguments) || this;
}
var _proto = Loader.prototype;
_proto.resolve = function resolve(from, to) {
return path.resolve(path.dirname(from), to);
};
_proto.isRelative = function isRelative(filename) {
return filename.indexOf('./') === 0 || filename.indexOf('../') === 0;
};
return Loader;
}(EmitterObj);
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// A simple class system, more documentation to come
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var EventEmitter = __webpack_require__(13);
var lib = __webpack_require__(1);
function parentWrap(parent, prop) {
if (typeof parent !== 'function' || typeof prop !== 'function') {
return prop;
}
return function wrap() {
// Save the current parent method
var tmp = this.parent;
// Set parent to the previous method, call, and restore
this.parent = parent;
var res = prop.apply(this, arguments);
this.parent = tmp;
return res;
};
}
function extendClass(cls, name, props) {
props = props || {};
lib.keys(props).forEach(function (k) {
props[k] = parentWrap(cls.prototype[k], props[k]);
});
var subclass = /*#__PURE__*/function (_cls) {
_inheritsLoose(subclass, _cls);
function subclass() {
return _cls.apply(this, arguments) || this;
}
_createClass(subclass, [{
key: "typename",
get: function get() {
return name;
}
}]);
return subclass;
}(cls);
lib._assign(subclass.prototype, props);
return subclass;
}
var Obj = /*#__PURE__*/function () {
function Obj() {
// Unfortunately necessary for backwards compatibility
this.init.apply(this, arguments);
}
var _proto = Obj.prototype;
_proto.init = function init() {};
Obj.extend = function extend(name, props) {
if (typeof name === 'object') {
props = name;
name = 'anonymous';
}
return extendClass(this, name, props);
};
_createClass(Obj, [{
key: "typename",
get: function get() {
return this.constructor.name;
}
}]);
return Obj;
}();
var EmitterObj = /*#__PURE__*/function (_EventEmitter) {
_inheritsLoose(EmitterObj, _EventEmitter);
function EmitterObj() {
var _this2;
var _this;
_this = _EventEmitter.call(this) || this;
// Unfortunately necessary for backwards compatibility
(_this2 = _this).init.apply(_this2, arguments);
return _this;
}
var _proto2 = EmitterObj.prototype;
_proto2.init = function init() {};
EmitterObj.extend = function extend(name, props) {
if (typeof name === 'object') {
props = name;
name = 'anonymous';
}
return extendClass(this, name, props);
};
_createClass(EmitterObj, [{
key: "typename",
get: function get() {
return this.constructor.name;
}
}]);
return EmitterObj;
}(EventEmitter);
module.exports = {
Obj: Obj,
EmitterObj: EmitterObj
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var lib = __webpack_require__(1);
var _require = __webpack_require__(7),
Environment = _require.Environment,
Template = _require.Template;
var Loader = __webpack_require__(4);
var loaders = __webpack_require__(3);
var precompile = __webpack_require__(0);
var compiler = __webpack_require__(0);
var parser = __webpack_require__(0);
var lexer = __webpack_require__(0);
var runtime = __webpack_require__(2);
var nodes = __webpack_require__(0);
var installJinjaCompat = __webpack_require__(17);
// A single instance of an environment, since this is so commonly used
var e;
function configure(templatesPath, opts) {
opts = opts || {};
if (lib.isObject(templatesPath)) {
opts = templatesPath;
templatesPath = null;
}
var TemplateLoader;
if (loaders.FileSystemLoader) {
TemplateLoader = new loaders.FileSystemLoader(templatesPath, {
watch: opts.watch,
noCache: opts.noCache
});
} else if (loaders.WebLoader) {
TemplateLoader = new loaders.WebLoader(templatesPath, {
useCache: opts.web && opts.web.useCache,
async: opts.web && opts.web.async
});
}
e = new Environment(TemplateLoader, opts);
if (opts && opts.express) {
e.express(opts.express);
}
return e;
}
module.exports = {
Environment: Environment,
Template: Template,
Loader: Loader,
FileSystemLoader: loaders.FileSystemLoader,
NodeResolveLoader: loaders.NodeResolveLoader,
PrecompiledLoader: loaders.PrecompiledLoader,
WebLoader: loaders.WebLoader,
compiler: compiler,
parser: parser,
lexer: lexer,
runtime: runtime,
lib: lib,
nodes: nodes,
installJinjaCompat: installJinjaCompat,
configure: configure,
reset: function reset() {
e = undefined;
},
compile: function compile(src, env, path, eagerCompile) {
if (!e) {
configure();
}
return new Template(src, env, path, eagerCompile);
},
render: function render(name, ctx, cb) {
if (!e) {
configure();
}
return e.render(name, ctx, cb);
},
renderString: function renderString(src, ctx, cb) {
if (!e) {
configure();
}
return e.renderString(src, ctx, cb);
},
precompile: precompile ? precompile.precompile : undefined,
precompileString: precompile ? precompile.precompileString : undefined
};
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var asap = __webpack_require__(8);
var _waterfall = __webpack_require__(11);
var lib = __webpack_require__(1);
var compiler = __webpack_require__(0);
var filters = __webpack_require__(12);
var _require = __webpack_require__(3),
FileSystemLoader = _require.FileSystemLoader,
WebLoader = _require.WebLoader,
PrecompiledLoader = _require.PrecompiledLoader;
var tests = __webpack_require__(14);
var globals = __webpack_require__(15);
var _require2 = __webpack_require__(5),
Obj = _require2.Obj,
EmitterObj = _require2.EmitterObj;
var globalRuntime = __webpack_require__(2);
var handleError = globalRuntime.handleError,
Frame = globalRuntime.Frame;
var expressApp = __webpack_require__(16);
// If the user is using the async API, *always* call it
// asynchronously even if the template was synchronous.
function callbackAsap(cb, err, res) {
asap(function () {
cb(err, res);
});
}
/**
* A no-op template, for use with {% include ignore missing %}
*/
var noopTmplSrc = {
type: 'code',
obj: {
root: function root(env, context, frame, runtime, cb) {
try {
cb(null, '');
} catch (e) {
cb(handleError(e, null, null));
}
}
}
};
var Environment = /*#__PURE__*/function (_EmitterObj) {
_inheritsLoose(Environment, _EmitterObj);
function Environment() {
return _EmitterObj.apply(this, arguments) || this;
}
var _proto = Environment.prototype;
_proto.init = function init(loaders, opts) {
var _this = this;
// The dev flag determines the trace that'll be shown on errors.
// If set to true, returns the full trace from the error point,
// otherwise will return trace starting from Template.render
// (the full trace from within nunjucks may confuse developers using
// the library)
// defaults to false
opts = this.opts = opts || {};
this.opts.dev = !!opts.dev;
// The autoescape flag sets global autoescaping. If true,
// every string variable will be escaped by default.
// If false, strings can be manually escaped using the `escape` filter.
// defaults to true
this.opts.autoescape = opts.autoescape != null ? opts.autoescape : true;
// If true, this will make the system throw errors if trying
// to output a null or undefined value
this.opts.throwOnUndefined = !!opts.throwOnUndefined;
this.opts.trimBlocks = !!opts.trimBlocks;
this.opts.lstripBlocks = !!opts.lstripBlocks;
this.loaders = [];
if (!loaders) {
// The filesystem loader is only available server-side
if (FileSystemLoader) {
this.loaders = [new FileSystemLoader('views')];
} else if (WebLoader) {
this.loaders = [new WebLoader('/views')];
}
} else {
this.loaders = lib.isArray(loaders) ? loaders : [loaders];
}
// It's easy to use precompiled templates: just include them
// before you configure nunjucks and this will automatically
// pick it up and use it
if (typeof window !== 'undefined' && window.nunjucksPrecompiled) {
this.loaders.unshift(new PrecompiledLoader(window.nunjucksPrecompiled));
}
this._initLoaders();
this.globals = globals();
this.filters = {};
this.tests = {};
this.asyncFilters = [];
this.extensions = {};
this.extensionsList = [];
lib._entries(filters).forEach(function (_ref) {
var name = _ref[0],
filter = _ref[1];
return _this.addFilter(name, filter);
});
lib._entries(tests).forEach(function (_ref2) {
var name = _ref2[0],
test = _ref2[1];
return _this.addTest(name, test);
});
};
_proto._initLoaders = function _initLoaders() {
var _this2 = this;
this.loaders.forEach(function (loader) {
// Caching and cache busting
loader.cache = {};
if (typeof loader.on === 'function') {
loader.on('update', function (name, fullname) {
loader.cache[name] = null;
_this2.emit('update', name, fullname, loader);
});
loader.on('load', function (name, source) {
_this2.emit('load', name, source, loader);
});
}
});
};
_proto.invalidateCache = function invalidateCache() {
this.loaders.forEach(function (loader) {
loader.cache = {};
});
};
_proto.addExtension = function addExtension(name, extension) {
extension.__name = name;
this.extensions[name] = extension;
this.extensionsList.push(extension);
return this;
};
_proto.removeExtension = function removeExtension(name) {
var extension = this.getExtension(name);
if (!extension) {
return;
}
this.extensionsList = lib.without(this.extensionsList, extension);
delete this.extensions[name];
};
_proto.getExtension = function getExtension(name) {
return this.extensions[name];
};
_proto.hasExtension = function hasExtension(name) {
return !!this.extensions[name];
};
_proto.addGlobal = function addGlobal(name, value) {
this.globals[name] = value;
return this;
};
_proto.getGlobal = function getGlobal(name) {
if (typeof this.globals[name] === 'undefined') {
throw new Error('global not found: ' + name);
}
return this.globals[name];
};
_proto.addFilter = function addFilter(name, func, async) {
var wrapped = func;
if (async) {
this.asyncFilters.push(name);
}
this.filters[name] = wrapped;
return this;
};
_proto.getFilter = function getFilter(name) {
if (!this.filters[name]) {
throw new Error('filter not found: ' + name);
}
return this.filters[name];
};
_proto.addTest = function addTest(name, func) {
this.tests[name] = func;
return this;
};
_proto.getTest = function getTest(name) {
if (!this.tests[name]) {
throw new Error('test not found: ' + name);
}
return this.tests[name];
};
_proto.resolveTemplate = function resolveTemplate(loader, parentName, filename) {
var isRelative = loader.isRelative && parentName ? loader.isRelative(filename) : false;
return isRelative && loader.resolve ? loader.resolve(parentName, filename) : filename;
};
_proto.getTemplate = function getTemplate(name, eagerCompile, parentName, ignoreMissing, cb) {
var _this3 = this;
var that = this;
var tmpl = null;
if (name && name.raw) {
// this fixes autoescape for templates referenced in symbols
name = name.raw;
}
if (lib.isFunction(parentName)) {
cb = parentName;
parentName = null;
eagerCompile = eagerCompile || false;
}
if (lib.isFunction(eagerCompile)) {
cb = eagerCompile;
eagerCompile = false;
}
if (name instanceof Template) {
tmpl = name;
} else if (typeof name !== 'string') {
throw new Error('template names must be a string: ' + name);
} else {
for (var i = 0; i < this.loaders.length; i++) {
var loader = this.loaders[i];
tmpl = loader.cache[this.resolveTemplate(loader, parentName, name)];
if (tmpl) {
break;
}
}
}
if (tmpl) {
if (eagerCompile) {
tmpl.compile();
}
if (cb) {
cb(null, tmpl);
return undefined;
} else {
return tmpl;
}
}
var syncResult;
var createTemplate = function createTemplate(err, info) {
if (!info && !err && !ignoreMissing) {
err = new Error('template not found: ' + name);
}
if (err) {
if (cb) {
cb(err);
return;
} else {
throw err;
}
}
var newTmpl;
if (!info) {
newTmpl = new Template(noopTmplSrc, _this3, '', eagerCompile);
} else {
newTmpl = new Template(info.src, _this3, info.path, eagerCompile);
if (!info.noCache) {
info.loader.cache[name] = newTmpl;
}
}
if (cb) {
cb(null, newTmpl);
} else {
syncResult = newTmpl;
}
};
lib.asyncIter(this.loaders, function (loader, i, next, done) {
function handle(err, src) {
if (err) {
done(err);
} else if (src) {
src.loader = loader;
done(null, src);
} else {
next();
}
}
// Resolve name relative to parentName
name = that.resolveTemplate(loader, parentName, name);
if (loader.async) {
loader.getSource(name, handle);
} else {
handle(null, loader.getSource(name));
}
}, createTemplate);
return syncResult;
};
_proto.express = function express(app) {
return expressApp(this, app);
};
_proto.render = function render(name, ctx, cb) {
if (lib.isFunction(ctx)) {
cb = ctx;
ctx = null;
}
// We support a synchronous API to make it easier to migrate
// existing code to async. This works because if you don't do
// anything async work, the whole thing is actually run
// synchronously.
var syncResult = null;
this.getTemplate(name, function (err, tmpl) {
if (err && cb) {
callbackAsap(cb, err);
} else if (err) {
throw err;
} else {
syncResult = tmpl.render(ctx, cb);
}
});
return syncResult;
};
_proto.renderString = function renderString(src, ctx, opts, cb) {
if (lib.isFunction(opts)) {
cb = opts;
opts = {};
}
opts = opts || {};
var tmpl = new Template(src, this, opts.path);
return tmpl.render(ctx, cb);
};
_proto.waterfall = function waterfall(tasks, callback, forceAsync) {
return _waterfall(tasks, callback, forceAsync);
};
return Environment;
}(EmitterObj);
var Context = /*#__PURE__*/function (_Obj) {
_inheritsLoose(Context, _Obj);
function Context() {
return _Obj.apply(this, arguments) || this;
}
var _proto2 = Context.prototype;
_proto2.init = function init(ctx, blocks, env) {
var _this4 = this;
// Has to be tied to an environment so we can tap into its globals.
this.env = env || new Environment();
// Make a duplicate of ctx
this.ctx = lib.extend({}, ctx);
this.blocks = {};
this.exported = [];
lib.keys(blocks).forEach(function (name) {
_this4.addBlock(name, blocks[name]);
});
};
_proto2.lookup = function lookup(name) {
// This is one of the most called functions, so optimize for
// the typical case where the name isn't in the globals
if (name in this.env.globals && !(name in this.ctx)) {
return this.env.globals[name];
} else {
return this.ctx[name];
}
};
_proto2.setVariable = function setVariable(name, val) {
this.ctx[name] = val;
};
_proto2.getVariables = function getVariables() {
return this.ctx;
};
_proto2.addBlock = function addBlock(name, block) {
this.blocks[name] = this.blocks[name] || [];
this.blocks[name].push(block);
return this;
};
_proto2.getBlock = function getBlock(name) {
if (!this.blocks[name]) {
throw new Error('unknown block "' + name + '"');
}
return this.blocks[name][0];
};
_proto2.getSuper = function getSuper(env, name, block, frame, runtime, cb) {
var idx = lib.indexOf(this.blocks[name] || [], block);
var blk = this.blocks[name][idx + 1];
var context = this;
if (idx === -1 || !blk) {
throw new Error('no super block available for "' + name + '"');
}
blk(env, context, frame, runtime, cb);
};
_proto2.addExport = function addExport(name) {
this.exported.push(name);
};
_proto2.getExported = function getExported() {
var _this5 = this;
var exported = {};
this.exported.forEach(function (name) {
exported[name] = _this5.ctx[name];
});
return exported;
};
return Context;
}(Obj);
var Template = /*#__PURE__*/function (_Obj2) {
_inheritsLoose(Template, _Obj2);
function Template() {
return _Obj2.apply(this, arguments) || this;
}
var _proto3 = Template.prototype;
_proto3.init = function init(src, env, path, eagerCompile) {
this.env = env || new Environment();
if (lib.isObject(src)) {
switch (src.type) {
case 'code':
this.tmplProps = src.obj;
break;
case 'string':
this.tmplStr = src.obj;
break;
default:
throw new Error("Unexpected template object type " + src.type + "; expected 'code', or 'string'");
}
} else if (lib.isString(src)) {
this.tmplStr = src;
} else {
throw new Error('src must be a string or an object describing the source');
}
this.path = path;
if (eagerCompile) {
try {
this._compile();
} catch (err) {
throw lib._prettifyError(this.path, this.env.opts.dev, err);
}
} else {
this.compiled = false;
}
};
_proto3.render = function render(ctx, parentFrame, cb) {
var _this6 = this;
if (typeof ctx === 'function') {
cb = ctx;
ctx = {};
} else if (typeof parentFrame === 'function') {
cb = parentFrame;
parentFrame = null;
}
// If there is a parent frame, we are being called from internal
// code of another template, and the internal system
// depends on the sync/async nature of the parent template
// to be inherited, so force an async callback
var forceAsync = !parentFrame;
// Catch compile errors for async rendering
try {
this.compile();
} catch (e) {
var err = lib._prettifyError(this.path, this.env.opts.dev, e);
if (cb) {
return callbackAsap(cb, err);
} else {
throw err;
}
}
var context = new Context(ctx || {}, this.blocks, this.env);
var frame = parentFrame ? parentFrame.push(true) : new Frame();
frame.topLevel = true;
var syncResult = null;
var didError = false;
this.rootRenderFunc(this.env, context, frame, globalRuntime, function (err, res) {
// TODO: this is actually a bug in the compiled template (because waterfall
// tasks are both not passing errors up the chain of callbacks AND are not
// causing a return from the top-most render function). But fixing that
// will require a more substantial change to the compiler.
if (didError && cb && typeof res !== 'undefined') {
// prevent multiple calls to cb
return;
}
if (err) {
err = lib._prettifyError(_this6.path, _this6.env.opts.dev, err);
didError = true;
}
if (cb) {
if (forceAsync) {
callbackAsap(cb, err, res);
} else {
cb(err, res);
}
} else {
if (err) {
throw err;
}
syncResult = res;
}
});
return syncResult;
};
_proto3.getExported = function getExported(ctx, parentFrame, cb) {
// eslint-disable-line consistent-return
if (typeof ctx === 'function') {
cb = ctx;
ctx = {};
}
if (typeof parentFrame === 'function') {
cb = parentFrame;
parentFrame = null;
}
// Catch compile errors for async rendering
try {
this.compile();
} catch (e) {
if (cb) {
return cb(e);
} else {
throw e;
}
}
var frame = parentFrame ? parentFrame.push() : new Frame();
frame.topLevel = true;
// Run the rootRenderFunc to populate the context with exported vars
var context = new Context(ctx || {}, this.blocks, this.env);
this.rootRenderFunc(this.env, context, frame, globalRuntime, function (err) {
if (err) {
cb(err, null);
} else {
cb(null, context.getExported());
}
});
};
_proto3.compile = function compile() {
if (!this.compiled) {
this._compile();
}
};
_proto3._compile = function _compile() {
var props;
if (this.tmplProps) {
props = this.tmplProps;
} else {
var source = compiler.compile(this.tmplStr, this.env.asyncFilters, this.env.extensionsList, this.path, this.env.opts);
var func = new Function(source); // eslint-disable-line no-new-func
props = func();
}
this.blocks = this._getBlocks(props);
this.rootRenderFunc = props.root;
this.compiled = true;
};
_proto3._getBlocks = function _getBlocks(props) {
var blocks = {};
lib.keys(props).forEach(function (k) {
if (k.slice(0, 2) === 'b_') {
blocks[k.slice(2)] = props[k];
}
});
return blocks;
};
return Template;
}(Obj);
module.exports = {
Environment: Environment,
Template: Template
};
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// rawAsap provides everything we need except exception management.
var rawAsap = __webpack_require__(9);
// RawTasks are recycled to reduce GC churn.
var freeTasks = [];
// We queue errors to ensure they are thrown in right order (FIFO).
// Array-as-queue is good enough here, since we are just dealing with exceptions.
var pendingErrors = [];
var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError);
function throwFirstError() {
if (pendingErrors.length) {
throw pendingErrors.shift();
}
}
/**
* Calls a task as soon as possible after returning, in its own event, with priority
* over other events like animation, reflow, and repaint. An error thrown from an
* event will not interrupt, nor even substantially slow down the processing of
* other events, but will be rather postponed to a lower priority event.
* @param {{call}} task A callable object, typically a function that takes no
* arguments.
*/
module.exports = asap;
function asap(task) {
var rawTask;
if (freeTasks.length) {
rawTask = freeTasks.pop();
} else {
rawTask = new RawTask();
}
rawTask.task = task;
rawAsap(rawTask);
}
// We wrap tasks with recyclable task objects. A task object implements
// `call`, just like a function.
function RawTask() {
this.task = null;
}
// The sole purpose of wrapping the task is to catch the exception and recycle
// the task object after its single use.
RawTask.prototype.call = function () {
try {
this.task.call();
} catch (error) {
if (asap.onerror) {
// This hook exists purely for testing purposes.
// Its name will be periodically randomized to break any code that
// depends on its existence.
asap.onerror(error);
} else {
// In a web browser, exceptions are not fatal. However, to avoid
// slowing down the queue of pending tasks, we rethrow the error in a
// lower priority turn.
pendingErrors.push(error);
requestErrorThrow();
}
} finally {
this.task = null;
freeTasks[freeTasks.length] = this;
}
};
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including IO, animation, reflow, and redraw
// events in browsers.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
module.exports = rawAsap;
function rawAsap(task) {
if (!queue.length) {
requestFlush();
flushing = true;
}
// Equivalent to push, but avoids a function call.
queue[queue.length] = task;
}
var queue = [];
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
var flushing = false;
// `requestFlush` is an implementation-specific method that attempts to kick
// off a `flush` event as quickly as possible. `flush` will attempt to exhaust
// the event queue before yielding to the browser's own event loop.
var requestFlush;
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
var index = 0;
// If a task schedules additional tasks recursively, the task queue can grow
// unbounded. To prevent memory exhaustion, the task queue will periodically
// truncate already-completed tasks.
var capacity = 1024;
// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
while (index < queue.length) {
var currentIndex = index;
// Advance the