All files / lib/core/tooling prettierPlugin.js

83.3% Statements 439/527
91.89% Branches 102/111
61.11% Functions 11/18
83.3% Lines 439/527

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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 5282x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 25x 25x 25x 25x 168x 168x 168x 168x 155x 155x 168x 168x 168x 168x 168x 168x 168x 149x 149x 3x 3x 3x 146x 149x 1x 1x 1x 145x 149x 10x 10x 10x 10x 10x 135x 149x 17x 17x 13x 13x 13x 17x         17x 149x 13x 168x 8x 8x 8x 90x 90x 8x 168x 25x 25x 25x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 25x 25x 25x 25x 244x 244x 157x 157x 244x 244x 80x 80x 7x 7x 244x 14x 14x 7x 7x 7x 14x 7x 7x 7x 7x 14x 14x 7x 244x 25x 25x 25x 2x 2x 2x 2x 2x 2x 25x 25x 23x 23x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 25x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 70x 49x 49x 70x 25x 25x 25x 154x 154x 154x     154x 154x 154x 15x 15x 15x 15x 15x 104x 104x 15x 15x 15x 139x 154x 15x 15x     15x 15x 15x 15x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 124x 124x 154x 15x 15x     15x 15x 15x 15x 15x 154x 25x 25x 25x 25x 25x 25x 25x 25x 2x 2x 2x 2x 2x 2x 2570x 2570x 13x 13x 2557x 2570x 15x 15x 2557x 2570x 45x 25x 1x 1x 1x 25x   24x 2x 2x 25x 45x 2557x 2570x 9700x 2594x 194x 2594x 2400x 2400x 2594x 9700x 2570x 2x 2x 2x 2x 2x 2x 134x 134x 134x 119x 119x 15x 15x 15x 134x     134x 2x 2x 2x 2x 2x 2x                                                                           2x 2x 2x 2x 2x 2x 2x                                                                     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 25x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 25x 25x 25x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 134x 134x 15x 15x 119x 119x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x  
import * as prettier from 'prettier';
import * as prettierHtml from 'prettier/plugins/html';
import { tokenizeMarkup } from '../utils/markupLexer.js';
 
const AVENX_TAG_PREFIX = 'avenx-';
const AVENX_TAGS = [
  'css',
  'global',
  'if',
  'elseif',
  'elif',
  'else',
  'for',
  'defer',
  'suspense',
  'errorBoundary',
  'deadlock',
  'fallback',
  'empty',
];
const AVENX_TAG_SET = new Set(AVENX_TAGS);
const IF_CONTINUATION_TAGS = new Set(['elseif', 'elif', 'else']);
// The `@empty` arm of a `@for` loop has no closing form either, so a loop
// that contains one is preserved verbatim like an `<@if>` chain with
// continuation arms.
const FOR_CONTINUATION_TAGS = new Set(['empty']);
const DIRECTIVE_HDR_TAGS = new Set(['if', 'elseif', 'elif', 'for']);
const JS_BODY_TAGS = new Set(['action', 'computed', 'resource']);
const AVENX_HDR_ATTR = 'data-avenx-hdr';
const AVENX_PASSTHROUGH_PREFIX = 'avenx-passthrough:';
const AVENX_CSS_BLOCK_PATTERN = /<@(global|css)\s*>([\s\S]*?)<\/\s*@\1\s*>/g;
 
/**
 * Escapes a directive header for a double-quoted HTML attribute value.
 * @param {string} header - The raw directive header.
 * @returns {string} Attribute-safe text.
 */
function escapeHdrAttr(header) {
  return header.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
}
 
/**
 * Finds `<@if>` chains and `<@for>` loops that contain continuation arms.
 *
 * Continuation tags (`<@elseif>`, `<@elif>`, `<@else>`, and `<@empty>`
 * inside a `@for`) have no closing form, so Prettier's HTML parser cannot
 * accept a faithful encoding of the construct. Those spans are preserved
 * verbatim via passthrough comments instead.
 * @param {string} text - The Avenx template source.
 * @param {import('../utils/markupLexer.js').MarkupToken[]} tokens - Lexer tokens.
 * @returns {Array<{start: number, end: number}>} Inclusive source ranges to preserve.
 */
