All files / lib/compiler/parser/directives deadlock.js

100% Statements 131/131
92.5% Branches 37/40
100% Functions 1/1
100% Lines 131/131

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 132532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 920x 920x 920x 920x 920x 942x 942x 22x 22x 942x 942x 942x 942x 942x 942x 942x 942x 942x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 6x 6x 7x 22x 22x 22x 131x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 4x 4x 5x 22x 22x 22x 131x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 3x 22x 22x 22x 27x 17x 17x 17x 17x 17x 17x 22x 22x 22x 22x 22x 22x 33x 11x 11x 11x 11x 22x 22x 33x 942x 942x 942x 942x 942x 920x 920x  
/**
 * @file deadlock.js
 * @description Desugars `<@deadlock>` boundaries into DOM markers.
 */
import path from 'path';
import { AvenxErrorCodes } from '../../../core/runtime/AvenxError.js';
import { escapeTemplateMarkers } from '../../../core/utils/templateUtils.js';
import { TemplateValidationError } from '../../errors/index.js';
import { reportWarning } from '../../utils/warningReporter.js';
import { getLineAndColumn } from '../htmlTree.js';
import { loadAvenxConfig } from '../projectConfig.js';
 
/**
 * Processes <@deadlock> tags, converting them to DOM boundary markers.
 * Supports attributes: name="...", maxDepth="...", action="abort|fallback|throw", isolated="true|false",
 * and optional inner <@fallback as="..."> tags for error recovery.
 *
 * Invalid attribute values are reported as AVX_W35 and dropped; the boundary
 * itself is still emitted.
 * @param {string} template - The template string.
 * @param {string} [filePath] - The component file path for source location tracking.
 * @param {string} [componentName] - The component name for diagnostics.
 * @param {object} [options] - Parser state the pass reads.
 * @param {object|null} [options.config] - The parser's explicit project configuration. When
 *   absent, the configuration is resolved from `filePath`.
 * @returns {string} The processed template.
 */
export function processDeadlock(template, filePath = '', componentName = '', { config = null } = {}) {
  let currentTemplate = template;
  const deadlockRegex = /<@deadlock\b([^>]*)>((?:(?!<@deadlock\b)[\s\S])*?)<\/ ?@deadlock>/i;
  const activeConfig = config || (filePath ? loadAvenxConfig(path.dirname(filePath)) : null);
 
  while (true) {
    const match = currentTemplate.match(deadlockRegex);
    if (!match) break;
 
    const fullMatch = match[0];
    const attrsStr = match[1] || '';
    const inner = match[2];
 
    const nameMatch = attrsStr.match(/\bname=["']([^"']*)["']/i);
    const name = nameMatch ? nameMatch[1].trim() : 'anonymous';
 
    const depthMatch = attrsStr.match(/\bmaxDepth=["']([^"']*)["']/i);
    let depthAttr = '';
    if (depthMatch) {
      const rawDepth = depthMatch[1].trim();
      const parsedDepth = Number(rawDepth);
      if (!/^\d+$/.test(rawDepth) || !Number.isInteger(parsedDepth) || parsedDepth <= 0) {
        reportWarning(
          AvenxErrorCodes.COMPILER_DEADLOCK_PARSE_FAILED,
          new TemplateValidationError(
            AvenxErrorCodes.COMPILER_DEADLOCK_PARSE_FAILED,
            componentName || (filePath ? path.basename(filePath) : 'Component'),
            `invalid maxDepth "${rawDepth}". Expected a positive integer.`,
          ),
          activeConfig,
        );
      } else {
        depthAttr = ` data-ax-deadlock-depth="${parsedDepth}"`;
      }
    }
 
    const actionMatch = attrsStr.match(/\baction=["']([^"']*)["']/i);
    let actionAttr = '';
    if (actionMatch) {
      const rawAction = actionMatch[1].trim().toLowerCase();
      if (!['abort', 'fallback', 'throw'].includes(rawAction)) {
        reportWarning(
          AvenxErrorCodes.COMPILER_DEADLOCK_PARSE_FAILED,
          new TemplateValidationError(
            AvenxErrorCodes.COMPILER_DEADLOCK_PARSE_FAILED,
            componentName || (filePath ? path.basename(filePath) : 'Component'),
            `invalid action "${rawAction}". Expected "abort", "fallback", or "throw".`,
          ),
          activeConfig,
        );
      } else {
        actionAttr = ` data-ax-deadlock-action="${rawAction}"`;
      }
    }
 
    const isolatedMatch = attrsStr.match(/\bisolated=["']([^"']*)["']/i);
    let isolatedAttr = '';
    if (isolatedMatch) {
      const rawIsolated = isolatedMatch[1].trim().toLowerCase();
      if (rawIsolated !== 'true' && rawIsolated !== 'false') {
        reportWarning(
          AvenxErrorCodes.COMPILER_DEADLOCK_PARSE_FAILED,
          new TemplateValidationError(
            AvenxErrorCodes.COMPILER_DEADLOCK_PARSE_FAILED,
            componentName || (filePath ? path.basename(filePath) : 'Component'),
            `invalid isolated "${rawIsolated}". Expected "true" or "false".`,
          ),
          activeConfig,
        );
      } else {
        isolatedAttr = ` data-ax-deadlock-isolated="${rawIsolated}"`;
      }
    }
 
    // Compute location if possible
    let locAttr = '';
    if (filePath) {
      const matchIdx = currentTemplate.indexOf(fullMatch);
      if (matchIdx !== -1) {
        const pos = getLineAndColumn(currentTemplate, matchIdx);
        locAttr = ` data-ax-deadlock-loc="${filePath}:${pos.line}:${pos.column}"`;
      }
    }
 
    // Extract <@fallback as="...">
    let fallbackContent = '';
    let errorAs = 'error';
    let boundaryContent = inner;
    const fallbackMatch = inner.match(/<@fallback(?:\s+as="([^"]*)")?>([\s\S]*?)<\/ ?@fallback>/i);
    if (fallbackMatch) {
      errorAs = fallbackMatch[1] || 'error';
      fallbackContent = escapeTemplateMarkers(fallbackMatch[2]);
      boundaryContent = inner.replace(fallbackMatch[0], '');
    }
 
    const fallbackTpl = fallbackMatch
      ? `<template data-ax-deadlock-fallback="true" data-ax-error-as="${errorAs}"><div class="ax-deadlock-fallback">${fallbackContent}</div></template>`
      : '';
 
    const replacement = `<div data-ax-deadlock="true" data-ax-deadlock-name="${name}"${depthAttr}${actionAttr}${isolatedAttr}${locAttr}>${fallbackTpl}${boundaryContent}</div>`;
    currentTemplate = currentTemplate.replace(fullMatch, replacement);
  }
  return currentTemplate;
}