All files / server/services/compiler header-processor.ts

100% Statements 44/44
80.95% Branches 17/21
100% Functions 5/5
100% Lines 40/40

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            14x                                 17x 20x 20x 20x 20x                   3x 2x 2x   2x 2x 2x                   17x 17x   17x 19x   16x 16x 16x 16x 16x           1x     1x                                   73x 2x     71x 71x   71x 56x     15x   15x 17x 17x 17x 17x 16x         15x 15x 15x     15x    
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { Logger } from "@shared/logger";
import { resolvePathWithinRoot } from "../../security/safe-paths";
import { resolveSourceProject } from "@shared/source-project";
 
const logger = new Logger("HeaderProcessor");
 
export interface HeaderInclude {
  name: string;
  content: string;
}
 
export interface HeaderProcessingResult {
  processedCode: string;
  lineOffset: number;
}
 
async function writeHeaderFiles(
  headers: HeaderInclude[],
  sketchDir: string,
  logWrites = false,
): Promise<void> {
  for (const header of headers) {
    const headerPath = resolvePathWithinRoot(sketchDir, header.name);
    if (logWrites) logger.debug(`Writing header: ${headerPath}`);
    await mkdir(dirname(headerPath), { recursive: true });
    await writeFile(headerPath, header.content);
  }
}
 
async function processProjectHeaders(
  code: string,
  headers: HeaderInclude[],
  sketchDir: string | undefined,
  entryFile: string,
): Promise<HeaderProcessingResult> {
  const files = Object.fromEntries(headers.map((header) => [header.name, header.content]));
  const resolved = resolveSourceProject({ entryFile, files: { [entryFile]: code, ...files } });
  Eif (sketchDir) await writeHeaderFiles(headers, sketchDir);
 
  const sourceLines = resolved.source.split("\n").length;
  const codeLines = code.split("\n").length;
  return {
    processedCode: resolved.source,
    lineOffset: Math.max(0, sourceLines - codeLines),
  };
}
 
function replaceHeaderInclude(
  code: string,
  header: HeaderInclude,
): { code: string; lineOffset: number; found: boolean } {
  const headerWithoutExt = header.name.replace(/\.[^/.]+$/, "");
  const includeVariants = [`#include "${header.name}"`, `#include "${headerWithoutExt}"`];
 
  for (const includeStatement of includeVariants) {
    if (!code.includes(includeStatement)) continue;
 
    logger.debug(`Found include for: ${header.name} (pattern: ${includeStatement})`);
    const replacement = `// --- Start of ${header.name} ---\n${header.content}\n// --- End of ${header.name} ---`;
    const escapedInclude = includeStatement.split('"')[1].replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
    const patternString = String.raw`#include\s*"${escapedInclude}"`;
    return {
      code: code.replaceAll(new RegExp(patternString, "g"), replacement),
      lineOffset: (replacement.match(/\n/g) || []).length,
      found: true,
    };
  }
  logger.debug(
    `Include not found for: ${header.name} (tried: ${includeVariants.join(", ")})`,
  );
  return { code, lineOffset: 0, found: false };
}
 
/**
 * Processes header includes by replacing #include statements with actual header content.
 * Tracks line offset for later error correction.
 * 
 * @param code - The original sketch code
 * @param headers - Array of header includes with name and content
 * @param sketchDir - Optional directory to write header files to
 * @returns Processed code and cumulative line offset
 */
export async function processHeaderIncludes(
  code: string,
  headers?: HeaderInclude[],
  sketchDir?: string,
  entryFile?: string,
): Promise<HeaderProcessingResult> {
  if (entryFile) {
    return processProjectHeaders(code, headers ?? [], sketchDir, entryFile);
  }
 
  let processedCode = code;
  let lineOffset = 0;
 
  if (!headers || headers.length === 0) {
    return { processedCode, lineOffset };
  }
 
  logger.debug(`Processing ${headers.length} header includes`);
 
  for (const header of headers) {
    const replacement = replaceHeaderInclude(processedCode, header);
    processedCode = replacement.code;
    lineOffset += replacement.lineOffset;
    if (replacement.found) {
      logger.debug(`Replaced include for: ${header.name}, line offset now: ${lineOffset}`);
    }
  }
 
  // Write header files to disk as separate files
  Eif (sketchDir) {
    logger.debug(`Writing ${headers.length} header files to ${sketchDir}`);
    await writeHeaderFiles(headers, sketchDir, true);
  }
 
  return { processedCode, lineOffset };
}