function findIfChainsWithContinuations(text, tokens) {
  const ranges = [];
 
  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    const isIf = token.type === 'open' && token.directive && token.name === '@if';
    const isFor = token.type === 'open' && token.directive && token.name === '@for';
    if (!isIf && !isFor) {
      continue;
    }
    const continuations = isIf ? IF_CONTINUATION_TAGS : FOR_CONTINUATION_TAGS;
 
    let depth = 1;
    let hasContinuation = false;
    let end = -1;
 
    for (let j = i + 1; j < tokens.length; j++) {
      const next = tokens[j];
      if (next.type === 'open' && next.directive && next.name === '@if') {
        depth += 1;
        continue;
      }
 
      if (next.type === 'open' && next.directive && next.name === '@for') {
        depth += 1;
        continue;
      }
 
      if (next.type === 'open' && next.directive && continuations.has(next.name.slice(1))) {
        if (depth === 1) {
          hasContinuation = true;
        }
        continue;
      }
 
      if (next.type === 'close' && (next.name === '@if' || next.name === '@for')) {
        depth -= 1;
        if (depth === 0 && next.name === (isIf ? '@if' : '@for')) {
          end = next.end;
          break;
        }
        if (depth === 0) {
          // Mismatched nesting cannot occur in well-formed source; bail on it
          // rather than silently preserving a wrong span.
          break;
        }
      }
    }
 
    if (hasContinuation && end !== -1) {
      ranges.push({ start: token.start, end });
      // Skip tokens inside this construct; nested ones are preserved with the outer span.
      while (i + 1 < tokens.length && tokens[i + 1].start < end) {
        i += 1;
      }
    }
  }
 
  return ranges;
}
 
/**
 * Finds tags whose bodies are JavaScript (<action>, <computed>, <resource>).
 *
 * Prettier's HTML printer treats tag bodies as HTML text and collapses their
 * whitespace, which silently breaks JavaScript containing line comments or
 * multi-line template literals (#1622). These spans are preserved verbatim
 * via passthrough comments.
 * @param {string} text - The Avenx template source.
 * @param {import('../utils/markupLexer.js').MarkupToken[]} tokens - Lexer tokens.
 * @returns {Array<{start: number, end: number}>} Inclusive source ranges to preserve.
 */
function findJsBodyTags(text, tokens) {
  const ranges = [];
 
  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    if (token.type !== 'open' || token.selfClosing) {
      continue;
    }
    const lower = token.name?.toLowerCase();
    if (!JS_BODY_TAGS.has(lower)) {
      continue;
    }
 
    let end = -1;
    for (let j = i + 1; j < tokens.length; j++) {
      const next = tokens[j];
      if (next.type === 'close' && next.name?.toLowerCase() === lower) {
        end = next.end;
        break;
      }
    }
 
    if (end !== -1) {
      ranges.push({ start: token.start, end });
      while (i + 1 < tokens.length && tokens[i + 1].start < end) {
        i += 1;
      }
    }
  }
 
  return ranges;
}
 
/**
 * Merges and sorts source ranges in document order.
 * @param {Array<{start: number, end: number}>} ranges - Source ranges.
 * @returns {Array<{start: number, end: number}>} Non-overlapping ranges.
 */
function mergeRanges(ranges) {
  if (ranges.length <= 1) {
    return ranges;
  }
  const sorted = [...ranges].sort((a, b) => a.start - b.start);
  const merged = [sorted[0]];
 
  for (let i = 1; i < sorted.length; i++) {
    const prev = merged[merged.length - 1];
    const curr = sorted[i];
    if (curr.start < prev.end) {
      prev.end = Math.max(prev.end, curr.end);
    } else {
      merged.push(curr);
    }
  }
 
  return merged;
}
 
/**
 * Encodes Avenx-specific template syntax into HTML-compatible syntax.
 *
 * `<@elseif>` / `<@elif>` / `<@else>` continue an `<@if>` chain and have no
 * closing form. Chains that use those arms are wrapped in a passthrough
 * comment so Prettier does not need a well-formed HTML tree for them.
 * Headers that contain `>` (for example `<@if (n > 0)>`) are moved into
 * `data-avenx-hdr` so the comparison is not read as the end of the tag.
 * @param {string} text - The Avenx template source.
 * @returns {string} HTML-compatible source.
 */
