All files / lib/core/renderer renderTemplate.js

94.2% Statements 244/259
87.5% Branches 49/56
100% Functions 6/6
94.2% Lines 244/259

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 260256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 590x 590x 590x 590x             590x 590x 590x 590x 590x 590x 590x 590x 590x 590x 590x 590x 590x 256x 256x 256x 256x 256x 256x 256x 20538x 20538x 20538x 20538x 20538x 20538x 20504x 20501x 20501x 20501x 20501x 20501x 20504x 20504x 20504x 20504x 20504x 20504x 20504x 20504x 20504x 20538x 20538x 20531x 20531x 20531x 20531x 20531x 20538x 20538x 20538x 256x 256x 256x 256x 256x 1x 1x 256x 256x 256x 256x 256x 256x 256x 256x 21279x 21278x 21278x 21279x 20537x 20537x 20537x 21278x 21278x 21279x 63847x 63847x 42552x 63838x 21295x 21295x 21295x 21295x 21295x 13x 13x 21295x 15x 21290x 21263x 21263x 21295x 4x 1x 1x 4x 1x 1x 2x 2x 2x 21295x 63847x 21274x 21274x 21279x 256x 256x 256x 256x 256x 256x 256x 256x 21284x 21278x 21278x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 10x 94x 17x 94x 8x 8x 8x 8x 94x 6x 6x 6x 8x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x     8x 8x 8x 2x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x   6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 21284x 256x  
import { AvenxErrorCodes, formatMessage } from '../runtime/AvenxError.js';
import { HtmlEscaper, SafeHtml } from '../security/escapeHtml.js';
import { logger } from '../runtime/AvenxLogger.js';
import { LruCache } from '../utils/LruCache.js';
import { createInterpolationRegex } from '../utils/templateUtils.js';
import { findTagEnd } from '../utils/markupLexer.js';
 
const templateEscaper = new HtmlEscaper();
const DEFAULT_TEMPLATE_CACHE_CAPACITY = 500;
 
/**
 * Segment structure for parsed template AST:
 * @typedef {object} TemplateSegment
 * @property {boolean} isExpression - True if this segment is an interpolation expression.
 * @property {string} [value] - Static text content when isExpression is false.
 * @property {string} [expression] - Expression source code when isExpression is true.
 * @property {boolean} [isRaw] - True if raw interpolation {{{ ... }}} was used.
 */
 
/**
 * Handles the rendering of HTML templates by resolving interpolation expressions.
 * Uses an LruCache to cache parsed template AST segments with bounded capacity.
 */
export class TemplateRenderer {
  /**
   * Constructs the TemplateRenderer with a configurable LRU cache capacity.
   * @param {number|object} [capacityOrConfig] - Maximum LRU cache capacity or configuration object.
   */
  constructor(capacityOrConfig = DEFAULT_TEMPLATE_CACHE_CAPACITY) {
    let capacity = DEFAULT_TEMPLATE_CACHE_CAPACITY;
    if (typeof capacityOrConfig === 'number' && capacityOrConfig > 0) {
      capacity = capacityOrConfig;
    } else if (capacityOrConfig && typeof capacityOrConfig === 'object') {
      if (typeof capacityOrConfig.templateCacheCapacity === 'number' && capacityOrConfig.templateCacheCapacity > 0) {
        capacity = capacityOrConfig.templateCacheCapacity;
      } else if (typeof capacityOrConfig.capacity === 'number' && capacityOrConfig.capacity > 0) {
        capacity = capacityOrConfig.capacity;
      }
    }
 
    /**
     * Maximum capacity of the LRU cache.
     * @type {number}
     */
    this.capacity = capacity;
 
    /**
     * LRU Cache storing parsed template AST segments.
     * @type {LruCache}
     */
    this.cache = new LruCache(capacity);
  }
 
  /**
   * Parses a raw HTML template string into tokenized AST segments.
   * @param {string} template - The HTML template string.
   * @returns {TemplateSegment[]} Array of template segments.
   */
  parseTemplate(template) {
    const segments = [];
    const regex = createInterpolationRegex();
    let lastIndex = 0;
    let match;
 
    while ((match = regex.exec(template)) !== null) {
      if (match.index > lastIndex) {
        segments.push({
          isExpression: false,
          value: template.substring(lastIndex, match.index),
        });
      }
      const isRaw = match[1] !== undefined;
      const expression = isRaw ? match[1] : match[2];
      segments.push({
        isExpression: true,
        expression,
        isRaw,
      });
      lastIndex = regex.lastIndex;
    }
 
    if (lastIndex < template.length) {
      segments.push({
        isExpression: false,
        value: template.substring(lastIndex),
      });
    }
 
    return segments;
  }
 
  /**
   * Clears the template LRU cache.
   */
  clearCache() {
    this.cache.clear();
  }
 
