All files / src/llm-orchestration/action-handlers/dto sanitizer.decorator.ts

100% Statements 8/8
100% Branches 3/3
100% Functions 2/2
100% Lines 8/8

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 3311x                               11x 48x 72x 1x     71x     71x       71x      
import { Transform } from 'class-transformer';
 
/**
 * A custom decorator that sanitizes a string by removing markdown code fences.
 * It's a "best-effort" transform that will not fail if the input is not a string
 * or does not contain code fences.
 *
 * @example
 * ```typescript
 * class MyDto {
 *   @SanitizeCodeBlock()
 *   @IsString()
 *   code: string;
 * }
 * ```
 */
export function SanitizeCodeBlock() {
  return Transform(({ value }) => {
    if (typeof value !== 'string') {
      return value; // Let other validators handle non-string types
    }
 
    const trimmedValue = value.trim();
    // Use an anchored regex to only match if fences are at the start and end.
    // This is robust against code that contains ``` in string literals.
    const codeMatch = trimmedValue.match(/^```(?:\w*\n)?([\s\S]*)```$/);
 
    // If a match is found, return the captured group (the code inside).
    // Otherwise, return the original trimmed value.
    return codeMatch ? codeMatch[1].trim() : trimmedValue;
  });
}