function encodeAvenxSyntax(text) {
  const tokens = tokenizeMarkup(text);
  const passthroughRanges = mergeRanges([
    ...findIfChainsWithContinuations(text, tokens),
    ...findJsBodyTags(text, tokens),
  ]);
  const parts = [];
  let copyFrom = 0;
  let rangeIndex = 0;
 
  const emitThrough = (until) => {
    if (until > copyFrom) {
      parts.push(text.slice(copyFrom, until));
    }
    copyFrom = until;
  };
 
  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];
 
    while (rangeIndex < passthroughRanges.length && passthroughRanges[rangeIndex].end <= copyFrom) {
      rangeIndex += 1;
    }
 
    const range = passthroughRanges[rangeIndex];
    if (range && token.start >= range.start && token.start < range.end) {
      emitThrough(range.start);
      const original = text.slice(range.start, range.end);
      parts.push(`<!--${AVENX_PASSTHROUGH_PREFIX}${Buffer.from(original, 'utf8').toString('base64')}-->`);
      copyFrom = range.end;
      while (i + 1 < tokens.length && tokens[i + 1].start < range.end) {
        i += 1;
      }
      rangeIndex += 1;
      continue;
    }
 
    if (token.type === 'open' && token.directive) {
      const tag = token.name.slice(1);
      if (!AVENX_TAG_SET.has(tag)) {
        continue;
      }
 
      const header = text.slice(token.nameEnd, token.attrEnd).trim();
 
      if (DIRECTIVE_HDR_TAGS.has(tag) && header.includes('>')) {
        emitThrough(token.start);
        const selfClose = token.selfClosing ? ' /' : '';
        parts.push(`<${AVENX_TAG_PREFIX}${tag} ${AVENX_HDR_ATTR}="${escapeHdrAttr(header)}"${selfClose}>`);
        copyFrom = token.end;
        continue;
      }
 
      emitThrough(token.start);
      parts.push(`<${AVENX_TAG_PREFIX}${tag}${text.slice(token.nameEnd, token.end)}`);
      copyFrom = token.end;
      continue;
    }
 
    // Close tokens do not set `directive`; the leading `@` on the name is the signal.
    if (token.type === 'close' && token.name?.[0] === '@') {
      const tag = token.name.slice(1);
      if (!AVENX_TAG_SET.has(tag)) {
        continue;
      }
 
      emitThrough(token.start);
      parts.push(`</${AVENX_TAG_PREFIX}${tag}>`);
      copyFrom = token.end;
    }
  }
 
  emitThrough(text.length);
 
  let encoded = parts.join('');
  encoded = encoded.replaceAll('@css', 'data-avenx-css');
  encoded = encoded.replaceAll('@click', 'data-avenx-click');
  return encoded;
}
 
/**
 * Restores Avenx-specific syntax in a parsed HTML AST.
 * @param {object} node - The AST node to restore.
 * @returns {void}
 */
function restoreAvenxNode(node) {
  if (!node || typeof node !== 'object') {
    return;
  }
 
  if (typeof node.name === 'string' && node.name.startsWith(AVENX_TAG_PREFIX)) {
    node.name = `@${node.name.slice(AVENX_TAG_PREFIX.length)}`;
  }
 
  if (Array.isArray(node.attrs)) {
    for (const attribute of node.attrs) {
      if (attribute?.name === AVENX_HDR_ATTR) {
        // Print the header as a raw directive suffix: `<@if (n > 0)>`.
        attribute.name = attribute.value;
        attribute.value = null;
      } else if (attribute?.name === 'data-avenx-css') {
        attribute.name = '@css';
      } else if (attribute?.name === 'data-avenx-click') {
        attribute.name = '@click';
      }
    }
  }
 
  for (const value of Object.values(node)) {
    if (value && typeof value === 'object') {
      if (Array.isArray(value)) {
        value.forEach(restoreAvenxNode);
      } else {
        restoreAvenxNode(value);
      }
    }
  }
}
 
/**
 * Prints a preserved if-chain comment back to its original Avenx source.
 * @param {object} node - A Prettier HTML comment node.
 * @returns {string|undefined} The original chain source, or undefined when unrelated.
 */
function printPassthroughComment(node) {
  const value = String(node.value ?? '');
  if (!value.startsWith(AVENX_PASSTHROUGH_PREFIX)) {
    return undefined;
  }
 
  try {
    return Buffer.from(value.slice(AVENX_PASSTHROUGH_PREFIX.length), 'base64').toString('utf8');
  } catch {
    return undefined;
  }
}
 
/**
 * Parses an Avenx CSS stylesheet into formatter-friendly sections.
 * @param {string} text - The Avenx CSS source.
 * @returns {object} Parsed Avenx CSS AST.
 */
