All files helpers.js

93.47% Statements 86/92
81.25% Branches 52/64
100% Functions 13/13
94.18% Lines 81/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263                                                                                                      39x                   85x 523x 523x 523x 523x 14x 11x   14x                         85x 85x           4x                       2298x                   1149x 1149x 1149x 1149x                               321x 291x   321x 321x 321x       321x   321x 419x   321x     321x     320x   320x 320x 98x 98x 96x   2x           1x   320x   319x 19x     2x 2x   321x 321x             11x 11x 11x 11x 11x 148x 148x 2x 2x 146x 2x 2x 144x 5x 5x   139x     11x 11x   11x             323x     323x 323x   24x 24x 24x     24x 16x   24x       299x 299x             16x     16x 2x       14x     14x         14x 14x         14x 14x  
/* istanbul ignore next */
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
/* istanbul ignore next */
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
/* istanbul ignore next */
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
/* istanbul ignore next */
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
/* istanbul ignore next */
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
/* istanbul ignore next */
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
/* istanbul ignore next */
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
/* istanbul ignore next */
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
/* istanbul ignore next */
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
/* istanbul ignore next */
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
/* istanbul ignore next */
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
import "core-js/modules/es.symbol.js";
import "core-js/modules/es.symbol.description.js";
import "core-js/modules/es.symbol.iterator.js";
import "core-js/modules/es.array.concat.js";
import "core-js/modules/es.array.from.js";
import "core-js/modules/es.array.is-array.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.array.map.js";
import "core-js/modules/es.array.slice.js";
import "core-js/modules/es.date.to-string.js";
import "core-js/modules/es.function.name.js";
import "core-js/modules/es.object.entries.js";
import "core-js/modules/es.object.from-entries.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.parse-float.js";
import "core-js/modules/es.regexp.constructor.js";
import "core-js/modules/es.regexp.exec.js";
import "core-js/modules/es.regexp.to-string.js";
import "core-js/modules/es.string.ends-with.js";
import "core-js/modules/es.string.iterator.js";
import "core-js/modules/es.string.match.js";
import "core-js/modules/es.string.replace.js";
import "core-js/modules/es.string.starts-with.js";
import "core-js/modules/es.string.trim.js";
import "core-js/modules/web.dom-collections.iterator.js";
import { logError } from './logger';
import { getProp } from './utils';
 
// Global counter for node IDs
var nodeIdCounter = 0;
 
/**
 * Wraps all methods in comp.methods to automatically inject the app instance
 * as the first parameter when called from expression contexts (e.g., c-if).
 *
 * @param {Object} comp - The AppBlock component instance
 * @returns {Object} Object with wrapped methods
 */
export function wrapMethodsWithAppInstance(comp) {
  return Object.fromEntries(Object.entries(comp.methods).map(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
      k = _ref2[0],
      v = _ref2[1];
    return [k, typeof v === 'function' ? function () {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      return v.call.apply(v, [comp, comp].concat(args));
    } : v];
  }));
}
 
/**
 * Creates the context object used for expression evaluation in directives.
 *
 * @param {Object} comp - The AppBlock component instance
 * @param {Object} pointers - Optional pointer context from c-for loops
 * @returns {Object} Context object with data, pointers, methods, allowBuiltins, and logWarning
 */
export function createExpressionContext(comp, pointers) {
  var wrappedMethods = wrapMethodsWithAppInstance(comp);
  return {
    data: comp.data,
    pointers: pointers || {},
    methods: wrappedMethods,
    allowBuiltins: comp.allowBuiltins || [],
    logWarning: function logWarning(msg) {
      return logError(comp, msg);
    }
  };
}
 
/**
 * Escapes special regex characters in a string.
 *
 * @param {string} str - String to escape
 * @returns {string} Escaped string safe for use in RegExp
 */
export function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
 
/**
 * Builds a regex pattern for matching placeholders with custom delimiters.
 *
 * @param {Array<string>} delimiters - Array of [openDelimiter, closeDelimiter]
 * @returns {RegExp} Regular expression for matching delimited placeholders
 */
export function buildDelimiterRegex(delimiters) {
  var validDelimiters = Array.isArray(delimiters) && delimiters.length === 2 && typeof delimiters[0] === 'string' && typeof delimiters[1] === 'string' && delimiters[0].length > 0 && delimiters[1].length > 0 ? delimiters : ['{', '}'];
  var open = escapeRegExp(validDelimiters[0]);
  var close = escapeRegExp(validDelimiters[1]);
  return new RegExp(open + '([\\s\\S]*?)' + close, 'g');
}
 
