All files / core/engine template-renderer.service.ts

97.22% Statements 35/36
84% Branches 21/25
100% Functions 4/4
97.05% Lines 33/34

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 711x 1x     1x         8x 8x 7x   1x                 7x 7x 7x 7x 7x   7x 463x 463x   463x 34x 25x 25x   429x 9x 9x 420x 9x 9x     411x     463x     7x 6x     7x 31x     31x           31x          
import { Injectable } from '@nestjs/common';
import { render } from 'ejs';
 
@Injectable()
export class TemplateRendererService {
  render(
    templateContent: string,
    context: Record<string, unknown>
  ): string[] {
    try {
      const rendered = render(templateContent, context);
      return this.splitIntoArgs(rendered);
    } catch (error) {
      throw new Error(
        `Template rendering failed: ${
          error instanceof Error ? error.message : String(error)
        }. Template: ${templateContent.substring(0, 100)}...`
      );
    }
  }
 
  private splitIntoArgs(rendered: string): string[] {
    const args: string[] = [];
    let currentArg = '';
    let inQuotes = false;
    let quoteChar = '';
    let i = 0;
 
    while (i < rendered.length) {
      const char = rendered[i];
      const isWhitespace = /\s/.test(char);
 
      if (!inQuotes && isWhitespace) {
        if (currentArg.trim()) {
          args.push(currentArg.trim());
          currentArg = '';
        }
      } else if (!inQuotes && (char === '"' || char === '\'')) {
        inQuotes = true;
        quoteChar = char;
      } else if (inQuotes && char === quoteChar) {
        inQuotes = false;
        quoteChar = '';
        // Don't include the closing quote in the arg
      } else {
        currentArg += char;
      }
 
      i++;
    }
 
    if (currentArg.trim()) {
      args.push(currentArg.trim());
    }
 
    return args
      .filter((arg) => arg.length > 0)
      .map((arg) => {
        // Remove surrounding quotes if present
        Iif (
          (arg.startsWith('"') && arg.endsWith('"')) ||
          (arg.startsWith('\'') && arg.endsWith('\''))
        ) {
          return arg.slice(1, -1);
        }
        return arg;
      });
  }
}