function parseAvenxCss(text) {
  const sections = [];
  let lastIndex = 0;

  for (const match of text.matchAll(AVENX_CSS_BLOCK_PATTERN)) {
    const start = match.index ?? 0;

    if (start > lastIndex) {
      sections.push({
        type: 'raw',
        value: text.slice(lastIndex, start),
      });
    }

    sections.push({
      type: 'block',
      name: match[1],
      content: match[2],
    });

    lastIndex = start + match[0].length;
  }

  if (lastIndex < text.length) {
    sections.push({
      type: 'raw',
      value: text.slice(lastIndex),
    });
  }

  return {
    type: 'avenx-css-root',
    sections,
    source: text,
    range: [0, text.length],
  };
}
 
/**
 * Creates a Prettier document for an Avenx CSS stylesheet.
 * @param {object} path - Prettier AST path.
 * @param {object} options - Prettier options.
 * @returns {Function|undefined} Embedded document formatter.
 */
function embedAvenxCss(path, options) {
  if (path.node.type !== 'avenx-css-root') {
    return undefined;
  }

  return async (textToDoc) => {
    const { hardline, indent } = prettier.doc.builders;
    const docs = [];

    for (const section of path.node.sections) {
      if (section.type === 'raw') {
        if (section.value.trim()) {
          const rawDoc = await textToDoc(section.value.trim(), {
            ...options,
            parser: 'css',
          });

          docs.push(rawDoc, hardline);
        }

        continue;
      }

      const cssDoc = await textToDoc(section.content.trim(), {
        ...options,
        parser: 'css',
      });

      docs.push(`<@${section.name}>`, indent([hardline, cssDoc]), hardline, `</@${section.name}>`, hardline, hardline);
    }

    return docs;
  };
}
 
const htmlParser = prettierHtml.parsers.html;
const htmlPrinter = prettierHtml.printers.html;
 
export const languages = [
  {
    name: 'Avenx Template',
    parsers: ['avenx-template'],
    extensions: ['.component.js', '.page.js'],
    filenames: [],
  },
  {
    name: 'Avenx CSS',
    parsers: ['avenx-css'],
    extensions: ['.component.css', '.page.css'],
    filenames: [],
  },
];
 
export const parsers = {
  'avenx-template': {
    ...htmlParser,
 
    /**
     * Parses an Avenx template using Prettier's HTML parser.
     * @param {string} text - The Avenx template source.
     * @param {object} options - Prettier parser options.
     * @returns {object} Parsed HTML AST.
     */
    parse(text, options) {
      return htmlParser.parse(encodeAvenxSyntax(text), options);
    },
 
    astFormat: 'html',
  },
 
  'avenx-css': {
    parse: parseAvenxCss,
    astFormat: 'avenx-css',
    locStart: (node) => node.range[0],
    locEnd: (node) => node.range[1],
  },
};
 
export const printers = {
  html: {
    ...htmlPrinter,
 
    /**
     * Chains the HTML printer's own preprocess, then restores Avenx syntax.
     * Skipping the original leaves the printer reading normalisation flags
     * that were never set, which crashes on any node with a child.
     * @param {object} ast - The parsed template AST.
     * @param {object} options - Prettier options.
     * @returns {object} Normalised, restored Avenx AST.
     */
    preprocess(ast, options) {
      const processed = typeof htmlPrinter.preprocess === 'function' ? htmlPrinter.preprocess(ast, options) : ast;
      restoreAvenxNode(processed);
      return processed;
    },
 
    /**
     * Restores passthrough if-chain comments to their original Avenx source.
     * @param {object} path - Prettier AST path.
     * @param {object} options - Prettier options.
     * @param {Function} print - Child printer.
     * @returns {unknown} Printed document.
     */
    print(path, options, print) {
      const passthrough = printPassthroughComment(path.node);
      if (passthrough !== undefined) {
        return passthrough;
      }
 
      return htmlPrinter.print(path, options, print);
    },
  },
 
  'avenx-css': {
    /**
     * Embeds standard CSS formatting inside Avenx CSS blocks.
     * @param {object} path - Prettier AST path.
     * @param {object} options - Prettier options.
     * @returns {Function|undefined} Embedded document formatter.
     */
    embed(path, options) {
      return embedAvenxCss(path, options);
    },
 
    /**
     * Prevents Prettier from traversing the custom Avenx CSS AST.
     * @returns {string[]} No traversable child nodes.
     */
    getVisitorKeys() {
      return [];
    },
 
    /**
     * Handles the root Avenx CSS node when embedding is unavailable.
     * @param {object} path - Prettier AST path.
     * @returns {string} Original source.
     */
    print(path) {
      return path.node.source;
    },
  },
};
 
export default {
  languages,
  parsers,
  printers,
};