/**
 * Evaluates a template expression that may include method calls with parameters.
 * Supports filter chains and caches results per-render.
 *
 * @param {Object} app - The AppBlock component instance
 * @param {Object} scope - The current scope (data, methods, etc.)
 * @param {Node} node - The DOM node for caching key
 * @param {string} expr - The expression string to evaluate
 * @param {Map} cache - Per-render cache map
 * @returns {*} The evaluated result
 */
export function evaluateTemplateExpression(app, scope, node, expr, cache) {
  // Assign node ID if not present
  if (!node._appBlockNodeId) {
    node._appBlockNodeId = ++nodeIdCounter;
  }
  var nodeId = node._appBlockNodeId;
  var cacheKey = "".concat(nodeId, "|").concat(expr);
  Iif (cache && cache.has(cacheKey)) {
    return cache.get(cacheKey);
  }
  var result;
  try {
    // Split by | for filters
    var parts = expr.split('|').map(function (p) {
      return p.trim();
    });
    var baseExpr = parts.shift();
 
    // Evaluate base expression
    result = evaluateBaseExpression(app, scope, baseExpr);
 
    // Apply filters
    var _iterator = _createForOfIteratorHelper(parts),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var filterName = _step.value;
        if (app.filters && app.filters[filterName]) {
          result = app.filters[filterName](app, result);
        } else {
          logError(app, "Unknown filter: ".concat(filterName));
        }
      }
 
      // Convert undefined/null to empty string for placeholders
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    if (result === undefined || result === null) {
      result = '';
    }
  } catch (error) {
    logError(app, "[method-call-error] ".concat(expr, " : ").concat(error.message));
    result = '';
  }
  if (cache) cache.set(cacheKey, result);
  return result;
}
 
/**
 * Parses method arguments accounting for nested parentheses
 */
function parseMethodArguments(argsStr) {
  Iif (!argsStr.trim()) return [];
  var args = [];
  var current = '';
  var parenDepth = 0;
  for (var i = 0; i < argsStr.length; i++) {
    var _char = argsStr[i];
    if (_char === '(') {
      parenDepth++;
      current += _char;
    } else if (_char === ')') {
      parenDepth--;
      current += _char;
    } else if (_char === ',' && parenDepth === 0) {
      args.push(current.trim());
      current = '';
    } else {
      current += _char;
    }
  }
  Eif (current.trim()) {
    args.push(current.trim());
  }
  return args;
}
 
/**
 * Evaluates the base expression (without filters)
 */
function evaluateBaseExpression(app, scope, expr) {
  expr = expr.trim();
 
  // Check if it's a method call
  var methodMatch = expr.match(/^(\w+)\((.*)\)$/);
  if (methodMatch) {
    var _app$methods$methodNa;
    var methodName = methodMatch[1];
    var argsStr = methodMatch[2].trim();
    Iif (!app.methods || !app.methods[methodName]) {
      throw new Error("Method ".concat(methodName, " not found"));
    }
    var args = argsStr ? parseMethodArguments(argsStr).map(function (arg) {
      return evaluateArgument(app, scope, arg);
    }) : [];
    return (_app$methods$methodNa = app.methods[methodName]).call.apply(_app$methods$methodNa, [app, app].concat(_toConsumableArray(args)));
  }
 
  // Otherwise, treat as property path
  var propKeys = expr.split('.');
  return getProp(app, propKeys, scope);
}
 
/**
 * Evaluates a single argument expression
 */
function evaluateArgument(app, scope, arg) {
  arg = arg.trim();
 
  // Check if it's a method call
  if (arg.match(/^(\w+)\(/)) {
    return evaluateBaseExpression(app, scope, arg);
  }
 
  // String literal
  Iif (arg.startsWith('"') && arg.endsWith('"')) {
    return arg.slice(1, -1);
  }
  Iif (arg.startsWith("'") && arg.endsWith("'")) {
    return arg.slice(1, -1);
  }
 
  // Number
  var num = parseFloat(arg);
  Iif (!isNaN(num) && isFinite(num)) {
    return num;
  }
 
  // Property path
  var propKeys = arg.split('.');
  return getProp(app, propKeys, scope);
}