  /**
   * Renders the template by replacing {{ expression }} and {{{ expression }}} with evaluated values.
   * @param {string} template - The HTML template string.
   * @param {function(string): any} resolveExpression - Function to evaluate expressions.
   * @returns {string} The rendered HTML string.
   */
  render(template, resolveExpression) {
    if (!template) return '';
 
    let segments = this.cache.get(template);
    if (!segments) {
      segments = this.parseTemplate(template);
      this.cache.set(template, segments);
    }
 
    let result = '';
    for (let i = 0; i < segments.length; i++) {
      const seg = segments[i];
      if (!seg.isExpression) {
        result += seg.value;
      } else {
        const expression = seg.expression;
        const isRaw = seg.isRaw;
        try {
          const value = resolveExpression(expression);
          if (value == null) {
            continue;
          }
          if (isRaw || value instanceof SafeHtml) {
            result += String(value);
          } else {
            result += templateEscaper.escape(value);
          }
        } catch (error) {
          if (error instanceof Promise) {
            throw error; // Suspense: bubble up the promise without logging
          }
          if (error && error.code === AvenxErrorCodes.STATE_MUTATION_IN_UPDATE) {
            throw error;
          }
          logger.warn(formatMessage(AvenxErrorCodes.TEMPLATE_RENDER_ERROR, expression, error));
          throw error;
        }
      }
    }
 
    return this.resolveDynamicAttributes(result, resolveExpression);
  }
 
  /**
   * Resolves dynamic attribute name binding syntax (:[attrName]="attrValue") in HTML string.
   * @param {string} html - The HTML string.
   * @param {function(string): any} resolveExpression - Function to evaluate expressions.
   * @returns {string} The HTML string with dynamic attributes resolved.
   */
  resolveDynamicAttributes(html, resolveExpression) {
    if (!html || typeof html !== 'string' || !html.includes(':[')) {
      return html;
    }
 
    // Tags are located with the shared lexer's scanner rather than with
    // `/<([a-zA-Z0-9@/!-][^>]*?)>/g`, which ends a tag at the first `>` wherever
    // it appears. On `<div title="a > b" :[name]="val">` that regex matched only
    // `<div title="a >`, so the dynamic attribute fell outside the tag, was
    // never resolved, and `:[name]="val"` was left on the element as literal
    // markup -- silently, with the intended attribute simply absent.
    //
    // This runs after interpolation, so the `>` need not even be in the
    // template: any rendered value containing one, in any attribute before the
    // dynamic one, was enough.
    const rewritten = [];
    let cursor = 0;
    for (let i = 0; i < html.length; i++) {
      if (html[i] !== '<') continue;
      const end = findTagEnd(html, i);
      if (end === -1) continue;
 
      const fullTag = html.slice(i, end + 1);
      const tagInner = html.slice(i + 1, end);
      const replaced = rewriteTag(fullTag, tagInner);
      if (replaced !== fullTag) {
        rewritten.push(html.slice(cursor, i), replaced);
        cursor = end + 1;
      }
      i = end;
    }
    rewritten.push(html.slice(cursor));
    return rewritten.join('');
 
    /**
     * Resolves the dynamic attributes of one tag.
     * @param {string} fullTag - The tag as written, including its angle brackets.
     * @param {string} tagInner - The tag's contents, without the angle brackets.
     * @returns {string} The rewritten tag, or `fullTag` when nothing changed.
     */
    function rewriteTag(fullTag, tagInner) {
      if (tagInner.startsWith('/') || tagInner.startsWith('!') || tagInner.startsWith('?')) {
        return fullTag;
      }
 
      const dynAttrRegex = /:\[(.*?)\]\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
      if (!dynAttrRegex.test(tagInner)) {
        return fullTag;
      }
      dynAttrRegex.lastIndex = 0;
 
      const activeDynAttrs = [];
      const parts = [];
      let lastIdx = 0;
      let match;
 
      while ((match = dynAttrRegex.exec(tagInner)) !== null) {
        parts.push(tagInner.substring(lastIdx, match.index));
        const nameExpr = match[1];
        const valExpr = match[2] !== undefined ? match[2] : (match[3] !== undefined ? match[3] : match[4]);
 
        let resolvedName = null;
        try {
          resolvedName = resolveExpression(nameExpr);
        } catch (error) {
          logger.warn(formatMessage(AvenxErrorCodes.TEMPLATE_RENDER_ERROR, nameExpr, error));
        }
 
        if (resolvedName != null && String(resolvedName).trim() !== '') {
          const attrName = String(resolvedName).trim();
          let resolvedVal = null;
          if (valExpr !== undefined && valExpr !== null) {
            try {
              resolvedVal = resolveExpression(valExpr);
            } catch (error) {
              logger.warn(formatMessage(AvenxErrorCodes.TEMPLATE_RENDER_ERROR, valExpr, error));
            }
          }
 
          if (resolvedVal !== false && resolvedVal != null) {
            activeDynAttrs.push(attrName);
            if (resolvedVal === true) {
              parts.push(`${attrName}="true"`);
            } else {
              const escapedVal = templateEscaper.escape(String(resolvedVal));
              parts.push(`${attrName}="${escapedVal}"`);
            }
          } else {
            activeDynAttrs.push(attrName);
          }
        }
 
        lastIdx = dynAttrRegex.lastIndex;
      }
 
      parts.push(tagInner.substring(lastIdx));
      let newTagInner = parts.join('');
 
      if (activeDynAttrs.length > 0) {
        newTagInner += ` data-ax-dyn-attrs="${activeDynAttrs.join(',')}"`;
      }
 
      return `<${newTagInner}>`;
    }
  }
}