/*
* liquidjs@10.14.0, https://github.com/harttle/liquidjs
* (c) 2016-2024 harttle
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.liquidjs = {}));
}(this, (function (exports) { 'use strict';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
var Token = /** @class */ (function () {
function Token(kind, input, begin, end, file) {
this.kind = kind;
this.input = input;
this.begin = begin;
this.end = end;
this.file = file;
}
Token.prototype.getText = function () {
return this.input.slice(this.begin, this.end);
};
Token.prototype.getPosition = function () {
var _a = __read([1, 1], 2), row = _a[0], col = _a[1];
for (var i = 0; i < this.begin; i++) {
if (this.input[i] === '\n') {
row++;
col = 1;
}
else
col++;
}
return [row, col];
};
Token.prototype.size = function () {
return this.end - this.begin;
};
return Token;
}());
var Drop = /** @class */ (function () {
function Drop() {
}
Drop.prototype.liquidMethodMissing = function (key) {
return undefined;
};
return Drop;
}());
var toString$1 = Object.prototype.toString;
var toLowerCase = String.prototype.toLowerCase;
var hasOwnProperty = Object.hasOwnProperty;
function isString(value) {
return typeof value === 'string';
}
// eslint-disable-next-line @typescript-eslint/ban-types
function isFunction(value) {
return typeof value === 'function';
}
function isPromise(val) {
return val && isFunction(val.then);
}
function isIterator(val) {
return val && isFunction(val.next) && isFunction(val.throw) && isFunction(val.return);
}
function escapeRegex(str) {
return str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
}
function stringify(value) {
value = toValue(value);
if (isString(value))
return value;
if (isNil(value))
return '';
if (isArray(value))
return value.map(function (x) { return stringify(x); }).join('');
return String(value);
}
function toEnumerable(val) {
val = toValue(val);
if (isArray(val))
return val;
if (isString(val) && val.length > 0)
return [val];
if (isIterable(val))
return Array.from(val);
if (isObject(val))
return Object.keys(val).map(function (key) { return [key, val[key]]; });
return [];
}
function toArray(val) {
val = toValue(val);
if (isNil(val))
return [];
if (isArray(val))
return val;
return [val];
}
function toValue(value) {
return (value instanceof Drop && isFunction(value.valueOf)) ? value.valueOf() : value;
}
function isNumber(value) {
return typeof value === 'number';
}
function toLiquid(value) {
if (value && isFunction(value.toLiquid))
return toLiquid(value.toLiquid());
return value;
}
function isNil(value) {
return value == null;
}
function isUndefined(value) {
return value === undefined;
}
function isArray(value) {
// be compatible with IE 8
return toString$1.call(value) === '[object Array]';
}
function isIterable(value) {
return isObject(value) && Symbol.iterator in value;
}
/*
* Iterates over own enumerable string keyed properties of an object and invokes iteratee for each property.
* The iteratee is invoked with three arguments: (value, key, object).
* Iteratee functions may exit iteration early by explicitly returning false.
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @return {Object} Returns object.
*/
function forOwn(obj, iteratee) {
obj = obj || {};
for (var k in obj) {
if (hasOwnProperty.call(obj, k)) {
if (iteratee(obj[k], k, obj) === false)
break;
}
}
return obj;
}
function last(arr) {
return arr[arr.length - 1];
}
/*
* Checks if value is the language type of Object.
* (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))
* @param {any} value The value to check.
* @return {Boolean} Returns true if value is an object, else false.
*/
function isObject(value) {
var type = typeof value;
return value !== null && (type === 'object' || type === 'function');
}
function range(start, stop, step) {
if (step === void 0) { step = 1; }
var arr = [];
for (var i = start; i < stop; i += step) {
arr.push(i);
}
return arr;
}
function padStart(str, length, ch) {
if (ch === void 0) { ch = ' '; }
return pad(str, length, ch, function (str, ch) { return ch + str; });
}
function padEnd(str, length, ch) {
if (ch === void 0) { ch = ' '; }
return pad(str, length, ch, function (str, ch) { return str + ch; });
}
function pad(str, length, ch, add) {
str = String(str);
var n = length - str.length;
while (n-- > 0)
str = add(str, ch);
return str;
}
function identify(val) {
return val;
}
function changeCase(str) {
var hasLowerCase = __spreadArray([], __read(str), false).some(function (ch) { return ch >= 'a' && ch <= 'z'; });
return hasLowerCase ? str.toUpperCase() : str.toLowerCase();
}
function ellipsis(str, N) {
return str.length > N ? str.slice(0, N - 3) + '...' : str;
}
// compare string in case-insensitive way, undefined values to the tail
function caseInsensitiveCompare(a, b) {
if (a == null && b == null)
return 0;
if (a == null)
return 1;
if (b == null)
return -1;
a = toLowerCase.call(a);
b = toLowerCase.call(b);
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
function argumentsToValue(fn) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return fn.apply(void 0, __spreadArray([], __read(args.map(toValue)), false));
};
}
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
/**
* targeting ES5, extends Error won't create a proper prototype chain, need a trait to keep track of classes
*/
var TRAIT = '__liquidClass__';
var LiquidError = /** @class */ (function (_super) {
__extends(LiquidError, _super);
function LiquidError(err, token) {
var _this =
/**
* note: for ES5 targeting, `this` will be replaced by return value of Error(),
* thus everything on `this` will be lost, avoid calling `LiquidError` methods here
*/
_super.call(this, typeof err === 'string' ? err : err.message) || this;
_this.context = '';
if (typeof err !== 'string')
Object.defineProperty(_this, 'originalError', { value: err, enumerable: false });
Object.defineProperty(_this, 'token', { value: token, enumerable: false });
Object.defineProperty(_this, TRAIT, { value: 'LiquidError', enumerable: false });
return _this;
}
LiquidError.prototype.update = function () {
Object.defineProperty(this, 'context', { value: mkContext(this.token), enumerable: false });
this.message = mkMessage(this.message, this.token);
this.stack = this.message + '\n' + this.context +
'\n' + this.stack;
if (this.originalError)
this.stack += '\nFrom ' + this.originalError.stack;
};
LiquidError.is = function (obj) {
return (obj === null || obj === void 0 ? void 0 : obj[TRAIT]) === 'LiquidError';
};
return LiquidError;
}(Error));
var TokenizationError = /** @class */ (function (_super) {
__extends(TokenizationError, _super);
function TokenizationError(message, token) {
var _this = _super.call(this, message, token) || this;
_this.name = 'TokenizationError';
_super.prototype.update.call(_this);
return _this;
}
return TokenizationError;
}(LiquidError));
var ParseError = /** @class */ (function (_super) {
__extends(ParseError, _super);
function ParseError(err, token) {
var _this = _super.call(this, err, token) || this;
_this.name = 'ParseError';
_this.message = err.message;
_super.prototype.update.call(_this);
return _this;
}
return ParseError;
}(LiquidError));
var RenderError = /** @class */ (function (_super) {
__extends(RenderError, _super);
function RenderError(err, tpl) {
var _this = _super.call(this, err, tpl.token) || this;
_this.name = 'RenderError';
_this.message = err.message;
_super.prototype.update.call(_this);
return _this;
}
RenderError.is = function (obj) {
return obj.name === 'RenderError';
};
return RenderError;
}(LiquidError));
var LiquidErrors = /** @class */ (function (_super) {
__extends(LiquidErrors, _super);
function LiquidErrors(errors) {
var _this = _super.call(this, errors[0], errors[0].token) || this;
_this.errors = errors;
_this.name = 'LiquidErrors';
var s = errors.length > 1 ? 's' : '';
_this.message = "".concat(errors.length, " error").concat(s, " found");
_super.prototype.update.call(_this);
return _this;
}
LiquidErrors.is = function (obj) {
return obj.name === 'LiquidErrors';
};
return LiquidErrors;
}(LiquidError));
var UndefinedVariableError = /** @class */ (function (_super) {
__extends(UndefinedVariableError, _super);
function UndefinedVariableError(err, token) {
var _this = _super.call(this, err, token) || this;
_this.name = 'UndefinedVariableError';
_this.message = err.message;
_super.prototype.update.call(_this);
return _this;
}
return UndefinedVariableError;
}(LiquidError));
// only used internally; raised where we don't have token information,
// so it can't be an UndefinedVariableError.
var InternalUndefinedVariableError = /** @class */ (function (_super) {
__extends(InternalUndefinedVariableError, _super);
function InternalUndefinedVariableError(variableName) {
var _this = _super.call(this, "undefined variable: ".concat(variableName)) || this;
_this.name = 'InternalUndefinedVariableError';
_this.variableName = variableName;
return _this;
}
return InternalUndefinedVariableError;
}(Error));
var AssertionError = /** @class */ (function (_super) {
__extends(AssertionError, _super);
function AssertionError(message) {
var _this = _super.call(this, message) || this;
_this.name = 'AssertionError';
_this.message = message + '';
return _this;
}
return AssertionError;
}(Error));
function mkContext(token) {
var _a = __read(token.getPosition(), 2), line = _a[0], col = _a[1];
var lines = token.input.split('\n');
var begin = Math.max(line - 2, 1);
var end = Math.min(line + 3, lines.length);
var context = range(begin, end + 1)
.map(function (lineNumber) {
var rowIndicator = (lineNumber === line) ? '>> ' : ' ';
var num = padStart(String(lineNumber), String(end).length);
var text = "".concat(rowIndicator).concat(num, "| ");
var colIndicator = lineNumber === line
? '\n' + padStart('^', col + text.length)
: '';
text += lines[lineNumber - 1];
text += colIndicator;
return text;
})
.join('\n');
return context;
}
function mkMessage(msg, token) {
if (token.file)
msg += ", file:".concat(token.file);
var _a = __read(token.getPosition(), 2), line = _a[0], col = _a[1];
msg += ", line:".concat(line, ", col:").concat(col);
return msg;
}
// **DO NOT CHANGE THIS FILE**
//
// This file is generated by bin/character-gen.js
// bitmask character types to boost performance
var TYPES = [0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 4, 4, 4, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 2, 8, 0, 0, 0, 0, 8, 0, 0, 0, 64, 0, 65, 0, 0, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 0, 0, 2, 2, 2, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
var WORD = 1;
var BLANK = 4;
var QUOTE = 8;
var INLINE_BLANK = 16;
var NUMBER = 32;
var SIGN = 64;
var PUNCTUATION = 128;
function isWord(char) {
var code = char.charCodeAt(0);
return code >= 128 ? !TYPES[code] : !!(TYPES[code] & WORD);
}
TYPES[160] = TYPES[5760] = TYPES[6158] = TYPES[8192] = TYPES[8193] = TYPES[8194] = TYPES[8195] = TYPES[8196] = TYPES[8197] = TYPES[8198] = TYPES[8199] = TYPES[8200] = TYPES[8201] = TYPES[8202] = TYPES[8232] = TYPES[8233] = TYPES[8239] = TYPES[8287] = TYPES[12288] = BLANK;
TYPES[8220] = TYPES[8221] = PUNCTUATION;
function assert(predicate, message) {
if (!predicate) {
var msg = typeof message === 'function'
? message()
: (message || "expect ".concat(predicate, " to be true"));
throw new AssertionError(msg);
}
}
var NullDrop = /** @class */ (function (_super) {
__extends(NullDrop, _super);
function NullDrop() {
return _super !== null && _super.apply(this, arguments) || this;
}
NullDrop.prototype.equals = function (value) {
return isNil(toValue(value));
};
NullDrop.prototype.gt = function () {
return false;
};
NullDrop.prototype.geq = function () {
return false;
};
NullDrop.prototype.lt = function () {
return false;
};
NullDrop.prototype.leq = function () {
return false;
};
NullDrop.prototype.valueOf = function () {
return null;
};
return NullDrop;
}(Drop));
var EmptyDrop = /** @class */ (function (_super) {
__extends(EmptyDrop, _super);
function EmptyDrop() {
return _super !== null && _super.apply(this, arguments) || this;
}
EmptyDrop.prototype.equals = function (value) {
if (value instanceof EmptyDrop)
return false;
value = toValue(value);
if (isString(value) || isArray(value))
return value.length === 0;
if (isObject(value))
return Object.keys(value).length === 0;
return false;
};
EmptyDrop.prototype.gt = function () {
return false;
};
EmptyDrop.prototype.geq = function () {
return false;
};
EmptyDrop.prototype.lt = function () {
return false;
};
EmptyDrop.prototype.leq = function () {
return false;
};
EmptyDrop.prototype.valueOf = function () {
return '';
};
return EmptyDrop;
}(Drop));
var BlankDrop = /** @class */ (function (_super) {
__extends(BlankDrop, _super);
function BlankDrop() {
return _super !== null && _super.apply(this, arguments) || this;
}
BlankDrop.prototype.equals = function (value) {
if (value === false)
return true;
if (isNil(toValue(value)))
return true;
if (isString(value))
return /^\s*$/.test(value);
return _super.prototype.equals.call(this, value);
};
return BlankDrop;
}(EmptyDrop));
var ForloopDrop = /** @class */ (function (_super) {
__extends(ForloopDrop, _super);
function ForloopDrop(length, collection, variable) {
var _this = _super.call(this) || this;
_this.i = 0;
_this.length = length;
_this.name = "".concat(variable, "-").concat(collection);
return _this;
}
ForloopDrop.prototype.next = function () {
this.i++;
};
ForloopDrop.prototype.index0 = function () {
return this.i;
};
ForloopDrop.prototype.index = function () {
return this.i + 1;
};
ForloopDrop.prototype.first = function () {
return this.i === 0;
};
ForloopDrop.prototype.last = function () {
return this.i === this.length - 1;
};
ForloopDrop.prototype.rindex = function () {
return this.length - this.i;
};
ForloopDrop.prototype.rindex0 = function () {
return this.length - this.i - 1;
};
ForloopDrop.prototype.valueOf = function () {
return JSON.stringify(this);
};
return ForloopDrop;
}(Drop));
var BlockDrop = /** @class */ (function (_super) {
__extends(BlockDrop, _super);
function BlockDrop(
// the block render from layout template
superBlockRender) {
if (superBlockRender === void 0) { superBlockRender = function () { return ''; }; }
var _this = _super.call(this) || this;
_this.superBlockRender = superBlockRender;
return _this;
}
/**
* Provide parent access in child block by
* {{ block.super }}
*/
BlockDrop.prototype.super = function () {
return this.superBlockRender();
};
return BlockDrop;
}(Drop));
function isComparable(arg) {
return (arg &&
isFunction(arg.equals) &&
isFunction(arg.gt) &&
isFunction(arg.geq) &&
isFunction(arg.lt) &&
isFunction(arg.leq));
}
var nil = new NullDrop();
var literalValues = {
'true': true,
'false': false,
'nil': nil,
'null': nil,
'empty': new EmptyDrop(),
'blank': new BlankDrop()
};
function createTrie(input) {
var e_1, _a;
var trie = {};
try {
for (var _b = __values(Object.entries(input)), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), name_1 = _d[0], data = _d[1];
var node = trie;
for (var i = 0; i < name_1.length; i++) {
var c = name_1[i];
node[c] = node[c] || {};
if (i === name_1.length - 1 && isWord(name_1[i])) {
node[c].needBoundary = true;
}
node = node[c];
}
node.data = data;
node.end = true;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return trie;
}
// convert an async iterator to a Promise
function toPromise(val) {
return __awaiter(this, void 0, void 0, function () {
var value, done, next, state, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!isIterator(val))
return [2 /*return*/, val];
done = false;
next = 'next';
_a.label = 1;
case 1:
state = val[next](value);
done = state.done;
value = state.value;
next = 'next';
_a.label = 2;
case 2:
_a.trys.push([2, 5, , 6]);
if (isIterator(value))
value = toPromise(value);
if (!isPromise(value)) return [3 /*break*/, 4];
return [4 /*yield*/, value];
case 3:
value = _a.sent();
_a.label = 4;
case 4: return [3 /*break*/, 6];
case 5:
err_1 = _a.sent();
next = 'throw';
value = err_1;
return [3 /*break*/, 6];
case 6:
if (!done) return [3 /*break*/, 1];
_a.label = 7;
case 7: return [2 /*return*/, value];
}
});
});
}
// convert an async iterator to a value in a synchronous manner
function toValueSync(val) {
if (!isIterator(val))
return val;
var value;
var done = false;
var next = 'next';
do {
var state = val[next](value);
done = state.done;
value = state.value;
next = 'next';
if (isIterator(value)) {
try {
value = toValueSync(value);
}
catch (err) {
next = 'throw';
value = err;
}
}
} while (!done);
return value;
}
var rFormat = /%([-_0^#:]+)?(\d+)?([EO])?(.)/;
var monthNames = [
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'
];
var dayNames = [
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
];
var monthNamesShort = monthNames.map(abbr);
var dayNamesShort = dayNames.map(abbr);
function abbr(str) {
return str.slice(0, 3);
}
// prototype extensions
function daysInMonth(d) {
var feb = isLeapYear(d) ? 29 : 28;
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
}
function getDayOfYear(d) {
var num = 0;
for (var i = 0; i < d.getMonth(); ++i) {
num += daysInMonth(d)[i];
}
return num + d.getDate();
}
function getWeekOfYear(d, startDay) {
// Skip to startDay of this week
var now = getDayOfYear(d) + (startDay - d.getDay());
// Find the first startDay of the year
var jan1 = new Date(d.getFullYear(), 0, 1);
var then = (7 - jan1.getDay() + startDay);
return String(Math.floor((now - then) / 7) + 1);
}
function isLeapYear(d) {
var year = d.getFullYear();
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)));
}
function ordinal(d) {
var date = d.getDate();
if ([11, 12, 13].includes(date))
return 'th';
switch (date % 10) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
default: return 'th';
}
}
function century(d) {
return parseInt(d.getFullYear().toString().substring(0, 2), 10);
}
// default to 0
var padWidths = {
d: 2,
e: 2,
H: 2,
I: 2,
j: 3,
k: 2,
l: 2,
L: 3,
m: 2,
M: 2,
S: 2,
U: 2,
W: 2
};
// default to '0'
var padChars = {
a: ' ',
A: ' ',
b: ' ',
B: ' ',
c: ' ',
e: ' ',
k: ' ',
l: ' ',
p: ' ',
P: ' '
};
function getTimezoneOffset(d, opts) {
var nOffset = Math.abs(d.getTimezoneOffset());
var h = Math.floor(nOffset / 60);
var m = nOffset % 60;
return (d.getTimezoneOffset() > 0 ? '-' : '+') +
padStart(h, 2, '0') +
(opts.flags[':'] ? ':' : '') +
padStart(m, 2, '0');
}
var formatCodes = {
a: function (d) { return dayNamesShort[d.getDay()]; },
A: function (d) { return dayNames[d.getDay()]; },
b: function (d) { return monthNamesShort[d.getMonth()]; },
B: function (d) { return monthNames[d.getMonth()]; },
c: function (d) { return d.toLocaleString(); },
C: function (d) { return century(d); },
d: function (d) { return d.getDate(); },
e: function (d) { return d.getDate(); },
H: function (d) { return d.getHours(); },
I: function (d) { return String(d.getHours() % 12 || 12); },
j: function (d) { return getDayOfYear(d); },
k: function (d) { return d.getHours(); },
l: function (d) { return String(d.getHours() % 12 || 12); },
L: function (d) { return d.getMilliseconds(); },
m: function (d) { return d.getMonth() + 1; },
M: function (d) { return d.getMinutes(); },
N: function (d, opts) {
var width = Number(opts.width) || 9;
var str = String(d.getMilliseconds()).slice(0, width);
return padEnd(str, width, '0');
},
p: function (d) { return (d.getHours() < 12 ? 'AM' : 'PM'); },
P: function (d) { return (d.getHours() < 12 ? 'am' : 'pm'); },
q: function (d) { return ordinal(d); },
s: function (d) { return Math.round(d.getTime() / 1000); },
S: function (d) { return d.getSeconds(); },
u: function (d) { return d.getDay() || 7; },
U: function (d) { return getWeekOfYear(d, 0); },
w: function (d) { return d.getDay(); },
W: function (d) { return getWeekOfYear(d, 1); },
x: function (d) { return d.toLocaleDateString(); },
X: function (d) { return d.toLocaleTimeString(); },
y: function (d) { return d.getFullYear().toString().slice(2, 4); },
Y: function (d) { return d.getFullYear(); },
z: getTimezoneOffset,
Z: function (d, opts) {
if (d.getTimezoneName) {
return d.getTimezoneName() || getTimezoneOffset(d, opts);
}
return (typeof Intl !== 'undefined' ? Intl.DateTimeFormat().resolvedOptions().timeZone : '');
},
't': function () { return '\t'; },
'n': function () { return '\n'; },
'%': function () { return '%'; }
};
formatCodes.h = formatCodes.b;
function strftime(d, formatStr) {
var output = '';
var remaining = formatStr;
var match;
while ((match = rFormat.exec(remaining))) {
output += remaining.slice(0, match.index);
remaining = remaining.slice(match.index + match[0].length);
output += format(d, match);
}
return output + remaining;
}
function format(d, match) {
var e_1, _a;
var _b = __read(match, 5), input = _b[0], _c = _b[1], flagStr = _c === void 0 ? '' : _c, width = _b[2], modifier = _b[3], conversion = _b[4];
var convert = formatCodes[conversion];
if (!convert)
return input;
var flags = {};
try {
for (var flagStr_1 = __values(flagStr), flagStr_1_1 = flagStr_1.next(); !flagStr_1_1.done; flagStr_1_1 = flagStr_1.next()) {
var flag = flagStr_1_1.value;
flags[flag] = true;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (flagStr_1_1 && !flagStr_1_1.done && (_a = flagStr_1.return)) _a.call(flagStr_1);
}
finally { if (e_1) throw e_1.error; }
}
var ret = String(convert(d, { flags: flags, width: width, modifier: modifier }));
var padChar = padChars[conversion] || '0';
var padWidth = width || padWidths[conversion] || 0;
if (flags['^'])
ret = ret.toUpperCase();
else if (flags['#'])
ret = changeCase(ret);
if (flags['_'])
padChar = ' ';
else if (flags['0'])
padChar = '0';
if (flags['-'])
padWidth = 0;
return padStart(ret, padWidth, padChar);
}
// one minute in milliseconds
var OneMinute = 60000;
var ISO8601_TIMEZONE_PATTERN = /([zZ]|([+-])(\d{2}):(\d{2}))$/;
/**
* A date implementation with timezone info, just like Ruby date
*
* Implementation:
* - create a Date offset by it's timezone difference, avoiding overriding a bunch of methods
* - rewrite getTimezoneOffset() to trick strftime
*/
var TimezoneDate = /** @class */ (function () {
function TimezoneDate(init, timezone) {
this.date = init instanceof TimezoneDate
? init.date
: new Date(init);
this.timezoneOffset = isString(timezone) ? TimezoneDate.getTimezoneOffset(timezone, this.date) : timezone;
this.timezoneName = isString(timezone) ? timezone : '';
var diff = (this.date.getTimezoneOffset() - this.timezoneOffset) * OneMinute;
var time = this.date.getTime() + diff;
this.displayDate = new Date(time);
}
TimezoneDate.prototype.getTime = function () {
return this.displayDate.getTime();
};
TimezoneDate.prototype.getMilliseconds = function () {
return this.displayDate.getMilliseconds();
};
TimezoneDate.prototype.getSeconds = function () {
return this.displayDate.getSeconds();
};
TimezoneDate.prototype.getMinutes = function () {
return this.displayDate.getMinutes();
};
TimezoneDate.prototype.getHours = function () {
return this.displayDate.getHours();
};
TimezoneDate.prototype.getDay = function () {
return this.displayDate.getDay();
};
TimezoneDate.prototype.getDate = function () {
return this.displayDate.getDate();
};
TimezoneDate.prototype.getMonth = function () {
return this.displayDate.getMonth();
};
TimezoneDate.prototype.getFullYear = function () {
return this.displayDate.getFullYear();
};
TimezoneDate.prototype.toLocaleString = function (locale, init) {
if (init === null || init === void 0 ? void 0 : init.timeZone) {
return this.date.toLocaleString(locale, init);
}
return this.displayDate.toLocaleString(locale, init);
};
TimezoneDate.prototype.toLocaleTimeString = function (locale) {
return this.displayDate.toLocaleTimeString(locale);
};
TimezoneDate.prototype.toLocaleDateString = function (locale) {
return this.displayDate.toLocaleDateString(locale);
};
TimezoneDate.prototype.getTimezoneOffset = function () {
return this.timezoneOffset;
};
TimezoneDate.prototype.getTimezoneName = function () {
return this.timezoneName;
};
/**
* Create a Date object fixed to it's declared Timezone. Both
* - 2021-08-06T02:29:00.000Z and
* - 2021-08-06T02:29:00.000+08:00
* will always be displayed as
* - 2021-08-06 02:29:00
* regardless timezoneOffset in JavaScript realm
*
* The implementation hack:
* Instead of calling `.getMonth()`/`.getUTCMonth()` respect to `preserveTimezones`,
* we create a different Date to trick strftime, it's both simpler and more performant.
* Given that a template is expected to be parsed fewer times than rendered.
*/
TimezoneDate.createDateFixedToTimezone = function (dateString) {
var m = dateString.match(ISO8601_TIMEZONE_PATTERN);
// representing a UTC timestamp
if (m && m[1] === 'Z') {
return new TimezoneDate(+new Date(dateString), 0);
}
// has a timezone specified
if (m && m[2] && m[3] && m[4]) {
var _a = __read(m, 5), sign = _a[2], hours = _a[3], minutes = _a[4];
var offset = (sign === '+' ? -1 : 1) * (parseInt(hours, 10) * 60 + parseInt(minutes, 10));
return new TimezoneDate(+new Date(dateString), offset);
}
return new Date(dateString);
};
TimezoneDate.getTimezoneOffset = function (timezoneName, date) {
if (date === void 0) { date = new Date(); }
var localDateString = date.toLocaleString('en-US', { timeZone: timezoneName });
var utcDateString = date.toLocaleString('en-US', { timeZone: 'UTC' });
var localDate = new Date(localDateString);
var utcDate = new Date(utcDateString);
return (+utcDate - +localDate) / (60 * 1000);
};
return TimezoneDate;
}());
var DelimitedToken = /** @class */ (function (_super) {
__extends(DelimitedToken, _super);
function DelimitedToken(kind, _a, input, begin, end, trimLeft, trimRight, file) {
var _b = __read(_a, 2), contentBegin = _b[0], contentEnd = _b[1];
var _this = _super.call(this, kind, input, begin, end, file) || this;
_this.trimLeft = false;
_this.trimRight = false;
var tl = input[contentBegin] === '-';
var tr = input[contentEnd - 1] === '-';
var l = tl ? contentBegin + 1 : contentBegin;
var r = tr ? contentEnd - 1 : contentEnd;
while (l < r && (TYPES[input.charCodeAt(l)] & BLANK))
l++;
while (r > l && (TYPES[input.charCodeAt(r - 1)] & BLANK))
r--;
_this.contentRange = [l, r];
_this.trimLeft = tl || trimLeft;
_this.trimRight = tr || trimRight;
return _this;
}
Object.defineProperty(DelimitedToken.prototype, "content", {
get: function () {
return this.input.slice(this.contentRange[0], this.contentRange[1]);
},
enumerable: false,
configurable: true
});
return DelimitedToken;
}(Token));
var TagToken = /** @class */ (function (_super) {
__extends(TagToken, _super);
function TagToken(input, begin, end, options, file) {
var _this = this;
var trimTagLeft = options.trimTagLeft, trimTagRight = options.trimTagRight, tagDelimiterLeft = options.tagDelimiterLeft, tagDelimiterRight = options.tagDelimiterRight;
var _a = __read([begin + tagDelimiterLeft.length, end - tagDelimiterRight.length], 2), valueBegin = _a[0], valueEnd = _a[1];
_this = _super.call(this, exports.TokenKind.Tag, [valueBegin, valueEnd], input, begin, end, trimTagLeft, trimTagRight, file) || this;
_this.tokenizer = new Tokenizer(input, options.operators, file, _this.contentRange);
_this.name = _this.tokenizer.readTagName();
_this.tokenizer.assert(_this.name, "illegal tag syntax, tag name expected");
_this.tokenizer.skipBlank();
return _this;
}
Object.defineProperty(TagToken.prototype, "args", {
get: function () {
return this.tokenizer.input.slice(this.tokenizer.p, this.contentRange[1]);
},
enumerable: false,
configurable: true
});
return TagToken;
}(DelimitedToken));
var OutputToken = /** @class */ (function (_super) {
__extends(OutputToken, _super);
function OutputToken(input, begin, end, options, file) {
var trimOutputLeft = options.trimOutputLeft, trimOutputRight = options.trimOutputRight, outputDelimiterLeft = options.outputDelimiterLeft, outputDelimiterRight = options.outputDelimiterRight;
var valueRange = [begin + outputDelimiterLeft.length, end - outputDelimiterRight.length];
return _super.call(this, exports.TokenKind.Output, valueRange, input, begin, end, trimOutputLeft, trimOutputRight, file) || this;
}
return OutputToken;
}(DelimitedToken));
var HTMLToken = /** @class */ (function (_super) {
__extends(HTMLToken, _super);
function HTMLToken(input, begin, end, file) {
var _this = _super.call(this, exports.TokenKind.HTML, input, begin, end, file) || this;
_this.input = input;
_this.begin = begin;
_this.end = end;
_this.file = file;
_this.trimLeft = 0;
_this.trimRight = 0;
return _this;
}
HTMLToken.prototype.getContent = function () {
return this.input.slice(this.begin + this.trimLeft, this.end - this.trimRight);
};
return HTMLToken;
}(Token));
var NumberToken = /** @class */ (function (_super) {
__extends(NumberToken, _super);
function NumberToken(input, begin, end, file) {
var _this = _super.call(this, exports.TokenKind.Number, input, begin, end, file) || this;
_this.input = input;
_this.begin = begin;
_this.end = end;
_this.file = file;
_this.content = Number(_this.getText());
return _this;
}
return NumberToken;
}(Token));
var IdentifierToken = /** @class */ (function (_super) {
__extends(IdentifierToken, _super);
function IdentifierToken(input, begin, end, file) {
var _this = _super.call(this, exports.TokenKind.Word, input, begin, end, file) || this;
_this.input = input;
_this.begin = begin;
_this.end = end;
_this.file = file;
_this.content = _this.getText();
return _this;
}
IdentifierToken.prototype.isNumber = function (allowSign) {
if (allowSign === void 0) { allowSign = false; }
var begin = allowSign && TYPES[this.input.charCodeAt(this.begin)] & SIGN
? this.begin + 1
: this.begin;
for (var i = begin; i < this.end; i++) {
if (!(TYPES[this.input.charCodeAt(i)] & NUMBER))
return false;
}
return true;
};
return IdentifierToken;
}(Token));
var LiteralToken = /** @class */ (function (_super) {
__extends(LiteralToken, _super);
function LiteralToken(input, begin, end, file) {
var _this = _super.call(this, exports.TokenKind.Literal, input, begin, end, file) || this;
_this.input = input;
_this.begin = begin;
_this.end = end;
_this.file = file;
_this.literal = _this.getText();
_this.content = literalValues[_this.literal];
return _this;
}
return LiteralToken;
}(Token));
var operatorPrecedences = {
'==': 2,
'!=': 2,
'>': 2,
'<': 2,
'>=': 2,
'<=': 2,
'contains': 2,
'not': 1,
'and': 0,
'or': 0
};
var operatorTypes = {
'==': 0 /* OperatorType.Binary */,
'!=': 0 /* OperatorType.Binary */,
'>': 0 /* OperatorType.Binary */,
'<': 0 /* OperatorType.Binary */,
'>=': 0 /* OperatorType.Binary */,
'<=': 0 /* OperatorType.Binary */,
'contains': 0 /* OperatorType.Binary */,
'not': 1 /* OperatorType.Unary */,
'and': 0 /* OperatorType.Binary */,
'or': 0 /* OperatorType.Binary */
};
var OperatorToken = /** @class */ (function (_super) {
__extends(OperatorToken, _super);
function OperatorToken(input, begin, end, file) {
var _this = _super.call(this, exports.TokenKind.Operator, input, begin, end, file) || this;
_this.input = input;
_this.begin = begin;
_this.end = end;
_this.file = file;
_this.operator = _this.getText();
return _this;
}
OperatorToken.prototype.getPrecedence = function () {
var key = this.getText();
return key in operatorPrecedences ? operatorPrecedences[key] : 1;
};
return OperatorToken;
}(Token));
var PropertyAccessToken = /** @class */ (function (_super) {
__extends(PropertyAccessToken, _super);
function PropertyAccessToken(variable, props, input, begin, end, file) {
var _this = _super.call(this, exports.TokenKind.PropertyAccess, input, begin, end, file) || this;
_this.variable = variable;
_this.props = props;
return _this;
}
return PropertyAccessToken;
}(Token));
var FilterToken = /** @class */ (function (_super) {
__extends(FilterToken, _super);
function FilterToken(name, args, input, begin, end, file) {
var _this = _super.call(this, exports.TokenKind.Filter, input, begin, end, file) || this;
_this.name = name;
_this.args = args;
return _this;
}
return FilterToken;
}(Token));
var HashToken = /** @class */ (function (_super) {
__extends(HashToken, _super);
function HashToken(input, begin, end, name, value, file) {
var _this = _super.call(this, exports.TokenKind.Hash, input, begin, end, file) || this;
_this.input = input;
_this.begin = begin;
_this.end = end;
_this.name = name;
_this.value = value;
_this.file = file;
return _this;
}
return HashToken;
}(Token));
var rHex = /[\da-fA-F]/;
var rOct = /[0-7]/;
var escapeChar = {
b: '\b',
f: '\f',
n: '\n',
r: '\r',
t: '\t',
v: '\x0B'
};
function hexVal(c) {
var code = c.charCodeAt(0);
if (code >= 97)
return code - 87;
if (code >= 65)
return code - 55;
return code - 48;
}
function parseStringLiteral(str) {
var ret = '';
for (var i = 1; i < str.length - 1; i++) {
if (str[i] !== '\\') {
ret += str[i];
continue;
}
if (escapeChar[str[i + 1]] !== undefined) {
ret += escapeChar[str[++i]];
}
else if (str[i + 1] === 'u') {
var val = 0;
var j = i + 2;
while (j <= i + 5 && rHex.test(str[j])) {
val = val * 16 + hexVal(str[j++]);
}
i = j - 1;
ret += String.fromCharCode(val);
}
else if (!rOct.test(str[i + 1])) {
ret += str[++i];
}
else {
var j = i + 1;
var val = 0;
while (j <= i + 3 && rOct.test(str[j])) {
val = val * 8 + hexVal(str[j++]);
}
i = j - 1;
ret += String.fromCharCode(val);
}
}
return ret;
}
var QuotedToken = /** @class */ (function (_super) {
__extends(QuotedToken, _super);
function QuotedToken(input, begin, end, file) {
var _this = _super.call(this, exports.TokenKind.Quoted, input, begin, end, file) || this;
_this.input = input;
_this.begin = begin;
_this.end = end;
_this.file = file;
_this.content = parseStringLiteral(_this.getText());
return _this;
}
return QuotedToken;
}(Token));
var RangeToken = /** @class */ (function (_super) {
__extends(RangeToken, _super);
function RangeToken(input, begin, end, lhs, rhs, file) {
var _this = _super.call(this, exports.TokenKind.Range, input, begin, end, file) || this;
_this.input = input;
_this.begin = begin;
_this.end = end;
_this.lhs = lhs;
_this.rhs = rhs;
_this.file = file;
return _this;
}
return RangeToken;
}(Token));
/**
* LiquidTagToken is different from TagToken by not having delimiters `{%` or `%}`
*/
var LiquidTagToken = /** @class */ (function (_super) {
__extends(LiquidTagToken, _super);
function LiquidTagToken(input, begin, end, options, file) {
var _this = _super.call(this, exports.TokenKind.Tag, [begin, end], input, begin, end, false, false, file) || this;
_this.tokenizer = new Tokenizer(input, options.operators, file, _this.contentRange);
_this.name = _this.tokenizer.readTagName();
_this.tokenizer.assert(_this.name, 'illegal liquid tag syntax');
_this.tokenizer.skipBlank();
_this.args = _this.tokenizer.remaining();
return _this;
}
return LiquidTagToken;
}(DelimitedToken));
/**
* value expression with optional filters
* e.g.
* {% assign foo="bar" | append: "coo" %}
*/
var FilteredValueToken = /** @class */ (function (_super) {
__extends(FilteredValueToken, _super);
function FilteredValueToken(initial, filters, input, begin, end, file) {
var _this = _super.call(this, exports.TokenKind.FilteredValue, input, begin, end, file) || this;
_this.initial = initial;
_this.filters = filters;
_this.input = input;
_this.begin = begin;
_this.end = end;
_this.file = file;
return _this;
}
return FilteredValueToken;
}(Token));
var SimpleEmitter = /** @class */ (function () {
function SimpleEmitter() {
this.buffer = '';
}
SimpleEmitter.prototype.write = function (html) {
this.buffer += stringify(html);
};
return SimpleEmitter;
}());
var StreamedEmitter = /** @class */ (function () {
function StreamedEmitter() {
this.buffer = '';
this.stream = null;
throw new Error('streaming not supported in browser');
}
return StreamedEmitter;
}());
var KeepingTypeEmitter = /** @class */ (function () {
function KeepingTypeEmitter() {
this.buffer = '';
}
KeepingTypeEmitter.prototype.write = function (html) {
html = toValue(html);
// This will only preserve the type if the value is isolated.
// I.E:
// {{ my-port }} -> 42
// {{ my-host }}:{{ my-port }} -> 'host:42'
if (typeof html !== 'string' && this.buffer === '') {
this.buffer = html;
}
else {
this.buffer = stringify(this.buffer) + stringify(html);
}
};
return KeepingTypeEmitter;
}());
var Render = /** @class */ (function () {
function Render() {
}
Render.prototype.renderTemplatesToNodeStream = function (templates, ctx) {
var _this = this;
var emitter = new StreamedEmitter();
Promise.resolve().then(function () { return toPromise(_this.renderTemplates(templates, ctx, emitter)); })
.then(function () { return emitter.end(); }, function (err) { return emitter.error(err); });
return emitter.stream;
};
Render.prototype.renderTemplates = function (templates, ctx, emitter) {
var errors, templates_1, templates_1_1, tpl, html, e_1, err, e_2_1;
var e_2, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!emitter) {
emitter = ctx.opts.keepOutputType ? new KeepingTypeEmitter() : new SimpleEmitter();
}
errors = [];
_b.label = 1;
case 1:
_b.trys.push([1, 8, 9, 10]);
templates_1 = __values(templates), templates_1_1 = templates_1.next();
_b.label = 2;
case 2:
if (!!templates_1_1.done) return [3 /*break*/, 7];
tpl = templates_1_1.value;
_b.label = 3;
case 3:
_b.trys.push([3, 5, , 6]);
return [4 /*yield*/, tpl.render(ctx, emitter)
// if not, it'll return an `html`, write to the emitter for it
];
case 4:
html = _b.sent();
// if not, it'll return an `html`, write to the emitter for it
html && emitter.write(html);
if (emitter['break'] || emitter['continue'])
return [3 /*break*/, 7];
return [3 /*break*/, 6];
case 5:
e_1 = _b.sent();
err = LiquidError.is(e_1) ? e_1 : new RenderError(e_1, tpl);
if (ctx.opts.catchAllErrors)
errors.push(err);
else
throw err;
return [3 /*break*/, 6];
case 6:
templates_1_1 = templates_1.next();
return [3 /*break*/, 2];
case 7: return [3 /*break*/, 10];
case 8:
e_2_1 = _b.sent();
e_2 = { error: e_2_1 };
return [3 /*break*/, 10];
case 9:
try {
if (templates_1_1 && !templates_1_1.done && (_a = templates_1.return)) _a.call(templates_1);
}
finally { if (e_2) throw e_2.error; }
return [7 /*endfinally*/];
case 10:
if (errors.length) {
throw new LiquidErrors(errors);
}
return [2 /*return*/, emitter.buffer];
}
});
};
return Render;
}());
var Expression = /** @class */ (function () {
function Expression(tokens) {
this.postfix = __spreadArray([], __read(toPostfix(tokens)), false);
}
Expression.prototype.evaluate = function (ctx, lenient) {
var operands, _a, _b, token, r, result, l, _c, _d, e_1_1;
var e_1, _e;
return __generator(this, function (_f) {
switch (_f.label) {
case 0:
assert(ctx, 'unable to evaluate: context not defined');
operands = [];
_f.label = 1;
case 1:
_f.trys.push([1, 11, 12, 13]);
_a = __values(this.postfix), _b = _a.next();
_f.label = 2;
case 2:
if (!!_b.done) return [3 /*break*/, 10];
token = _b.value;
if (!isOperatorToken(token)) return [3 /*break*/, 7];
r = operands.pop();
result = void 0;
if (!(operatorTypes[token.operator] === 1 /* OperatorType.Unary */)) return [3 /*break*/, 4];
return [4 /*yield*/, ctx.opts.operators[token.operator](r, ctx)];
case 3:
result = _f.sent();
return [3 /*break*/, 6];
case 4:
l = operands.pop();
return [4 /*yield*/, ctx.opts.operators[token.operator](l, r, ctx)];
case 5:
result = _f.sent();
_f.label = 6;
case 6:
operands.push(result);
return [3 /*break*/, 9];
case 7:
_d = (_c = operands).push;
return [4 /*yield*/, evalToken(token, ctx, lenient)];
case 8:
_d.apply(_c, [_f.sent()]);
_f.label = 9;
case 9:
_b = _a.next();
return [3 /*break*/, 2];
case 10: return [3 /*break*/, 13];
case 11:
e_1_1 = _f.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 13];
case 12:
try {
if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
}
finally { if (e_1) throw e_1.error; }
return [7 /*endfinally*/];
case 13: return [2 /*return*/, operands[0]];
}
});
};
Expression.prototype.valid = function () {
return !!this.postfix.length;
};
return Expression;
}());
function evalToken(token, ctx, lenient) {
if (lenient === void 0) { lenient = false; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!token)
return [2 /*return*/];
if ('content' in token)
return [2 /*return*/, token.content];
if (!isPropertyAccessToken(token)) return [3 /*break*/, 2];
return [4 /*yield*/, evalPropertyAccessToken(token, ctx, lenient)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
if (!isRangeToken(token)) return [3 /*break*/, 4];
return [4 /*yield*/, evalRangeToken(token, ctx)];
case 3: return [2 /*return*/, _a.sent()];
case 4: return [2 /*return*/];
}
});
}
function evalPropertyAccessToken(token, ctx, lenient) {
var props, _a, _b, prop, _c, _d, e_2_1, variable, e_3;
var e_2, _e;
return __generator(this, function (_f) {
switch (_f.label) {
case 0:
props = [];
_f.label = 1;
case 1:
_f.trys.push([1, 6, 7, 8]);
_a = __values(token.props), _b = _a.next();
_f.label = 2;
case 2:
if (!!_b.done) return [3 /*break*/, 5];
prop = _b.value;
_d = (_c = props).push;
return [4 /*yield*/, evalToken(prop, ctx, false)];
case 3:
_d.apply(_c, [(_f.sent())]);
_f.label = 4;
case 4:
_b = _a.next();
return [3 /*break*/, 2];
case 5: return [3 /*break*/, 8];
case 6:
e_2_1 = _f.sent();
e_2 = { error: e_2_1 };
return [3 /*break*/, 8];
case 7:
try {
if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
}
finally { if (e_2) throw e_2.error; }
return [7 /*endfinally*/];
case 8:
_f.trys.push([8, 14, , 15]);
if (!token.variable) return [3 /*break*/, 11];
return [4 /*yield*/, evalToken(token.variable, ctx, lenient)];
case 9:
variable = _f.sent();
return [4 /*yield*/, ctx._getFromScope(variable, props)];
case 10: return [2 /*return*/, _f.sent()];
case 11: return [4 /*yield*/, ctx._get(props)];
case 12: return [2 /*return*/, _f.sent()];
case 13: return [3 /*break*/, 15];
case 14:
e_3 = _f.sent();
if (lenient && e_3.name === 'InternalUndefinedVariableError')
return [2 /*return*/, null];
throw (new UndefinedVariableError(e_3, token));
case 15: return [2 /*return*/];
}
});
}
function evalQuotedToken(token) {
return token.content;
}
function evalRangeToken(token, ctx) {
var low, high;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, evalToken(token.lhs, ctx)];
case 1:
low = _a.sent();
return [4 /*yield*/, evalToken(token.rhs, ctx)];
case 2:
high = _a.sent();
return [2 /*return*/, range(+low, +high + 1)];
}
});
}
function toPostfix(tokens) {
var ops, tokens_1, tokens_1_1, token, e_4_1;
var e_4, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
ops = [];
_b.label = 1;
case 1:
_b.trys.push([1, 10, 11, 12]);
tokens_1 = __values(tokens), tokens_1_1 = tokens_1.next();
_b.label = 2;
case 2:
if (!!tokens_1_1.done) return [3 /*break*/, 9];
token = tokens_1_1.value;
if (!isOperatorToken(token)) return [3 /*break*/, 6];
_b.label = 3;
case 3:
if (!(ops.length && ops[ops.length - 1].getPrecedence() > token.getPrecedence())) return [3 /*break*/, 5];
return [4 /*yield*/, ops.pop()];
case 4:
_b.sent();
return [3 /*break*/, 3];
case 5:
ops.push(token);
return [3 /*break*/, 8];
case 6: return [4 /*yield*/, token];
case 7:
_b.sent();
_b.label = 8;
case 8:
tokens_1_1 = tokens_1.next();
return [3 /*break*/, 2];
case 9: return [3 /*break*/, 12];
case 10:
e_4_1 = _b.sent();
e_4 = { error: e_4_1 };
return [3 /*break*/, 12];
case 11:
try {
if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
}
finally { if (e_4) throw e_4.error; }
return [7 /*endfinally*/];
case 12:
if (!ops.length) return [3 /*break*/, 14];
return [4 /*yield*/, ops.pop()];
case 13:
_b.sent();
return [3 /*break*/, 12];
case 14: return [2 /*return*/];
}
});
}
function isTruthy(val, ctx) {
return !isFalsy(val, ctx);
}
function isFalsy(val, ctx) {
val = toValue(val);
if (ctx.opts.jsTruthy) {
return !val;
}
else {
return val === false || undefined === val || val === null;
}
}
var defaultOperators = {
'==': equals,
'!=': function (l, r) { return !equals(l, r); },
'>': function (l, r) {
if (isComparable(l))
return l.gt(r);
if (isComparable(r))
return r.lt(l);
return toValue(l) > toValue(r);
},
'<': function (l, r) {
if (isComparable(l))
return l.lt(r);
if (isComparable(r))
return r.gt(l);
return toValue(l) < toValue(r);
},
'>=': function (l, r) {
if (isComparable(l))
return l.geq(r);
if (isComparable(r))
return r.leq(l);
return toValue(l) >= toValue(r);
},
'<=': function (l, r) {
if (isComparable(l))
return l.leq(r);
if (isComparable(r))
return r.geq(l);
return toValue(l) <= toValue(r);
},
'contains': function (l, r) {
l = toValue(l);
if (isArray(l))
return l.some(function (i) { return equals(i, r); });
if (isFunction(l === null || l === void 0 ? void 0 : l.indexOf))
return l.indexOf(toValue(r)) > -1;
return false;
},
'not': function (v, ctx) { return isFalsy(toValue(v), ctx); },
'and': function (l, r, ctx) { return isTruthy(toValue(l), ctx) && isTruthy(toValue(r), ctx); },
'or': function (l, r, ctx) { return isTruthy(toValue(l), ctx) || isTruthy(toValue(r), ctx); }
};
function equals(lhs, rhs) {
if (isComparable(lhs))
return lhs.equals(rhs);
if (isComparable(rhs))
return rhs.equals(lhs);
lhs = toValue(lhs);
rhs = toValue(rhs);
if (isArray(lhs)) {
return isArray(rhs) && arrayEquals(lhs, rhs);
}
return lhs === rhs;
}
function arrayEquals(lhs, rhs) {
if (lhs.length !== rhs.length)
return false;
return !lhs.some(function (value, i) { return !equals(value, rhs[i]); });
}
var Node = /** @class */ (function () {
function Node(key, value, next, prev) {
this.key = key;
this.value = value;
this.next = next;
this.prev = prev;
}
return Node;
}());
var LRU = /** @class */ (function () {
function LRU(limit, size) {
if (size === void 0) { size = 0; }
this.limit = limit;
this.size = size;
this.cache = {};
this.head = new Node('HEAD', null, null, null);
this.tail = new Node('TAIL', null, null, null);
this.head.next = this.tail;
this.tail.prev = this.head;
}
LRU.prototype.write = function (key, value) {
if (this.cache[key]) {
this.cache[key].value = value;
}
else {
var node = new Node(key, value, this.head.next, this.head);
this.head.next.prev = node;
this.head.next = node;
this.cache[key] = node;
this.size++;
this.ensureLimit();
}
};
LRU.prototype.read = function (key) {
if (!this.cache[key])
return;
var value = this.cache[key].value;
this.remove(key);
this.write(key, value);
return value;
};
LRU.prototype.remove = function (key) {
var node = this.cache[key];
node.prev.next = node.next;
node.next.prev = node.prev;
delete this.cache[key];
this.size--;
};
LRU.prototype.clear = function () {
this.head.next = this.tail;
this.tail.prev = this.head;
this.size = 0;
this.cache = {};
};
LRU.prototype.ensureLimit = function () {
if (this.size > this.limit)
this.remove(this.tail.prev.key);
};
return LRU;
}());
function domResolve(root, path) {
var base = document.createElement('base');
base.href = root;
var head = document.getElementsByTagName('head')[0];
head.insertBefore(base, head.firstChild);
var a = document.createElement('a');
a.href = path;
var resolved = a.href;
head.removeChild(base);
return resolved;
}
function resolve(root, filepath, ext) {
if (root.length && last(root) !== '/')
root += '/';
var url = domResolve(root, filepath);
return url.replace(/^(\w+:\/\/[^/]+)(\/[^?]+)/, function (str, origin, path) {
var last = path.split('/').pop();
if (/\.\w+$/.test(last))
return str;
return origin + path + ext;
});
}
function readFile(url) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
}
else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = function () {
reject(new Error('An error occurred whilst receiving the response.'));
};
xhr.open('GET', url);
xhr.send();
})];
});
});
}
function readFileSync(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
if (xhr.status < 200 || xhr.status >= 300) {
throw new Error(xhr.statusText);
}
return xhr.responseText;
}
function exists(filepath) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, true];
});
});
}
function existsSync(filepath) {
return true;
}
function dirname(filepath) {
return domResolve(filepath, '.');
}
var sep = '/';
var fs = /*#__PURE__*/Object.freeze({
__proto__: null,
resolve: resolve,
readFile: readFile,
readFileSync: readFileSync,
exists: exists,
existsSync: existsSync,
dirname: dirname,
sep: sep
});
function defaultFilter(value, defaultValue) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
value = toValue(value);
if (isArray(value) || isString(value))
return value.length ? value : defaultValue;
if (value === false && (new Map(args)).get('allow_false'))
return false;
return isFalsy(value, this.context) ? defaultValue : value;
}
function json(value, space) {
if (space === void 0) { space = 0; }
return JSON.stringify(value, null, space);
}
function inspect(value, space) {
if (space === void 0) { space = 0; }
var ancestors = [];
return JSON.stringify(value, function (_key, value) {
if (typeof value !== 'object' || value === null)
return value;
// `this` is the object that value is contained in, i.e., its direct parent.
while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
ancestors.pop();
if (ancestors.includes(value))
return '[Circular]';
ancestors.push(value);
return value;
}, space);
}
function to_integer(value) {
return Number(value);
}
var raw = {
raw: true,
handler: identify
};
var misc = {
default: defaultFilter,
raw: raw,
jsonify: json,
to_integer: to_integer,
json: json,
inspect: inspect
};
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
var unescapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
};
function escape(str) {
return stringify(str).replace(/&|<|>|"|'/g, function (m) { return escapeMap[m]; });
}
function xml_escape(str) {
return escape(str);
}
function unescape(str) {
return stringify(str).replace(/&(amp|lt|gt|#34|#39);/g, function (m) { return unescapeMap[m]; });
}
function escape_once(str) {
return escape(unescape(stringify(str)));
}
function newline_to_br(v) {
return stringify(v).replace(/\r?\n/gm, '
\n');
}
function strip_html(v) {
return stringify(v).replace(/