1/*! Browser bundle of nunjucks 3.2.4 */ 2(function webpackUniversalModuleDefinition(root, factory) { 3 if(typeof exports === 'object' && typeof module === 'object') 4 module.exports = factory(); 5 else if(typeof define === 'function' && define.amd) 6 define([], factory); 7 else if(typeof exports === 'object') 8 exports["nunjucks"] = factory(); 9 else 10 root["nunjucks"] = factory(); 11})(typeof self !== 'undefined' ? self : this, function() { 12return /******/ (function(modules) { // webpackBootstrap 13/******/ // The module cache 14/******/ var installedModules = {}; 15/******/ 16/******/ // The require function 17/******/ function __webpack_require__(moduleId) { 18/******/ 19/******/ // Check if module is in cache 20/******/ if(installedModules[moduleId]) { 21/******/ return installedModules[moduleId].exports; 22/******/ } 23/******/ // Create a new module (and put it into the cache) 24/******/ var module = installedModules[moduleId] = { 25/******/ i: moduleId, 26/******/ l: false, 27/******/ exports: {} 28/******/ }; 29/******/ 30/******/ // Execute the module function 31/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 32/******/ 33/******/ // Flag the module as loaded 34/******/ module.l = true; 35/******/ 36/******/ // Return the exports of the module 37/******/ return module.exports; 38/******/ } 39/******/ 40/******/ 41/******/ // expose the modules object (__webpack_modules__) 42/******/ __webpack_require__.m = modules; 43/******/ 44/******/ // expose the module cache 45/******/ __webpack_require__.c = installedModules; 46/******/ 47/******/ // define getter function for harmony exports 48/******/ __webpack_require__.d = function(exports, name, getter) { 49/******/ if(!__webpack_require__.o(exports, name)) { 50/******/ Object.defineProperty(exports, name, { 51/******/ configurable: false, 52/******/ enumerable: true, 53/******/ get: getter 54/******/ }); 55/******/ } 56/******/ }; 57/******/ 58/******/ // getDefaultExport function for compatibility with non-harmony modules 59/******/ __webpack_require__.n = function(module) { 60/******/ var getter = module && module.__esModule ? 61/******/ function getDefault() { return module['default']; } : 62/******/ function getModuleExports() { return module; }; 63/******/ __webpack_require__.d(getter, 'a', getter); 64/******/ return getter; 65/******/ }; 66/******/ 67/******/ // Object.prototype.hasOwnProperty.call 68/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; 69/******/ 70/******/ // __webpack_public_path__ 71/******/ __webpack_require__.p = ""; 72/******/ 73/******/ // Load entry module and return exports 74/******/ return __webpack_require__(__webpack_require__.s = 11); 75/******/ }) 76/************************************************************************/ 77/******/ ([ 78/* 0 */ 79/***/ (function(module, exports, __webpack_require__) { 80 81"use strict"; 82 83 84var ArrayProto = Array.prototype; 85var ObjProto = Object.prototype; 86var escapeMap = { 87 '&': '&', 88 '"': '"', 89 '\'': ''', 90 '<': '<', 91 '>': '>', 92 '\\': '\' 93}; 94var escapeRegex = /[&"'<>\\]/g; 95var exports = module.exports = {}; 96function hasOwnProp(obj, k) { 97 return ObjProto.hasOwnProperty.call(obj, k); 98} 99exports.hasOwnProp = hasOwnProp; 100function lookupEscape(ch) { 101 return escapeMap[ch]; 102} 103function _prettifyError(path, withInternals, err) { 104 if (!err.Update) { 105 // not one of ours, cast it 106 err = new exports.TemplateError(err); 107 } 108 err.Update(path); 109 110 // Unless they marked the dev flag, show them a trace from here 111 if (!withInternals) { 112 var old = err; 113 err = new Error(old.message); 114 err.name = old.name; 115 } 116 return err; 117} 118exports._prettifyError = _prettifyError; 119function TemplateError(message, lineno, colno) { 120 var err; 121 var cause; 122 if (message instanceof Error) { 123 cause = message; 124 message = cause.name + ": " + cause.message; 125 } 126 if (Object.setPrototypeOf) { 127 err = new Error(message); 128 Object.setPrototypeOf(err, TemplateError.prototype); 129 } else { 130 err = this; 131 Object.defineProperty(err, 'message', { 132 enumerable: false, 133 writable: true, 134 value: message 135 }); 136 } 137 Object.defineProperty(err, 'name', { 138 value: 'Template render error' 139 }); 140 if (Error.captureStackTrace) { 141 Error.captureStackTrace(err, this.constructor); 142 } 143 var getStack; 144 if (cause) { 145 var stackDescriptor = Object.getOwnPropertyDescriptor(cause, 'stack'); 146 getStack = stackDescriptor && (stackDescriptor.get || function () { 147 return stackDescriptor.value; 148 }); 149 if (!getStack) { 150 getStack = function getStack() { 151 return cause.stack; 152 }; 153 } 154 } else { 155 var stack = new Error(message).stack; 156 getStack = function getStack() { 157 return stack; 158 }; 159 } 160 Object.defineProperty(err, 'stack', { 161 get: function get() { 162 return getStack.call(err); 163 } 164 }); 165 Object.defineProperty(err, 'cause', { 166 value: cause 167 }); 168 err.lineno = lineno; 169 err.colno = colno; 170 err.firstUpdate = true; 171 err.Update = function Update(path) { 172 var msg = '(' + (path || 'unknown path') + ')'; 173 174 // only show lineno + colno next to path of template 175 // where error occurred 176 if (this.firstUpdate) { 177 if (this.lineno && this.colno) { 178 msg += " [Line " + this.lineno + ", Column " + this.colno + "]"; 179 } else if (this.lineno) { 180 msg += " [Line " + this.lineno + "]"; 181 } 182 } 183 msg += '\n '; 184 if (this.firstUpdate) { 185 msg += ' '; 186 } 187 this.message = msg + (this.message || ''); 188 this.firstUpdate = false; 189 return this; 190 }; 191 return err; 192} 193if (Object.setPrototypeOf) { 194 Object.setPrototypeOf(TemplateError.prototype, Error.prototype); 195} else { 196 TemplateError.prototype = Object.create(Error.prototype, { 197 constructor: { 198 value: TemplateError 199 } 200 }); 201} 202exports.TemplateError = TemplateError; 203function escape(val) { 204 return val.replace(escapeRegex, lookupEscape); 205} 206exports.escape = escape; 207function isFunction(obj) { 208 return ObjProto.toString.call(obj) === '[object Function]'; 209} 210exports.isFunction = isFunction; 211function isArray(obj) { 212 return ObjProto.toString.call(obj) === '[object Array]'; 213} 214exports.isArray = isArray; 215function isString(obj) { 216 return ObjProto.toString.call(obj) === '[object String]'; 217} 218exports.isString = isString; 219function isObject(obj) { 220 return ObjProto.toString.call(obj) === '[object Object]'; 221} 222exports.isObject = isObject; 223 224/** 225 * @param {string|number} attr 226 * @returns {(string|number)[]} 227 * @private 228 */ 229function _prepareAttributeParts(attr) { 230 if (!attr) { 231 return []; 232 } 233 if (typeof attr === 'string') { 234 return attr.split('.'); 235 } 236 return [attr]; 237} 238 239/** 240 * @param {string} attribute Attribute value. Dots allowed. 241 * @returns {function(Object): *} 242 */ 243function getAttrGetter(attribute) { 244 var parts = _prepareAttributeParts(attribute); 245 return function attrGetter(item) { 246 var _item = item; 247 for (var i = 0; i < parts.length; i++) { 248 var part = parts[i]; 249 250 // If item is not an object, and we still got parts to handle, it means 251 // that something goes wrong. Just roll out to undefined in that case. 252 if (hasOwnProp(_item, part)) { 253 _item = _item[part]; 254 } else { 255 return undefined; 256 } 257 } 258 return _item; 259 }; 260} 261exports.getAttrGetter = getAttrGetter; 262function groupBy(obj, val, throwOnUndefined) { 263 var result = {}; 264 var iterator = isFunction(val) ? val : getAttrGetter(val); 265 for (var i = 0; i < obj.length; i++) { 266 var value = obj[i]; 267 var key = iterator(value, i); 268 if (key === undefined && throwOnUndefined === true) { 269 throw new TypeError("groupby: attribute \"" + val + "\" resolved to undefined"); 270 } 271 (result[key] || (result[key] = [])).push(value); 272 } 273 return result; 274} 275exports.groupBy = groupBy; 276function toArray(obj) { 277 return Array.prototype.slice.call(obj); 278} 279exports.toArray = toArray; 280function without(array) { 281 var result = []; 282 if (!array) { 283 return result; 284 } 285 var length = array.length; 286 var contains = toArray(arguments).slice(1); 287 var index = -1; 288 while (++index < length) { 289 if (indexOf(contains, array[index]) === -1) { 290 result.push(array[index]); 291 } 292 } 293 return result; 294} 295exports.without = without; 296function repeat(char_, n) { 297 var str = ''; 298 for (var i = 0; i < n; i++) { 299 str += char_; 300 } 301 return str; 302} 303exports.repeat = repeat; 304function each(obj, func, context) { 305 if (obj == null) { 306 return; 307 } 308 if (ArrayProto.forEach && obj.forEach === ArrayProto.forEach) { 309 obj.forEach(func, context); 310 } else if (obj.length === +obj.length) { 311 for (var i = 0, l = obj.length; i < l; i++) { 312 func.call(context, obj[i], i, obj); 313 } 314 } 315} 316exports.each = each; 317function map(obj, func) { 318 var results = []; 319 if (obj == null) { 320 return results; 321 } 322 if (ArrayProto.map && obj.map === ArrayProto.map) { 323 return obj.map(func); 324 } 325 for (var i = 0; i < obj.length; i++) { 326 results[results.length] = func(obj[i], i); 327 } 328 if (obj.length === +obj.length) { 329 results.length = obj.length; 330 } 331 return results; 332} 333exports.map = map; 334function asyncIter(arr, iter, cb) { 335 var i = -1; 336 function next() { 337 i++; 338 if (i < arr.length) { 339 iter(arr[i], i, next, cb); 340 } else { 341 cb(); 342 } 343 } 344 next(); 345} 346exports.asyncIter = asyncIter; 347function asyncFor(obj, iter, cb) { 348 var keys = keys_(obj || {}); 349 var len = keys.length; 350 var i = -1; 351 function next() { 352 i++; 353 var k = keys[i]; 354 if (i < len) { 355 iter(k, obj[k], i, len, next); 356 } else { 357 cb(); 358 } 359 } 360 next(); 361} 362exports.asyncFor = asyncFor; 363function indexOf(arr, searchElement, fromIndex) { 364 return Array.prototype.indexOf.call(arr || [], searchElement, fromIndex); 365} 366exports.indexOf = indexOf; 367function keys_(obj) { 368 /* eslint-disable no-restricted-syntax */ 369 var arr = []; 370 for (var k in obj) { 371 if (hasOwnProp(obj, k)) { 372 arr.push(k); 373 } 374 } 375 return arr; 376} 377exports.keys = keys_; 378function _entries(obj) { 379 return keys_(obj).map(function (k) { 380 return [k, obj[k]]; 381 }); 382} 383exports._entries = _entries; 384function _values(obj) { 385 return keys_(obj).map(function (k) { 386 return obj[k]; 387 }); 388} 389exports._values = _values; 390function extend(obj1, obj2) { 391 obj1 = obj1 || {}; 392 keys_(obj2).forEach(function (k) { 393 obj1[k] = obj2[k]; 394 }); 395 return obj1; 396} 397exports._assign = exports.extend = extend; 398function inOperator(key, val) { 399 if (isArray(val) || isString(val)) { 400 return val.indexOf(key) !== -1; 401 } else if (isObject(val)) { 402 return key in val; 403 } 404 throw new Error('Cannot use "in" operator to search for "' + key + '" in unexpected types.'); 405} 406exports.inOperator = inOperator; 407 408/***/ }), 409/* 1 */ 410/***/ (function(module, exports, __webpack_require__) { 411 412"use strict"; 413 414 415// A simple class system, more documentation to come 416function _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); } } 417function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } 418function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } 419function _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); } 420function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } 421function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 422var EventEmitter = __webpack_require__(16); 423var lib = __webpack_require__(0); 424function parentWrap(parent, prop) { 425 if (typeof parent !== 'function' || typeof prop !== 'function') { 426 return prop; 427 } 428 return function wrap() { 429 // Save the current parent method 430 var tmp = this.parent; 431 432 // Set parent to the previous method, call, and restore 433 this.parent = parent; 434 var res = prop.apply(this, arguments); 435 this.parent = tmp; 436 return res; 437 }; 438} 439function extendClass(cls, name, props) { 440 props = props || {}; 441 lib.keys(props).forEach(function (k) { 442 props[k] = parentWrap(cls.prototype[k], props[k]); 443 }); 444 var subclass = /*#__PURE__*/function (_cls) { 445 _inheritsLoose(subclass, _cls); 446 function subclass() { 447 return _cls.apply(this, arguments) || this; 448 } 449 _createClass(subclass, [{ 450 key: "typename", 451 get: function get() { 452 return name; 453 } 454 }]); 455 return subclass; 456 }(cls); 457 lib._assign(subclass.prototype, props); 458 return subclass; 459} 460var Obj = /*#__PURE__*/function () { 461 function Obj() { 462 // Unfortunately necessary for backwards compatibility 463 this.init.apply(this, arguments); 464 } 465 var _proto = Obj.prototype; 466 _proto.init = function init() {}; 467 Obj.extend = function extend(name, props) { 468 if (typeof name === 'object') { 469 props = name; 470 name = 'anonymous'; 471 } 472 return extendClass(this, name, props); 473 }; 474 _createClass(Obj, [{ 475 key: "typename", 476 get: function get() { 477 return this.constructor.name; 478 } 479 }]); 480 return Obj; 481}(); 482var EmitterObj = /*#__PURE__*/function (_EventEmitter) { 483 _inheritsLoose(EmitterObj, _EventEmitter); 484 function EmitterObj() { 485 var _this2; 486 var _this; 487 _this = _EventEmitter.call(this) || this; 488 // Unfortunately necessary for backwards compatibility 489 (_this2 = _this).init.apply(_this2, arguments); 490 return _this; 491 } 492 var _proto2 = EmitterObj.prototype; 493 _proto2.init = function init() {}; 494 EmitterObj.extend = function extend(name, props) { 495 if (typeof name === 'object') { 496 props = name; 497 name = 'anonymous'; 498 } 499 return extendClass(this, name, props); 500 }; 501 _createClass(EmitterObj, [{ 502 key: "typename", 503 get: function get() { 504 return this.constructor.name; 505 } 506 }]); 507 return EmitterObj; 508}(EventEmitter); 509module.exports = { 510 Obj: Obj, 511 EmitterObj: EmitterObj 512}; 513 514/***/ }), 515/* 2 */ 516/***/ (function(module, exports, __webpack_require__) { 517 518"use strict"; 519 520 521var lib = __webpack_require__(0); 522var arrayFrom = Array.from; 523var supportsIterators = typeof Symbol === 'function' && Symbol.iterator && typeof arrayFrom === 'function'; 524 525// Frames keep track of scoping both at compile-time and run-time so 526// we know how to access variables. Block tags can introduce special 527// variables, for example. 528var Frame = /*#__PURE__*/function () { 529 function Frame(parent, isolateWrites) { 530 this.variables = Object.create(null); 531 this.parent = parent; 532 this.topLevel = false; 533 // if this is true, writes (set) should never propagate upwards past 534 // this frame to its parent (though reads may). 535 this.isolateWrites = isolateWrites; 536 } 537 var _proto = Frame.prototype; 538 _proto.set = function set(name, val, resolveUp) { 539 // Allow variables with dots by automatically creating the 540 // nested structure 541 var parts = name.split('.'); 542 var obj = this.variables; 543 var frame = this; 544 if (resolveUp) { 545 if (frame = this.resolve(parts[0], true)) { 546 frame.set(name, val); 547 return; 548 } 549 } 550 for (var i = 0; i < parts.length - 1; i++) { 551 var id = parts[i]; 552 if (!obj[id]) { 553 obj[id] = {}; 554 } 555 obj = obj[id]; 556 } 557 obj[parts[parts.length - 1]] = val; 558 }; 559 _proto.get = function get(name) { 560 var val = this.variables[name]; 561 if (val !== undefined) { 562 return val; 563 } 564 return null; 565 }; 566 _proto.lookup = function lookup(name) { 567 var p = this.parent; 568 var val = this.variables[name]; 569 if (val !== undefined) { 570 return val; 571 } 572 return p && p.lookup(name); 573 }; 574 _proto.resolve = function resolve(name, forWrite) { 575 var p = forWrite && this.isolateWrites ? undefined : this.parent; 576 var val = this.variables[name]; 577 if (val !== undefined) { 578 return this; 579 } 580 return p && p.resolve(name); 581 }; 582 _proto.push = function push(isolateWrites) { 583 return new Frame(this, isolateWrites); 584 }; 585 _proto.pop = function pop() { 586 return this.parent; 587 }; 588 return Frame; 589}(); 590function makeMacro(argNames, kwargNames, func) { 591 return function macro() { 592 for (var _len = arguments.length, macroArgs = new Array(_len), _key = 0; _key < _len; _key++) { 593 macroArgs[_key] = arguments[_key]; 594 } 595 var argCount = numArgs(macroArgs); 596 var args; 597 var kwargs = getKeywordArgs(macroArgs); 598 if (argCount > argNames.length) { 599 args = macroArgs.slice(0, argNames.length); 600 601 // Positional arguments that should be passed in as 602 // keyword arguments (essentially default values) 603 macroArgs.slice(args.length, argCount).forEach(function (val, i) { 604 if (i < kwargNames.length) { 605 kwargs[kwargNames[i]] = val; 606 } 607 }); 608 args.push(kwargs); 609 } else if (argCount < argNames.length) { 610 args = macroArgs.slice(0, argCount); 611 for (var i = argCount; i < argNames.length; i++) { 612 var arg = argNames[i]; 613 614 // Keyword arguments that should be passed as 615 // positional arguments, i.e. the caller explicitly 616 // used the name of a positional arg 617 args.push(kwargs[arg]); 618 delete kwargs[arg]; 619 } 620 args.push(kwargs); 621 } else { 622 args = macroArgs; 623 } 624 return func.apply(this, args); 625 }; 626} 627function makeKeywordArgs(obj) { 628 obj.__keywords = true; 629 return obj; 630} 631function isKeywordArgs(obj) { 632 return obj && Object.prototype.hasOwnProperty.call(obj, '__keywords'); 633} 634function getKeywordArgs(args) { 635 var len = args.length; 636 if (len) { 637 var lastArg = args[len - 1]; 638 if (isKeywordArgs(lastArg)) { 639 return lastArg; 640 } 641 } 642 return {}; 643} 644function numArgs(args) { 645 var len = args.length; 646 if (len === 0) { 647 return 0; 648 } 649 var lastArg = args[len - 1]; 650 if (isKeywordArgs(lastArg)) { 651 return len - 1; 652 } else { 653 return len; 654 } 655} 656 657// A SafeString object indicates that the string should not be 658// autoescaped. This happens magically because autoescaping only 659// occurs on primitive string objects. 660function SafeString(val) { 661 if (typeof val !== 'string') { 662 return val; 663 } 664 this.val = val; 665 this.length = val.length; 666} 667SafeString.prototype = Object.create(String.prototype, { 668 length: { 669 writable: true, 670 configurable: true, 671 value: 0 672 } 673}); 674SafeString.prototype.valueOf = function valueOf() { 675 return this.val; 676}; 677SafeString.prototype.toString = function toString() { 678 return this.val; 679}; 680function copySafeness(dest, target) { 681 if (dest instanceof SafeString) { 682 return new SafeString(target); 683 } 684 return target.toString(); 685} 686function markSafe(val) { 687 var type = typeof val; 688 if (type === 'string') { 689 return new SafeString(val); 690 } else if (type !== 'function') { 691 return val; 692 } else { 693 return function wrapSafe(args) { 694 var ret = val.apply(this, arguments); 695 if (typeof ret === 'string') { 696 return new SafeString(ret); 697 } 698 return ret; 699 }; 700 } 701} 702function suppressValue(val, autoescape) { 703 val = val !== undefined && val !== null ? val : ''; 704 if (autoescape && !(val instanceof SafeString)) { 705 val = lib.escape(val.toString()); 706 } 707 return val; 708} 709function ensureDefined(val, lineno, colno) { 710 if (val === null || val === undefined) { 711 throw new lib.TemplateError('attempted to output null or undefined value', lineno + 1, colno + 1); 712 } 713 return val; 714} 715function memberLookup(obj, val) { 716 if (obj === undefined || obj === null) { 717 return undefined; 718 } 719 if (typeof obj[val] === 'function') { 720 return function () { 721 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { 722 args[_key2] = arguments[_key2]; 723 } 724 return obj[val].apply(obj, args); 725 }; 726 } 727 return obj[val]; 728} 729function callWrap(obj, name, context, args) { 730 if (!obj) { 731 throw new Error('Unable to call `' + name + '`, which is undefined or falsey'); 732 } else if (typeof obj !== 'function') { 733 throw new Error('Unable to call `' + name + '`, which is not a function'); 734 } 735 return obj.apply(context, args); 736} 737function contextOrFrameLookup(context, frame, name) { 738 var val = frame.lookup(name); 739 return val !== undefined ? val : context.lookup(name); 740} 741function handleError(error, lineno, colno) { 742 if (error.lineno) { 743 return error; 744 } else { 745 return new lib.TemplateError(error, lineno, colno); 746 } 747} 748function asyncEach(arr, dimen, iter, cb) { 749 if (lib.isArray(arr)) { 750 var len = arr.length; 751 lib.asyncIter(arr, function iterCallback(item, i, next) { 752 switch (dimen) { 753 case 1: 754 iter(item, i, len, next); 755 break; 756 case 2: 757 iter(item[0], item[1], i, len, next); 758 break; 759 case 3: 760 iter(item[0], item[1], item[2], i, len, next); 761 break; 762 default: 763 item.push(i, len, next); 764 iter.apply(this, item); 765 } 766 }, cb); 767 } else { 768 lib.asyncFor(arr, function iterCallback(key, val, i, len, next) { 769 iter(key, val, i, len, next); 770 }, cb); 771 } 772} 773function asyncAll(arr, dimen, func, cb) { 774 var finished = 0; 775 var len; 776 var outputArr; 777 function done(i, output) { 778 finished++; 779 outputArr[i] = output; 780 if (finished === len) { 781 cb(null, outputArr.join('')); 782 } 783 } 784 if (lib.isArray(arr)) { 785 len = arr.length; 786 outputArr = new Array(len); 787 if (len === 0) { 788 cb(null, ''); 789 } else { 790 for (var i = 0; i < arr.length; i++) { 791 var item = arr[i]; 792 switch (dimen) { 793 case 1: 794 func(item, i, len, done); 795 break; 796 case 2: 797 func(item[0], item[1], i, len, done); 798 break; 799 case 3: 800 func(item[0], item[1], item[2], i, len, done); 801 break; 802 default: 803 item.push(i, len, done); 804 func.apply(this, item); 805 } 806 } 807 } 808 } else { 809 var keys = lib.keys(arr || {}); 810 len = keys.length; 811 outputArr = new Array(len); 812 if (len === 0) { 813 cb(null, ''); 814 } else { 815 for (var _i = 0; _i < keys.length; _i++) { 816 var k = keys[_i]; 817 func(k, arr[k], _i, len, done); 818 } 819 } 820 } 821} 822function fromIterator(arr) { 823 if (typeof arr !== 'object' || arr === null || lib.isArray(arr)) { 824 return arr; 825 } else if (supportsIterators && Symbol.iterator in arr) { 826 return arrayFrom(arr); 827 } else { 828 return arr; 829 } 830} 831module.exports = { 832 Frame: Frame, 833 makeMacro: makeMacro, 834 makeKeywordArgs: makeKeywordArgs, 835 numArgs: numArgs, 836 suppressValue: suppressValue, 837 ensureDefined: ensureDefined, 838 memberLookup: memberLookup, 839 contextOrFrameLookup: contextOrFrameLookup, 840 callWrap: callWrap, 841 handleError: handleError, 842 isArray: lib.isArray, 843 keys: lib.keys, 844 SafeString: SafeString, 845 copySafeness: copySafeness, 846 markSafe: markSafe, 847 asyncEach: asyncEach, 848 asyncAll: asyncAll, 849 inOperator: lib.inOperator, 850 fromIterator: fromIterator 851}; 852 853/***/ }), 854/* 3 */ 855/***/ (function(module, exports, __webpack_require__) { 856 857"use strict"; 858 859 860function _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); } } 861function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } 862function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } 863function _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); } 864function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } 865function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 866var _require = __webpack_require__(1), 867 Obj = _require.Obj; 868function traverseAndCheck(obj, type, results) { 869 if (obj instanceof type) { 870 results.push(obj); 871 } 872 if (obj instanceof Node) { 873 obj.findAll(type, results); 874 } 875} 876var Node = /*#__PURE__*/function (_Obj) { 877 _inheritsLoose(Node, _Obj); 878 function Node() { 879 return _Obj.apply(this, arguments) || this; 880 } 881 var _proto = Node.prototype; 882 _proto.init = function init(lineno, colno) { 883 var _arguments = arguments, 884 _this = this; 885 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { 886 args[_key - 2] = arguments[_key]; 887 } 888 this.lineno = lineno; 889 this.colno = colno; 890 this.fields.forEach(function (field, i) { 891 // The first two args are line/col numbers, so offset by 2 892 var val = _arguments[i + 2]; 893 894 // Fields should never be undefined, but null. It makes 895 // testing easier to normalize values. 896 if (val === undefined) { 897 val = null; 898 } 899 _this[field] = val; 900 }); 901 }; 902 _proto.findAll = function findAll(type, results) { 903 var _this2 = this; 904 results = results || []; 905 if (this instanceof NodeList) { 906 this.children.forEach(function (child) { 907 return traverseAndCheck(child, type, results); 908 }); 909 } else { 910 this.fields.forEach(function (field) { 911 return traverseAndCheck(_this2[field], type, results); 912 }); 913 } 914 return results; 915 }; 916 _proto.iterFields = function iterFields(func) { 917 var _this3 = this; 918 this.fields.forEach(function (field) { 919 func(_this3[field], field); 920 }); 921 }; 922 return Node; 923}(Obj); // Abstract nodes 924var Value = /*#__PURE__*/function (_Node) { 925 _inheritsLoose(Value, _Node); 926 function Value() { 927 return _Node.apply(this, arguments) || this; 928 } 929 _createClass(Value, [{ 930 key: "typename", 931 get: function get() { 932 return 'Value'; 933 } 934 }, { 935 key: "fields", 936 get: function get() { 937 return ['value']; 938 } 939 }]); 940 return Value; 941}(Node); // Concrete nodes 942var NodeList = /*#__PURE__*/function (_Node2) { 943 _inheritsLoose(NodeList, _Node2); 944 function NodeList() { 945 return _Node2.apply(this, arguments) || this; 946 } 947 var _proto2 = NodeList.prototype; 948 _proto2.init = function init(lineno, colno, nodes) { 949 _Node2.prototype.init.call(this, lineno, colno, nodes || []); 950 }; 951 _proto2.addChild = function addChild(node) { 952 this.children.push(node); 953 }; 954 _createClass(NodeList, [{ 955 key: "typename", 956 get: function get() { 957 return 'NodeList'; 958 } 959 }, { 960 key: "fields", 961 get: function get() { 962 return ['children']; 963 } 964 }]); 965 return NodeList; 966}(Node); 967var Root = NodeList.extend('Root'); 968var Literal = Value.extend('Literal'); 969var _Symbol = Value.extend('Symbol'); 970var Group = NodeList.extend('Group'); 971var ArrayNode = NodeList.extend('Array'); 972var Pair = Node.extend('Pair', { 973 fields: ['key', 'value'] 974}); 975var Dict = NodeList.extend('Dict'); 976var LookupVal = Node.extend('LookupVal', { 977 fields: ['target', 'val'] 978}); 979var If = Node.extend('If', { 980 fields: ['cond', 'body', 'else_'] 981}); 982var IfAsync = If.extend('IfAsync'); 983var InlineIf = Node.extend('InlineIf', { 984 fields: ['cond', 'body', 'else_'] 985}); 986var For = Node.extend('For', { 987 fields: ['arr', 'name', 'body', 'else_'] 988}); 989var AsyncEach = For.extend('AsyncEach'); 990var AsyncAll = For.extend('AsyncAll'); 991var Macro = Node.extend('Macro', { 992 fields: ['name', 'args', 'body'] 993}); 994var Caller = Macro.extend('Caller'); 995var Import = Node.extend('Import', { 996 fields: ['template', 'target', 'withContext'] 997}); 998var FromImport = /*#__PURE__*/function (_Node3) { 999 _inheritsLoose(FromImport, _Node3); 1000 function FromImport() { 1001 return _Node3.apply(this, arguments) || this; 1002 } 1003 var _proto3 = FromImport.prototype; 1004 _proto3.init = function init(lineno, colno, template, names, withContext) { 1005 _Node3.prototype.init.call(this, lineno, colno, template, names || new NodeList(), withContext); 1006 }; 1007 _createClass(FromImport, [{ 1008 key: "typename", 1009 get: function get() { 1010 return 'FromImport'; 1011 } 1012 }, { 1013 key: "fields", 1014 get: function get() { 1015 return ['template', 'names', 'withContext']; 1016 } 1017 }]); 1018 return FromImport; 1019}(Node); 1020var FunCall = Node.extend('FunCall', { 1021 fields: ['name', 'args'] 1022}); 1023var Filter = FunCall.extend('Filter'); 1024var FilterAsync = Filter.extend('FilterAsync', { 1025 fields: ['name', 'args', 'symbol'] 1026}); 1027var KeywordArgs = Dict.extend('KeywordArgs'); 1028var Block = Node.extend('Block', { 1029 fields: ['name', 'body'] 1030}); 1031var Super = Node.extend('Super', { 1032 fields: ['blockName', 'symbol'] 1033}); 1034var TemplateRef = Node.extend('TemplateRef', { 1035 fields: ['template'] 1036}); 1037var Extends = TemplateRef.extend('Extends'); 1038var Include = Node.extend('Include', { 1039 fields: ['template', 'ignoreMissing'] 1040}); 1041var Set = Node.extend('Set', { 1042 fields: ['targets', 'value'] 1043}); 1044var Switch = Node.extend('Switch', { 1045 fields: ['expr', 'cases', 'default'] 1046}); 1047var Case = Node.extend('Case', { 1048 fields: ['cond', 'body'] 1049}); 1050var Output = NodeList.extend('Output'); 1051var Capture = Node.extend('Capture', { 1052 fields: ['body'] 1053}); 1054var TemplateData = Literal.extend('TemplateData'); 1055var UnaryOp = Node.extend('UnaryOp', { 1056 fields: ['target'] 1057}); 1058var BinOp = Node.extend('BinOp', { 1059 fields: ['left', 'right'] 1060}); 1061var In = BinOp.extend('In'); 1062var Is = BinOp.extend('Is'); 1063var Or = BinOp.extend('Or'); 1064var And = BinOp.extend('And'); 1065var Not = UnaryOp.extend('Not'); 1066var Add = BinOp.extend('Add'); 1067var Concat = BinOp.extend('Concat'); 1068var Sub = BinOp.extend('Sub'); 1069var Mul = BinOp.extend('Mul'); 1070var Div = BinOp.extend('Div'); 1071var FloorDiv = BinOp.extend('FloorDiv'); 1072var Mod = BinOp.extend('Mod'); 1073var Pow = BinOp.extend('Pow'); 1074var Neg = UnaryOp.extend('Neg'); 1075var Pos = UnaryOp.extend('Pos'); 1076var Compare = Node.extend('Compare', { 1077 fields: ['expr', 'ops'] 1078}); 1079var CompareOperand = Node.extend('CompareOperand', { 1080 fields: ['expr', 'type'] 1081}); 1082var CallExtension = Node.extend('CallExtension', { 1083 init: function init(ext, prop, args, contentArgs) { 1084 this.parent(); 1085 this.extName = ext.__name || ext; 1086 this.prop = prop; 1087 this.args = args || new NodeList(); 1088 this.contentArgs = contentArgs || []; 1089 this.autoescape = ext.autoescape; 1090 }, 1091 fields: ['extName', 'prop', 'args', 'contentArgs'] 1092}); 1093var CallExtensionAsync = CallExtension.extend('CallExtensionAsync'); 1094 1095// This is hacky, but this is just a debugging function anyway 1096function print(str, indent, inline) { 1097 var lines = str.split('\n'); 1098 lines.forEach(function (line, i) { 1099 if (line && (inline && i > 0 || !inline)) { 1100 process.stdout.write(' '.repeat(indent)); 1101 } 1102 var nl = i === lines.length - 1 ? '' : '\n'; 1103 process.stdout.write("" + line + nl); 1104 }); 1105} 1106 1107// Print the AST in a nicely formatted tree format for debuggin 1108function printNodes(node, indent) { 1109 indent = indent || 0; 1110 print(node.typename + ': ', indent); 1111 if (node instanceof NodeList) { 1112 print('\n'); 1113 node.children.forEach(function (n) { 1114 printNodes(n, indent + 2); 1115 }); 1116 } else if (node instanceof CallExtension) { 1117 print(node.extName + "." + node.prop + "\n"); 1118 if (node.args) { 1119 printNodes(node.args, indent + 2); 1120 } 1121 if (node.contentArgs) { 1122 node.contentArgs.forEach(function (n) { 1123 printNodes(n, indent + 2); 1124 }); 1125 } 1126 } else { 1127 var nodes = []; 1128 var props = null; 1129 node.iterFields(function (val, fieldName) { 1130 if (val instanceof Node) { 1131 nodes.push([fieldName, val]); 1132 } else { 1133 props = props || {}; 1134 props[fieldName] = val; 1135 } 1136 }); 1137 if (props) { 1138 print(JSON.stringify(props, null, 2) + '\n', null, true); 1139 } else { 1140 print('\n'); 1141 } 1142 nodes.forEach(function (_ref) { 1143 var fieldName = _ref[0], 1144 n = _ref[1]; 1145 print("[" + fieldName + "] =>", indent + 2); 1146 printNodes(n, indent + 4); 1147 }); 1148 } 1149} 1150module.exports = { 1151 Node: Node, 1152 Root: Root, 1153 NodeList: NodeList, 1154 Value: Value, 1155 Literal: Literal, 1156 Symbol: _Symbol, 1157 Group: Group, 1158 Array: ArrayNode, 1159 Pair: Pair, 1160 Dict: Dict, 1161 Output: Output, 1162 Capture: Capture, 1163 TemplateData: TemplateData, 1164 If: If, 1165 IfAsync: IfAsync, 1166 InlineIf: InlineIf, 1167 For: For, 1168 AsyncEach: AsyncEach, 1169 AsyncAll: AsyncAll, 1170 Macro: Macro, 1171 Caller: Caller, 1172 Import: Import, 1173 FromImport: FromImport, 1174 FunCall: FunCall, 1175 Filter: Filter, 1176 FilterAsync: FilterAsync, 1177 KeywordArgs: KeywordArgs, 1178 Block: Block, 1179 Super: Super, 1180 Extends: Extends, 1181 Include: Include, 1182 Set: Set, 1183 Switch: Switch, 1184 Case: Case, 1185 LookupVal: LookupVal, 1186 BinOp: BinOp, 1187 In: In, 1188 Is: Is, 1189 Or: Or, 1190 And: And, 1191 Not: Not, 1192 Add: Add, 1193 Concat: Concat, 1194 Sub: Sub, 1195 Mul: Mul, 1196 Div: Div, 1197 FloorDiv: FloorDiv, 1198 Mod: Mod, 1199 Pow: Pow, 1200 Neg: Neg, 1201 Pos: Pos, 1202 Compare: Compare, 1203 CompareOperand: CompareOperand, 1204 CallExtension: CallExtension, 1205 CallExtensionAsync: CallExtensionAsync, 1206 printNodes: printNodes 1207}; 1208 1209/***/ }), 1210/* 4 */ 1211/***/ (function(module, exports) { 1212 1213 1214 1215/***/ }), 1216/* 5 */ 1217/***/ (function(module, exports, __webpack_require__) { 1218 1219"use strict"; 1220 1221 1222function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } 1223function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 1224var parser = __webpack_require__(8); 1225var transformer = __webpack_require__(17); 1226var nodes = __webpack_require__(3); 1227var _require = __webpack_require__(0), 1228 TemplateError = _require.TemplateError; 1229var _require2 = __webpack_require__(2), 1230 Frame = _require2.Frame; 1231var _require3 = __webpack_require__(1), 1232 Obj = _require3.Obj; 1233 1234// These are all the same for now, but shouldn't be passed straight 1235// through 1236var compareOps = { 1237 '==': '==', 1238 '===': '===', 1239 '!=': '!=', 1240 '!==': '!==', 1241 '<': '<', 1242 '>': '>', 1243 '<=': '<=', 1244 '>=': '>=' 1245}; 1246var Compiler = /*#__PURE__*/function (_Obj) { 1247 _inheritsLoose(Compiler, _Obj); 1248 function Compiler() { 1249 return _Obj.apply(this, arguments) || this; 1250 } 1251 var _proto = Compiler.prototype; 1252 _proto.init = function init(templateName, throwOnUndefined) { 1253 this.templateName = templateName; 1254 this.codebuf = []; 1255 this.lastId = 0; 1256 this.buffer = null; 1257 this.bufferStack = []; 1258 this._scopeClosers = ''; 1259 this.inBlock = false; 1260 this.throwOnUndefined = throwOnUndefined; 1261 }; 1262 _proto.fail = function fail(msg, lineno, colno) { 1263 if (lineno !== undefined) { 1264 lineno += 1; 1265 } 1266 if (colno !== undefined) { 1267 colno += 1; 1268 } 1269 throw new TemplateError(msg, lineno, colno); 1270 }; 1271 _proto._pushBuffer = function _pushBuffer() { 1272 var id = this._tmpid(); 1273 this.bufferStack.push(this.buffer); 1274 this.buffer = id; 1275 this._emit("var " + this.buffer + " = \"\";"); 1276 return id; 1277 }; 1278 _proto._popBuffer = function _popBuffer() { 1279 this.buffer = this.bufferStack.pop(); 1280 }; 1281 _proto._emit = function _emit(code) { 1282 this.codebuf.push(code); 1283 }; 1284 _proto._emitLine = function _emitLine(code) { 1285 this._emit(code + '\n'); 1286 }; 1287 _proto._emitLines = function _emitLines() { 1288 var _this = this; 1289 for (var _len = arguments.length, lines = new Array(_len), _key = 0; _key < _len; _key++) { 1290 lines[_key] = arguments[_key]; 1291 } 1292 lines.forEach(function (line) { 1293 return _this._emitLine(line); 1294 }); 1295 }; 1296 _proto._emitFuncBegin = function _emitFuncBegin(node, name) { 1297 this.buffer = 'output'; 1298 this._scopeClosers = ''; 1299 this._emitLine("function " + name + "(env, context, frame, runtime, cb) {"); 1300 this._emitLine("var lineno = " + node.lineno + ";"); 1301 this._emitLine("var colno = " + node.colno + ";"); 1302 this._emitLine("var " + this.buffer + " = \"\";"); 1303 this._emitLine('try {'); 1304 }; 1305 _proto._emitFuncEnd = function _emitFuncEnd(noReturn) { 1306 if (!noReturn) { 1307 this._emitLine('cb(null, ' + this.buffer + ');'); 1308 } 1309 this._closeScopeLevels(); 1310 this._emitLine('} catch (e) {'); 1311 this._emitLine(' cb(runtime.handleError(e, lineno, colno));'); 1312 this._emitLine('}'); 1313 this._emitLine('}'); 1314 this.buffer = null; 1315 }; 1316 _proto._addScopeLevel = function _addScopeLevel() { 1317 this._scopeClosers += '})'; 1318 }; 1319 _proto._closeScopeLevels = function _closeScopeLevels() { 1320 this._emitLine(this._scopeClosers + ';'); 1321 this._scopeClosers = ''; 1322 }; 1323 _proto._withScopedSyntax = function _withScopedSyntax(func) { 1324 var _scopeClosers = this._scopeClosers; 1325 this._scopeClosers = ''; 1326 func.call(this); 1327 this._closeScopeLevels(); 1328 this._scopeClosers = _scopeClosers; 1329 }; 1330 _proto._makeCallback = function _makeCallback(res) { 1331 var err = this._tmpid(); 1332 return 'function(' + err + (res ? ',' + res : '') + ') {\n' + 'if(' + err + ') { cb(' + err + '); return; }'; 1333 }; 1334 _proto._tmpid = function _tmpid() { 1335 this.lastId++; 1336 return 't_' + this.lastId; 1337 }; 1338 _proto._templateName = function _templateName() { 1339 return this.templateName == null ? 'undefined' : JSON.stringify(this.templateName); 1340 }; 1341 _proto._compileChildren = function _compileChildren(node, frame) { 1342 var _this2 = this; 1343 node.children.forEach(function (child) { 1344 _this2.compile(child, frame); 1345 }); 1346 }; 1347 _proto._compileAggregate = function _compileAggregate(node, frame, startChar, endChar) { 1348 var _this3 = this; 1349 if (startChar) { 1350 this._emit(startChar); 1351 } 1352 node.children.forEach(function (child, i) { 1353 if (i > 0) { 1354 _this3._emit(','); 1355 } 1356 _this3.compile(child, frame); 1357 }); 1358 if (endChar) { 1359 this._emit(endChar); 1360 } 1361 }; 1362 _proto._compileExpression = function _compileExpression(node, frame) { 1363 // TODO: I'm not really sure if this type check is worth it or 1364 // not. 1365 this.assertType(node, nodes.Literal, nodes.Symbol, nodes.Group, nodes.Array, nodes.Dict, nodes.FunCall, nodes.Caller, nodes.Filter, nodes.LookupVal, nodes.Compare, nodes.InlineIf, nodes.In, nodes.Is, nodes.And, nodes.Or, nodes.Not, nodes.Add, nodes.Concat, nodes.Sub, nodes.Mul, nodes.Div, nodes.FloorDiv, nodes.Mod, nodes.Pow, nodes.Neg, nodes.Pos, nodes.Compare, nodes.NodeList); 1366 this.compile(node, frame); 1367 }; 1368 _proto.assertType = function assertType(node) { 1369 for (var _len2 = arguments.length, types = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { 1370 types[_key2 - 1] = arguments[_key2]; 1371 } 1372 if (!types.some(function (t) { 1373 return node instanceof t; 1374 })) { 1375 this.fail("assertType: invalid type: " + node.typename, node.lineno, node.colno); 1376 } 1377 }; 1378 _proto.compileCallExtension = function compileCallExtension(node, frame, async) { 1379 var _this4 = this; 1380 var args = node.args; 1381 var contentArgs = node.contentArgs; 1382 var autoescape = typeof node.autoescape === 'boolean' ? node.autoescape : true; 1383 if (!async) { 1384 this._emit(this.buffer + " += runtime.suppressValue("); 1385 } 1386 this._emit("env.getExtension(\"" + node.extName + "\")[\"" + node.prop + "\"]("); 1387 this._emit('context'); 1388 if (args || contentArgs) { 1389 this._emit(','); 1390 } 1391 if (args) { 1392 if (!(args instanceof nodes.NodeList)) { 1393 this.fail('compileCallExtension: arguments must be a NodeList, ' + 'use `parser.parseSignature`'); 1394 } 1395 args.children.forEach(function (arg, i) { 1396 // Tag arguments are passed normally to the call. Note 1397 // that keyword arguments are turned into a single js 1398 // object as the last argument, if they exist. 1399 _this4._compileExpression(arg, frame); 1400 if (i !== args.children.length - 1 || contentArgs.length) { 1401 _this4._emit(','); 1402 } 1403 }); 1404 } 1405 if (contentArgs.length) { 1406 contentArgs.forEach(function (arg, i) { 1407 if (i > 0) { 1408 _this4._emit(','); 1409 } 1410 if (arg) { 1411 _this4._emitLine('function(cb) {'); 1412 _this4._emitLine('if(!cb) { cb = function(err) { if(err) { throw err; }}}'); 1413 var id = _this4._pushBuffer(); 1414 _this4._withScopedSyntax(function () { 1415 _this4.compile(arg, frame); 1416 _this4._emitLine("cb(null, " + id + ");"); 1417 }); 1418 _this4._popBuffer(); 1419 _this4._emitLine("return " + id + ";"); 1420 _this4._emitLine('}'); 1421 } else { 1422 _this4._emit('null'); 1423 } 1424 }); 1425 } 1426 if (async) { 1427 var res = this._tmpid(); 1428 this._emitLine(', ' + this._makeCallback(res)); 1429 this._emitLine(this.buffer + " += runtime.suppressValue(" + res + ", " + autoescape + " && env.opts.autoescape);"); 1430 this._addScopeLevel(); 1431 } else { 1432 this._emit(')'); 1433 this._emit(", " + autoescape + " && env.opts.autoescape);\n"); 1434 } 1435 }; 1436 _proto.compileCallExtensionAsync = function compileCallExtensionAsync(node, frame) { 1437 this.compileCallExtension(node, frame, true); 1438 }; 1439 _proto.compileNodeList = function compileNodeList(node, frame) { 1440 this._compileChildren(node, frame); 1441 }; 1442 _proto.compileLiteral = function compileLiteral(node) { 1443 if (typeof node.value === 'string') { 1444 var val = node.value.replace(/\\/g, '\\\\'); 1445 val = val.replace(/"/g, '\\"'); 1446 val = val.replace(/\n/g, '\\n'); 1447 val = val.replace(/\r/g, '\\r'); 1448 val = val.replace(/\t/g, '\\t'); 1449 val = val.replace(/\u2028/g, "\\u2028"); 1450 this._emit("\"" + val + "\""); 1451 } else if (node.value === null) { 1452 this._emit('null'); 1453 } else { 1454 this._emit(node.value.toString()); 1455 } 1456 }; 1457 _proto.compileSymbol = function compileSymbol(node, frame) { 1458 var name = node.value; 1459 var v = frame.lookup(name); 1460 if (v) { 1461 this._emit(v); 1462 } else { 1463 this._emit('runtime.contextOrFrameLookup(' + 'context, frame, "' + name + '")'); 1464 } 1465 }; 1466 _proto.compileGroup = function compileGroup(node, frame) { 1467 this._compileAggregate(node, frame, '(', ')'); 1468 }; 1469 _proto.compileArray = function compileArray(node, frame) { 1470 this._compileAggregate(node, frame, '[', ']'); 1471 }; 1472 _proto.compileDict = function compileDict(node, frame) { 1473 this._compileAggregate(node, frame, '{', '}'); 1474 }; 1475 _proto.compilePair = function compilePair(node, frame) { 1476 var key = node.key; 1477 var val = node.value; 1478 if (key instanceof nodes.Symbol) { 1479 key = new nodes.Literal(key.lineno, key.colno, key.value); 1480 } else if (!(key instanceof nodes.Literal && typeof key.value === 'string')) { 1481 this.fail('compilePair: Dict keys must be strings or names', key.lineno, key.colno); 1482 } 1483 this.compile(key, frame); 1484 this._emit(': '); 1485 this._compileExpression(val, frame); 1486 }; 1487 _proto.compileInlineIf = function compileInlineIf(node, frame) { 1488 this._emit('('); 1489 this.compile(node.cond, frame); 1490 this._emit('?'); 1491 this.compile(node.body, frame); 1492 this._emit(':'); 1493 if (node.else_ !== null) { 1494 this.compile(node.else_, frame); 1495 } else { 1496 this._emit('""'); 1497 } 1498 this._emit(')'); 1499 }; 1500 _proto.compileIn = function compileIn(node, frame) { 1501 this._emit('runtime.inOperator('); 1502 this.compile(node.left, frame); 1503 this._emit(','); 1504 this.compile(node.right, frame); 1505 this._emit(')'); 1506 }; 1507 _proto.compileIs = function compileIs(node, frame) { 1508 // first, we need to try to get the name of the test function, if it's a 1509 // callable (i.e., has args) and not a symbol. 1510 var right = node.right.name ? node.right.name.value 1511 // otherwise go with the symbol value 1512 : node.right.value; 1513 this._emit('env.getTest("' + right + '").call(context, '); 1514 this.compile(node.left, frame); 1515 // compile the arguments for the callable if they exist 1516 if (node.right.args) { 1517 this._emit(','); 1518 this.compile(node.right.args, frame); 1519 } 1520 this._emit(') === true'); 1521 }; 1522 _proto._binOpEmitter = function _binOpEmitter(node, frame, str) { 1523 this.compile(node.left, frame); 1524 this._emit(str); 1525 this.compile(node.right, frame); 1526 } 1527 1528 // ensure concatenation instead of addition 1529 // by adding empty string in between 1530 ; 1531 _proto.compileOr = function compileOr(node, frame) { 1532 return this._binOpEmitter(node, frame, ' || '); 1533 }; 1534 _proto.compileAnd = function compileAnd(node, frame) { 1535 return this._binOpEmitter(node, frame, ' && '); 1536 }; 1537 _proto.compileAdd = function compileAdd(node, frame) { 1538 return this._binOpEmitter(node, frame, ' + '); 1539 }; 1540 _proto.compileConcat = function compileConcat(node, frame) { 1541 return this._binOpEmitter(node, frame, ' + "" + '); 1542 }; 1543 _proto.compileSub = function compileSub(node, frame) { 1544 return this._binOpEmitter(node, frame, ' - '); 1545 }; 1546 _proto.compileMul = function compileMul(node, frame) { 1547 return this._binOpEmitter(node, frame, ' * '); 1548 }; 1549 _proto.compileDiv = function compileDiv(node, frame) { 1550 return this._binOpEmitter(node, frame, ' / '); 1551 }; 1552 _proto.compileMod = function compileMod(node, frame) { 1553 return this._binOpEmitter(node, frame, ' % '); 1554 }; 1555 _proto.compileNot = function compileNot(node, frame) { 1556 this._emit('!'); 1557 this.compile(node.target, frame); 1558 }; 1559 _proto.compileFloorDiv = function compileFloorDiv(node, frame) { 1560 this._emit('Math.floor('); 1561 this.compile(node.left, frame); 1562 this._emit(' / '); 1563 this.compile(node.right, frame); 1564 this._emit(')'); 1565 }; 1566 _proto.compilePow = function compilePow(node, frame) { 1567 this._emit('Math.pow('); 1568 this.compile(node.left, frame); 1569 this._emit(', '); 1570 this.compile(node.right, frame); 1571 this._emit(')'); 1572 }; 1573 _proto.compileNeg = function compileNeg(node, frame) { 1574 this._emit('-'); 1575 this.compile(node.target, frame); 1576 }; 1577 _proto.compilePos = function compilePos(node, frame) { 1578 this._emit('+'); 1579 this.compile(node.target, frame); 1580 }; 1581 _proto.compileCompare = function compileCompare(node, frame) { 1582 var _this5 = this; 1583 this.compile(node.expr, frame); 1584 node.ops.forEach(function (op) { 1585 _this5._emit(" " + compareOps[op.type] + " "); 1586 _this5.compile(op.expr, frame); 1587 }); 1588 }; 1589 _proto.compileLookupVal = function compileLookupVal(node, frame) { 1590 this._emit('runtime.memberLookup(('); 1591 this._compileExpression(node.target, frame); 1592 this._emit('),'); 1593 this._compileExpression(node.val, frame); 1594 this._emit(')'); 1595 }; 1596 _proto._getNodeName = function _getNodeName(node) { 1597 switch (node.typename) { 1598 case 'Symbol': 1599 return node.value; 1600 case 'FunCall': 1601 return 'the return value of (' + this._getNodeName(node.name) + ')'; 1602 case 'LookupVal': 1603 return this._getNodeName(node.target) + '["' + this._getNodeName(node.val) + '"]'; 1604 case 'Literal': 1605 return node.value.toString(); 1606 default: 1607 return '--expression--'; 1608 } 1609 }; 1610 _proto.compileFunCall = function compileFunCall(node, frame) { 1611 // Keep track of line/col info at runtime by settings 1612 // variables within an expression. An expression in javascript 1613 // like (x, y, z) returns the last value, and x and y can be 1614 // anything 1615 this._emit('(lineno = ' + node.lineno + ', colno = ' + node.colno + ', '); 1616 this._emit('runtime.callWrap('); 1617 // Compile it as normal. 1618 this._compileExpression(node.name, frame); 1619 1620 // Output the name of what we're calling so we can get friendly errors 1621 // if the lookup fails. 1622 this._emit(', "' + this._getNodeName(node.name).replace(/"/g, '\\"') + '", context, '); 1623 this._compileAggregate(node.args, frame, '[', '])'); 1624 this._emit(')'); 1625 }; 1626 _proto.compileFilter = function compileFilter(node, frame) { 1627 var name = node.name; 1628 this.assertType(name, nodes.Symbol); 1629 this._emit('env.getFilter("' + name.value + '").call(context, '); 1630 this._compileAggregate(node.args, frame); 1631 this._emit(')'); 1632 }; 1633 _proto.compileFilterAsync = function compileFilterAsync(node, frame) { 1634 var name = node.name; 1635 var symbol = node.symbol.value; 1636 this.assertType(name, nodes.Symbol); 1637 frame.set(symbol, symbol); 1638 this._emit('env.getFilter("' + name.value + '").call(context, '); 1639 this._compileAggregate(node.args, frame); 1640 this._emitLine(', ' + this._makeCallback(symbol)); 1641 this._addScopeLevel(); 1642 }; 1643 _proto.compileKeywordArgs = function compileKeywordArgs(node, frame) { 1644 this._emit('runtime.makeKeywordArgs('); 1645 this.compileDict(node, frame); 1646 this._emit(')'); 1647 }; 1648 _proto.compileSet = function compileSet(node, frame) { 1649 var _this6 = this; 1650 var ids = []; 1651 1652 // Lookup the variable names for each identifier and create 1653 // new ones if necessary 1654 node.targets.forEach(function (target) { 1655 var name = target.value; 1656 var id = frame.lookup(name); 1657 if (id === null || id === undefined) { 1658 id = _this6._tmpid(); 1659 1660 // Note: This relies on js allowing scope across 1661 // blocks, in case this is created inside an `if` 1662 _this6._emitLine('var ' + id + ';'); 1663 } 1664 ids.push(id); 1665 }); 1666 if (node.value) { 1667 this._emit(ids.join(' = ') + ' = '); 1668 this._compileExpression(node.value, frame); 1669 this._emitLine(';'); 1670 } else { 1671 this._emit(ids.join(' = ') + ' = '); 1672 this.compile(node.body, frame); 1673 this._emitLine(';'); 1674 } 1675 node.targets.forEach(function (target, i) { 1676 var id = ids[i]; 1677 var name = target.value; 1678 1679 // We are running this for every var, but it's very 1680 // uncommon to assign to multiple vars anyway 1681 _this6._emitLine("frame.set(\"" + name + "\", " + id + ", true);"); 1682 _this6._emitLine('if(frame.topLevel) {'); 1683 _this6._emitLine("context.setVariable(\"" + name + "\", " + id + ");"); 1684 _this6._emitLine('}'); 1685 if (name.charAt(0) !== '_') { 1686 _this6._emitLine('if(frame.topLevel) {'); 1687 _this6._emitLine("context.addExport(\"" + name + "\", " + id + ");"); 1688 _this6._emitLine('}'); 1689 } 1690 }); 1691 }; 1692 _proto.compileSwitch = function compileSwitch(node, frame) { 1693 var _this7 = this; 1694 this._emit('switch ('); 1695 this.compile(node.expr, frame); 1696 this._emit(') {'); 1697 node.cases.forEach(function (c, i) { 1698 _this7._emit('case '); 1699 _this7.compile(c.cond, frame); 1700 _this7._emit(': '); 1701 _this7.compile(c.body, frame); 1702 // preserve fall-throughs 1703 if (c.body.children.length) { 1704 _this7._emitLine('break;'); 1705 } 1706 }); 1707 if (node.default) { 1708 this._emit('default:'); 1709 this.compile(node.default, frame); 1710 } 1711 this._emit('}'); 1712 }; 1713 _proto.compileIf = function compileIf(node, frame, async) { 1714 var _this8 = this; 1715 this._emit('if('); 1716 this._compileExpression(node.cond, frame); 1717 this._emitLine(') {'); 1718 this._withScopedSyntax(function () { 1719 _this8.compile(node.body, frame); 1720 if (async) { 1721 _this8._emit('cb()'); 1722 } 1723 }); 1724 if (node.else_) { 1725 this._emitLine('}\nelse {'); 1726 this._withScopedSyntax(function () { 1727 _this8.compile(node.else_, frame); 1728 if (async) { 1729 _this8._emit('cb()'); 1730 } 1731 }); 1732 } else if (async) { 1733 this._emitLine('}\nelse {'); 1734 this._emit('cb()'); 1735 } 1736 this._emitLine('}'); 1737 }; 1738 _proto.compileIfAsync = function compileIfAsync(node, frame) { 1739 this._emit('(function(cb) {'); 1740 this.compileIf(node, frame, true); 1741 this._emit('})(' + this._makeCallback()); 1742 this._addScopeLevel(); 1743 }; 1744 _proto._emitLoopBindings = function _emitLoopBindings(node, arr, i, len) { 1745 var _this9 = this; 1746 var bindings = [{ 1747 name: 'index', 1748 val: i + " + 1" 1749 }, { 1750 name: 'index0', 1751 val: i 1752 }, { 1753 name: 'revindex', 1754 val: len + " - " + i 1755 }, { 1756 name: 'revindex0', 1757 val: len + " - " + i + " - 1" 1758 }, { 1759 name: 'first', 1760 val: i + " === 0" 1761 }, { 1762 name: 'last', 1763 val: i + " === " + len + " - 1" 1764 }, { 1765 name: 'length', 1766 val: len 1767 }]; 1768 bindings.forEach(function (b) { 1769 _this9._emitLine("frame.set(\"loop." + b.name + "\", " + b.val + ");"); 1770 }); 1771 }; 1772 _proto.compileFor = function compileFor(node, frame) { 1773 var _this10 = this; 1774 // Some of this code is ugly, but it keeps the generated code 1775 // as fast as possible. ForAsync also shares some of this, but 1776 // not much. 1777 1778 var i = this._tmpid(); 1779 var len = this._tmpid(); 1780 var arr = this._tmpid(); 1781 frame = frame.push(); 1782 this._emitLine('frame = frame.push();'); 1783 this._emit("var " + arr + " = "); 1784 this._compileExpression(node.arr, frame); 1785 this._emitLine(';'); 1786 this._emit("if(" + arr + ") {"); 1787 this._emitLine(arr + ' = runtime.fromIterator(' + arr + ');'); 1788 1789 // If multiple names are passed, we need to bind them 1790 // appropriately 1791 if (node.name instanceof nodes.Array) { 1792 this._emitLine("var " + i + ";"); 1793 1794 // The object could be an arroy or object. Note that the 1795 // body of the loop is duplicated for each condition, but 1796 // we are optimizing for speed over size. 1797 this._emitLine("if(runtime.isArray(" + arr + ")) {"); 1798 this._emitLine("var " + len + " = " + arr + ".length;"); 1799 this._emitLine("for(" + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); 1800 1801 // Bind each declared var 1802 node.name.children.forEach(function (child, u) { 1803 var tid = _this10._tmpid(); 1804 _this10._emitLine("var " + tid + " = " + arr + "[" + i + "][" + u + "];"); 1805 _this10._emitLine("frame.set(\"" + child + "\", " + arr + "[" + i + "][" + u + "]);"); 1806 frame.set(node.name.children[u].value, tid); 1807 }); 1808 this._emitLoopBindings(node, arr, i, len); 1809 this._withScopedSyntax(function () { 1810 _this10.compile(node.body, frame); 1811 }); 1812 this._emitLine('}'); 1813 this._emitLine('} else {'); 1814 // Iterate over the key/values of an object 1815 var _node$name$children = node.name.children, 1816 key = _node$name$children[0], 1817 val = _node$name$children[1]; 1818 var k = this._tmpid(); 1819 var v = this._tmpid(); 1820 frame.set(key.value, k); 1821 frame.set(val.value, v); 1822 this._emitLine(i + " = -1;"); 1823 this._emitLine("var " + len + " = runtime.keys(" + arr + ").length;"); 1824 this._emitLine("for(var " + k + " in " + arr + ") {"); 1825 this._emitLine(i + "++;"); 1826 this._emitLine("var " + v + " = " + arr + "[" + k + "];"); 1827 this._emitLine("frame.set(\"" + key.value + "\", " + k + ");"); 1828 this._emitLine("frame.set(\"" + val.value + "\", " + v + ");"); 1829 this._emitLoopBindings(node, arr, i, len); 1830 this._withScopedSyntax(function () { 1831 _this10.compile(node.body, frame); 1832 }); 1833 this._emitLine('}'); 1834 this._emitLine('}'); 1835 } else { 1836 // Generate a typical array iteration 1837 var _v = this._tmpid(); 1838 frame.set(node.name.value, _v); 1839 this._emitLine("var " + len + " = " + arr + ".length;"); 1840 this._emitLine("for(var " + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); 1841 this._emitLine("var " + _v + " = " + arr + "[" + i + "];"); 1842 this._emitLine("frame.set(\"" + node.name.value + "\", " + _v + ");"); 1843 this._emitLoopBindings(node, arr, i, len); 1844 this._withScopedSyntax(function () { 1845 _this10.compile(node.body, frame); 1846 }); 1847 this._emitLine('}'); 1848 } 1849 this._emitLine('}'); 1850 if (node.else_) { 1851 this._emitLine('if (!' + len + ') {'); 1852 this.compile(node.else_, frame); 1853 this._emitLine('}'); 1854 } 1855 this._emitLine('frame = frame.pop();'); 1856 }; 1857 _proto._compileAsyncLoop = function _compileAsyncLoop(node, frame, parallel) { 1858 var _this11 = this; 1859 // This shares some code with the For tag, but not enough to 1860 // worry about. This iterates across an object asynchronously, 1861 // but not in parallel. 1862 1863 var i = this._tmpid(); 1864 var len = this._tmpid(); 1865 var arr = this._tmpid(); 1866 var asyncMethod = parallel ? 'asyncAll' : 'asyncEach'; 1867 frame = frame.push(); 1868 this._emitLine('frame = frame.push();'); 1869 this._emit('var ' + arr + ' = runtime.fromIterator('); 1870 this._compileExpression(node.arr, frame); 1871 this._emitLine(');'); 1872 if (node.name instanceof nodes.Array) { 1873 var arrayLen = node.name.children.length; 1874 this._emit("runtime." + asyncMethod + "(" + arr + ", " + arrayLen + ", function("); 1875 node.name.children.forEach(function (name) { 1876 _this11._emit(name.value + ","); 1877 }); 1878 this._emit(i + ',' + len + ',next) {'); 1879 node.name.children.forEach(function (name) { 1880 var id = name.value; 1881 frame.set(id, id); 1882 _this11._emitLine("frame.set(\"" + id + "\", " + id + ");"); 1883 }); 1884 } else { 1885 var id = node.name.value; 1886 this._emitLine("runtime." + asyncMethod + "(" + arr + ", 1, function(" + id + ", " + i + ", " + len + ",next) {"); 1887 this._emitLine('frame.set("' + id + '", ' + id + ');'); 1888 frame.set(id, id); 1889 } 1890 this._emitLoopBindings(node, arr, i, len); 1891 this._withScopedSyntax(function () { 1892 var buf; 1893 if (parallel) { 1894 buf = _this11._pushBuffer(); 1895 } 1896 _this11.compile(node.body, frame); 1897 _this11._emitLine('next(' + i + (buf ? ',' + buf : '') + ');'); 1898 if (parallel) { 1899 _this11._popBuffer(); 1900 } 1901 }); 1902 var output = this._tmpid(); 1903 this._emitLine('}, ' + this._makeCallback(output)); 1904 this._addScopeLevel(); 1905 if (parallel) { 1906 this._emitLine(this.buffer + ' += ' + output + ';'); 1907 } 1908 if (node.else_) { 1909 this._emitLine('if (!' + arr + '.length) {'); 1910 this.compile(node.else_, frame); 1911 this._emitLine('}'); 1912 } 1913 this._emitLine('frame = frame.pop();'); 1914 }; 1915 _proto.compileAsyncEach = function compileAsyncEach(node, frame) { 1916 this._compileAsyncLoop(node, frame); 1917 }; 1918 _proto.compileAsyncAll = function compileAsyncAll(node, frame) { 1919 this._compileAsyncLoop(node, frame, true); 1920 }; 1921 _proto._compileMacro = function _compileMacro(node, frame) { 1922 var _this12 = this; 1923 var args = []; 1924 var kwargs = null; 1925 var funcId = 'macro_' + this._tmpid(); 1926 var keepFrame = frame !== undefined; 1927 1928 // Type check the definition of the args 1929 node.args.children.forEach(function (arg, i) { 1930 if (i === node.args.children.length - 1 && arg instanceof nodes.Dict) { 1931 kwargs = arg; 1932 } else { 1933 _this12.assertType(arg, nodes.Symbol); 1934 args.push(arg); 1935 } 1936 }); 1937 var realNames = [].concat(args.map(function (n) { 1938 return "l_" + n.value; 1939 }), ['kwargs']); 1940 1941 // Quoted argument names 1942 var argNames = args.map(function (n) { 1943 return "\"" + n.value + "\""; 1944 }); 1945 var kwargNames = (kwargs && kwargs.children || []).map(function (n) { 1946 return "\"" + n.key.value + "\""; 1947 }); 1948 1949 // We pass a function to makeMacro which destructures the 1950 // arguments so support setting positional args with keywords 1951 // args and passing keyword args as positional args 1952 // (essentially default values). See runtime.js. 1953 var currFrame; 1954 if (keepFrame) { 1955 currFrame = frame.push(true); 1956 } else { 1957 currFrame = new Frame(); 1958 } 1959 this._emitLines("var " + funcId + " = runtime.makeMacro(", "[" + argNames.join(', ') + "], ", "[" + kwargNames.join(', ') + "], ", "function (" + realNames.join(', ') + ") {", 'var callerFrame = frame;', 'frame = ' + (keepFrame ? 'frame.push(true);' : 'new runtime.Frame();'), 'kwargs = kwargs || {};', 'if (Object.prototype.hasOwnProperty.call(kwargs, "caller")) {', 'frame.set("caller", kwargs.caller); }'); 1960 1961 // Expose the arguments to the template. Don't need to use 1962 // random names because the function 1963 // will create a new run-time scope for us 1964 args.forEach(function (arg) { 1965 _this12._emitLine("frame.set(\"" + arg.value + "\", l_" + arg.value + ");"); 1966 currFrame.set(arg.value, "l_" + arg.value); 1967 }); 1968 1969 // Expose the keyword arguments 1970 if (kwargs) { 1971 kwargs.children.forEach(function (pair) { 1972 var name = pair.key.value; 1973 _this12._emit("frame.set(\"" + name + "\", "); 1974 _this12._emit("Object.prototype.hasOwnProperty.call(kwargs, \"" + name + "\")"); 1975 _this12._emit(" ? kwargs[\"" + name + "\"] : "); 1976 _this12._compileExpression(pair.value, currFrame); 1977 _this12._emit(');'); 1978 }); 1979 } 1980 var bufferId = this._pushBuffer(); 1981 this._withScopedSyntax(function () { 1982 _this12.compile(node.body, currFrame); 1983 }); 1984 this._emitLine('frame = ' + (keepFrame ? 'frame.pop();' : 'callerFrame;')); 1985 this._emitLine("return new runtime.SafeString(" + bufferId + ");"); 1986 this._emitLine('});'); 1987 this._popBuffer(); 1988 return funcId; 1989 }; 1990 _proto.compileMacro = function compileMacro(node, frame) { 1991 var funcId = this._compileMacro(node); 1992 1993 // Expose the macro to the templates 1994 var name = node.name.value; 1995 frame.set(name, funcId); 1996 if (frame.parent) { 1997 this._emitLine("frame.set(\"" + name + "\", " + funcId + ");"); 1998 } else { 1999 if (node.name.value.charAt(0) !== '_') { 2000 this._emitLine("context.addExport(\"" + name + "\");"); 2001 } 2002 this._emitLine("context.setVariable(\"" + name + "\", " + funcId + ");"); 2003 } 2004 }; 2005 _proto.compileCaller = function compileCaller(node, frame) { 2006 // basically an anonymous "macro expression" 2007 this._emit('(function (){'); 2008 var funcId = this._compileMacro(node, frame); 2009 this._emit("return " + funcId + ";})()"); 2010 }; 2011 _proto._compileGetTemplate = function _compileGetTemplate(node, frame, eagerCompile, ignoreMissing) { 2012 var parentTemplateId = this._tmpid(); 2013 var parentName = this._templateName(); 2014 var cb = this._makeCallback(parentTemplateId); 2015 var eagerCompileArg = eagerCompile ? 'true' : 'false'; 2016 var ignoreMissingArg = ignoreMissing ? 'true' : 'false'; 2017 this._emit('env.getTemplate('); 2018 this._compileExpression(node.template, frame); 2019 this._emitLine(", " + eagerCompileArg + ", " + parentName + ", " + ignoreMissingArg + ", " + cb); 2020 return parentTemplateId; 2021 }; 2022 _proto.compileImport = function compileImport(node, frame) { 2023 var target = node.target.value; 2024 var id = this._compileGetTemplate(node, frame, false, false); 2025 this._addScopeLevel(); 2026 this._emitLine(id + '.getExported(' + (node.withContext ? 'context.getVariables(), frame, ' : '') + this._makeCallback(id)); 2027 this._addScopeLevel(); 2028 frame.set(target, id); 2029 if (frame.parent) { 2030 this._emitLine("frame.set(\"" + target + "\", " + id + ");"); 2031 } else { 2032 this._emitLine("context.setVariable(\"" + target + "\", " + id + ");"); 2033 } 2034 }; 2035 _proto.compileFromImport = function compileFromImport(node, frame) { 2036 var _this13 = this; 2037 var importedId = this._compileGetTemplate(node, frame, false, false); 2038 this._addScopeLevel(); 2039 this._emitLine(importedId + '.getExported(' + (node.withContext ? 'context.getVariables(), frame, ' : '') + this._makeCallback(importedId)); 2040 this._addScopeLevel(); 2041 node.names.children.forEach(function (nameNode) { 2042 var name; 2043 var alias; 2044 var id = _this13._tmpid(); 2045 if (nameNode instanceof nodes.Pair) { 2046 name = nameNode.key.value; 2047 alias = nameNode.value.value; 2048 } else { 2049 name = nameNode.value; 2050 alias = name; 2051 } 2052 _this13._emitLine("if(Object.prototype.hasOwnProperty.call(" + importedId + ", \"" + name + "\")) {"); 2053 _this13._emitLine("var " + id + " = " + importedId + "." + name + ";"); 2054 _this13._emitLine('} else {'); 2055 _this13._emitLine("cb(new Error(\"cannot import '" + name + "'\")); return;"); 2056 _this13._emitLine('}'); 2057 frame.set(alias, id); 2058 if (frame.parent) { 2059 _this13._emitLine("frame.set(\"" + alias + "\", " + id + ");"); 2060 } else { 2061 _this13._emitLine("context.setVariable(\"" + alias + "\", " + id + ");"); 2062 } 2063 }); 2064 }; 2065 _proto.compileBlock = function compileBlock(node) { 2066 var id = this._tmpid(); 2067 2068 // If we are executing outside a block (creating a top-level 2069 // block), we really don't want to execute its code because it 2070 // will execute twice: once when the child template runs and 2071 // again when the parent template runs. Note that blocks 2072 // within blocks will *always* execute immediately *and* 2073 // wherever else they are invoked (like used in a parent 2074 // template). This may have behavioral differences from jinja 2075 // because blocks can have side effects, but it seems like a 2076 // waste of performance to always execute huge top-level 2077 // blocks twice 2078 if (!this.inBlock) { 2079 this._emit('(parentTemplate ? function(e, c, f, r, cb) { cb(""); } : '); 2080 } 2081 this._emit("context.getBlock(\"" + node.name.value + "\")"); 2082 if (!this.inBlock) { 2083 this._emit(')'); 2084 } 2085 this._emitLine('(env, context, frame, runtime, ' + this._makeCallback(id)); 2086 this._emitLine(this.buffer + " += " + id + ";"); 2087 this._addScopeLevel(); 2088 }; 2089 _proto.compileSuper = function compileSuper(node, frame) { 2090 var name = node.blockName.value; 2091 var id = node.symbol.value; 2092 var cb = this._makeCallback(id); 2093 this._emitLine("context.getSuper(env, \"" + name + "\", b_" + name + ", frame, runtime, " + cb); 2094 this._emitLine(id + " = runtime.markSafe(" + id + ");"); 2095 this._addScopeLevel(); 2096 frame.set(id, id); 2097 }; 2098 _proto.compileExtends = function compileExtends(node, frame) { 2099 var k = this._tmpid(); 2100 var parentTemplateId = this._compileGetTemplate(node, frame, true, false); 2101 2102 // extends is a dynamic tag and can occur within a block like 2103 // `if`, so if this happens we need to capture the parent 2104 // template in the top-level scope 2105 this._emitLine("parentTemplate = " + parentTemplateId); 2106 this._emitLine("for(var " + k + " in parentTemplate.blocks) {"); 2107 this._emitLine("context.addBlock(" + k + ", parentTemplate.blocks[" + k + "]);"); 2108 this._emitLine('}'); 2109 this._addScopeLevel(); 2110 }; 2111 _proto.compileInclude = function compileInclude(node, frame) { 2112 this._emitLine('var tasks = [];'); 2113 this._emitLine('tasks.push('); 2114 this._emitLine('function(callback) {'); 2115 var id = this._compileGetTemplate(node, frame, false, node.ignoreMissing); 2116 this._emitLine("callback(null," + id + ");});"); 2117 this._emitLine('});'); 2118 var id2 = this._tmpid(); 2119 this._emitLine('tasks.push('); 2120 this._emitLine('function(template, callback){'); 2121 this._emitLine('template.render(context.getVariables(), frame, ' + this._makeCallback(id2)); 2122 this._emitLine('callback(null,' + id2 + ');});'); 2123 this._emitLine('});'); 2124 this._emitLine('tasks.push('); 2125 this._emitLine('function(result, callback){'); 2126 this._emitLine(this.buffer + " += result;"); 2127 this._emitLine('callback(null);'); 2128 this._emitLine('});'); 2129 this._emitLine('env.waterfall(tasks, function(){'); 2130 this._addScopeLevel(); 2131 }; 2132 _proto.compileTemplateData = function compileTemplateData(node, frame) { 2133 this.compileLiteral(node, frame); 2134 }; 2135 _proto.compileCapture = function compileCapture(node, frame) { 2136 var _this14 = this; 2137 // we need to temporarily override the current buffer id as 'output' 2138 // so the set block writes to the capture output instead of the buffer 2139 var buffer = this.buffer; 2140 this.buffer = 'output'; 2141 this._emitLine('(function() {'); 2142 this._emitLine('var output = "";'); 2143 this._withScopedSyntax(function () { 2144 _this14.compile(node.body, frame); 2145 }); 2146 this._emitLine('return output;'); 2147 this._emitLine('})()'); 2148 // and of course, revert back to the old buffer id 2149 this.buffer = buffer; 2150 }; 2151 _proto.compileOutput = function compileOutput(node, frame) { 2152 var _this15 = this; 2153 var children = node.children; 2154 children.forEach(function (child) { 2155 // TemplateData is a special case because it is never 2156 // autoescaped, so simply output it for optimization 2157 if (child instanceof nodes.TemplateData) { 2158 if (child.value) { 2159 _this15._emit(_this15.buffer + " += "); 2160 _this15.compileLiteral(child, frame); 2161 _this15._emitLine(';'); 2162 } 2163 } else { 2164 _this15._emit(_this15.buffer + " += runtime.suppressValue("); 2165 if (_this15.throwOnUndefined) { 2166 _this15._emit('runtime.ensureDefined('); 2167 } 2168 _this15.compile(child, frame); 2169 if (_this15.throwOnUndefined) { 2170 _this15._emit("," + node.lineno + "," + node.colno + ")"); 2171 } 2172 _this15._emit(', env.opts.autoescape);\n'); 2173 } 2174 }); 2175 }; 2176 _proto.compileRoot = function compileRoot(node, frame) { 2177 var _this16 = this; 2178 if (frame) { 2179 this.fail('compileRoot: root node can\'t have frame'); 2180 } 2181 frame = new Frame(); 2182 this._emitFuncBegin(node, 'root'); 2183 this._emitLine('var parentTemplate = null;'); 2184 this._compileChildren(node, frame); 2185 this._emitLine('if(parentTemplate) {'); 2186 this._emitLine('parentTemplate.rootRenderFunc(env, context, frame, runtime, cb);'); 2187 this._emitLine('} else {'); 2188 this._emitLine("cb(null, " + this.buffer + ");"); 2189 this._emitLine('}'); 2190 this._emitFuncEnd(true); 2191 this.inBlock = true; 2192 var blockNames = []; 2193 var blocks = node.findAll(nodes.Block); 2194 blocks.forEach(function (block, i) { 2195 var name = block.name.value; 2196 if (blockNames.indexOf(name) !== -1) { 2197 throw new Error("Block \"" + name + "\" defined more than once."); 2198 } 2199 blockNames.push(name); 2200 _this16._emitFuncBegin(block, "b_" + name); 2201 var tmpFrame = new Frame(); 2202 _this16._emitLine('var frame = frame.push(true);'); 2203 _this16.compile(block.body, tmpFrame); 2204 _this16._emitFuncEnd(); 2205 }); 2206 this._emitLine('return {'); 2207 blocks.forEach(function (block, i) { 2208 var blockName = "b_" + block.name.value; 2209 _this16._emitLine(blockName + ": " + blockName + ","); 2210 }); 2211 this._emitLine('root: root\n};'); 2212 }; 2213 _proto.compile = function compile(node, frame) { 2214 var _compile = this['compile' + node.typename]; 2215 if (_compile) { 2216 _compile.call(this, node, frame); 2217 } else { 2218 this.fail("compile: Cannot compile node: " + node.typename, node.lineno, node.colno); 2219 } 2220 }; 2221 _proto.getCode = function getCode() { 2222 return this.codebuf.join(''); 2223 }; 2224 return Compiler; 2225}(Obj); 2226module.exports = { 2227 compile: function compile(src, asyncFilters, extensions, name, opts) { 2228 if (opts === void 0) { 2229 opts = {}; 2230 } 2231 var c = new Compiler(name, opts.throwOnUndefined); 2232 2233 // Run the extension preprocessors against the source. 2234 var preprocessors = (extensions || []).map(function (ext) { 2235 return ext.preprocess; 2236 }).filter(function (f) { 2237 return !!f; 2238 }); 2239 var processedSrc = preprocessors.reduce(function (s, processor) { 2240 return processor(s); 2241 }, src); 2242 c.compile(transformer.transform(parser.parse(processedSrc, extensions, opts), asyncFilters, name)); 2243 return c.getCode(); 2244 }, 2245 Compiler: Compiler 2246}; 2247 2248/***/ }), 2249/* 6 */ 2250/***/ (function(module, exports, __webpack_require__) { 2251 2252"use strict"; 2253 2254 2255function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } 2256function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 2257var path = __webpack_require__(4); 2258var _require = __webpack_require__(1), 2259 EmitterObj = _require.EmitterObj; 2260module.exports = /*#__PURE__*/function (_EmitterObj) { 2261 _inheritsLoose(Loader, _EmitterObj); 2262 function Loader() { 2263 return _EmitterObj.apply(this, arguments) || this; 2264 } 2265 var _proto = Loader.prototype; 2266 _proto.resolve = function resolve(from, to) { 2267 return path.resolve(path.dirname(from), to); 2268 }; 2269 _proto.isRelative = function isRelative(filename) { 2270 return filename.indexOf('./') === 0 || filename.indexOf('../') === 0; 2271 }; 2272 return Loader; 2273}(EmitterObj); 2274 2275/***/ }), 2276/* 7 */ 2277/***/ (function(module, exports, __webpack_require__) { 2278 2279"use strict"; 2280 2281 2282function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } 2283function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 2284var asap = __webpack_require__(12); 2285var _waterfall = __webpack_require__(15); 2286var lib = __webpack_require__(0); 2287var compiler = __webpack_require__(5); 2288var filters = __webpack_require__(18); 2289var _require = __webpack_require__(10), 2290 FileSystemLoader = _require.FileSystemLoader, 2291 WebLoader = _require.WebLoader, 2292 PrecompiledLoader = _require.PrecompiledLoader; 2293var tests = __webpack_require__(20); 2294var globals = __webpack_require__(21); 2295var _require2 = __webpack_require__(1), 2296 Obj = _require2.Obj, 2297 EmitterObj = _require2.EmitterObj; 2298var globalRuntime = __webpack_require__(2); 2299var handleError = globalRuntime.handleError, 2300 Frame = globalRuntime.Frame; 2301var expressApp = __webpack_require__(22); 2302 2303// If the user is using the async API, *always* call it 2304// asynchronously even if the template was synchronous. 2305function callbackAsap(cb, err, res) { 2306 asap(function () { 2307 cb(err, res); 2308 }); 2309} 2310 2311/** 2312 * A no-op template, for use with {% include ignore missing %} 2313 */ 2314var noopTmplSrc = { 2315 type: 'code', 2316 obj: { 2317 root: function root(env, context, frame, runtime, cb) { 2318 try { 2319 cb(null, ''); 2320 } catch (e) { 2321 cb(handleError(e, null, null)); 2322 } 2323 } 2324 } 2325}; 2326var Environment = /*#__PURE__*/function (_EmitterObj) { 2327 _inheritsLoose(Environment, _EmitterObj); 2328 function Environment() { 2329 return _EmitterObj.apply(this, arguments) || this; 2330 } 2331 var _proto = Environment.prototype; 2332 _proto.init = function init(loaders, opts) { 2333 var _this = this; 2334 // The dev flag determines the trace that'll be shown on errors. 2335 // If set to true, returns the full trace from the error point, 2336 // otherwise will return trace starting from Template.render 2337 // (the full trace from within nunjucks may confuse developers using 2338 // the library) 2339 // defaults to false 2340 opts = this.opts = opts || {}; 2341 this.opts.dev = !!opts.dev; 2342 2343 // The autoescape flag sets global autoescaping. If true, 2344 // every string variable will be escaped by default. 2345 // If false, strings can be manually escaped using the `escape` filter. 2346 // defaults to true 2347 this.opts.autoescape = opts.autoescape != null ? opts.autoescape : true; 2348 2349 // If true, this will make the system throw errors if trying 2350 // to output a null or undefined value 2351 this.opts.throwOnUndefined = !!opts.throwOnUndefined; 2352 this.opts.trimBlocks = !!opts.trimBlocks; 2353 this.opts.lstripBlocks = !!opts.lstripBlocks; 2354 this.loaders = []; 2355 if (!loaders) { 2356 // The filesystem loader is only available server-side 2357 if (FileSystemLoader) { 2358 this.loaders = [new FileSystemLoader('views')]; 2359 } else if (WebLoader) { 2360 this.loaders = [new WebLoader('/views')]; 2361 } 2362 } else { 2363 this.loaders = lib.isArray(loaders) ? loaders : [loaders]; 2364 } 2365 2366 // It's easy to use precompiled templates: just include them 2367 // before you configure nunjucks and this will automatically 2368 // pick it up and use it 2369 if (typeof window !== 'undefined' && window.nunjucksPrecompiled) { 2370 this.loaders.unshift(new PrecompiledLoader(window.nunjucksPrecompiled)); 2371 } 2372 this._initLoaders(); 2373 this.globals = globals(); 2374 this.filters = {}; 2375 this.tests = {}; 2376 this.asyncFilters = []; 2377 this.extensions = {}; 2378 this.extensionsList = []; 2379 lib._entries(filters).forEach(function (_ref) { 2380 var name = _ref[0], 2381 filter = _ref[1]; 2382 return _this.addFilter(name, filter); 2383 }); 2384 lib._entries(tests).forEach(function (_ref2) { 2385 var name = _ref2[0], 2386 test = _ref2[1]; 2387 return _this.addTest(name, test); 2388 }); 2389 }; 2390 _proto._initLoaders = function _initLoaders() { 2391 var _this2 = this; 2392 this.loaders.forEach(function (loader) { 2393 // Caching and cache busting 2394 loader.cache = {}; 2395 if (typeof loader.on === 'function') { 2396 loader.on('update', function (name, fullname) { 2397 loader.cache[name] = null; 2398 _this2.emit('update', name, fullname, loader); 2399 }); 2400 loader.on('load', function (name, source) { 2401 _this2.emit('load', name, source, loader); 2402 }); 2403 } 2404 }); 2405 }; 2406 _proto.invalidateCache = function invalidateCache() { 2407 this.loaders.forEach(function (loader) { 2408 loader.cache = {}; 2409 }); 2410 }; 2411 _proto.addExtension = function addExtension(name, extension) { 2412 extension.__name = name; 2413 this.extensions[name] = extension; 2414 this.extensionsList.push(extension); 2415 return this; 2416 }; 2417 _proto.removeExtension = function removeExtension(name) { 2418 var extension = this.getExtension(name); 2419 if (!extension) { 2420 return; 2421 } 2422 this.extensionsList = lib.without(this.extensionsList, extension); 2423 delete this.extensions[name]; 2424 }; 2425 _proto.getExtension = function getExtension(name) { 2426 return this.extensions[name]; 2427 }; 2428 _proto.hasExtension = function hasExtension(name) { 2429 return !!this.extensions[name]; 2430 }; 2431 _proto.addGlobal = function addGlobal(name, value) { 2432 this.globals[name] = value; 2433 return this; 2434 }; 2435 _proto.getGlobal = function getGlobal(name) { 2436 if (typeof this.globals[name] === 'undefined') { 2437 throw new Error('global not found: ' + name); 2438 } 2439 return this.globals[name]; 2440 }; 2441 _proto.addFilter = function addFilter(name, func, async) { 2442 var wrapped = func; 2443 if (async) { 2444 this.asyncFilters.push(name); 2445 } 2446 this.filters[name] = wrapped; 2447 return this; 2448 }; 2449 _proto.getFilter = function getFilter(name) { 2450 if (!this.filters[name]) { 2451 throw new Error('filter not found: ' + name); 2452 } 2453 return this.filters[name]; 2454 }; 2455 _proto.addTest = function addTest(name, func) { 2456 this.tests[name] = func; 2457 return this; 2458 }; 2459 _proto.getTest = function getTest(name) { 2460 if (!this.tests[name]) { 2461 throw new Error('test not found: ' + name); 2462 } 2463 return this.tests[name]; 2464 }; 2465 _proto.resolveTemplate = function resolveTemplate(loader, parentName, filename) { 2466 var isRelative = loader.isRelative && parentName ? loader.isRelative(filename) : false; 2467 return isRelative && loader.resolve ? loader.resolve(parentName, filename) : filename; 2468 }; 2469 _proto.getTemplate = function getTemplate(name, eagerCompile, parentName, ignoreMissing, cb) { 2470 var _this3 = this; 2471 var that = this; 2472 var tmpl = null; 2473 if (name && name.raw) { 2474 // this fixes autoescape for templates referenced in symbols 2475 name = name.raw; 2476 } 2477 if (lib.isFunction(parentName)) { 2478 cb = parentName; 2479 parentName = null; 2480 eagerCompile = eagerCompile || false; 2481 } 2482 if (lib.isFunction(eagerCompile)) { 2483 cb = eagerCompile; 2484 eagerCompile = false; 2485 } 2486 if (name instanceof Template) { 2487 tmpl = name; 2488 } else if (typeof name !== 'string') { 2489 throw new Error('template names must be a string: ' + name); 2490 } else { 2491 for (var i = 0; i < this.loaders.length; i++) { 2492 var loader = this.loaders[i]; 2493 tmpl = loader.cache[this.resolveTemplate(loader, parentName, name)]; 2494 if (tmpl) { 2495 break; 2496 } 2497 } 2498 } 2499 if (tmpl) { 2500 if (eagerCompile) { 2501 tmpl.compile(); 2502 } 2503 if (cb) { 2504 cb(null, tmpl); 2505 return undefined; 2506 } else { 2507 return tmpl; 2508 } 2509 } 2510 var syncResult; 2511 var createTemplate = function createTemplate(err, info) { 2512 if (!info && !err && !ignoreMissing) { 2513 err = new Error('template not found: ' + name); 2514 } 2515 if (err) { 2516 if (cb) { 2517 cb(err); 2518 return; 2519 } else { 2520 throw err; 2521 } 2522 } 2523 var newTmpl; 2524 if (!info) { 2525 newTmpl = new Template(noopTmplSrc, _this3, '', eagerCompile); 2526 } else { 2527 newTmpl = new Template(info.src, _this3, info.path, eagerCompile); 2528 if (!info.noCache) { 2529 info.loader.cache[name] = newTmpl; 2530 } 2531 } 2532 if (cb) { 2533 cb(null, newTmpl); 2534 } else { 2535 syncResult = newTmpl; 2536 } 2537 }; 2538 lib.asyncIter(this.loaders, function (loader, i, next, done) { 2539 function handle(err, src) { 2540 if (err) { 2541 done(err); 2542 } else if (src) { 2543 src.loader = loader; 2544 done(null, src); 2545 } else { 2546 next(); 2547 } 2548 } 2549 2550 // Resolve name relative to parentName 2551 name = that.resolveTemplate(loader, parentName, name); 2552 if (loader.async) { 2553 loader.getSource(name, handle); 2554 } else { 2555 handle(null, loader.getSource(name)); 2556 } 2557 }, createTemplate); 2558 return syncResult; 2559 }; 2560 _proto.express = function express(app) { 2561 return expressApp(this, app); 2562 }; 2563 _proto.render = function render(name, ctx, cb) { 2564 if (lib.isFunction(ctx)) { 2565 cb = ctx; 2566 ctx = null; 2567 } 2568 2569 // We support a synchronous API to make it easier to migrate 2570 // existing code to async. This works because if you don't do 2571 // anything async work, the whole thing is actually run 2572 // synchronously. 2573 var syncResult = null; 2574 this.getTemplate(name, function (err, tmpl) { 2575 if (err && cb) { 2576 callbackAsap(cb, err); 2577 } else if (err) { 2578 throw err; 2579 } else { 2580 syncResult = tmpl.render(ctx, cb); 2581 } 2582 }); 2583 return syncResult; 2584 }; 2585 _proto.renderString = function renderString(src, ctx, opts, cb) { 2586 if (lib.isFunction(opts)) { 2587 cb = opts; 2588 opts = {}; 2589 } 2590 opts = opts || {}; 2591 var tmpl = new Template(src, this, opts.path); 2592 return tmpl.render(ctx, cb); 2593 }; 2594 _proto.waterfall = function waterfall(tasks, callback, forceAsync) { 2595 return _waterfall(tasks, callback, forceAsync); 2596 }; 2597 return Environment; 2598}(EmitterObj); 2599var Context = /*#__PURE__*/function (_Obj) { 2600 _inheritsLoose(Context, _Obj); 2601 function Context() { 2602 return _Obj.apply(this, arguments) || this; 2603 } 2604 var _proto2 = Context.prototype; 2605 _proto2.init = function init(ctx, blocks, env) { 2606 var _this4 = this; 2607 // Has to be tied to an environment so we can tap into its globals. 2608 this.env = env || new Environment(); 2609 2610 // Make a duplicate of ctx 2611 this.ctx = lib.extend({}, ctx); 2612 this.blocks = {}; 2613 this.exported = []; 2614 lib.keys(blocks).forEach(function (name) { 2615 _this4.addBlock(name, blocks[name]); 2616 }); 2617 }; 2618 _proto2.lookup = function lookup(name) { 2619 // This is one of the most called functions, so optimize for 2620 // the typical case where the name isn't in the globals 2621 if (name in this.env.globals && !(name in this.ctx)) { 2622 return this.env.globals[name]; 2623 } else { 2624 return this.ctx[name]; 2625 } 2626 }; 2627 _proto2.setVariable = function setVariable(name, val) { 2628 this.ctx[name] = val; 2629 }; 2630 _proto2.getVariables = function getVariables() { 2631 return this.ctx; 2632 }; 2633 _proto2.addBlock = function addBlock(name, block) { 2634 this.blocks[name] = this.blocks[name] || []; 2635 this.blocks[name].push(block); 2636 return this; 2637 }; 2638 _proto2.getBlock = function getBlock(name) { 2639 if (!this.blocks[name]) { 2640 throw new Error('unknown block "' + name + '"'); 2641 } 2642 return this.blocks[name][0]; 2643 }; 2644 _proto2.getSuper = function getSuper(env, name, block, frame, runtime, cb) { 2645 var idx = lib.indexOf(this.blocks[name] || [], block); 2646 var blk = this.blocks[name][idx + 1]; 2647 var context = this; 2648 if (idx === -1 || !blk) { 2649 throw new Error('no super block available for "' + name + '"'); 2650 } 2651 blk(env, context, frame, runtime, cb); 2652 }; 2653 _proto2.addExport = function addExport(name) { 2654 this.exported.push(name); 2655 }; 2656 _proto2.getExported = function getExported() { 2657 var _this5 = this; 2658 var exported = {}; 2659 this.exported.forEach(function (name) { 2660 exported[name] = _this5.ctx[name]; 2661 }); 2662 return exported; 2663 }; 2664 return Context; 2665}(Obj); 2666var Template = /*#__PURE__*/function (_Obj2) { 2667 _inheritsLoose(Template, _Obj2); 2668 function Template() { 2669 return _Obj2.apply(this, arguments) || this; 2670 } 2671 var _proto3 = Template.prototype; 2672 _proto3.init = function init(src, env, path, eagerCompile) { 2673 this.env = env || new Environment(); 2674 if (lib.isObject(src)) { 2675 switch (src.type) { 2676 case 'code': 2677 this.tmplProps = src.obj; 2678 break; 2679 case 'string': 2680 this.tmplStr = src.obj; 2681 break; 2682 default: 2683 throw new Error("Unexpected template object type " + src.type + "; expected 'code', or 'string'"); 2684 } 2685 } else if (lib.isString(src)) { 2686 this.tmplStr = src; 2687 } else { 2688 throw new Error('src must be a string or an object describing the source'); 2689 } 2690 this.path = path; 2691 if (eagerCompile) { 2692 try { 2693 this._compile(); 2694 } catch (err) { 2695 throw lib._prettifyError(this.path, this.env.opts.dev, err); 2696 } 2697 } else { 2698 this.compiled = false; 2699 } 2700 }; 2701 _proto3.render = function render(ctx, parentFrame, cb) { 2702 var _this6 = this; 2703 if (typeof ctx === 'function') { 2704 cb = ctx; 2705 ctx = {}; 2706 } else if (typeof parentFrame === 'function') { 2707 cb = parentFrame; 2708 parentFrame = null; 2709 } 2710 2711 // If there is a parent frame, we are being called from internal 2712 // code of another template, and the internal system 2713 // depends on the sync/async nature of the parent template 2714 // to be inherited, so force an async callback 2715 var forceAsync = !parentFrame; 2716 2717 // Catch compile errors for async rendering 2718 try { 2719 this.compile(); 2720 } catch (e) { 2721 var err = lib._prettifyError(this.path, this.env.opts.dev, e); 2722 if (cb) { 2723 return callbackAsap(cb, err); 2724 } else { 2725 throw err; 2726 } 2727 } 2728 var context = new Context(ctx || {}, this.blocks, this.env); 2729 var frame = parentFrame ? parentFrame.push(true) : new Frame(); 2730 frame.topLevel = true; 2731 var syncResult = null; 2732 var didError = false; 2733 this.rootRenderFunc(this.env, context, frame, globalRuntime, function (err, res) { 2734 // TODO: this is actually a bug in the compiled template (because waterfall 2735 // tasks are both not passing errors up the chain of callbacks AND are not 2736 // causing a return from the top-most render function). But fixing that 2737 // will require a more substantial change to the compiler. 2738 if (didError && cb && typeof res !== 'undefined') { 2739 // prevent multiple calls to cb 2740 return; 2741 } 2742 if (err) { 2743 err = lib._prettifyError(_this6.path, _this6.env.opts.dev, err); 2744 didError = true; 2745 } 2746 if (cb) { 2747 if (forceAsync) { 2748 callbackAsap(cb, err, res); 2749 } else { 2750 cb(err, res); 2751 } 2752 } else { 2753 if (err) { 2754 throw err; 2755 } 2756 syncResult = res; 2757 } 2758 }); 2759 return syncResult; 2760 }; 2761 _proto3.getExported = function getExported(ctx, parentFrame, cb) { 2762 // eslint-disable-line consistent-return 2763 if (typeof ctx === 'function') { 2764 cb = ctx; 2765 ctx = {}; 2766 } 2767 if (typeof parentFrame === 'function') { 2768 cb = parentFrame; 2769 parentFrame = null; 2770 } 2771 2772 // Catch compile errors for async rendering 2773 try { 2774 this.compile(); 2775 } catch (e) { 2776 if (cb) { 2777 return cb(e); 2778 } else { 2779 throw e; 2780 } 2781 } 2782 var frame = parentFrame ? parentFrame.push() : new Frame(); 2783 frame.topLevel = true; 2784 2785 // Run the rootRenderFunc to populate the context with exported vars 2786 var context = new Context(ctx || {}, this.blocks, this.env); 2787 this.rootRenderFunc(this.env, context, frame, globalRuntime, function (err) { 2788 if (err) { 2789 cb(err, null); 2790 } else { 2791 cb(null, context.getExported()); 2792 } 2793 }); 2794 }; 2795 _proto3.compile = function compile() { 2796 if (!this.compiled) { 2797 this._compile(); 2798 } 2799 }; 2800 _proto3._compile = function _compile() { 2801 var props; 2802 if (this.tmplProps) { 2803 props = this.tmplProps; 2804 } else { 2805 var source = compiler.compile(this.tmplStr, this.env.asyncFilters, this.env.extensionsList, this.path, this.env.opts); 2806 var func = new Function(source); // eslint-disable-line no-new-func 2807 props = func(); 2808 } 2809 this.blocks = this._getBlocks(props); 2810 this.rootRenderFunc = props.root; 2811 this.compiled = true; 2812 }; 2813 _proto3._getBlocks = function _getBlocks(props) { 2814 var blocks = {}; 2815 lib.keys(props).forEach(function (k) { 2816 if (k.slice(0, 2) === 'b_') { 2817 blocks[k.slice(2)] = props[k]; 2818 } 2819 }); 2820 return blocks; 2821 }; 2822 return Template; 2823}(Obj); 2824module.exports = { 2825 Environment: Environment, 2826 Template: Template 2827}; 2828 2829/***/ }), 2830/* 8 */ 2831/***/ (function(module, exports, __webpack_require__) { 2832 2833"use strict"; 2834 2835 2836function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } 2837function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 2838var lexer = __webpack_require__(9); 2839var nodes = __webpack_require__(3); 2840var Obj = __webpack_require__(1).Obj; 2841var lib = __webpack_require__(0); 2842var Parser = /*#__PURE__*/function (_Obj) { 2843 _inheritsLoose(Parser, _Obj); 2844 function Parser() { 2845 return _Obj.apply(this, arguments) || this; 2846 } 2847 var _proto = Parser.prototype; 2848 _proto.init = function init(tokens) { 2849 this.tokens = tokens; 2850 this.peeked = null; 2851 this.breakOnBlocks = null; 2852 this.dropLeadingWhitespace = false; 2853 this.extensions = []; 2854 }; 2855 _proto.nextToken = function nextToken(withWhitespace) { 2856 var tok; 2857 if (this.peeked) { 2858 if (!withWhitespace && this.peeked.type === lexer.TOKEN_WHITESPACE) { 2859 this.peeked = null; 2860 } else { 2861 tok = this.peeked; 2862 this.peeked = null; 2863 return tok; 2864 } 2865 } 2866 tok = this.tokens.nextToken(); 2867 if (!withWhitespace) { 2868 while (tok && tok.type === lexer.TOKEN_WHITESPACE) { 2869 tok = this.tokens.nextToken(); 2870 } 2871 } 2872 return tok; 2873 }; 2874 _proto.peekToken = function peekToken() { 2875 this.peeked = this.peeked || this.nextToken(); 2876 return this.peeked; 2877 }; 2878 _proto.pushToken = function pushToken(tok) { 2879 if (this.peeked) { 2880 throw new Error('pushToken: can only push one token on between reads'); 2881 } 2882 this.peeked = tok; 2883 }; 2884 _proto.error = function error(msg, lineno, colno) { 2885 if (lineno === undefined || colno === undefined) { 2886 var tok = this.peekToken() || {}; 2887 lineno = tok.lineno; 2888 colno = tok.colno; 2889 } 2890 if (lineno !== undefined) { 2891 lineno += 1; 2892 } 2893 if (colno !== undefined) { 2894 colno += 1; 2895 } 2896 return new lib.TemplateError(msg, lineno, colno); 2897 }; 2898 _proto.fail = function fail(msg, lineno, colno) { 2899 throw this.error(msg, lineno, colno); 2900 }; 2901 _proto.skip = function skip(type) { 2902 var tok = this.nextToken(); 2903 if (!tok || tok.type !== type) { 2904 this.pushToken(tok); 2905 return false; 2906 } 2907 return true; 2908 }; 2909 _proto.expect = function expect(type) { 2910 var tok = this.nextToken(); 2911 if (tok.type !== type) { 2912 this.fail('expected ' + type + ', got ' + tok.type, tok.lineno, tok.colno); 2913 } 2914 return tok; 2915 }; 2916 _proto.skipValue = function skipValue(type, val) { 2917 var tok = this.nextToken(); 2918 if (!tok || tok.type !== type || tok.value !== val) { 2919 this.pushToken(tok); 2920 return false; 2921 } 2922 return true; 2923 }; 2924 _proto.skipSymbol = function skipSymbol(val) { 2925 return this.skipValue(lexer.TOKEN_SYMBOL, val); 2926 }; 2927 _proto.advanceAfterBlockEnd = function advanceAfterBlockEnd(name) { 2928 var tok; 2929 if (!name) { 2930 tok = this.peekToken(); 2931 if (!tok) { 2932 this.fail('unexpected end of file'); 2933 } 2934 if (tok.type !== lexer.TOKEN_SYMBOL) { 2935 this.fail('advanceAfterBlockEnd: expected symbol token or ' + 'explicit name to be passed'); 2936 } 2937 name = this.nextToken().value; 2938 } 2939 tok = this.nextToken(); 2940 if (tok && tok.type === lexer.TOKEN_BLOCK_END) { 2941 if (tok.value.charAt(0) === '-') { 2942 this.dropLeadingWhitespace = true; 2943 } 2944 } else { 2945 this.fail('expected block end in ' + name + ' statement'); 2946 } 2947 return tok; 2948 }; 2949 _proto.advanceAfterVariableEnd = function advanceAfterVariableEnd() { 2950 var tok = this.nextToken(); 2951 if (tok && tok.type === lexer.TOKEN_VARIABLE_END) { 2952 this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.VARIABLE_END.length - 1) === '-'; 2953 } else { 2954 this.pushToken(tok); 2955 this.fail('expected variable end'); 2956 } 2957 }; 2958 _proto.parseFor = function parseFor() { 2959 var forTok = this.peekToken(); 2960 var node; 2961 var endBlock; 2962 if (this.skipSymbol('for')) { 2963 node = new nodes.For(forTok.lineno, forTok.colno); 2964 endBlock = 'endfor'; 2965 } else if (this.skipSymbol('asyncEach')) { 2966 node = new nodes.AsyncEach(forTok.lineno, forTok.colno); 2967 endBlock = 'endeach'; 2968 } else if (this.skipSymbol('asyncAll')) { 2969 node = new nodes.AsyncAll(forTok.lineno, forTok.colno); 2970 endBlock = 'endall'; 2971 } else { 2972 this.fail('parseFor: expected for{Async}', forTok.lineno, forTok.colno); 2973 } 2974 node.name = this.parsePrimary(); 2975 if (!(node.name instanceof nodes.Symbol)) { 2976 this.fail('parseFor: variable name expected for loop'); 2977 } 2978 var type = this.peekToken().type; 2979 if (type === lexer.TOKEN_COMMA) { 2980 // key/value iteration 2981 var key = node.name; 2982 node.name = new nodes.Array(key.lineno, key.colno); 2983 node.name.addChild(key); 2984 while (this.skip(lexer.TOKEN_COMMA)) { 2985 var prim = this.parsePrimary(); 2986 node.name.addChild(prim); 2987 } 2988 } 2989 if (!this.skipSymbol('in')) { 2990 this.fail('parseFor: expected "in" keyword for loop', forTok.lineno, forTok.colno); 2991 } 2992 node.arr = this.parseExpression(); 2993 this.advanceAfterBlockEnd(forTok.value); 2994 node.body = this.parseUntilBlocks(endBlock, 'else'); 2995 if (this.skipSymbol('else')) { 2996 this.advanceAfterBlockEnd('else'); 2997 node.else_ = this.parseUntilBlocks(endBlock); 2998 } 2999 this.advanceAfterBlockEnd(); 3000 return node; 3001 }; 3002 _proto.parseMacro = function parseMacro() { 3003 var macroTok = this.peekToken(); 3004 if (!this.skipSymbol('macro')) { 3005 this.fail('expected macro'); 3006 } 3007 var name = this.parsePrimary(true); 3008 var args = this.parseSignature(); 3009 var node = new nodes.Macro(macroTok.lineno, macroTok.colno, name, args); 3010 this.advanceAfterBlockEnd(macroTok.value); 3011 node.body = this.parseUntilBlocks('endmacro'); 3012 this.advanceAfterBlockEnd(); 3013 return node; 3014 }; 3015 _proto.parseCall = function parseCall() { 3016 // a call block is parsed as a normal FunCall, but with an added 3017 // 'caller' kwarg which is a Caller node. 3018 var callTok = this.peekToken(); 3019 if (!this.skipSymbol('call')) { 3020 this.fail('expected call'); 3021 } 3022 var callerArgs = this.parseSignature(true) || new nodes.NodeList(); 3023 var macroCall = this.parsePrimary(); 3024 this.advanceAfterBlockEnd(callTok.value); 3025 var body = this.parseUntilBlocks('endcall'); 3026 this.advanceAfterBlockEnd(); 3027 var callerName = new nodes.Symbol(callTok.lineno, callTok.colno, 'caller'); 3028 var callerNode = new nodes.Caller(callTok.lineno, callTok.colno, callerName, callerArgs, body); 3029 3030 // add the additional caller kwarg, adding kwargs if necessary 3031 var args = macroCall.args.children; 3032 if (!(args[args.length - 1] instanceof nodes.KeywordArgs)) { 3033 args.push(new nodes.KeywordArgs()); 3034 } 3035 var kwargs = args[args.length - 1]; 3036 kwargs.addChild(new nodes.Pair(callTok.lineno, callTok.colno, callerName, callerNode)); 3037 return new nodes.Output(callTok.lineno, callTok.colno, [macroCall]); 3038 }; 3039 _proto.parseWithContext = function parseWithContext() { 3040 var tok = this.peekToken(); 3041 var withContext = null; 3042 if (this.skipSymbol('with')) { 3043 withContext = true; 3044 } else if (this.skipSymbol('without')) { 3045 withContext = false; 3046 } 3047 if (withContext !== null) { 3048 if (!this.skipSymbol('context')) { 3049 this.fail('parseFrom: expected context after with/without', tok.lineno, tok.colno); 3050 } 3051 } 3052 return withContext; 3053 }; 3054 _proto.parseImport = function parseImport() { 3055 var importTok = this.peekToken(); 3056 if (!this.skipSymbol('import')) { 3057 this.fail('parseImport: expected import', importTok.lineno, importTok.colno); 3058 } 3059 var template = this.parseExpression(); 3060 if (!this.skipSymbol('as')) { 3061 this.fail('parseImport: expected "as" keyword', importTok.lineno, importTok.colno); 3062 } 3063 var target = this.parseExpression(); 3064 var withContext = this.parseWithContext(); 3065 var node = new nodes.Import(importTok.lineno, importTok.colno, template, target, withContext); 3066 this.advanceAfterBlockEnd(importTok.value); 3067 return node; 3068 }; 3069 _proto.parseFrom = function parseFrom() { 3070 var fromTok = this.peekToken(); 3071 if (!this.skipSymbol('from')) { 3072 this.fail('parseFrom: expected from'); 3073 } 3074 var template = this.parseExpression(); 3075 if (!this.skipSymbol('import')) { 3076 this.fail('parseFrom: expected import', fromTok.lineno, fromTok.colno); 3077 } 3078 var names = new nodes.NodeList(); 3079 var withContext; 3080 while (1) { 3081 // eslint-disable-line no-constant-condition 3082 var nextTok = this.peekToken(); 3083 if (nextTok.type === lexer.TOKEN_BLOCK_END) { 3084 if (!names.children.length) { 3085 this.fail('parseFrom: Expected at least one import name', fromTok.lineno, fromTok.colno); 3086 } 3087 3088 // Since we are manually advancing past the block end, 3089 // need to keep track of whitespace control (normally 3090 // this is done in `advanceAfterBlockEnd` 3091 if (nextTok.value.charAt(0) === '-') { 3092 this.dropLeadingWhitespace = true; 3093 } 3094 this.nextToken(); 3095 break; 3096 } 3097 if (names.children.length > 0 && !this.skip(lexer.TOKEN_COMMA)) { 3098 this.fail('parseFrom: expected comma', fromTok.lineno, fromTok.colno); 3099 } 3100 var name = this.parsePrimary(); 3101 if (name.value.charAt(0) === '_') { 3102 this.fail('parseFrom: names starting with an underscore cannot be imported', name.lineno, name.colno); 3103 } 3104 if (this.skipSymbol('as')) { 3105 var alias = this.parsePrimary(); 3106 names.addChild(new nodes.Pair(name.lineno, name.colno, name, alias)); 3107 } else { 3108 names.addChild(name); 3109 } 3110 withContext = this.parseWithContext(); 3111 } 3112 return new nodes.FromImport(fromTok.lineno, fromTok.colno, template, names, withContext); 3113 }; 3114 _proto.parseBlock = function parseBlock() { 3115 var tag = this.peekToken(); 3116 if (!this.skipSymbol('block')) { 3117 this.fail('parseBlock: expected block', tag.lineno, tag.colno); 3118 } 3119 var node = new nodes.Block(tag.lineno, tag.colno); 3120 node.name = this.parsePrimary(); 3121 if (!(node.name instanceof nodes.Symbol)) { 3122 this.fail('parseBlock: variable name expected', tag.lineno, tag.colno); 3123 } 3124 this.advanceAfterBlockEnd(tag.value); 3125 node.body = this.parseUntilBlocks('endblock'); 3126 this.skipSymbol('endblock'); 3127 this.skipSymbol(node.name.value); 3128 var tok = this.peekToken(); 3129 if (!tok) { 3130 this.fail('parseBlock: expected endblock, got end of file'); 3131 } 3132 this.advanceAfterBlockEnd(tok.value); 3133 return node; 3134 }; 3135 _proto.parseExtends = function parseExtends() { 3136 var tagName = 'extends'; 3137 var tag = this.peekToken(); 3138 if (!this.skipSymbol(tagName)) { 3139 this.fail('parseTemplateRef: expected ' + tagName); 3140 } 3141 var node = new nodes.Extends(tag.lineno, tag.colno); 3142 node.template = this.parseExpression(); 3143 this.advanceAfterBlockEnd(tag.value); 3144 return node; 3145 }; 3146 _proto.parseInclude = function parseInclude() { 3147 var tagName = 'include'; 3148 var tag = this.peekToken(); 3149 if (!this.skipSymbol(tagName)) { 3150 this.fail('parseInclude: expected ' + tagName); 3151 } 3152 var node = new nodes.Include(tag.lineno, tag.colno); 3153 node.template = this.parseExpression(); 3154 if (this.skipSymbol('ignore') && this.skipSymbol('missing')) { 3155 node.ignoreMissing = true; 3156 } 3157 this.advanceAfterBlockEnd(tag.value); 3158 return node; 3159 }; 3160 _proto.parseIf = function parseIf() { 3161 var tag = this.peekToken(); 3162 var node; 3163 if (this.skipSymbol('if') || this.skipSymbol('elif') || this.skipSymbol('elseif')) { 3164 node = new nodes.If(tag.lineno, tag.colno); 3165 } else if (this.skipSymbol('ifAsync')) { 3166 node = new nodes.IfAsync(tag.lineno, tag.colno); 3167 } else { 3168 this.fail('parseIf: expected if, elif, or elseif', tag.lineno, tag.colno); 3169 } 3170 node.cond = this.parseExpression(); 3171 this.advanceAfterBlockEnd(tag.value); 3172 node.body = this.parseUntilBlocks('elif', 'elseif', 'else', 'endif'); 3173 var tok = this.peekToken(); 3174 switch (tok && tok.value) { 3175 case 'elseif': 3176 case 'elif': 3177 node.else_ = this.parseIf(); 3178 break; 3179 case 'else': 3180 this.advanceAfterBlockEnd(); 3181 node.else_ = this.parseUntilBlocks('endif'); 3182 this.advanceAfterBlockEnd(); 3183 break; 3184 case 'endif': 3185 node.else_ = null; 3186 this.advanceAfterBlockEnd(); 3187 break; 3188 default: 3189 this.fail('parseIf: expected elif, else, or endif, got end of file'); 3190 } 3191 return node; 3192 }; 3193 _proto.parseSet = function parseSet() { 3194 var tag = this.peekToken(); 3195 if (!this.skipSymbol('set')) { 3196 this.fail('parseSet: expected set', tag.lineno, tag.colno); 3197 } 3198 var node = new nodes.Set(tag.lineno, tag.colno, []); 3199 var target; 3200 while (target = this.parsePrimary()) { 3201 node.targets.push(target); 3202 if (!this.skip(lexer.TOKEN_COMMA)) { 3203 break; 3204 } 3205 } 3206 if (!this.skipValue(lexer.TOKEN_OPERATOR, '=')) { 3207 if (!this.skip(lexer.TOKEN_BLOCK_END)) { 3208 this.fail('parseSet: expected = or block end in set tag', tag.lineno, tag.colno); 3209 } else { 3210 node.body = new nodes.Capture(tag.lineno, tag.colno, this.parseUntilBlocks('endset')); 3211 node.value = null; 3212 this.advanceAfterBlockEnd(); 3213 } 3214 } else { 3215 node.value = this.parseExpression(); 3216 this.advanceAfterBlockEnd(tag.value); 3217 } 3218 return node; 3219 }; 3220 _proto.parseSwitch = function parseSwitch() { 3221 /* 3222 * Store the tag names in variables in case someone ever wants to 3223 * customize this. 3224 */ 3225 var switchStart = 'switch'; 3226 var switchEnd = 'endswitch'; 3227 var caseStart = 'case'; 3228 var caseDefault = 'default'; 3229 3230 // Get the switch tag. 3231 var tag = this.peekToken(); 3232 3233 // fail early if we get some unexpected tag. 3234 if (!this.skipSymbol(switchStart) && !this.skipSymbol(caseStart) && !this.skipSymbol(caseDefault)) { 3235 this.fail('parseSwitch: expected "switch," "case" or "default"', tag.lineno, tag.colno); 3236 } 3237 3238 // parse the switch expression 3239 var expr = this.parseExpression(); 3240 3241 // advance until a start of a case, a default case or an endswitch. 3242 this.advanceAfterBlockEnd(switchStart); 3243 this.parseUntilBlocks(caseStart, caseDefault, switchEnd); 3244 3245 // this is the first case. it could also be an endswitch, we'll check. 3246 var tok = this.peekToken(); 3247 3248 // create new variables for our cases and default case. 3249 var cases = []; 3250 var defaultCase; 3251 3252 // while we're dealing with new cases nodes... 3253 do { 3254 // skip the start symbol and get the case expression 3255 this.skipSymbol(caseStart); 3256 var cond = this.parseExpression(); 3257 this.advanceAfterBlockEnd(switchStart); 3258 // get the body of the case node and add it to the array of cases. 3259 var body = this.parseUntilBlocks(caseStart, caseDefault, switchEnd); 3260 cases.push(new nodes.Case(tok.line, tok.col, cond, body)); 3261 // get our next case 3262 tok = this.peekToken(); 3263 } while (tok && tok.value === caseStart); 3264 3265 // we either have a default case or a switch end. 3266 switch (tok.value) { 3267 case caseDefault: 3268 this.advanceAfterBlockEnd(); 3269 defaultCase = this.parseUntilBlocks(switchEnd); 3270 this.advanceAfterBlockEnd(); 3271 break; 3272 case switchEnd: 3273 this.advanceAfterBlockEnd(); 3274 break; 3275 default: 3276 // otherwise bail because EOF 3277 this.fail('parseSwitch: expected "case," "default" or "endswitch," got EOF.'); 3278 } 3279 3280 // and return the switch node. 3281 return new nodes.Switch(tag.lineno, tag.colno, expr, cases, defaultCase); 3282 }; 3283 _proto.parseStatement = function parseStatement() { 3284 var tok = this.peekToken(); 3285 var node; 3286 if (tok.type !== lexer.TOKEN_SYMBOL) { 3287 this.fail('tag name expected', tok.lineno, tok.colno); 3288 } 3289 if (this.breakOnBlocks && lib.indexOf(this.breakOnBlocks, tok.value) !== -1) { 3290 return null; 3291 } 3292 switch (tok.value) { 3293 case 'raw': 3294 return this.parseRaw(); 3295 case 'verbatim': 3296 return this.parseRaw('verbatim'); 3297 case 'if': 3298 case 'ifAsync': 3299 return this.parseIf(); 3300 case 'for': 3301 case 'asyncEach': 3302 case 'asyncAll': 3303 return this.parseFor(); 3304 case 'block': 3305 return this.parseBlock(); 3306 case 'extends': 3307 return this.parseExtends(); 3308 case 'include': 3309 return this.parseInclude(); 3310 case 'set': 3311 return this.parseSet(); 3312 case 'macro': 3313 return this.parseMacro(); 3314 case 'call': 3315 return this.parseCall(); 3316 case 'import': 3317 return this.parseImport(); 3318 case 'from': 3319 return this.parseFrom(); 3320 case 'filter': 3321 return this.parseFilterStatement(); 3322 case 'switch': 3323 return this.parseSwitch(); 3324 default: 3325 if (this.extensions.length) { 3326 for (var i = 0; i < this.extensions.length; i++) { 3327 var ext = this.extensions[i]; 3328 if (lib.indexOf(ext.tags || [], tok.value) !== -1) { 3329 return ext.parse(this, nodes, lexer); 3330 } 3331 } 3332 } 3333 this.fail('unknown block tag: ' + tok.value, tok.lineno, tok.colno); 3334 } 3335 return node; 3336 }; 3337 _proto.parseRaw = function parseRaw(tagName) { 3338 tagName = tagName || 'raw'; 3339 var endTagName = 'end' + tagName; 3340 // Look for upcoming raw blocks (ignore all other kinds of blocks) 3341 var rawBlockRegex = new RegExp('([\\s\\S]*?){%\\s*(' + tagName + '|' + endTagName + ')\\s*(?=%})%}'); 3342 var rawLevel = 1; 3343 var str = ''; 3344 var matches = null; 3345 3346 // Skip opening raw token 3347 // Keep this token to track line and column numbers 3348 var begun = this.advanceAfterBlockEnd(); 3349 3350 // Exit when there's nothing to match 3351 // or when we've found the matching "endraw" block 3352 while ((matches = this.tokens._extractRegex(rawBlockRegex)) && rawLevel > 0) { 3353 var all = matches[0]; 3354 var pre = matches[1]; 3355 var blockName = matches[2]; 3356 3357 // Adjust rawlevel 3358 if (blockName === tagName) { 3359 rawLevel += 1; 3360 } else if (blockName === endTagName) { 3361 rawLevel -= 1; 3362 } 3363 3364 // Add to str 3365 if (rawLevel === 0) { 3366 // We want to exclude the last "endraw" 3367 str += pre; 3368 // Move tokenizer to beginning of endraw block 3369 this.tokens.backN(all.length - pre.length); 3370 } else { 3371 str += all; 3372 } 3373 } 3374 return new nodes.Output(begun.lineno, begun.colno, [new nodes.TemplateData(begun.lineno, begun.colno, str)]); 3375 }; 3376 _proto.parsePostfix = function parsePostfix(node) { 3377 var lookup; 3378 var tok = this.peekToken(); 3379 while (tok) { 3380 if (tok.type === lexer.TOKEN_LEFT_PAREN) { 3381 // Function call 3382 node = new nodes.FunCall(tok.lineno, tok.colno, node, this.parseSignature()); 3383 } else if (tok.type === lexer.TOKEN_LEFT_BRACKET) { 3384 // Reference 3385 lookup = this.parseAggregate(); 3386 if (lookup.children.length > 1) { 3387 this.fail('invalid index'); 3388 } 3389 node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup.children[0]); 3390 } else if (tok.type === lexer.TOKEN_OPERATOR && tok.value === '.') { 3391 // Reference 3392 this.nextToken(); 3393 var val = this.nextToken(); 3394 if (val.type !== lexer.TOKEN_SYMBOL) { 3395 this.fail('expected name as lookup value, got ' + val.value, val.lineno, val.colno); 3396 } 3397 3398 // Make a literal string because it's not a variable 3399 // reference 3400 lookup = new nodes.Literal(val.lineno, val.colno, val.value); 3401 node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup); 3402 } else { 3403 break; 3404 } 3405 tok = this.peekToken(); 3406 } 3407 return node; 3408 }; 3409 _proto.parseExpression = function parseExpression() { 3410 var node = this.parseInlineIf(); 3411 return node; 3412 }; 3413 _proto.parseInlineIf = function parseInlineIf() { 3414 var node = this.parseOr(); 3415 if (this.skipSymbol('if')) { 3416 var condNode = this.parseOr(); 3417 var bodyNode = node; 3418 node = new nodes.InlineIf(node.lineno, node.colno); 3419 node.body = bodyNode; 3420 node.cond = condNode; 3421 if (this.skipSymbol('else')) { 3422 node.else_ = this.parseOr(); 3423 } else { 3424 node.else_ = null; 3425 } 3426 } 3427 return node; 3428 }; 3429 _proto.parseOr = function parseOr() { 3430 var node = this.parseAnd(); 3431 while (this.skipSymbol('or')) { 3432 var node2 = this.parseAnd(); 3433 node = new nodes.Or(node.lineno, node.colno, node, node2); 3434 } 3435 return node; 3436 }; 3437 _proto.parseAnd = function parseAnd() { 3438 var node = this.parseNot(); 3439 while (this.skipSymbol('and')) { 3440 var node2 = this.parseNot(); 3441 node = new nodes.And(node.lineno, node.colno, node, node2); 3442 } 3443 return node; 3444 }; 3445 _proto.parseNot = function parseNot() { 3446 var tok = this.peekToken(); 3447 if (this.skipSymbol('not')) { 3448 return new nodes.Not(tok.lineno, tok.colno, this.parseNot()); 3449 } 3450 return this.parseIn(); 3451 }; 3452 _proto.parseIn = function parseIn() { 3453 var node = this.parseIs(); 3454 while (1) { 3455 // eslint-disable-line no-constant-condition 3456 // check if the next token is 'not' 3457 var tok = this.nextToken(); 3458 if (!tok) { 3459 break; 3460 } 3461 var invert = tok.type === lexer.TOKEN_SYMBOL && tok.value === 'not'; 3462 // if it wasn't 'not', put it back 3463 if (!invert) { 3464 this.pushToken(tok); 3465 } 3466 if (this.skipSymbol('in')) { 3467 var node2 = this.parseIs(); 3468 node = new nodes.In(node.lineno, node.colno, node, node2); 3469 if (invert) { 3470 node = new nodes.Not(node.lineno, node.colno, node); 3471 } 3472 } else { 3473 // if we'd found a 'not' but this wasn't an 'in', put back the 'not' 3474 if (invert) { 3475 this.pushToken(tok); 3476 } 3477 break; 3478 } 3479 } 3480 return node; 3481 } 3482 3483 // I put this right after "in" in the operator precedence stack. That can 3484 // obviously be changed to be closer to Jinja. 3485 ; 3486 _proto.parseIs = function parseIs() { 3487 var node = this.parseCompare(); 3488 // look for an is 3489 if (this.skipSymbol('is')) { 3490 // look for a not 3491 var not = this.skipSymbol('not'); 3492 // get the next node 3493 var node2 = this.parseCompare(); 3494 // create an Is node using the next node and the info from our Is node. 3495 node = new nodes.Is(node.lineno, node.colno, node, node2); 3496 // if we have a Not, create a Not node from our Is node. 3497 if (not) { 3498 node = new nodes.Not(node.lineno, node.colno, node); 3499 } 3500 } 3501 // return the node. 3502 return node; 3503 }; 3504 _proto.parseCompare = function parseCompare() { 3505 var compareOps = ['==', '===', '!=', '!==', '<', '>', '<=', '>=']; 3506 var expr = this.parseConcat(); 3507 var ops = []; 3508 while (1) { 3509 // eslint-disable-line no-constant-condition 3510 var tok = this.nextToken(); 3511 if (!tok) { 3512 break; 3513 } else if (compareOps.indexOf(tok.value) !== -1) { 3514 ops.push(new nodes.CompareOperand(tok.lineno, tok.colno, this.parseConcat(), tok.value)); 3515 } else { 3516 this.pushToken(tok); 3517 break; 3518 } 3519 } 3520 if (ops.length) { 3521 return new nodes.Compare(ops[0].lineno, ops[0].colno, expr, ops); 3522 } else { 3523 return expr; 3524 } 3525 } 3526 3527 // finds the '~' for string concatenation 3528 ; 3529 _proto.parseConcat = function parseConcat() { 3530 var node = this.parseAdd(); 3531 while (this.skipValue(lexer.TOKEN_TILDE, '~')) { 3532 var node2 = this.parseAdd(); 3533 node = new nodes.Concat(node.lineno, node.colno, node, node2); 3534 } 3535 return node; 3536 }; 3537 _proto.parseAdd = function parseAdd() { 3538 var node = this.parseSub(); 3539 while (this.skipValue(lexer.TOKEN_OPERATOR, '+')) { 3540 var node2 = this.parseSub(); 3541 node = new nodes.Add(node.lineno, node.colno, node, node2); 3542 } 3543 return node; 3544 }; 3545 _proto.parseSub = function parseSub() { 3546 var node = this.parseMul(); 3547 while (this.skipValue(lexer.TOKEN_OPERATOR, '-')) { 3548 var node2 = this.parseMul(); 3549 node = new nodes.Sub(node.lineno, node.colno, node, node2); 3550 } 3551 return node; 3552 }; 3553 _proto.parseMul = function parseMul() { 3554 var node = this.parseDiv(); 3555 while (this.skipValue(lexer.TOKEN_OPERATOR, '*')) { 3556 var node2 = this.parseDiv(); 3557 node = new nodes.Mul(node.lineno, node.colno, node, node2); 3558 } 3559 return node; 3560 }; 3561 _proto.parseDiv = function parseDiv() { 3562 var node = this.parseFloorDiv(); 3563 while (this.skipValue(lexer.TOKEN_OPERATOR, '/')) { 3564 var node2 = this.parseFloorDiv(); 3565 node = new nodes.Div(node.lineno, node.colno, node, node2); 3566 } 3567 return node; 3568 }; 3569 _proto.parseFloorDiv = function parseFloorDiv() { 3570 var node = this.parseMod(); 3571 while (this.skipValue(lexer.TOKEN_OPERATOR, '//')) { 3572 var node2 = this.parseMod(); 3573 node = new nodes.FloorDiv(node.lineno, node.colno, node, node2); 3574 } 3575 return node; 3576 }; 3577 _proto.parseMod = function parseMod() { 3578 var node = this.parsePow(); 3579 while (this.skipValue(lexer.TOKEN_OPERATOR, '%')) { 3580 var node2 = this.parsePow(); 3581 node = new nodes.Mod(node.lineno, node.colno, node, node2); 3582 } 3583 return node; 3584 }; 3585 _proto.parsePow = function parsePow() { 3586 var node = this.parseUnary(); 3587 while (this.skipValue(lexer.TOKEN_OPERATOR, '**')) { 3588 var node2 = this.parseUnary(); 3589 node = new nodes.Pow(node.lineno, node.colno, node, node2); 3590 } 3591 return node; 3592 }; 3593 _proto.parseUnary = function parseUnary(noFilters) { 3594 var tok = this.peekToken(); 3595 var node; 3596 if (this.skipValue(lexer.TOKEN_OPERATOR, '-')) { 3597 node = new nodes.Neg(tok.lineno, tok.colno, this.parseUnary(true)); 3598 } else if (this.skipValue(lexer.TOKEN_OPERATOR, '+')) { 3599 node = new nodes.Pos(tok.lineno, tok.colno, this.parseUnary(true)); 3600 } else { 3601 node = this.parsePrimary(); 3602 } 3603 if (!noFilters) { 3604 node = this.parseFilter(node); 3605 } 3606 return node; 3607 }; 3608 _proto.parsePrimary = function parsePrimary(noPostfix) { 3609 var tok = this.nextToken(); 3610 var val; 3611 var node = null; 3612 if (!tok) { 3613 this.fail('expected expression, got end of file'); 3614 } else if (tok.type === lexer.TOKEN_STRING) { 3615 val = tok.value; 3616 } else if (tok.type === lexer.TOKEN_INT) { 3617 val = parseInt(tok.value, 10); 3618 } else if (tok.type === lexer.TOKEN_FLOAT) { 3619 val = parseFloat(tok.value); 3620 } else if (tok.type === lexer.TOKEN_BOOLEAN) { 3621 if (tok.value === 'true') { 3622 val = true; 3623 } else if (tok.value === 'false') { 3624 val = false; 3625 } else { 3626 this.fail('invalid boolean: ' + tok.value, tok.lineno, tok.colno); 3627 } 3628 } else if (tok.type === lexer.TOKEN_NONE) { 3629 val = null; 3630 } else if (tok.type === lexer.TOKEN_REGEX) { 3631 val = new RegExp(tok.value.body, tok.value.flags); 3632 } 3633 if (val !== undefined) { 3634 node = new nodes.Literal(tok.lineno, tok.colno, val); 3635 } else if (tok.type === lexer.TOKEN_SYMBOL) { 3636 node = new nodes.Symbol(tok.lineno, tok.colno, tok.value); 3637 } else { 3638 // See if it's an aggregate type, we need to push the 3639 // current delimiter token back on 3640 this.pushToken(tok); 3641 node = this.parseAggregate(); 3642 } 3643 if (!noPostfix) { 3644 node = this.parsePostfix(node); 3645 } 3646 if (node) { 3647 return node; 3648 } else { 3649 throw this.error("unexpected token: " + tok.value, tok.lineno, tok.colno); 3650 } 3651 }; 3652 _proto.parseFilterName = function parseFilterName() { 3653 var tok = this.expect(lexer.TOKEN_SYMBOL); 3654 var name = tok.value; 3655 while (this.skipValue(lexer.TOKEN_OPERATOR, '.')) { 3656 name += '.' + this.expect(lexer.TOKEN_SYMBOL).value; 3657 } 3658 return new nodes.Symbol(tok.lineno, tok.colno, name); 3659 }; 3660 _proto.parseFilterArgs = function parseFilterArgs(node) { 3661 if (this.peekToken().type === lexer.TOKEN_LEFT_PAREN) { 3662 // Get a FunCall node and add the parameters to the 3663 // filter 3664 var call = this.parsePostfix(node); 3665 return call.args.children; 3666 } 3667 return []; 3668 }; 3669 _proto.parseFilter = function parseFilter(node) { 3670 while (this.skip(lexer.TOKEN_PIPE)) { 3671 var name = this.parseFilterName(); 3672 node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [node].concat(this.parseFilterArgs(node)))); 3673 } 3674 return node; 3675 }; 3676 _proto.parseFilterStatement = function parseFilterStatement() { 3677 var filterTok = this.peekToken(); 3678 if (!this.skipSymbol('filter')) { 3679 this.fail('parseFilterStatement: expected filter'); 3680 } 3681 var name = this.parseFilterName(); 3682 var args = this.parseFilterArgs(name); 3683 this.advanceAfterBlockEnd(filterTok.value); 3684 var body = new nodes.Capture(name.lineno, name.colno, this.parseUntilBlocks('endfilter')); 3685 this.advanceAfterBlockEnd(); 3686 var node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [body].concat(args))); 3687 return new nodes.Output(name.lineno, name.colno, [node]); 3688 }; 3689 _proto.parseAggregate = function parseAggregate() { 3690 var tok = this.nextToken(); 3691 var node; 3692 switch (tok.type) { 3693 case lexer.TOKEN_LEFT_PAREN: 3694 node = new nodes.Group(tok.lineno, tok.colno); 3695 break; 3696 case lexer.TOKEN_LEFT_BRACKET: 3697 node = new nodes.Array(tok.lineno, tok.colno); 3698 break; 3699 case lexer.TOKEN_LEFT_CURLY: 3700 node = new nodes.Dict(tok.lineno, tok.colno); 3701 break; 3702 default: 3703 return null; 3704 } 3705 while (1) { 3706 // eslint-disable-line no-constant-condition 3707 var type = this.peekToken().type; 3708 if (type === lexer.TOKEN_RIGHT_PAREN || type === lexer.TOKEN_RIGHT_BRACKET || type === lexer.TOKEN_RIGHT_CURLY) { 3709 this.nextToken(); 3710 break; 3711 } 3712 if (node.children.length > 0) { 3713 if (!this.skip(lexer.TOKEN_COMMA)) { 3714 this.fail('parseAggregate: expected comma after expression', tok.lineno, tok.colno); 3715 } 3716 } 3717 if (node instanceof nodes.Dict) { 3718 // TODO: check for errors 3719 var key = this.parsePrimary(); 3720 3721 // We expect a key/value pair for dicts, separated by a 3722 // colon 3723 if (!this.skip(lexer.TOKEN_COLON)) { 3724 this.fail('parseAggregate: expected colon after dict key', tok.lineno, tok.colno); 3725 } 3726 3727 // TODO: check for errors 3728 var value = this.parseExpression(); 3729 node.addChild(new nodes.Pair(key.lineno, key.colno, key, value)); 3730 } else { 3731 // TODO: check for errors 3732 var expr = this.parseExpression(); 3733 node.addChild(expr); 3734 } 3735 } 3736 return node; 3737 }; 3738 _proto.parseSignature = function parseSignature(tolerant, noParens) { 3739 var tok = this.peekToken(); 3740 if (!noParens && tok.type !== lexer.TOKEN_LEFT_PAREN) { 3741 if (tolerant) { 3742 return null; 3743 } else { 3744 this.fail('expected arguments', tok.lineno, tok.colno); 3745 } 3746 } 3747 if (tok.type === lexer.TOKEN_LEFT_PAREN) { 3748 tok = this.nextToken(); 3749 } 3750 var args = new nodes.NodeList(tok.lineno, tok.colno); 3751 var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno); 3752 var checkComma = false; 3753 while (1) { 3754 // eslint-disable-line no-constant-condition 3755 tok = this.peekToken(); 3756 if (!noParens && tok.type === lexer.TOKEN_RIGHT_PAREN) { 3757 this.nextToken(); 3758 break; 3759 } else if (noParens && tok.type === lexer.TOKEN_BLOCK_END) { 3760 break; 3761 } 3762 if (checkComma && !this.skip(lexer.TOKEN_COMMA)) { 3763 this.fail('parseSignature: expected comma after expression', tok.lineno, tok.colno); 3764 } else { 3765 var arg = this.parseExpression(); 3766 if (this.skipValue(lexer.TOKEN_OPERATOR, '=')) { 3767 kwargs.addChild(new nodes.Pair(arg.lineno, arg.colno, arg, this.parseExpression())); 3768 } else { 3769 args.addChild(arg); 3770 } 3771 } 3772 checkComma = true; 3773 } 3774 if (kwargs.children.length) { 3775 args.addChild(kwargs); 3776 } 3777 return args; 3778 }; 3779 _proto.parseUntilBlocks = function parseUntilBlocks() { 3780 var prev = this.breakOnBlocks; 3781 for (var _len = arguments.length, blockNames = new Array(_len), _key = 0; _key < _len; _key++) { 3782 blockNames[_key] = arguments[_key]; 3783 } 3784 this.breakOnBlocks = blockNames; 3785 var ret = this.parse(); 3786 this.breakOnBlocks = prev; 3787 return ret; 3788 }; 3789 _proto.parseNodes = function parseNodes() { 3790 var tok; 3791 var buf = []; 3792 while (tok = this.nextToken()) { 3793 if (tok.type === lexer.TOKEN_DATA) { 3794 var data = tok.value; 3795 var nextToken = this.peekToken(); 3796 var nextVal = nextToken && nextToken.value; 3797 3798 // If the last token has "-" we need to trim the 3799 // leading whitespace of the data. This is marked with 3800 // the `dropLeadingWhitespace` variable. 3801 if (this.dropLeadingWhitespace) { 3802 // TODO: this could be optimized (don't use regex) 3803 data = data.replace(/^\s*/, ''); 3804 this.dropLeadingWhitespace = false; 3805 } 3806 3807 // Same for the succeeding block start token 3808 if (nextToken && (nextToken.type === lexer.TOKEN_BLOCK_START && nextVal.charAt(nextVal.length - 1) === '-' || nextToken.type === lexer.TOKEN_VARIABLE_START && nextVal.charAt(this.tokens.tags.VARIABLE_START.length) === '-' || nextToken.type === lexer.TOKEN_COMMENT && nextVal.charAt(this.tokens.tags.COMMENT_START.length) === '-')) { 3809 // TODO: this could be optimized (don't use regex) 3810 data = data.replace(/\s*$/, ''); 3811 } 3812 buf.push(new nodes.Output(tok.lineno, tok.colno, [new nodes.TemplateData(tok.lineno, tok.colno, data)])); 3813 } else if (tok.type === lexer.TOKEN_BLOCK_START) { 3814 this.dropLeadingWhitespace = false; 3815 var n = this.parseStatement(); 3816 if (!n) { 3817 break; 3818 } 3819 buf.push(n); 3820 } else if (tok.type === lexer.TOKEN_VARIABLE_START) { 3821 var e = this.parseExpression(); 3822 this.dropLeadingWhitespace = false; 3823 this.advanceAfterVariableEnd(); 3824 buf.push(new nodes.Output(tok.lineno, tok.colno, [e])); 3825 } else if (tok.type === lexer.TOKEN_COMMENT) { 3826 this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.COMMENT_END.length - 1) === '-'; 3827 } else { 3828 // Ignore comments, otherwise this should be an error 3829 this.fail('Unexpected token at top-level: ' + tok.type, tok.lineno, tok.colno); 3830 } 3831 } 3832 return buf; 3833 }; 3834 _proto.parse = function parse() { 3835 return new nodes.NodeList(0, 0, this.parseNodes()); 3836 }; 3837 _proto.parseAsRoot = function parseAsRoot() { 3838 return new nodes.Root(0, 0, this.parseNodes()); 3839 }; 3840 return Parser; 3841}(Obj); // var util = require('util'); 3842// var l = lexer.lex('{%- if x -%}\n hello {% endif %}'); 3843// var t; 3844// while((t = l.nextToken())) { 3845// console.log(util.inspect(t)); 3846// } 3847// var p = new Parser(lexer.lex('hello {% filter title %}' + 3848// 'Hello madam how are you' + 3849// '{% endfilter %}')); 3850// var n = p.parseAsRoot(); 3851// nodes.printNodes(n); 3852module.exports = { 3853 parse: function parse(src, extensions, opts) { 3854 var p = new Parser(lexer.lex(src, opts)); 3855 if (extensions !== undefined) { 3856 p.extensions = extensions; 3857 } 3858 return p.parseAsRoot(); 3859 }, 3860 Parser: Parser 3861}; 3862 3863/***/ }), 3864/* 9 */ 3865/***/ (function(module, exports, __webpack_require__) { 3866 3867"use strict"; 3868 3869 3870var lib = __webpack_require__(0); 3871var whitespaceChars = " \n\t\r\xA0"; 3872var delimChars = '()[]{}%*-+~/#,:|.<>=!'; 3873var intChars = '0123456789'; 3874var BLOCK_START = '{%'; 3875var BLOCK_END = '%}'; 3876var VARIABLE_START = '{{'; 3877var VARIABLE_END = '}}'; 3878var COMMENT_START = '{#'; 3879var COMMENT_END = '#}'; 3880var TOKEN_STRING = 'string'; 3881var TOKEN_WHITESPACE = 'whitespace'; 3882var TOKEN_DATA = 'data'; 3883var TOKEN_BLOCK_START = 'block-start'; 3884var TOKEN_BLOCK_END = 'block-end'; 3885var TOKEN_VARIABLE_START = 'variable-start'; 3886var TOKEN_VARIABLE_END = 'variable-end'; 3887var TOKEN_COMMENT = 'comment'; 3888var TOKEN_LEFT_PAREN = 'left-paren'; 3889var TOKEN_RIGHT_PAREN = 'right-paren'; 3890var TOKEN_LEFT_BRACKET = 'left-bracket'; 3891var TOKEN_RIGHT_BRACKET = 'right-bracket'; 3892var TOKEN_LEFT_CURLY = 'left-curly'; 3893var TOKEN_RIGHT_CURLY = 'right-curly'; 3894var TOKEN_OPERATOR = 'operator'; 3895var TOKEN_COMMA = 'comma'; 3896var TOKEN_COLON = 'colon'; 3897var TOKEN_TILDE = 'tilde'; 3898var TOKEN_PIPE = 'pipe'; 3899var TOKEN_INT = 'int'; 3900var TOKEN_FLOAT = 'float'; 3901var TOKEN_BOOLEAN = 'boolean'; 3902var TOKEN_NONE = 'none'; 3903var TOKEN_SYMBOL = 'symbol'; 3904var TOKEN_SPECIAL = 'special'; 3905var TOKEN_REGEX = 'regex'; 3906function token(type, value, lineno, colno) { 3907 return { 3908 type: type, 3909 value: value, 3910 lineno: lineno, 3911 colno: colno 3912 }; 3913} 3914var Tokenizer = /*#__PURE__*/function () { 3915 function Tokenizer(str, opts) { 3916 this.str = str; 3917 this.index = 0; 3918 this.len = str.length; 3919 this.lineno = 0; 3920 this.colno = 0; 3921 this.in_code = false; 3922 opts = opts || {}; 3923 var tags = opts.tags || {}; 3924 this.tags = { 3925 BLOCK_START: tags.blockStart || BLOCK_START, 3926 BLOCK_END: tags.blockEnd || BLOCK_END, 3927 VARIABLE_START: tags.variableStart || VARIABLE_START, 3928 VARIABLE_END: tags.variableEnd || VARIABLE_END, 3929 COMMENT_START: tags.commentStart || COMMENT_START, 3930 COMMENT_END: tags.commentEnd || COMMENT_END 3931 }; 3932 this.trimBlocks = !!opts.trimBlocks; 3933 this.lstripBlocks = !!opts.lstripBlocks; 3934 } 3935 var _proto = Tokenizer.prototype; 3936 _proto.nextToken = function nextToken() { 3937 var lineno = this.lineno; 3938 var colno = this.colno; 3939 var tok; 3940 if (this.in_code) { 3941 // Otherwise, if we are in a block parse it as code 3942 var cur = this.current(); 3943 if (this.isFinished()) { 3944 // We have nothing else to parse 3945 return null; 3946 } else if (cur === '"' || cur === '\'') { 3947 // We've hit a string 3948 return token(TOKEN_STRING, this._parseString(cur), lineno, colno); 3949 } else if (tok = this._extract(whitespaceChars)) { 3950 // We hit some whitespace 3951 return token(TOKEN_WHITESPACE, tok, lineno, colno); 3952 } else if ((tok = this._extractString(this.tags.BLOCK_END)) || (tok = this._extractString('-' + this.tags.BLOCK_END))) { 3953 // Special check for the block end tag 3954 // 3955 // It is a requirement that start and end tags are composed of 3956 // delimiter characters (%{}[] etc), and our code always 3957 // breaks on delimiters so we can assume the token parsing 3958 // doesn't consume these elsewhere 3959 this.in_code = false; 3960 if (this.trimBlocks) { 3961 cur = this.current(); 3962 if (cur === '\n') { 3963 // Skip newline 3964 this.forward(); 3965 } else if (cur === '\r') { 3966 // Skip CRLF newline 3967 this.forward(); 3968 cur = this.current(); 3969 if (cur === '\n') { 3970 this.forward(); 3971 } else { 3972 // Was not a CRLF, so go back 3973 this.back(); 3974 } 3975 } 3976 } 3977 return token(TOKEN_BLOCK_END, tok, lineno, colno); 3978 } else if ((tok = this._extractString(this.tags.VARIABLE_END)) || (tok = this._extractString('-' + this.tags.VARIABLE_END))) { 3979 // Special check for variable end tag (see above) 3980 this.in_code = false; 3981 return token(TOKEN_VARIABLE_END, tok, lineno, colno); 3982 } else if (cur === 'r' && this.str.charAt(this.index + 1) === '/') { 3983 // Skip past 'r/'. 3984 this.forwardN(2); 3985 3986 // Extract until the end of the regex -- / ends it, \/ does not. 3987 var regexBody = ''; 3988 while (!this.isFinished()) { 3989 if (this.current() === '/' && this.previous() !== '\\') { 3990 this.forward(); 3991 break; 3992 } else { 3993 regexBody += this.current(); 3994 this.forward(); 3995 } 3996 } 3997 3998 // Check for flags. 3999 // The possible flags are according to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) 4000 var POSSIBLE_FLAGS = ['g', 'i', 'm', 'y']; 4001 var regexFlags = ''; 4002 while (!this.isFinished()) { 4003 var isCurrentAFlag = POSSIBLE_FLAGS.indexOf(this.current()) !== -1; 4004 if (isCurrentAFlag) { 4005 regexFlags += this.current(); 4006 this.forward(); 4007 } else { 4008 break; 4009 } 4010 } 4011 return token(TOKEN_REGEX, { 4012 body: regexBody, 4013 flags: regexFlags 4014 }, lineno, colno); 4015 } else if (delimChars.indexOf(cur) !== -1) { 4016 // We've hit a delimiter (a special char like a bracket) 4017 this.forward(); 4018 var complexOps = ['==', '===', '!=', '!==', '<=', '>=', '//', '**']; 4019 var curComplex = cur + this.current(); 4020 var type; 4021 if (lib.indexOf(complexOps, curComplex) !== -1) { 4022 this.forward(); 4023 cur = curComplex; 4024 4025 // See if this is a strict equality/inequality comparator 4026 if (lib.indexOf(complexOps, curComplex + this.current()) !== -1) { 4027 cur = curComplex + this.current(); 4028 this.forward(); 4029 } 4030 } 4031 switch (cur) { 4032 case '(': 4033 type = TOKEN_LEFT_PAREN; 4034 break; 4035 case ')': 4036 type = TOKEN_RIGHT_PAREN; 4037 break; 4038 case '[': 4039 type = TOKEN_LEFT_BRACKET; 4040 break; 4041 case ']': 4042 type = TOKEN_RIGHT_BRACKET; 4043 break; 4044 case '{': 4045 type = TOKEN_LEFT_CURLY; 4046 break; 4047 case '}': 4048 type = TOKEN_RIGHT_CURLY; 4049 break; 4050 case ',': 4051 type = TOKEN_COMMA; 4052 break; 4053 case ':': 4054 type = TOKEN_COLON; 4055 break; 4056 case '~': 4057 type = TOKEN_TILDE; 4058 break; 4059 case '|': 4060 type = TOKEN_PIPE; 4061 break; 4062 default: 4063 type = TOKEN_OPERATOR; 4064 } 4065 return token(type, cur, lineno, colno); 4066 } else { 4067 // We are not at whitespace or a delimiter, so extract the 4068 // text and parse it 4069 tok = this._extractUntil(whitespaceChars + delimChars); 4070 if (tok.match(/^[-+]?[0-9]+$/)) { 4071 if (this.current() === '.') { 4072 this.forward(); 4073 var dec = this._extract(intChars); 4074 return token(TOKEN_FLOAT, tok + '.' + dec, lineno, colno); 4075 } else { 4076 return token(TOKEN_INT, tok, lineno, colno); 4077 } 4078 } else if (tok.match(/^(true|false)$/)) { 4079 return token(TOKEN_BOOLEAN, tok, lineno, colno); 4080 } else if (tok === 'none') { 4081 return token(TOKEN_NONE, tok, lineno, colno); 4082 /* 4083 * Added to make the test `null is null` evaluate truthily. 4084 * Otherwise, Nunjucks will look up null in the context and 4085 * return `undefined`, which is not what we want. This *may* have 4086 * consequences is someone is using null in their templates as a 4087 * variable. 4088 */ 4089 } else if (tok === 'null') { 4090 return token(TOKEN_NONE, tok, lineno, colno); 4091 } else if (tok) { 4092 return token(TOKEN_SYMBOL, tok, lineno, colno); 4093 } else { 4094 throw new Error('Unexpected value while parsing: ' + tok); 4095 } 4096 } 4097 } else { 4098 // Parse out the template text, breaking on tag 4099 // delimiters because we need to look for block/variable start 4100 // tags (don't use the full delimChars for optimization) 4101 var beginChars = this.tags.BLOCK_START.charAt(0) + this.tags.VARIABLE_START.charAt(0) + this.tags.COMMENT_START.charAt(0) + this.tags.COMMENT_END.charAt(0); 4102 if (this.isFinished()) { 4103 return null; 4104 } else if ((tok = this._extractString(this.tags.BLOCK_START + '-')) || (tok = this._extractString(this.tags.BLOCK_START))) { 4105 this.in_code = true; 4106 return token(TOKEN_BLOCK_START, tok, lineno, colno); 4107 } else if ((tok = this._extractString(this.tags.VARIABLE_START + '-')) || (tok = this._extractString(this.tags.VARIABLE_START))) { 4108 this.in_code = true; 4109 return token(TOKEN_VARIABLE_START, tok, lineno, colno); 4110 } else { 4111 tok = ''; 4112 var data; 4113 var inComment = false; 4114 if (this._matches(this.tags.COMMENT_START)) { 4115 inComment = true; 4116 tok = this._extractString(this.tags.COMMENT_START); 4117 } 4118 4119 // Continually consume text, breaking on the tag delimiter 4120 // characters and checking to see if it's a start tag. 4121 // 4122 // We could hit the end of the template in the middle of 4123 // our looping, so check for the null return value from 4124 // _extractUntil 4125 while ((data = this._extractUntil(beginChars)) !== null) { 4126 tok += data; 4127 if ((this._matches(this.tags.BLOCK_START) || this._matches(this.tags.VARIABLE_START) || this._matches(this.tags.COMMENT_START)) && !inComment) { 4128 if (this.lstripBlocks && this._matches(this.tags.BLOCK_START) && this.colno > 0 && this.colno <= tok.length) { 4129 var lastLine = tok.slice(-this.colno); 4130 if (/^\s+$/.test(lastLine)) { 4131 // Remove block leading whitespace from beginning of the string 4132 tok = tok.slice(0, -this.colno); 4133 if (!tok.length) { 4134 // All data removed, collapse to avoid unnecessary nodes 4135 // by returning next token (block start) 4136 return this.nextToken(); 4137 } 4138 } 4139 } 4140 // If it is a start tag, stop looping 4141 break; 4142 } else if (this._matches(this.tags.COMMENT_END)) { 4143 if (!inComment) { 4144 throw new Error('unexpected end of comment'); 4145 } 4146 tok += this._extractString(this.tags.COMMENT_END); 4147 break; 4148 } else { 4149 // It does not match any tag, so add the character and 4150 // carry on 4151 tok += this.current(); 4152 this.forward(); 4153 } 4154 } 4155 if (data === null && inComment) { 4156 throw new Error('expected end of comment, got end of file'); 4157 } 4158 return token(inComment ? TOKEN_COMMENT : TOKEN_DATA, tok, lineno, colno); 4159 } 4160 } 4161 }; 4162 _proto._parseString = function _parseString(delimiter) { 4163 this.forward(); 4164 var str = ''; 4165 while (!this.isFinished() && this.current() !== delimiter) { 4166 var cur = this.current(); 4167 if (cur === '\\') { 4168 this.forward(); 4169 switch (this.current()) { 4170 case 'n': 4171 str += '\n'; 4172 break; 4173 case 't': 4174 str += '\t'; 4175 break; 4176 case 'r': 4177 str += '\r'; 4178 break; 4179 default: 4180 str += this.current(); 4181 } 4182 this.forward(); 4183 } else { 4184 str += cur; 4185 this.forward(); 4186 } 4187 } 4188 this.forward(); 4189 return str; 4190 }; 4191 _proto._matches = function _matches(str) { 4192 if (this.index + str.length > this.len) { 4193 return null; 4194 } 4195 var m = this.str.slice(this.index, this.index + str.length); 4196 return m === str; 4197 }; 4198 _proto._extractString = function _extractString(str) { 4199 if (this._matches(str)) { 4200 this.forwardN(str.length); 4201 return str; 4202 } 4203 return null; 4204 }; 4205 _proto._extractUntil = function _extractUntil(charString) { 4206 // Extract all non-matching chars, with the default matching set 4207 // to everything 4208 return this._extractMatching(true, charString || ''); 4209 }; 4210 _proto._extract = function _extract(charString) { 4211 // Extract all matching chars (no default, so charString must be 4212 // explicit) 4213 return this._extractMatching(false, charString); 4214 }; 4215 _proto._extractMatching = function _extractMatching(breakOnMatch, charString) { 4216 // Pull out characters until a breaking char is hit. 4217 // If breakOnMatch is false, a non-matching char stops it. 4218 // If breakOnMatch is true, a matching char stops it. 4219 4220 if (this.isFinished()) { 4221 return null; 4222 } 4223 var first = charString.indexOf(this.current()); 4224 4225 // Only proceed if the first character doesn't meet our condition 4226 if (breakOnMatch && first === -1 || !breakOnMatch && first !== -1) { 4227 var t = this.current(); 4228 this.forward(); 4229 4230 // And pull out all the chars one at a time until we hit a 4231 // breaking char 4232 var idx = charString.indexOf(this.current()); 4233 while ((breakOnMatch && idx === -1 || !breakOnMatch && idx !== -1) && !this.isFinished()) { 4234 t += this.current(); 4235 this.forward(); 4236 idx = charString.indexOf(this.current()); 4237 } 4238 return t; 4239 } 4240 return ''; 4241 }; 4242 _proto._extractRegex = function _extractRegex(regex) { 4243 var matches = this.currentStr().match(regex); 4244 if (!matches) { 4245 return null; 4246 } 4247 4248 // Move forward whatever was matched 4249 this.forwardN(matches[0].length); 4250 return matches; 4251 }; 4252 _proto.isFinished = function isFinished() { 4253 return this.index >= this.len; 4254 }; 4255 _proto.forwardN = function forwardN(n) { 4256 for (var i = 0; i < n; i++) { 4257 this.forward(); 4258 } 4259 }; 4260 _proto.forward = function forward() { 4261 this.index++; 4262 if (this.previous() === '\n') { 4263 this.lineno++; 4264 this.colno = 0; 4265 } else { 4266 this.colno++; 4267 } 4268 }; 4269 _proto.backN = function backN(n) { 4270 for (var i = 0; i < n; i++) { 4271 this.back(); 4272 } 4273 }; 4274 _proto.back = function back() { 4275 this.index--; 4276 if (this.current() === '\n') { 4277 this.lineno--; 4278 var idx = this.src.lastIndexOf('\n', this.index - 1); 4279 if (idx === -1) { 4280 this.colno = this.index; 4281 } else { 4282 this.colno = this.index - idx; 4283 } 4284 } else { 4285 this.colno--; 4286 } 4287 } 4288 4289 // current returns current character 4290 ; 4291 _proto.current = function current() { 4292 if (!this.isFinished()) { 4293 return this.str.charAt(this.index); 4294 } 4295 return ''; 4296 } 4297 4298 // currentStr returns what's left of the unparsed string 4299 ; 4300 _proto.currentStr = function currentStr() { 4301 if (!this.isFinished()) { 4302 return this.str.substr(this.index); 4303 } 4304 return ''; 4305 }; 4306 _proto.previous = function previous() { 4307 return this.str.charAt(this.index - 1); 4308 }; 4309 return Tokenizer; 4310}(); 4311module.exports = { 4312 lex: function lex(src, opts) { 4313 return new Tokenizer(src, opts); 4314 }, 4315 TOKEN_STRING: TOKEN_STRING, 4316 TOKEN_WHITESPACE: TOKEN_WHITESPACE, 4317 TOKEN_DATA: TOKEN_DATA, 4318 TOKEN_BLOCK_START: TOKEN_BLOCK_START, 4319 TOKEN_BLOCK_END: TOKEN_BLOCK_END, 4320 TOKEN_VARIABLE_START: TOKEN_VARIABLE_START, 4321 TOKEN_VARIABLE_END: TOKEN_VARIABLE_END, 4322 TOKEN_COMMENT: TOKEN_COMMENT, 4323 TOKEN_LEFT_PAREN: TOKEN_LEFT_PAREN, 4324 TOKEN_RIGHT_PAREN: TOKEN_RIGHT_PAREN, 4325 TOKEN_LEFT_BRACKET: TOKEN_LEFT_BRACKET, 4326 TOKEN_RIGHT_BRACKET: TOKEN_RIGHT_BRACKET, 4327 TOKEN_LEFT_CURLY: TOKEN_LEFT_CURLY, 4328 TOKEN_RIGHT_CURLY: TOKEN_RIGHT_CURLY, 4329 TOKEN_OPERATOR: TOKEN_OPERATOR, 4330 TOKEN_COMMA: TOKEN_COMMA, 4331 TOKEN_COLON: TOKEN_COLON, 4332 TOKEN_TILDE: TOKEN_TILDE, 4333 TOKEN_PIPE: TOKEN_PIPE, 4334 TOKEN_INT: TOKEN_INT, 4335 TOKEN_FLOAT: TOKEN_FLOAT, 4336 TOKEN_BOOLEAN: TOKEN_BOOLEAN, 4337 TOKEN_NONE: TOKEN_NONE, 4338 TOKEN_SYMBOL: TOKEN_SYMBOL, 4339 TOKEN_SPECIAL: TOKEN_SPECIAL, 4340 TOKEN_REGEX: TOKEN_REGEX 4341}; 4342 4343/***/ }), 4344/* 10 */ 4345/***/ (function(module, exports, __webpack_require__) { 4346 4347"use strict"; 4348 4349 4350function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } 4351function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 4352var Loader = __webpack_require__(6); 4353var _require = __webpack_require__(19), 4354 PrecompiledLoader = _require.PrecompiledLoader; 4355var WebLoader = /*#__PURE__*/function (_Loader) { 4356 _inheritsLoose(WebLoader, _Loader); 4357 function WebLoader(baseURL, opts) { 4358 var _this; 4359 _this = _Loader.call(this) || this; 4360 _this.baseURL = baseURL || '.'; 4361 opts = opts || {}; 4362 4363 // By default, the cache is turned off because there's no way 4364 // to "watch" templates over HTTP, so they are re-downloaded 4365 // and compiled each time. (Remember, PRECOMPILE YOUR 4366 // TEMPLATES in production!) 4367 _this.useCache = !!opts.useCache; 4368 4369 // We default `async` to false so that the simple synchronous 4370 // API can be used when you aren't doing anything async in 4371 // your templates (which is most of the time). This performs a 4372 // sync ajax request, but that's ok because it should *only* 4373 // happen in development. PRECOMPILE YOUR TEMPLATES. 4374 _this.async = !!opts.async; 4375 return _this; 4376 } 4377 var _proto = WebLoader.prototype; 4378 _proto.resolve = function resolve(from, to) { 4379 throw new Error('relative templates not support in the browser yet'); 4380 }; 4381 _proto.getSource = function getSource(name, cb) { 4382 var _this2 = this; 4383 var useCache = this.useCache; 4384 var result; 4385 this.fetch(this.baseURL + '/' + name, function (err, src) { 4386 if (err) { 4387 if (cb) { 4388 cb(err.content); 4389 } else if (err.status === 404) { 4390 result = null; 4391 } else { 4392 throw err.content; 4393 } 4394 } else { 4395 result = { 4396 src: src, 4397 path: name, 4398 noCache: !useCache 4399 }; 4400 _this2.emit('load', name, result); 4401 if (cb) { 4402 cb(null, result); 4403 } 4404 } 4405 }); 4406 4407 // if this WebLoader isn't running asynchronously, the 4408 // fetch above would actually run sync and we'll have a 4409 // result here 4410 return result; 4411 }; 4412 _proto.fetch = function fetch(url, cb) { 4413 // Only in the browser please 4414 if (typeof window === 'undefined') { 4415 throw new Error('WebLoader can only by used in a browser'); 4416 } 4417 var ajax = new XMLHttpRequest(); 4418 var loading = true; 4419 ajax.onreadystatechange = function () { 4420 if (ajax.readyState === 4 && loading) { 4421 loading = false; 4422 if (ajax.status === 0 || ajax.status === 200) { 4423 cb(null, ajax.responseText); 4424 } else { 4425 cb({ 4426 status: ajax.status, 4427 content: ajax.responseText 4428 }); 4429 } 4430 } 4431 }; 4432 url += (url.indexOf('?') === -1 ? '?' : '&') + 's=' + new Date().getTime(); 4433 ajax.open('GET', url, this.async); 4434 ajax.send(); 4435 }; 4436 return WebLoader; 4437}(Loader); 4438module.exports = { 4439 WebLoader: WebLoader, 4440 PrecompiledLoader: PrecompiledLoader 4441}; 4442 4443/***/ }), 4444/* 11 */ 4445/***/ (function(module, exports, __webpack_require__) { 4446 4447"use strict"; 4448 4449 4450var lib = __webpack_require__(0); 4451var _require = __webpack_require__(7), 4452 Environment = _require.Environment, 4453 Template = _require.Template; 4454var Loader = __webpack_require__(6); 4455var loaders = __webpack_require__(10); 4456var precompile = __webpack_require__(23); 4457var compiler = __webpack_require__(5); 4458var parser = __webpack_require__(8); 4459var lexer = __webpack_require__(9); 4460var runtime = __webpack_require__(2); 4461var nodes = __webpack_require__(3); 4462var installJinjaCompat = __webpack_require__(25); 4463 4464// A single instance of an environment, since this is so commonly used 4465var e; 4466function configure(templatesPath, opts) { 4467 opts = opts || {}; 4468 if (lib.isObject(templatesPath)) { 4469 opts = templatesPath; 4470 templatesPath = null; 4471 } 4472 var TemplateLoader; 4473 if (loaders.FileSystemLoader) { 4474 TemplateLoader = new loaders.FileSystemLoader(templatesPath, { 4475 watch: opts.watch, 4476 noCache: opts.noCache 4477 }); 4478 } else if (loaders.WebLoader) { 4479 TemplateLoader = new loaders.WebLoader(templatesPath, { 4480 useCache: opts.web && opts.web.useCache, 4481 async: opts.web && opts.web.async 4482 }); 4483 } 4484 e = new Environment(TemplateLoader, opts); 4485 if (opts && opts.express) { 4486 e.express(opts.express); 4487 } 4488 return e; 4489} 4490module.exports = { 4491 Environment: Environment, 4492 Template: Template, 4493 Loader: Loader, 4494 FileSystemLoader: loaders.FileSystemLoader, 4495 NodeResolveLoader: loaders.NodeResolveLoader, 4496 PrecompiledLoader: loaders.PrecompiledLoader, 4497 WebLoader: loaders.WebLoader, 4498 compiler: compiler, 4499 parser: parser, 4500 lexer: lexer, 4501 runtime: runtime, 4502 lib: lib, 4503 nodes: nodes, 4504 installJinjaCompat: installJinjaCompat, 4505 configure: configure, 4506 reset: function reset() { 4507 e = undefined; 4508 }, 4509 compile: function compile(src, env, path, eagerCompile) { 4510 if (!e) { 4511 configure(); 4512 } 4513 return new Template(src, env, path, eagerCompile); 4514 }, 4515 render: function render(name, ctx, cb) { 4516 if (!e) { 4517 configure(); 4518 } 4519 return e.render(name, ctx, cb); 4520 }, 4521 renderString: function renderString(src, ctx, cb) { 4522 if (!e) { 4523 configure(); 4524 } 4525 return e.renderString(src, ctx, cb); 4526 }, 4527 precompile: precompile ? precompile.precompile : undefined, 4528 precompileString: precompile ? precompile.precompileString : undefined 4529}; 4530 4531/***/ }), 4532/* 12 */ 4533/***/ (function(module, exports, __webpack_require__) { 4534 4535"use strict"; 4536 4537 4538// rawAsap provides everything we need except exception management. 4539var rawAsap = __webpack_require__(13); 4540// RawTasks are recycled to reduce GC churn. 4541var freeTasks = []; 4542// We queue errors to ensure they are thrown in right order (FIFO). 4543// Array-as-queue is good enough here, since we are just dealing with exceptions. 4544var pendingErrors = []; 4545var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); 4546 4547function throwFirstError() { 4548 if (pendingErrors.length) { 4549 throw pendingErrors.shift(); 4550 } 4551} 4552 4553/** 4554 * Calls a task as soon as possible after returning, in its own event, with priority 4555 * over other events like animation, reflow, and repaint. An error thrown from an 4556 * event will not interrupt, nor even substantially slow down the processing of 4557 * other events, but will be rather postponed to a lower priority event. 4558 * @param {{call}} task A callable object, typically a function that takes no 4559 * arguments. 4560 */ 4561module.exports = asap; 4562function asap(task) { 4563 var rawTask; 4564 if (freeTasks.length) { 4565 rawTask = freeTasks.pop(); 4566 } else { 4567 rawTask = new RawTask(); 4568 } 4569 rawTask.task = task; 4570 rawAsap(rawTask); 4571} 4572 4573// We wrap tasks with recyclable task objects. A task object implements 4574// `call`, just like a function. 4575function RawTask() { 4576 this.task = null; 4577} 4578 4579// The sole purpose of wrapping the task is to catch the exception and recycle 4580// the task object after its single use. 4581RawTask.prototype.call = function () { 4582 try { 4583 this.task.call(); 4584 } catch (error) { 4585 if (asap.onerror) { 4586 // This hook exists purely for testing purposes. 4587 // Its name will be periodically randomized to break any code that 4588 // depends on its existence. 4589 asap.onerror(error); 4590 } else { 4591 // In a web browser, exceptions are not fatal. However, to avoid 4592 // slowing down the queue of pending tasks, we rethrow the error in a 4593 // lower priority turn. 4594 pendingErrors.push(error); 4595 requestErrorThrow(); 4596 } 4597 } finally { 4598 this.task = null; 4599 freeTasks[freeTasks.length] = this; 4600 } 4601}; 4602 4603 4604/***/ }), 4605/* 13 */ 4606/***/ (function(module, exports, __webpack_require__) { 4607 4608"use strict"; 4609/* WEBPACK VAR INJECTION */(function(global) { 4610 4611// Use the fastest means possible to execute a task in its own turn, with 4612// priority over other events including IO, animation, reflow, and redraw 4613// events in browsers. 4614// 4615// An exception thrown by a task will permanently interrupt the processing of 4616// subsequent tasks. The higher level `asap` function ensures that if an 4617// exception is thrown by a task, that the task queue will continue flushing as 4618// soon as possible, but if you use `rawAsap` directly, you are responsible to 4619// either ensure that no exceptions are thrown from your task, or to manually 4620// call `rawAsap.requestFlush` if an exception is thrown. 4621module.exports = rawAsap; 4622function rawAsap(task) { 4623 if (!queue.length) { 4624 requestFlush(); 4625 flushing = true; 4626 } 4627 // Equivalent to push, but avoids a function call. 4628 queue[queue.length] = task; 4629} 4630 4631var queue = []; 4632// Once a flush has been requested, no further calls to `requestFlush` are 4633// necessary until the next `flush` completes. 4634var flushing = false; 4635// `requestFlush` is an implementation-specific method that attempts to kick 4636// off a `flush` event as quickly as possible. `flush` will attempt to exhaust 4637// the event queue before yielding to the browser's own event loop. 4638var requestFlush; 4639// The position of the next task to execute in the task queue. This is 4640// preserved between calls to `flush` so that it can be resumed if 4641// a task throws an exception. 4642var index = 0; 4643// If a task schedules additional tasks recursively, the task queue can grow 4644// unbounded. To prevent memory exhaustion, the task queue will periodically 4645// truncate already-completed tasks. 4646var capacity = 1024; 4647 4648// The flush function processes all tasks that have been scheduled with 4649// `rawAsap` unless and until one of those tasks throws an exception. 4650// If a task throws an exception, `flush` ensures that its state will remain 4651// consistent and will resume where it left off when called again. 4652// However, `flush` does not make any arrangements to be called again if an 4653// exception is thrown. 4654function flush() { 4655 while (index < queue.length) { 4656 var currentIndex = index; 4657 // Advance the index before calling the task. This ensures that we will 4658 // begin flushing on the next task the task throws an error. 4659 index = index + 1; 4660 queue[currentIndex].call(); 4661 // Prevent leaking memory for long chains of recursive calls to `asap`. 4662 // If we call `asap` within tasks scheduled by `asap`, the queue will 4663 // grow, but to avoid an O(n) walk for every task we execute, we don't 4664 // shift tasks off the queue after they have been executed. 4665 // Instead, we periodically shift 1024 tasks off the queue. 4666 if (index > capacity) { 4667 // Manually shift all values starting at the index back to the 4668 // beginning of the queue. 4669 for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { 4670 queue[scan] = queue[scan + index]; 4671 } 4672 queue.length -= index; 4673 index = 0; 4674 } 4675 } 4676 queue.length = 0; 4677 index = 0; 4678 flushing = false; 4679} 4680 4681// `requestFlush` is implemented using a strategy based on data collected from 4682// every available SauceLabs Selenium web driver worker at time of writing. 4683// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 4684 4685// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that 4686// have WebKitMutationObserver but not un-prefixed MutationObserver. 4687// Must use `global` or `self` instead of `window` to work in both frames and web 4688// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. 4689 4690/* globals self */ 4691var scope = typeof global !== "undefined" ? global : self; 4692var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; 4693 4694// MutationObservers are desirable because they have high priority and work 4695// reliably everywhere they are implemented. 4696// They are implemented in all modern browsers. 4697// 4698// - Android 4-4.3 4699// - Chrome 26-34 4700// - Firefox 14-29 4701// - Internet Explorer 11 4702// - iPad Safari 6-7.1 4703// - iPhone Safari 7-7.1 4704// - Safari 6-7 4705if (typeof BrowserMutationObserver === "function") { 4706 requestFlush = makeRequestCallFromMutationObserver(flush); 4707 4708// MessageChannels are desirable because they give direct access to the HTML 4709// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera 4710// 11-12, and in web workers in many engines. 4711// Although message channels yield to any queued rendering and IO tasks, they 4712// would be better than imposing the 4ms delay of timers. 4713// However, they do not work reliably in Internet Explorer or Safari. 4714 4715// Internet Explorer 10 is the only browser that has setImmediate but does 4716// not have MutationObservers. 4717// Although setImmediate yields to the browser's renderer, it would be 4718// preferrable to falling back to setTimeout since it does not have 4719// the minimum 4ms penalty. 4720// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and 4721// Desktop to a lesser extent) that renders both setImmediate and 4722// MessageChannel useless for the purposes of ASAP. 4723// https://github.com/kriskowal/q/issues/396 4724 4725// Timers are implemented universally. 4726// We fall back to timers in workers in most engines, and in foreground 4727// contexts in the following browsers. 4728// However, note that even this simple case requires nuances to operate in a 4729// broad spectrum of browsers. 4730// 4731// - Firefox 3-13 4732// - Internet Explorer 6-9 4733// - iPad Safari 4.3 4734// - Lynx 2.8.7 4735} else { 4736 requestFlush = makeRequestCallFromTimer(flush); 4737} 4738 4739// `requestFlush` requests that the high priority event queue be flushed as 4740// soon as possible. 4741// This is useful to prevent an error thrown in a task from stalling the event 4742// queue if the exception handled by Node.js’s 4743// `process.on("uncaughtException")` or by a domain. 4744rawAsap.requestFlush = requestFlush; 4745 4746// To request a high priority event, we induce a mutation observer by toggling 4747// the text of a text node between "1" and "-1". 4748function makeRequestCallFromMutationObserver(callback) { 4749 var toggle = 1; 4750 var observer = new BrowserMutationObserver(callback); 4751 var node = document.createTextNode(""); 4752 observer.observe(node, {characterData: true}); 4753 return function requestCall() { 4754 toggle = -toggle; 4755 node.data = toggle; 4756 }; 4757} 4758 4759// The message channel technique was discovered by Malte Ubl and was the 4760// original foundation for this library. 4761// http://www.nonblocking.io/2011/06/windownexttick.html 4762 4763// Safari 6.0.5 (at least) intermittently fails to create message ports on a 4764// page's first load. Thankfully, this version of Safari supports 4765// MutationObservers, so we don't need to fall back in that case. 4766 4767// function makeRequestCallFromMessageChannel(callback) { 4768// var channel = new MessageChannel(); 4769// channel.port1.onmessage = callback; 4770// return function requestCall() { 4771// channel.port2.postMessage(0); 4772// }; 4773// } 4774 4775// For reasons explained above, we are also unable to use `setImmediate` 4776// under any circumstances. 4777// Even if we were, there is another bug in Internet Explorer 10. 4778// It is not sufficient to assign `setImmediate` to `requestFlush` because 4779// `setImmediate` must be called *by name* and therefore must be wrapped in a 4780// closure. 4781// Never forget. 4782 4783// function makeRequestCallFromSetImmediate(callback) { 4784// return function requestCall() { 4785// setImmediate(callback); 4786// }; 4787// } 4788 4789// Safari 6.0 has a problem where timers will get lost while the user is 4790// scrolling. This problem does not impact ASAP because Safari 6.0 supports 4791// mutation observers, so that implementation is used instead. 4792// However, if we ever elect to use timers in Safari, the prevalent work-around 4793// is to add a scroll event listener that calls for a flush. 4794 4795// `setTimeout` does not call the passed callback if the delay is less than 4796// approximately 7 in web workers in Firefox 8 through 18, and sometimes not 4797// even then. 4798 4799function makeRequestCallFromTimer(callback) { 4800 return function requestCall() { 4801 // We dispatch a timeout with a specified delay of 0 for engines that 4802 // can reliably accommodate that request. This will usually be snapped 4803 // to a 4 milisecond delay, but once we're flushing, there's no delay 4804 // between events. 4805 var timeoutHandle = setTimeout(handleTimer, 0); 4806 // However, since this timer gets frequently dropped in Firefox 4807 // workers, we enlist an interval handle that will try to fire 4808 // an event 20 times per second until it succeeds. 4809 var intervalHandle = setInterval(handleTimer, 50); 4810 4811 function handleTimer() { 4812 // Whichever timer succeeds will cancel both timers and 4813 // execute the callback. 4814 clearTimeout(timeoutHandle); 4815 clearInterval(intervalHandle); 4816 callback(); 4817 } 4818 }; 4819} 4820 4821// This is for `asap.js` only. 4822// Its name will be periodically randomized to break any code that depends on 4823// its existence. 4824rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; 4825 4826// ASAP was originally a nextTick shim included in Q. This was factored out 4827// into this ASAP package. It was later adapted to RSVP which made further 4828// amendments. These decisions, particularly to marginalize MessageChannel and 4829// to capture the MutationObserver implementation in a closure, were integrated 4830// back into ASAP proper. 4831// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js 4832 4833/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(14))) 4834 4835/***/ }), 4836/* 14 */ 4837/***/ (function(module, exports) { 4838 4839var g; 4840 4841// This works in non-strict mode 4842g = (function() { 4843 return this; 4844})(); 4845 4846try { 4847 // This works if eval is allowed (see CSP) 4848 g = g || Function("return this")() || (1,eval)("this"); 4849} catch(e) { 4850 // This works if the window reference is available 4851 if(typeof window === "object") 4852 g = window; 4853} 4854 4855// g can still be undefined, but nothing to do about it... 4856// We return undefined, instead of nothing here, so it's 4857// easier to handle this case. if(!global) { ...} 4858 4859module.exports = g; 4860 4861 4862/***/ }), 4863/* 15 */ 4864/***/ (function(module, exports, __webpack_require__) { 4865 4866var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// MIT license (by Elan Shanker). 4867(function(globals) { 4868 'use strict'; 4869 4870 var executeSync = function(){ 4871 var args = Array.prototype.slice.call(arguments); 4872 if (typeof args[0] === 'function'){ 4873 args[0].apply(null, args.splice(1)); 4874 } 4875 }; 4876 4877 var executeAsync = function(fn){ 4878 if (typeof setImmediate === 'function') { 4879 setImmediate(fn); 4880 } else if (typeof process !== 'undefined' && process.nextTick) { 4881 process.nextTick(fn); 4882 } else { 4883 setTimeout(fn, 0); 4884 } 4885 }; 4886 4887 var makeIterator = function (tasks) { 4888 var makeCallback = function (index) { 4889 var fn = function () { 4890 if (tasks.length) { 4891 tasks[index].apply(null, arguments); 4892 } 4893 return fn.next(); 4894 }; 4895 fn.next = function () { 4896 return (index < tasks.length - 1) ? makeCallback(index + 1): null; 4897 }; 4898 return fn; 4899 }; 4900 return makeCallback(0); 4901 }; 4902 4903 var _isArray = Array.isArray || function(maybeArray){ 4904 return Object.prototype.toString.call(maybeArray) === '[object Array]'; 4905 }; 4906 4907 var waterfall = function (tasks, callback, forceAsync) { 4908 var nextTick = forceAsync ? executeAsync : executeSync; 4909 callback = callback || function () {}; 4910 if (!_isArray(tasks)) { 4911 var err = new Error('First argument to waterfall must be an array of functions'); 4912 return callback(err); 4913 } 4914 if (!tasks.length) { 4915 return callback(); 4916 } 4917 var wrapIterator = function (iterator) { 4918 return function (err) { 4919 if (err) { 4920 callback.apply(null, arguments); 4921 callback = function () {}; 4922 } else { 4923 var args = Array.prototype.slice.call(arguments, 1); 4924 var next = iterator.next(); 4925 if (next) { 4926 args.push(wrapIterator(next)); 4927 } else { 4928 args.push(callback); 4929 } 4930 nextTick(function () { 4931 iterator.apply(null, args); 4932 }); 4933 } 4934 }; 4935 }; 4936 wrapIterator(makeIterator(tasks))(); 4937 }; 4938 4939 if (true) { 4940 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () { 4941 return waterfall; 4942 }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), 4943 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // RequireJS 4944 } else if (typeof module !== 'undefined' && module.exports) { 4945 module.exports = waterfall; // CommonJS 4946 } else { 4947 globals.waterfall = waterfall; // <script> 4948 } 4949})(this); 4950 4951 4952/***/ }), 4953/* 16 */ 4954/***/ (function(module, exports, __webpack_require__) { 4955 4956"use strict"; 4957// Copyright Joyent, Inc. and other Node contributors. 4958// 4959// Permission is hereby granted, free of charge, to any person obtaining a 4960// copy of this software and associated documentation files (the 4961// "Software"), to deal in the Software without restriction, including 4962// without limitation the rights to use, copy, modify, merge, publish, 4963// distribute, sublicense, and/or sell copies of the Software, and to permit 4964// persons to whom the Software is furnished to do so, subject to the 4965// following conditions: 4966// 4967// The above copyright notice and this permission notice shall be included 4968// in all copies or substantial portions of the Software. 4969// 4970// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 4971// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 4972// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 4973// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 4974// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 4975// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 4976// USE OR OTHER DEALINGS IN THE SOFTWARE. 4977 4978 4979 4980var R = typeof Reflect === 'object' ? Reflect : null 4981var ReflectApply = R && typeof R.apply === 'function' 4982 ? R.apply 4983 : function ReflectApply(target, receiver, args) { 4984 return Function.prototype.apply.call(target, receiver, args); 4985 } 4986 4987var ReflectOwnKeys 4988if (R && typeof R.ownKeys === 'function') { 4989 ReflectOwnKeys = R.ownKeys 4990} else if (Object.getOwnPropertySymbols) { 4991 ReflectOwnKeys = function ReflectOwnKeys(target) { 4992 return Object.getOwnPropertyNames(target) 4993 .concat(Object.getOwnPropertySymbols(target)); 4994 }; 4995} else { 4996 ReflectOwnKeys = function ReflectOwnKeys(target) { 4997 return Object.getOwnPropertyNames(target); 4998 }; 4999} 5000 5001function ProcessEmitWarning(warning) { 5002 if (console && console.warn) console.warn(warning); 5003} 5004 5005var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { 5006 return value !== value; 5007} 5008 5009function EventEmitter() { 5010 EventEmitter.init.call(this); 5011} 5012module.exports = EventEmitter; 5013module.exports.once = once; 5014 5015// Backwards-compat with node 0.10.x 5016EventEmitter.EventEmitter = EventEmitter; 5017 5018EventEmitter.prototype._events = undefined; 5019EventEmitter.prototype._eventsCount = 0; 5020EventEmitter.prototype._maxListeners = undefined; 5021 5022// By default EventEmitters will print a warning if more than 10 listeners are 5023// added to it. This is a useful default which helps finding memory leaks. 5024var defaultMaxListeners = 10; 5025 5026function checkListener(listener) { 5027 if (typeof listener !== 'function') { 5028 throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); 5029 } 5030} 5031 5032Object.defineProperty(EventEmitter, 'defaultMaxListeners', { 5033 enumerable: true, 5034 get: function() { 5035 return defaultMaxListeners; 5036 }, 5037 set: function(arg) { 5038 if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { 5039 throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); 5040 } 5041 defaultMaxListeners = arg; 5042 } 5043}); 5044 5045EventEmitter.init = function() { 5046 5047 if (this._events === undefined || 5048 this._events === Object.getPrototypeOf(this)._events) { 5049 this._events = Object.create(null); 5050 this._eventsCount = 0; 5051 } 5052 5053 this._maxListeners = this._maxListeners || undefined; 5054}; 5055 5056// Obviously not all Emitters should be limited to 10. This function allows 5057// that to be increased. Set to zero for unlimited. 5058EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { 5059 if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { 5060 throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); 5061 } 5062 this._maxListeners = n; 5063 return this; 5064}; 5065 5066function _getMaxListeners(that) { 5067 if (that._maxListeners === undefined) 5068 return EventEmitter.defaultMaxListeners; 5069 return that._maxListeners; 5070} 5071 5072EventEmitter.prototype.getMaxListeners = function getMaxListeners() { 5073 return _getMaxListeners(this); 5074}; 5075 5076EventEmitter.prototype.emit = function emit(type) { 5077 var args = []; 5078 for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); 5079 var doError = (type === 'error'); 5080 5081 var events = this._events; 5082 if (events !== undefined) 5083 doError = (doError && events.error === undefined); 5084 else if (!doError) 5085 return false; 5086 5087 // If there is no 'error' event listener then throw. 5088 if (doError) { 5089 var er; 5090 if (args.length > 0) 5091 er = args[0]; 5092 if (er instanceof Error) { 5093 // Note: The comments on the `throw` lines are intentional, they show 5094 // up in Node's output if this results in an unhandled exception. 5095 throw er; // Unhandled 'error' event 5096 } 5097 // At least give some kind of context to the user 5098 var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); 5099 err.context = er; 5100 throw err; // Unhandled 'error' event 5101 } 5102 5103 var handler = events[type]; 5104 5105 if (handler === undefined) 5106 return false; 5107 5108 if (typeof handler === 'function') { 5109 ReflectApply(handler, this, args); 5110 } else { 5111 var len = handler.length; 5112 var listeners = arrayClone(handler, len); 5113 for (var i = 0; i < len; ++i) 5114 ReflectApply(listeners[i], this, args); 5115 } 5116 5117 return true; 5118}; 5119 5120function _addListener(target, type, listener, prepend) { 5121 var m; 5122 var events; 5123 var existing; 5124 5125 checkListener(listener); 5126 5127 events = target._events; 5128 if (events === undefined) { 5129 events = target._events = Object.create(null); 5130 target._eventsCount = 0; 5131 } else { 5132 // To avoid recursion in the case that type === "newListener"! Before 5133 // adding it to the listeners, first emit "newListener". 5134 if (events.newListener !== undefined) { 5135 target.emit('newListener', type, 5136 listener.listener ? listener.listener : listener); 5137 5138 // Re-assign `events` because a newListener handler could have caused the 5139 // this._events to be assigned to a new object 5140 events = target._events; 5141 } 5142 existing = events[type]; 5143 } 5144 5145 if (existing === undefined) { 5146 // Optimize the case of one listener. Don't need the extra array object. 5147 existing = events[type] = listener; 5148 ++target._eventsCount; 5149 } else { 5150 if (typeof existing === 'function') { 5151 // Adding the second element, need to change to array. 5152 existing = events[type] = 5153 prepend ? [listener, existing] : [existing, listener]; 5154 // If we've already got an array, just append. 5155 } else if (prepend) { 5156 existing.unshift(listener); 5157 } else { 5158 existing.push(listener); 5159 } 5160 5161 // Check for listener leak 5162 m = _getMaxListeners(target); 5163 if (m > 0 && existing.length > m && !existing.warned) { 5164 existing.warned = true; 5165 // No error code for this since it is a Warning 5166 // eslint-disable-next-line no-restricted-syntax 5167 var w = new Error('Possible EventEmitter memory leak detected. ' + 5168 existing.length + ' ' + String(type) + ' listeners ' + 5169 'added. Use emitter.setMaxListeners() to ' + 5170 'increase limit'); 5171 w.name = 'MaxListenersExceededWarning'; 5172 w.emitter = target; 5173 w.type = type; 5174 w.count = existing.length; 5175 ProcessEmitWarning(w); 5176 } 5177 } 5178 5179 return target; 5180} 5181 5182EventEmitter.prototype.addListener = function addListener(type, listener) { 5183 return _addListener(this, type, listener, false); 5184}; 5185 5186EventEmitter.prototype.on = EventEmitter.prototype.addListener; 5187 5188EventEmitter.prototype.prependListener = 5189 function prependListener(type, listener) { 5190 return _addListener(this, type, listener, true); 5191 }; 5192 5193function onceWrapper() { 5194 if (!this.fired) { 5195 this.target.removeListener(this.type, this.wrapFn); 5196 this.fired = true; 5197 if (arguments.length === 0) 5198 return this.listener.call(this.target); 5199 return this.listener.apply(this.target, arguments); 5200 } 5201} 5202 5203function _onceWrap(target, type, listener) { 5204 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; 5205 var wrapped = onceWrapper.bind(state); 5206 wrapped.listener = listener; 5207 state.wrapFn = wrapped; 5208 return wrapped; 5209} 5210 5211EventEmitter.prototype.once = function once(type, listener) { 5212 checkListener(listener); 5213 this.on(type, _onceWrap(this, type, listener)); 5214 return this; 5215}; 5216 5217EventEmitter.prototype.prependOnceListener = 5218 function prependOnceListener(type, listener) { 5219 checkListener(listener); 5220 this.prependListener(type, _onceWrap(this, type, listener)); 5221 return this; 5222 }; 5223 5224// Emits a 'removeListener' event if and only if the listener was removed. 5225EventEmitter.prototype.removeListener = 5226 function removeListener(type, listener) { 5227 var list, events, position, i, originalListener; 5228 5229 checkListener(listener); 5230 5231 events = this._events; 5232 if (events === undefined) 5233 return this; 5234 5235 list = events[type]; 5236 if (list === undefined) 5237 return this; 5238 5239 if (list === listener || list.listener === listener) { 5240 if (--this._eventsCount === 0) 5241 this._events = Object.create(null); 5242 else { 5243 delete events[type]; 5244 if (events.removeListener) 5245 this.emit('removeListener', type, list.listener || listener); 5246 } 5247 } else if (typeof list !== 'function') { 5248 position = -1; 5249 5250 for (i = list.length - 1; i >= 0; i--) { 5251 if (list[i] === listener || list[i].listener === listener) { 5252 originalListener = list[i].listener; 5253 position = i; 5254 break; 5255 } 5256 } 5257 5258 if (position < 0) 5259 return this; 5260 5261 if (position === 0) 5262 list.shift(); 5263 else { 5264 spliceOne(list, position); 5265 } 5266 5267 if (list.length === 1) 5268 events[type] = list[0]; 5269 5270 if (events.removeListener !== undefined) 5271 this.emit('removeListener', type, originalListener || listener); 5272 } 5273 5274 return this; 5275 }; 5276 5277EventEmitter.prototype.off = EventEmitter.prototype.removeListener; 5278 5279EventEmitter.prototype.removeAllListeners = 5280 function removeAllListeners(type) { 5281 var listeners, events, i; 5282 5283 events = this._events; 5284 if (events === undefined) 5285 return this; 5286 5287 // not listening for removeListener, no need to emit 5288 if (events.removeListener === undefined) { 5289 if (arguments.length === 0) { 5290 this._events = Object.create(null); 5291 this._eventsCount = 0; 5292 } else if (events[type] !== undefined) { 5293 if (--this._eventsCount === 0) 5294 this._events = Object.create(null); 5295 else 5296 delete events[type]; 5297 } 5298 return this; 5299 } 5300 5301 // emit removeListener for all listeners on all events 5302 if (arguments.length === 0) { 5303 var keys = Object.keys(events); 5304 var key; 5305 for (i = 0; i < keys.length; ++i) { 5306 key = keys[i]; 5307 if (key === 'removeListener') continue; 5308 this.removeAllListeners(key); 5309 } 5310 this.removeAllListeners('removeListener'); 5311 this._events = Object.create(null); 5312 this._eventsCount = 0; 5313 return this; 5314 } 5315 5316 listeners = events[type]; 5317 5318 if (typeof listeners === 'function') { 5319 this.removeListener(type, listeners); 5320 } else if (listeners !== undefined) { 5321 // LIFO order 5322 for (i = listeners.length - 1; i >= 0; i--) { 5323 this.removeListener(type, listeners[i]); 5324 } 5325 } 5326 5327 return this; 5328 }; 5329 5330function _listeners(target, type, unwrap) { 5331 var events = target._events; 5332 5333 if (events === undefined) 5334 return []; 5335 5336 var evlistener = events[type]; 5337 if (evlistener === undefined) 5338 return []; 5339 5340 if (typeof evlistener === 'function') 5341 return unwrap ? [evlistener.listener || evlistener] : [evlistener]; 5342 5343 return unwrap ? 5344 unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); 5345} 5346 5347EventEmitter.prototype.listeners = function listeners(type) { 5348 return _listeners(this, type, true); 5349}; 5350 5351EventEmitter.prototype.rawListeners = function rawListeners(type) { 5352 return _listeners(this, type, false); 5353}; 5354 5355EventEmitter.listenerCount = function(emitter, type) { 5356 if (typeof emitter.listenerCount === 'function') { 5357 return emitter.listenerCount(type); 5358 } else { 5359 return listenerCount.call(emitter, type); 5360 } 5361}; 5362 5363EventEmitter.prototype.listenerCount = listenerCount; 5364function listenerCount(type) { 5365 var events = this._events; 5366 5367 if (events !== undefined) { 5368 var evlistener = events[type]; 5369 5370 if (typeof evlistener === 'function') { 5371 return 1; 5372 } else if (evlistener !== undefined) { 5373 return evlistener.length; 5374 } 5375 } 5376 5377 return 0; 5378} 5379 5380EventEmitter.prototype.eventNames = function eventNames() { 5381 return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; 5382}; 5383 5384function arrayClone(arr, n) { 5385 var copy = new Array(n); 5386 for (var i = 0; i < n; ++i) 5387 copy[i] = arr[i]; 5388 return copy; 5389} 5390 5391function spliceOne(list, index) { 5392 for (; index + 1 < list.length; index++) 5393 list[index] = list[index + 1]; 5394 list.pop(); 5395} 5396 5397function unwrapListeners(arr) { 5398 var ret = new Array(arr.length); 5399 for (var i = 0; i < ret.length; ++i) { 5400 ret[i] = arr[i].listener || arr[i]; 5401 } 5402 return ret; 5403} 5404 5405function once(emitter, name) { 5406 return new Promise(function (resolve, reject) { 5407 function errorListener(err) { 5408 emitter.removeListener(name, resolver); 5409 reject(err); 5410 } 5411 5412 function resolver() { 5413 if (typeof emitter.removeListener === 'function') { 5414 emitter.removeListener('error', errorListener); 5415 } 5416 resolve([].slice.call(arguments)); 5417 }; 5418 5419 eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); 5420 if (name !== 'error') { 5421 addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); 5422 } 5423 }); 5424} 5425 5426function addErrorHandlerIfEventEmitter(emitter, handler, flags) { 5427 if (typeof emitter.on === 'function') { 5428 eventTargetAgnosticAddListener(emitter, 'error', handler, flags); 5429 } 5430} 5431 5432function eventTargetAgnosticAddListener(emitter, name, listener, flags) { 5433 if (typeof emitter.on === 'function') { 5434 if (flags.once) { 5435 emitter.once(name, listener); 5436 } else { 5437 emitter.on(name, listener); 5438 } 5439 } else if (typeof emitter.addEventListener === 'function') { 5440 // EventTarget does not have `error` event semantics like Node 5441 // EventEmitters, we do not listen for `error` events here. 5442 emitter.addEventListener(name, function wrapListener(arg) { 5443 // IE does not have builtin `{ once: true }` support so we 5444 // have to do it manually. 5445 if (flags.once) { 5446 emitter.removeEventListener(name, wrapListener); 5447 } 5448 listener(arg); 5449 }); 5450 } else { 5451 throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); 5452 } 5453} 5454 5455 5456/***/ }), 5457/* 17 */ 5458/***/ (function(module, exports, __webpack_require__) { 5459 5460"use strict"; 5461 5462 5463var nodes = __webpack_require__(3); 5464var lib = __webpack_require__(0); 5465var sym = 0; 5466function gensym() { 5467 return 'hole_' + sym++; 5468} 5469 5470// copy-on-write version of map 5471function mapCOW(arr, func) { 5472 var res = null; 5473 for (var i = 0; i < arr.length; i++) { 5474 var item = func(arr[i]); 5475 if (item !== arr[i]) { 5476 if (!res) { 5477 res = arr.slice(); 5478 } 5479 res[i] = item; 5480 } 5481 } 5482 return res || arr; 5483} 5484function walk(ast, func, depthFirst) { 5485 if (!(ast instanceof nodes.Node)) { 5486 return ast; 5487 } 5488 if (!depthFirst) { 5489 var astT = func(ast); 5490 if (astT && astT !== ast) { 5491 return astT; 5492 } 5493 } 5494 if (ast instanceof nodes.NodeList) { 5495 var children = mapCOW(ast.children, function (node) { 5496 return walk(node, func, depthFirst); 5497 }); 5498 if (children !== ast.children) { 5499 ast = new nodes[ast.typename](ast.lineno, ast.colno, children); 5500 } 5501 } else if (ast instanceof nodes.CallExtension) { 5502 var args = walk(ast.args, func, depthFirst); 5503 var contentArgs = mapCOW(ast.contentArgs, function (node) { 5504 return walk(node, func, depthFirst); 5505 }); 5506 if (args !== ast.args || contentArgs !== ast.contentArgs) { 5507 ast = new nodes[ast.typename](ast.extName, ast.prop, args, contentArgs); 5508 } 5509 } else { 5510 var props = ast.fields.map(function (field) { 5511 return ast[field]; 5512 }); 5513 var propsT = mapCOW(props, function (prop) { 5514 return walk(prop, func, depthFirst); 5515 }); 5516 if (propsT !== props) { 5517 ast = new nodes[ast.typename](ast.lineno, ast.colno); 5518 propsT.forEach(function (prop, i) { 5519 ast[ast.fields[i]] = prop; 5520 }); 5521 } 5522 } 5523 return depthFirst ? func(ast) || ast : ast; 5524} 5525function depthWalk(ast, func) { 5526 return walk(ast, func, true); 5527} 5528function _liftFilters(node, asyncFilters, prop) { 5529 var children = []; 5530 var walked = depthWalk(prop ? node[prop] : node, function (descNode) { 5531 var symbol; 5532 if (descNode instanceof nodes.Block) { 5533 return descNode; 5534 } else if (descNode instanceof nodes.Filter && lib.indexOf(asyncFilters, descNode.name.value) !== -1 || descNode instanceof nodes.CallExtensionAsync) { 5535 symbol = new nodes.Symbol(descNode.lineno, descNode.colno, gensym()); 5536 children.push(new nodes.FilterAsync(descNode.lineno, descNode.colno, descNode.name, descNode.args, symbol)); 5537 } 5538 return symbol; 5539 }); 5540 if (prop) { 5541 node[prop] = walked; 5542 } else { 5543 node = walked; 5544 } 5545 if (children.length) { 5546 children.push(node); 5547 return new nodes.NodeList(node.lineno, node.colno, children); 5548 } else { 5549 return node; 5550 } 5551} 5552function liftFilters(ast, asyncFilters) { 5553 return depthWalk(ast, function (node) { 5554 if (node instanceof nodes.Output) { 5555 return _liftFilters(node, asyncFilters); 5556 } else if (node instanceof nodes.Set) { 5557 return _liftFilters(node, asyncFilters, 'value'); 5558 } else if (node instanceof nodes.For) { 5559 return _liftFilters(node, asyncFilters, 'arr'); 5560 } else if (node instanceof nodes.If) { 5561 return _liftFilters(node, asyncFilters, 'cond'); 5562 } else if (node instanceof nodes.CallExtension) { 5563 return _liftFilters(node, asyncFilters, 'args'); 5564 } else { 5565 return undefined; 5566 } 5567 }); 5568} 5569function liftSuper(ast) { 5570 return walk(ast, function (blockNode) { 5571 if (!(blockNode instanceof nodes.Block)) { 5572 return; 5573 } 5574 var hasSuper = false; 5575 var symbol = gensym(); 5576 blockNode.body = walk(blockNode.body, function (node) { 5577 // eslint-disable-line consistent-return 5578 if (node instanceof nodes.FunCall && node.name.value === 'super') { 5579 hasSuper = true; 5580 return new nodes.Symbol(node.lineno, node.colno, symbol); 5581 } 5582 }); 5583 if (hasSuper) { 5584 blockNode.body.children.unshift(new nodes.Super(0, 0, blockNode.name, new nodes.Symbol(0, 0, symbol))); 5585 } 5586 }); 5587} 5588function convertStatements(ast) { 5589 return depthWalk(ast, function (node) { 5590 if (!(node instanceof nodes.If) && !(node instanceof nodes.For)) { 5591 return undefined; 5592 } 5593 var async = false; 5594 walk(node, function (child) { 5595 if (child instanceof nodes.FilterAsync || child instanceof nodes.IfAsync || child instanceof nodes.AsyncEach || child instanceof nodes.AsyncAll || child instanceof nodes.CallExtensionAsync) { 5596 async = true; 5597 // Stop iterating by returning the node 5598 return child; 5599 } 5600 return undefined; 5601 }); 5602 if (async) { 5603 if (node instanceof nodes.If) { 5604 return new nodes.IfAsync(node.lineno, node.colno, node.cond, node.body, node.else_); 5605 } else if (node instanceof nodes.For && !(node instanceof nodes.AsyncAll)) { 5606 return new nodes.AsyncEach(node.lineno, node.colno, node.arr, node.name, node.body, node.else_); 5607 } 5608 } 5609 return undefined; 5610 }); 5611} 5612function cps(ast, asyncFilters) { 5613 return convertStatements(liftSuper(liftFilters(ast, asyncFilters))); 5614} 5615function transform(ast, asyncFilters) { 5616 return cps(ast, asyncFilters || []); 5617} 5618 5619// var parser = require('./parser'); 5620// var src = 'hello {% foo %}{% endfoo %} end'; 5621// var ast = transform(parser.parse(src, [new FooExtension()]), ['bar']); 5622// nodes.printNodes(ast); 5623 5624module.exports = { 5625 transform: transform 5626}; 5627 5628/***/ }), 5629/* 18 */ 5630/***/ (function(module, exports, __webpack_require__) { 5631 5632"use strict"; 5633 5634 5635var lib = __webpack_require__(0); 5636var r = __webpack_require__(2); 5637var exports = module.exports = {}; 5638function normalize(value, defaultValue) { 5639 if (value === null || value === undefined || value === false) { 5640 return defaultValue; 5641 } 5642 return value; 5643} 5644exports.abs = Math.abs; 5645function isNaN(num) { 5646 return num !== num; // eslint-disable-line no-self-compare 5647} 5648 5649function batch(arr, linecount, fillWith) { 5650 var i; 5651 var res = []; 5652 var tmp = []; 5653 for (i = 0; i < arr.length; i++) { 5654 if (i % linecount === 0 && tmp.length) { 5655 res.push(tmp); 5656 tmp = []; 5657 } 5658 tmp.push(arr[i]); 5659 } 5660 if (tmp.length) { 5661 if (fillWith) { 5662 for (i = tmp.length; i < linecount; i++) { 5663 tmp.push(fillWith); 5664 } 5665 } 5666 res.push(tmp); 5667 } 5668 return res; 5669} 5670exports.batch = batch; 5671function capitalize(str) { 5672 str = normalize(str, ''); 5673 var ret = str.toLowerCase(); 5674 return r.copySafeness(str, ret.charAt(0).toUpperCase() + ret.slice(1)); 5675} 5676exports.capitalize = capitalize; 5677function center(str, width) { 5678 str = normalize(str, ''); 5679 width = width || 80; 5680 if (str.length >= width) { 5681 return str; 5682 } 5683 var spaces = width - str.length; 5684 var pre = lib.repeat(' ', spaces / 2 - spaces % 2); 5685 var post = lib.repeat(' ', spaces / 2); 5686 return r.copySafeness(str, pre + str + post); 5687} 5688exports.center = center; 5689function default_(val, def, bool) { 5690 if (bool) { 5691 return val || def; 5692 } else { 5693 return val !== undefined ? val : def; 5694 } 5695} 5696 5697// TODO: it is confusing to export something called 'default' 5698exports['default'] = default_; // eslint-disable-line dot-notation 5699 5700function dictsort(val, caseSensitive, by) { 5701 if (!lib.isObject(val)) { 5702 throw new lib.TemplateError('dictsort filter: val must be an object'); 5703 } 5704 var array = []; 5705 // deliberately include properties from the object's prototype 5706 for (var k in val) { 5707 // eslint-disable-line guard-for-in, no-restricted-syntax 5708 array.push([k, val[k]]); 5709 } 5710 var si; 5711 if (by === undefined || by === 'key') { 5712 si = 0; 5713 } else if (by === 'value') { 5714 si = 1; 5715 } else { 5716 throw new lib.TemplateError('dictsort filter: You can only sort by either key or value'); 5717 } 5718 array.sort(function (t1, t2) { 5719 var a = t1[si]; 5720 var b = t2[si]; 5721 if (!caseSensitive) { 5722 if (lib.isString(a)) { 5723 a = a.toUpperCase(); 5724 } 5725 if (lib.isString(b)) { 5726 b = b.toUpperCase(); 5727 } 5728 } 5729 return a > b ? 1 : a === b ? 0 : -1; // eslint-disable-line no-nested-ternary 5730 }); 5731 5732 return array; 5733} 5734exports.dictsort = dictsort; 5735function dump(obj, spaces) { 5736 return JSON.stringify(obj, null, spaces); 5737} 5738exports.dump = dump; 5739function escape(str) { 5740 if (str instanceof r.SafeString) { 5741 return str; 5742 } 5743 str = str === null || str === undefined ? '' : str; 5744 return r.markSafe(lib.escape(str.toString())); 5745} 5746exports.escape = escape; 5747function safe(str) { 5748 if (str instanceof r.SafeString) { 5749 return str; 5750 } 5751 str = str === null || str === undefined ? '' : str; 5752 return r.markSafe(str.toString()); 5753} 5754exports.safe = safe; 5755function first(arr) { 5756 return arr[0]; 5757} 5758exports.first = first; 5759function forceescape(str) { 5760 str = str === null || str === undefined ? '' : str; 5761 return r.markSafe(lib.escape(str.toString())); 5762} 5763exports.forceescape = forceescape; 5764function groupby(arr, attr) { 5765 return lib.groupBy(arr, attr, this.env.opts.throwOnUndefined); 5766} 5767exports.groupby = groupby; 5768function indent(str, width, indentfirst) { 5769 str = normalize(str, ''); 5770 if (str === '') { 5771 return ''; 5772 } 5773 width = width || 4; 5774 // let res = ''; 5775 var lines = str.split('\n'); 5776 var sp = lib.repeat(' ', width); 5777 var res = lines.map(function (l, i) { 5778 return i === 0 && !indentfirst ? l : "" + sp + l; 5779 }).join('\n'); 5780 return r.copySafeness(str, res); 5781} 5782exports.indent = indent; 5783function join(arr, del, attr) { 5784 del = del || ''; 5785 if (attr) { 5786 arr = lib.map(arr, function (v) { 5787 return v[attr]; 5788 }); 5789 } 5790 return arr.join(del); 5791} 5792exports.join = join; 5793function last(arr) { 5794 return arr[arr.length - 1]; 5795} 5796exports.last = last; 5797function lengthFilter(val) { 5798 var value = normalize(val, ''); 5799 if (value !== undefined) { 5800 if (typeof Map === 'function' && value instanceof Map || typeof Set === 'function' && value instanceof Set) { 5801 // ECMAScript 2015 Maps and Sets 5802 return value.size; 5803 } 5804 if (lib.isObject(value) && !(value instanceof r.SafeString)) { 5805 // Objects (besides SafeStrings), non-primative Arrays 5806 return lib.keys(value).length; 5807 } 5808 return value.length; 5809 } 5810 return 0; 5811} 5812exports.length = lengthFilter; 5813function list(val) { 5814 if (lib.isString(val)) { 5815 return val.split(''); 5816 } else if (lib.isObject(val)) { 5817 return lib._entries(val || {}).map(function (_ref) { 5818 var key = _ref[0], 5819 value = _ref[1]; 5820 return { 5821 key: key, 5822 value: value 5823 }; 5824 }); 5825 } else if (lib.isArray(val)) { 5826 return val; 5827 } else { 5828 throw new lib.TemplateError('list filter: type not iterable'); 5829 } 5830} 5831exports.list = list; 5832function lower(str) { 5833 str = normalize(str, ''); 5834 return str.toLowerCase(); 5835} 5836exports.lower = lower; 5837function nl2br(str) { 5838 if (str === null || str === undefined) { 5839 return ''; 5840 } 5841 return r.copySafeness(str, str.replace(/\r\n|\n/g, '<br />\n')); 5842} 5843exports.nl2br = nl2br; 5844function random(arr) { 5845 return arr[Math.floor(Math.random() * arr.length)]; 5846} 5847exports.random = random; 5848 5849/** 5850 * Construct select or reject filter 5851 * 5852 * @param {boolean} expectedTestResult 5853 * @returns {function(array, string, *): array} 5854 */ 5855function getSelectOrReject(expectedTestResult) { 5856 function filter(arr, testName, secondArg) { 5857 if (testName === void 0) { 5858 testName = 'truthy'; 5859 } 5860 var context = this; 5861 var test = context.env.getTest(testName); 5862 return lib.toArray(arr).filter(function examineTestResult(item) { 5863 return test.call(context, item, secondArg) === expectedTestResult; 5864 }); 5865 } 5866 return filter; 5867} 5868exports.reject = getSelectOrReject(false); 5869function rejectattr(arr, attr) { 5870 return arr.filter(function (item) { 5871 return !item[attr]; 5872 }); 5873} 5874exports.rejectattr = rejectattr; 5875exports.select = getSelectOrReject(true); 5876function selectattr(arr, attr) { 5877 return arr.filter(function (item) { 5878 return !!item[attr]; 5879 }); 5880} 5881exports.selectattr = selectattr; 5882function replace(str, old, new_, maxCount) { 5883 var originalStr = str; 5884 if (old instanceof RegExp) { 5885 return str.replace(old, new_); 5886 } 5887 if (typeof maxCount === 'undefined') { 5888 maxCount = -1; 5889 } 5890 var res = ''; // Output 5891 5892 // Cast Numbers in the search term to string 5893 if (typeof old === 'number') { 5894 old = '' + old; 5895 } else if (typeof old !== 'string') { 5896 // If it is something other than number or string, 5897 // return the original string 5898 return str; 5899 } 5900 5901 // Cast numbers in the replacement to string 5902 if (typeof str === 'number') { 5903 str = '' + str; 5904 } 5905 5906 // If by now, we don't have a string, throw it back 5907 if (typeof str !== 'string' && !(str instanceof r.SafeString)) { 5908 return str; 5909 } 5910 5911 // ShortCircuits 5912 if (old === '') { 5913 // Mimic the python behaviour: empty string is replaced 5914 // by replacement e.g. "abc"|replace("", ".") -> .a.b.c. 5915 res = new_ + str.split('').join(new_) + new_; 5916 return r.copySafeness(str, res); 5917 } 5918 var nextIndex = str.indexOf(old); 5919 // if # of replacements to perform is 0, or the string to does 5920 // not contain the old value, return the string 5921 if (maxCount === 0 || nextIndex === -1) { 5922 return str; 5923 } 5924 var pos = 0; 5925 var count = 0; // # of replacements made 5926 5927 while (nextIndex > -1 && (maxCount === -1 || count < maxCount)) { 5928 // Grab the next chunk of src string and add it with the 5929 // replacement, to the result 5930 res += str.substring(pos, nextIndex) + new_; 5931 // Increment our pointer in the src string 5932 pos = nextIndex + old.length; 5933 count++; 5934 // See if there are any more replacements to be made 5935 nextIndex = str.indexOf(old, pos); 5936 } 5937 5938 // We've either reached the end, or done the max # of 5939 // replacements, tack on any remaining string 5940 if (pos < str.length) { 5941 res += str.substring(pos); 5942 } 5943 return r.copySafeness(originalStr, res); 5944} 5945exports.replace = replace; 5946function reverse(val) { 5947 var arr; 5948 if (lib.isString(val)) { 5949 arr = list(val); 5950 } else { 5951 // Copy it 5952 arr = lib.map(val, function (v) { 5953 return v; 5954 }); 5955 } 5956 arr.reverse(); 5957 if (lib.isString(val)) { 5958 return r.copySafeness(val, arr.join('')); 5959 } 5960 return arr; 5961} 5962exports.reverse = reverse; 5963function round(val, precision, method) { 5964 precision = precision || 0; 5965 var factor = Math.pow(10, precision); 5966 var rounder; 5967 if (method === 'ceil') { 5968 rounder = Math.ceil; 5969 } else if (method === 'floor') { 5970 rounder = Math.floor; 5971 } else { 5972 rounder = Math.round; 5973 } 5974 return rounder(val * factor) / factor; 5975} 5976exports.round = round; 5977function slice(arr, slices, fillWith) { 5978 var sliceLength = Math.floor(arr.length / slices); 5979 var extra = arr.length % slices; 5980 var res = []; 5981 var offset = 0; 5982 for (var i = 0; i < slices; i++) { 5983 var start = offset + i * sliceLength; 5984 if (i < extra) { 5985 offset++; 5986 } 5987 var end = offset + (i + 1) * sliceLength; 5988 var currSlice = arr.slice(start, end); 5989 if (fillWith && i >= extra) { 5990 currSlice.push(fillWith); 5991 } 5992 res.push(currSlice); 5993 } 5994 return res; 5995} 5996exports.slice = slice; 5997function sum(arr, attr, start) { 5998 if (start === void 0) { 5999 start = 0; 6000 } 6001 if (attr) { 6002 arr = lib.map(arr, function (v) { 6003 return v[attr]; 6004 }); 6005 } 6006 return start + arr.reduce(function (a, b) { 6007 return a + b; 6008 }, 0); 6009} 6010exports.sum = sum; 6011exports.sort = r.makeMacro(['value', 'reverse', 'case_sensitive', 'attribute'], [], function sortFilter(arr, reversed, caseSens, attr) { 6012 var _this = this; 6013 // Copy it 6014 var array = lib.map(arr, function (v) { 6015 return v; 6016 }); 6017 var getAttribute = lib.getAttrGetter(attr); 6018 array.sort(function (a, b) { 6019 var x = attr ? getAttribute(a) : a; 6020 var y = attr ? getAttribute(b) : b; 6021 if (_this.env.opts.throwOnUndefined && attr && (x === undefined || y === undefined)) { 6022 throw new TypeError("sort: attribute \"" + attr + "\" resolved to undefined"); 6023 } 6024 if (!caseSens && lib.isString(x) && lib.isString(y)) { 6025 x = x.toLowerCase(); 6026 y = y.toLowerCase(); 6027 } 6028 if (x < y) { 6029 return reversed ? 1 : -1; 6030 } else if (x > y) { 6031 return reversed ? -1 : 1; 6032 } else { 6033 return 0; 6034 } 6035 }); 6036 return array; 6037}); 6038function string(obj) { 6039 return r.copySafeness(obj, obj); 6040} 6041exports.string = string; 6042function striptags(input, preserveLinebreaks) { 6043 input = normalize(input, ''); 6044 var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>|<!--[\s\S]*?-->/gi; 6045 var trimmedInput = trim(input.replace(tags, '')); 6046 var res = ''; 6047 if (preserveLinebreaks) { 6048 res = trimmedInput.replace(/^ +| +$/gm, '') // remove leading and trailing spaces 6049 .replace(/ +/g, ' ') // squash adjacent spaces 6050 .replace(/(\r\n)/g, '\n') // normalize linebreaks (CRLF -> LF) 6051 .replace(/\n\n\n+/g, '\n\n'); // squash abnormal adjacent linebreaks 6052 } else { 6053 res = trimmedInput.replace(/\s+/gi, ' '); 6054 } 6055 return r.copySafeness(input, res); 6056} 6057exports.striptags = striptags; 6058function title(str) { 6059 str = normalize(str, ''); 6060 var words = str.split(' ').map(function (word) { 6061 return capitalize(word); 6062 }); 6063 return r.copySafeness(str, words.join(' ')); 6064} 6065exports.title = title; 6066function trim(str) { 6067 return r.copySafeness(str, str.replace(/^\s*|\s*$/g, '')); 6068} 6069exports.trim = trim; 6070function truncate(input, length, killwords, end) { 6071 var orig = input; 6072 input = normalize(input, ''); 6073 length = length || 255; 6074 if (input.length <= length) { 6075 return input; 6076 } 6077 if (killwords) { 6078 input = input.substring(0, length); 6079 } else { 6080 var idx = input.lastIndexOf(' ', length); 6081 if (idx === -1) { 6082 idx = length; 6083 } 6084 input = input.substring(0, idx); 6085 } 6086 input += end !== undefined && end !== null ? end : '...'; 6087 return r.copySafeness(orig, input); 6088} 6089exports.truncate = truncate; 6090function upper(str) { 6091 str = normalize(str, ''); 6092 return str.toUpperCase(); 6093} 6094exports.upper = upper; 6095function urlencode(obj) { 6096 var enc = encodeURIComponent; 6097 if (lib.isString(obj)) { 6098 return enc(obj); 6099 } else { 6100 var keyvals = lib.isArray(obj) ? obj : lib._entries(obj); 6101 return keyvals.map(function (_ref2) { 6102 var k = _ref2[0], 6103 v = _ref2[1]; 6104 return enc(k) + "=" + enc(v); 6105 }).join('&'); 6106 } 6107} 6108exports.urlencode = urlencode; 6109 6110// For the jinja regexp, see 6111// https://github.com/mitsuhiko/jinja2/blob/f15b814dcba6aa12bc74d1f7d0c881d55f7126be/jinja2/utils.py#L20-L23 6112var puncRe = /^(?:\(|<|<)?(.*?)(?:\.|,|\)|\n|>)?$/; 6113// from http://blog.gerv.net/2011/05/html5_email_address_regexp/ 6114var emailRe = /^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d\-]+(\.[a-z\d\-]+)+$/i; 6115var httpHttpsRe = /^https?:\/\/.*$/; 6116var wwwRe = /^www\./; 6117var tldRe = /\.(?:org|net|com)(?:\:|\/|$)/; 6118function urlize(str, length, nofollow) { 6119 if (isNaN(length)) { 6120 length = Infinity; 6121 } 6122 var noFollowAttr = nofollow === true ? ' rel="nofollow"' : ''; 6123 var words = str.split(/(\s+)/).filter(function (word) { 6124 // If the word has no length, bail. This can happen for str with 6125 // trailing whitespace. 6126 return word && word.length; 6127 }).map(function (word) { 6128 var matches = word.match(puncRe); 6129 var possibleUrl = matches ? matches[1] : word; 6130 var shortUrl = possibleUrl.substr(0, length); 6131 6132 // url that starts with http or https 6133 if (httpHttpsRe.test(possibleUrl)) { 6134 return "<a href=\"" + possibleUrl + "\"" + noFollowAttr + ">" + shortUrl + "</a>"; 6135 } 6136 6137 // url that starts with www. 6138 if (wwwRe.test(possibleUrl)) { 6139 return "<a href=\"http://" + possibleUrl + "\"" + noFollowAttr + ">" + shortUrl + "</a>"; 6140 } 6141 6142 // an email address of the form username@domain.tld 6143 if (emailRe.test(possibleUrl)) { 6144 return "<a href=\"mailto:" + possibleUrl + "\">" + possibleUrl + "</a>"; 6145 } 6146 6147 // url that ends in .com, .org or .net that is not an email address 6148 if (tldRe.test(possibleUrl)) { 6149 return "<a href=\"http://" + possibleUrl + "\"" + noFollowAttr + ">" + shortUrl + "</a>"; 6150 } 6151 return word; 6152 }); 6153 return words.join(''); 6154} 6155exports.urlize = urlize; 6156function wordcount(str) { 6157 str = normalize(str, ''); 6158 var words = str ? str.match(/\w+/g) : null; 6159 return words ? words.length : null; 6160} 6161exports.wordcount = wordcount; 6162function float(val, def) { 6163 var res = parseFloat(val); 6164 return isNaN(res) ? def : res; 6165} 6166exports.float = float; 6167var intFilter = r.makeMacro(['value', 'default', 'base'], [], function doInt(value, defaultValue, base) { 6168 if (base === void 0) { 6169 base = 10; 6170 } 6171 var res = parseInt(value, base); 6172 return isNaN(res) ? defaultValue : res; 6173}); 6174exports.int = intFilter; 6175 6176// Aliases 6177exports.d = exports.default; 6178exports.e = exports.escape; 6179 6180/***/ }), 6181/* 19 */ 6182/***/ (function(module, exports, __webpack_require__) { 6183 6184"use strict"; 6185 6186 6187function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } 6188function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 6189var Loader = __webpack_require__(6); 6190var PrecompiledLoader = /*#__PURE__*/function (_Loader) { 6191 _inheritsLoose(PrecompiledLoader, _Loader); 6192 function PrecompiledLoader(compiledTemplates) { 6193 var _this; 6194 _this = _Loader.call(this) || this; 6195 _this.precompiled = compiledTemplates || {}; 6196 return _this; 6197 } 6198 var _proto = PrecompiledLoader.prototype; 6199 _proto.getSource = function getSource(name) { 6200 if (this.precompiled[name]) { 6201 return { 6202 src: { 6203 type: 'code', 6204 obj: this.precompiled[name] 6205 }, 6206 path: name 6207 }; 6208 } 6209 return null; 6210 }; 6211 return PrecompiledLoader; 6212}(Loader); 6213module.exports = { 6214 PrecompiledLoader: PrecompiledLoader 6215}; 6216 6217/***/ }), 6218/* 20 */ 6219/***/ (function(module, exports, __webpack_require__) { 6220 6221"use strict"; 6222 6223 6224var SafeString = __webpack_require__(2).SafeString; 6225 6226/** 6227 * Returns `true` if the object is a function, otherwise `false`. 6228 * @param { any } value 6229 * @returns { boolean } 6230 */ 6231function callable(value) { 6232 return typeof value === 'function'; 6233} 6234exports.callable = callable; 6235 6236/** 6237 * Returns `true` if the object is strictly not `undefined`. 6238 * @param { any } value 6239 * @returns { boolean } 6240 */ 6241function defined(value) { 6242 return value !== undefined; 6243} 6244exports.defined = defined; 6245 6246/** 6247 * Returns `true` if the operand (one) is divisble by the test's argument 6248 * (two). 6249 * @param { number } one 6250 * @param { number } two 6251 * @returns { boolean } 6252 */ 6253function divisibleby(one, two) { 6254 return one % two === 0; 6255} 6256exports.divisibleby = divisibleby; 6257 6258/** 6259 * Returns true if the string has been escaped (i.e., is a SafeString). 6260 * @param { any } value 6261 * @returns { boolean } 6262 */ 6263function escaped(value) { 6264 return value instanceof SafeString; 6265} 6266exports.escaped = escaped; 6267 6268/** 6269 * Returns `true` if the arguments are strictly equal. 6270 * @param { any } one 6271 * @param { any } two 6272 */ 6273function equalto(one, two) { 6274 return one === two; 6275} 6276exports.equalto = equalto; 6277 6278// Aliases 6279exports.eq = exports.equalto; 6280exports.sameas = exports.equalto; 6281 6282/** 6283 * Returns `true` if the value is evenly divisible by 2. 6284 * @param { number } value 6285 * @returns { boolean } 6286 */ 6287function even(value) { 6288 return value % 2 === 0; 6289} 6290exports.even = even; 6291 6292/** 6293 * Returns `true` if the value is falsy - if I recall correctly, '', 0, false, 6294 * undefined, NaN or null. I don't know if we should stick to the default JS 6295 * behavior or attempt to replicate what Python believes should be falsy (i.e., 6296 * empty arrays, empty dicts, not 0...). 6297 * @param { any } value 6298 * @returns { boolean } 6299 */ 6300function falsy(value) { 6301 return !value; 6302} 6303exports.falsy = falsy; 6304 6305/** 6306 * Returns `true` if the operand (one) is greater or equal to the test's 6307 * argument (two). 6308 * @param { number } one 6309 * @param { number } two 6310 * @returns { boolean } 6311 */ 6312function ge(one, two) { 6313 return one >= two; 6314} 6315exports.ge = ge; 6316 6317/** 6318 * Returns `true` if the operand (one) is greater than the test's argument 6319 * (two). 6320 * @param { number } one 6321 * @param { number } two 6322 * @returns { boolean } 6323 */ 6324function greaterthan(one, two) { 6325 return one > two; 6326} 6327exports.greaterthan = greaterthan; 6328 6329// alias 6330exports.gt = exports.greaterthan; 6331 6332/** 6333 * Returns `true` if the operand (one) is less than or equal to the test's 6334 * argument (two). 6335 * @param { number } one 6336 * @param { number } two 6337 * @returns { boolean } 6338 */ 6339function le(one, two) { 6340 return one <= two; 6341} 6342exports.le = le; 6343 6344/** 6345 * Returns `true` if the operand (one) is less than the test's passed argument 6346 * (two). 6347 * @param { number } one 6348 * @param { number } two 6349 * @returns { boolean } 6350 */ 6351function lessthan(one, two) { 6352 return one < two; 6353} 6354exports.lessthan = lessthan; 6355 6356// alias 6357exports.lt = exports.lessthan; 6358 6359/** 6360 * Returns `true` if the string is lowercased. 6361 * @param { string } value 6362 * @returns { boolean } 6363 */ 6364function lower(value) { 6365 return value.toLowerCase() === value; 6366} 6367exports.lower = lower; 6368 6369/** 6370 * Returns `true` if the operand (one) is less than or equal to the test's 6371 * argument (two). 6372 * @param { number } one 6373 * @param { number } two 6374 * @returns { boolean } 6375 */ 6376function ne(one, two) { 6377 return one !== two; 6378} 6379exports.ne = ne; 6380 6381/** 6382 * Returns true if the value is strictly equal to `null`. 6383 * @param { any } 6384 * @returns { boolean } 6385 */ 6386function nullTest(value) { 6387 return value === null; 6388} 6389exports.null = nullTest; 6390 6391/** 6392 * Returns true if value is a number. 6393 * @param { any } 6394 * @returns { boolean } 6395 */ 6396function number(value) { 6397 return typeof value === 'number'; 6398} 6399exports.number = number; 6400 6401/** 6402 * Returns `true` if the value is *not* evenly divisible by 2. 6403 * @param { number } value 6404 * @returns { boolean } 6405 */ 6406function odd(value) { 6407 return value % 2 === 1; 6408} 6409exports.odd = odd; 6410 6411/** 6412 * Returns `true` if the value is a string, `false` if not. 6413 * @param { any } value 6414 * @returns { boolean } 6415 */ 6416function string(value) { 6417 return typeof value === 'string'; 6418} 6419exports.string = string; 6420 6421/** 6422 * Returns `true` if the value is not in the list of things considered falsy: 6423 * '', null, undefined, 0, NaN and false. 6424 * @param { any } value 6425 * @returns { boolean } 6426 */ 6427function truthy(value) { 6428 return !!value; 6429} 6430exports.truthy = truthy; 6431 6432/** 6433 * Returns `true` if the value is undefined. 6434 * @param { any } value 6435 * @returns { boolean } 6436 */ 6437function undefinedTest(value) { 6438 return value === undefined; 6439} 6440exports.undefined = undefinedTest; 6441 6442/** 6443 * Returns `true` if the string is uppercased. 6444 * @param { string } value 6445 * @returns { boolean } 6446 */ 6447function upper(value) { 6448 return value.toUpperCase() === value; 6449} 6450exports.upper = upper; 6451 6452/** 6453 * If ES6 features are available, returns `true` if the value implements the 6454 * `Symbol.iterator` method. If not, it's a string or Array. 6455 * 6456 * Could potentially cause issues if a browser exists that has Set and Map but 6457 * not Symbol. 6458 * 6459 * @param { any } value 6460 * @returns { boolean } 6461 */ 6462function iterable(value) { 6463 if (typeof Symbol !== 'undefined') { 6464 return !!value[Symbol.iterator]; 6465 } else { 6466 return Array.isArray(value) || typeof value === 'string'; 6467 } 6468} 6469exports.iterable = iterable; 6470 6471/** 6472 * If ES6 features are available, returns `true` if the value is an object hash 6473 * or an ES6 Map. Otherwise just return if it's an object hash. 6474 * @param { any } value 6475 * @returns { boolean } 6476 */ 6477function mapping(value) { 6478 // only maps and object hashes 6479 var bool = value !== null && value !== undefined && typeof value === 'object' && !Array.isArray(value); 6480 if (Set) { 6481 return bool && !(value instanceof Set); 6482 } else { 6483 return bool; 6484 } 6485} 6486exports.mapping = mapping; 6487 6488/***/ }), 6489/* 21 */ 6490/***/ (function(module, exports, __webpack_require__) { 6491 6492"use strict"; 6493 6494 6495function _cycler(items) { 6496 var index = -1; 6497 return { 6498 current: null, 6499 reset: function reset() { 6500 index = -1; 6501 this.current = null; 6502 }, 6503 next: function next() { 6504 index++; 6505 if (index >= items.length) { 6506 index = 0; 6507 } 6508 this.current = items[index]; 6509 return this.current; 6510 } 6511 }; 6512} 6513function _joiner(sep) { 6514 sep = sep || ','; 6515 var first = true; 6516 return function () { 6517 var val = first ? '' : sep; 6518 first = false; 6519 return val; 6520 }; 6521} 6522 6523// Making this a function instead so it returns a new object 6524// each time it's called. That way, if something like an environment 6525// uses it, they will each have their own copy. 6526function globals() { 6527 return { 6528 range: function range(start, stop, step) { 6529 if (typeof stop === 'undefined') { 6530 stop = start; 6531 start = 0; 6532 step = 1; 6533 } else if (!step) { 6534 step = 1; 6535 } 6536 var arr = []; 6537 if (step > 0) { 6538 for (var i = start; i < stop; i += step) { 6539 arr.push(i); 6540 } 6541 } else { 6542 for (var _i = start; _i > stop; _i += step) { 6543 // eslint-disable-line for-direction 6544 arr.push(_i); 6545 } 6546 } 6547 return arr; 6548 }, 6549 cycler: function cycler() { 6550 return _cycler(Array.prototype.slice.call(arguments)); 6551 }, 6552 joiner: function joiner(sep) { 6553 return _joiner(sep); 6554 } 6555 }; 6556} 6557module.exports = globals; 6558 6559/***/ }), 6560/* 22 */ 6561/***/ (function(module, exports, __webpack_require__) { 6562 6563var path = __webpack_require__(4); 6564module.exports = function express(env, app) { 6565 function NunjucksView(name, opts) { 6566 this.name = name; 6567 this.path = name; 6568 this.defaultEngine = opts.defaultEngine; 6569 this.ext = path.extname(name); 6570 if (!this.ext && !this.defaultEngine) { 6571 throw new Error('No default engine was specified and no extension was provided.'); 6572 } 6573 if (!this.ext) { 6574 this.name += this.ext = (this.defaultEngine[0] !== '.' ? '.' : '') + this.defaultEngine; 6575 } 6576 } 6577 NunjucksView.prototype.render = function render(opts, cb) { 6578 env.render(this.name, opts, cb); 6579 }; 6580 app.set('view', NunjucksView); 6581 app.set('nunjucksEnv', env); 6582 return env; 6583}; 6584 6585/***/ }), 6586/* 23 */ 6587/***/ (function(module, exports, __webpack_require__) { 6588 6589"use strict"; 6590 6591 6592var fs = __webpack_require__(4); 6593var path = __webpack_require__(4); 6594var _require = __webpack_require__(0), 6595 _prettifyError = _require._prettifyError; 6596var compiler = __webpack_require__(5); 6597var _require2 = __webpack_require__(7), 6598 Environment = _require2.Environment; 6599var precompileGlobal = __webpack_require__(24); 6600function match(filename, patterns) { 6601 if (!Array.isArray(patterns)) { 6602 return false; 6603 } 6604 return patterns.some(function (pattern) { 6605 return filename.match(pattern); 6606 }); 6607} 6608function precompileString(str, opts) { 6609 opts = opts || {}; 6610 opts.isString = true; 6611 var env = opts.env || new Environment([]); 6612 var wrapper = opts.wrapper || precompileGlobal; 6613 if (!opts.name) { 6614 throw new Error('the "name" option is required when compiling a string'); 6615 } 6616 return wrapper([_precompile(str, opts.name, env)], opts); 6617} 6618function precompile(input, opts) { 6619 // The following options are available: 6620 // 6621 // * name: name of the template (auto-generated when compiling a directory) 6622 // * isString: input is a string, not a file path 6623 // * asFunction: generate a callable function 6624 // * force: keep compiling on error 6625 // * env: the Environment to use (gets extensions and async filters from it) 6626 // * include: which file/folders to include (folders are auto-included, files are auto-excluded) 6627 // * exclude: which file/folders to exclude (folders are auto-included, files are auto-excluded) 6628 // * wrapper: function(templates, opts) {...} 6629 // Customize the output format to store the compiled template. 6630 // By default, templates are stored in a global variable used by the runtime. 6631 // A custom loader will be necessary to load your custom wrapper. 6632 6633 opts = opts || {}; 6634 var env = opts.env || new Environment([]); 6635 var wrapper = opts.wrapper || precompileGlobal; 6636 if (opts.isString) { 6637 return precompileString(input, opts); 6638 } 6639 var pathStats = fs.existsSync(input) && fs.statSync(input); 6640 var precompiled = []; 6641 var templates = []; 6642 function addTemplates(dir) { 6643 fs.readdirSync(dir).forEach(function (file) { 6644 var filepath = path.join(dir, file); 6645 var subpath = filepath.substr(path.join(input, '/').length); 6646 var stat = fs.statSync(filepath); 6647 if (stat && stat.isDirectory()) { 6648 subpath += '/'; 6649 if (!match(subpath, opts.exclude)) { 6650 addTemplates(filepath); 6651 } 6652 } else if (match(subpath, opts.include)) { 6653 templates.push(filepath); 6654 } 6655 }); 6656 } 6657 if (pathStats.isFile()) { 6658 precompiled.push(_precompile(fs.readFileSync(input, 'utf-8'), opts.name || input, env)); 6659 } else if (pathStats.isDirectory()) { 6660 addTemplates(input); 6661 for (var i = 0; i < templates.length; i++) { 6662 var name = templates[i].replace(path.join(input, '/'), ''); 6663 try { 6664 precompiled.push(_precompile(fs.readFileSync(templates[i], 'utf-8'), name, env)); 6665 } catch (e) { 6666 if (opts.force) { 6667 // Don't stop generating the output if we're 6668 // forcing compilation. 6669 console.error(e); // eslint-disable-line no-console 6670 } else { 6671 throw e; 6672 } 6673 } 6674 } 6675 } 6676 return wrapper(precompiled, opts); 6677} 6678function _precompile(str, name, env) { 6679 env = env || new Environment([]); 6680 var asyncFilters = env.asyncFilters; 6681 var extensions = env.extensionsList; 6682 var template; 6683 name = name.replace(/\\/g, '/'); 6684 try { 6685 template = compiler.compile(str, asyncFilters, extensions, name, env.opts); 6686 } catch (err) { 6687 throw _prettifyError(name, false, err); 6688 } 6689 return { 6690 name: name, 6691 template: template 6692 }; 6693} 6694module.exports = { 6695 precompile: precompile, 6696 precompileString: precompileString 6697}; 6698 6699/***/ }), 6700/* 24 */ 6701/***/ (function(module, exports, __webpack_require__) { 6702 6703"use strict"; 6704 6705 6706function precompileGlobal(templates, opts) { 6707 var out = ''; 6708 opts = opts || {}; 6709 for (var i = 0; i < templates.length; i++) { 6710 var name = JSON.stringify(templates[i].name); 6711 var template = templates[i].template; 6712 out += '(function() {' + '(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})' + '[' + name + '] = (function() {\n' + template + '\n})();\n'; 6713 if (opts.asFunction) { 6714 out += 'return function(ctx, cb) { return nunjucks.render(' + name + ', ctx, cb); }\n'; 6715 } 6716 out += '})();\n'; 6717 } 6718 return out; 6719} 6720module.exports = precompileGlobal; 6721 6722/***/ }), 6723/* 25 */ 6724/***/ (function(module, exports, __webpack_require__) { 6725 6726function installCompat() { 6727 'use strict'; 6728 6729 /* eslint-disable camelcase */ 6730 6731 // This must be called like `nunjucks.installCompat` so that `this` 6732 // references the nunjucks instance 6733 var runtime = this.runtime; 6734 var lib = this.lib; 6735 // Handle slim case where these 'modules' are excluded from the built source 6736 var Compiler = this.compiler.Compiler; 6737 var Parser = this.parser.Parser; 6738 var nodes = this.nodes; 6739 var lexer = this.lexer; 6740 var orig_contextOrFrameLookup = runtime.contextOrFrameLookup; 6741 var orig_memberLookup = runtime.memberLookup; 6742 var orig_Compiler_assertType; 6743 var orig_Parser_parseAggregate; 6744 if (Compiler) { 6745 orig_Compiler_assertType = Compiler.prototype.assertType; 6746 } 6747 if (Parser) { 6748 orig_Parser_parseAggregate = Parser.prototype.parseAggregate; 6749 } 6750 function uninstall() { 6751 runtime.contextOrFrameLookup = orig_contextOrFrameLookup; 6752 runtime.memberLookup = orig_memberLookup; 6753 if (Compiler) { 6754 Compiler.prototype.assertType = orig_Compiler_assertType; 6755 } 6756 if (Parser) { 6757 Parser.prototype.parseAggregate = orig_Parser_parseAggregate; 6758 } 6759 } 6760 runtime.contextOrFrameLookup = function contextOrFrameLookup(context, frame, key) { 6761 var val = orig_contextOrFrameLookup.apply(this, arguments); 6762 if (val !== undefined) { 6763 return val; 6764 } 6765 switch (key) { 6766 case 'True': 6767 return true; 6768 case 'False': 6769 return false; 6770 case 'None': 6771 return null; 6772 default: 6773 return undefined; 6774 } 6775 }; 6776 function getTokensState(tokens) { 6777 return { 6778 index: tokens.index, 6779 lineno: tokens.lineno, 6780 colno: tokens.colno 6781 }; 6782 } 6783 if ("STD" !== 'SLIM' && nodes && Compiler && Parser) { 6784 // i.e., not slim mode 6785 var Slice = nodes.Node.extend('Slice', { 6786 fields: ['start', 'stop', 'step'], 6787 init: function init(lineno, colno, start, stop, step) { 6788 start = start || new nodes.Literal(lineno, colno, null); 6789 stop = stop || new nodes.Literal(lineno, colno, null); 6790 step = step || new nodes.Literal(lineno, colno, 1); 6791 this.parent(lineno, colno, start, stop, step); 6792 } 6793 }); 6794 Compiler.prototype.assertType = function assertType(node) { 6795 if (node instanceof Slice) { 6796 return; 6797 } 6798 orig_Compiler_assertType.apply(this, arguments); 6799 }; 6800 Compiler.prototype.compileSlice = function compileSlice(node, frame) { 6801 this._emit('('); 6802 this._compileExpression(node.start, frame); 6803 this._emit('),('); 6804 this._compileExpression(node.stop, frame); 6805 this._emit('),('); 6806 this._compileExpression(node.step, frame); 6807 this._emit(')'); 6808 }; 6809 Parser.prototype.parseAggregate = function parseAggregate() { 6810 var _this = this; 6811 var origState = getTokensState(this.tokens); 6812 // Set back one accounting for opening bracket/parens 6813 origState.colno--; 6814 origState.index--; 6815 try { 6816 return orig_Parser_parseAggregate.apply(this); 6817 } catch (e) { 6818 var errState = getTokensState(this.tokens); 6819 var rethrow = function rethrow() { 6820 lib._assign(_this.tokens, errState); 6821 return e; 6822 }; 6823 6824 // Reset to state before original parseAggregate called 6825 lib._assign(this.tokens, origState); 6826 this.peeked = false; 6827 var tok = this.peekToken(); 6828 if (tok.type !== lexer.TOKEN_LEFT_BRACKET) { 6829 throw rethrow(); 6830 } else { 6831 this.nextToken(); 6832 } 6833 var node = new Slice(tok.lineno, tok.colno); 6834 6835 // If we don't encounter a colon while parsing, this is not a slice, 6836 // so re-raise the original exception. 6837 var isSlice = false; 6838 for (var i = 0; i <= node.fields.length; i++) { 6839 if (this.skip(lexer.TOKEN_RIGHT_BRACKET)) { 6840 break; 6841 } 6842 if (i === node.fields.length) { 6843 if (isSlice) { 6844 this.fail('parseSlice: too many slice components', tok.lineno, tok.colno); 6845 } else { 6846 break; 6847 } 6848 } 6849 if (this.skip(lexer.TOKEN_COLON)) { 6850 isSlice = true; 6851 } else { 6852 var field = node.fields[i]; 6853 node[field] = this.parseExpression(); 6854 isSlice = this.skip(lexer.TOKEN_COLON) || isSlice; 6855 } 6856 } 6857 if (!isSlice) { 6858 throw rethrow(); 6859 } 6860 return new nodes.Array(tok.lineno, tok.colno, [node]); 6861 } 6862 }; 6863 } 6864 function sliceLookup(obj, start, stop, step) { 6865 obj = obj || []; 6866 if (start === null) { 6867 start = step < 0 ? obj.length - 1 : 0; 6868 } 6869 if (stop === null) { 6870 stop = step < 0 ? -1 : obj.length; 6871 } else if (stop < 0) { 6872 stop += obj.length; 6873 } 6874 if (start < 0) { 6875 start += obj.length; 6876 } 6877 var results = []; 6878 for (var i = start;; i += step) { 6879 if (i < 0 || i > obj.length) { 6880 break; 6881 } 6882 if (step > 0 && i >= stop) { 6883 break; 6884 } 6885 if (step < 0 && i <= stop) { 6886 break; 6887 } 6888 results.push(runtime.memberLookup(obj, i)); 6889 } 6890 return results; 6891 } 6892 function hasOwnProp(obj, key) { 6893 return Object.prototype.hasOwnProperty.call(obj, key); 6894 } 6895 var ARRAY_MEMBERS = { 6896 pop: function pop(index) { 6897 if (index === undefined) { 6898 return this.pop(); 6899 } 6900 if (index >= this.length || index < 0) { 6901 throw new Error('KeyError'); 6902 } 6903 return this.splice(index, 1); 6904 }, 6905 append: function append(element) { 6906 return this.push(element); 6907 }, 6908 remove: function remove(element) { 6909 for (var i = 0; i < this.length; i++) { 6910 if (this[i] === element) { 6911 return this.splice(i, 1); 6912 } 6913 } 6914 throw new Error('ValueError'); 6915 }, 6916 count: function count(element) { 6917 var count = 0; 6918 for (var i = 0; i < this.length; i++) { 6919 if (this[i] === element) { 6920 count++; 6921 } 6922 } 6923 return count; 6924 }, 6925 index: function index(element) { 6926 var i; 6927 if ((i = this.indexOf(element)) === -1) { 6928 throw new Error('ValueError'); 6929 } 6930 return i; 6931 }, 6932 find: function find(element) { 6933 return this.indexOf(element); 6934 }, 6935 insert: function insert(index, elem) { 6936 return this.splice(index, 0, elem); 6937 } 6938 }; 6939 var OBJECT_MEMBERS = { 6940 items: function items() { 6941 return lib._entries(this); 6942 }, 6943 values: function values() { 6944 return lib._values(this); 6945 }, 6946 keys: function keys() { 6947 return lib.keys(this); 6948 }, 6949 get: function get(key, def) { 6950 var output = this[key]; 6951 if (output === undefined) { 6952 output = def; 6953 } 6954 return output; 6955 }, 6956 has_key: function has_key(key) { 6957 return hasOwnProp(this, key); 6958 }, 6959 pop: function pop(key, def) { 6960 var output = this[key]; 6961 if (output === undefined && def !== undefined) { 6962 output = def; 6963 } else if (output === undefined) { 6964 throw new Error('KeyError'); 6965 } else { 6966 delete this[key]; 6967 } 6968 return output; 6969 }, 6970 popitem: function popitem() { 6971 var keys = lib.keys(this); 6972 if (!keys.length) { 6973 throw new Error('KeyError'); 6974 } 6975 var k = keys[0]; 6976 var val = this[k]; 6977 delete this[k]; 6978 return [k, val]; 6979 }, 6980 setdefault: function setdefault(key, def) { 6981 if (def === void 0) { 6982 def = null; 6983 } 6984 if (!(key in this)) { 6985 this[key] = def; 6986 } 6987 return this[key]; 6988 }, 6989 update: function update(kwargs) { 6990 lib._assign(this, kwargs); 6991 return null; // Always returns None 6992 } 6993 }; 6994 6995 OBJECT_MEMBERS.iteritems = OBJECT_MEMBERS.items; 6996 OBJECT_MEMBERS.itervalues = OBJECT_MEMBERS.values; 6997 OBJECT_MEMBERS.iterkeys = OBJECT_MEMBERS.keys; 6998 runtime.memberLookup = function memberLookup(obj, val, autoescape) { 6999 if (arguments.length === 4) { 7000 return sliceLookup.apply(this, arguments); 7001 } 7002 obj = obj || {}; 7003 7004 // If the object is an object, return any of the methods that Python would 7005 // otherwise provide. 7006 if (lib.isArray(obj) && hasOwnProp(ARRAY_MEMBERS, val)) { 7007 return ARRAY_MEMBERS[val].bind(obj); 7008 } 7009 if (lib.isObject(obj) && hasOwnProp(OBJECT_MEMBERS, val)) { 7010 return OBJECT_MEMBERS[val].bind(obj); 7011 } 7012 return orig_memberLookup.apply(this, arguments); 7013 }; 7014 return uninstall; 7015} 7016module.exports = installCompat; 7017 7018/***/ }) 7019/******/ ]); 7020}); 7021//# sourceMappingURL=nunjucks.js.map