All files / backend/src/utils prompt-template-processor.ts

62.4% Statements 83/133
53.73% Branches 36/67
60% Functions 9/15
62.59% Lines 82/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 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                                                                                                                                                                                        18x 18x 18x                                     18x 18x 29x   18x                   14x         14x 14x 14x   1x 1x       14x 14x     14x     14x     14x   14x                                 12x                           4x         4x 4x 4x             4x 4x     4x     4x     4x   4x                                                                                                                                                       13x       13x 13x   13x 30x 1x       29x 29x                   29x       12x                   29x     29x 29x       29x 29x     29x 12x 9x         9x 4x       5x 3x 3x         17x 17x 9x         9x 9x       8x 6x 1x       5x 2x       3x 2x 2x                                                                                                   29x     29x                               29x 29x                       15x   15x 15x     15x 29x 29x 29x 29x   29x   29x     29x                 15x    
/**
 * Prompt Template Processor
 *
 * Processes prompt templates with variable replacement supporting:
 * - self.* variables (current file metadata and content)
 * - field.* variables (form field values)
 * - func.* functions (with pipe syntax)
 */
 
import fs from 'fs-extra';
import path from 'path';
import matter from 'gray-matter';
 
/**
 * Self object - metadata and content of the current file (for page context)
 */
export interface PageSelfObject {
  content: string;
  file_path: string;
  file_name: string;
  file_base_name: string;
  fields: Record<string, { content: unknown }>;
}
 
/**
 * Self object for field context - represents the current field
 */
export interface FieldSelfObject {
  content: string;
  key: string;
  type: string;
}
 
/**
 * Parent page object - represents the parent page in field context
 */
export interface ParentPageObject {
  content: string;
  file_path: string;
  file_name: string;
  file_base_name: string;
  fields: Record<string, { content: unknown }>;
}
 
/**
 * Legacy self object for backward compatibility
 */
export interface SelfObject {
  content: string;
  file_path: string;
  file_name: string;
  file_base_name: string;
}
 
/**
 * Field object - form field values from the prompt template
 */
export type FieldObject = Record<string, unknown>;
 
/**
 * Context for page variable replacement
 */
export interface PageVariableContext {
  self: PageSelfObject | null;
  field: FieldObject;
  workspacePath: string;
  contextType: 'page';
}
 
/**
 * Context for field variable replacement
 */
export interface FieldVariableContext {
  self: FieldSelfObject | null;
  parent_page: ParentPageObject | null;
  field: FieldObject;
  workspacePath: string;
  contextType: 'field';
}
 
/**
 * Union type for all variable contexts
 */
export type VariableContext = PageVariableContext | FieldVariableContext;
 
/**
 * Parse frontmatter from content string
 */
function parseFrontmatter(content: string): {
  data: Record<string, unknown>;
  body: string;
} {
  try {
    const parsed = matter(content);
    return {
      data: parsed.data || {},
      body: parsed.content || '',
    };
  } catch (error) {
    console.error('Failed to parse frontmatter:', error);
    return {
      data: {},
      body: content,
    };
  }
}
 
/**
 * Convert frontmatter data to fields object
 */
function buildFieldsFromFrontmatter(
  data: Record<string, unknown>
): Record<string, { content: unknown }> {
  const fields: Record<string, { content: unknown }> = {};
  for (const [key, value] of Object.entries(data)) {
    fields[key] = { content: value };
  }
  return fields;
}
 
/**
 * Build page self object from a file path (with parsed frontmatter fields)
 */
export async function buildPageSelfObject(
  workspacePath: string,
  filePath: string
): Promise<PageSelfObject> {
  const absolutePath = path.isAbsolute(filePath)
    ? filePath
    : path.join(workspacePath, filePath);
 
  // Read file content
  let content = '';
  try {
    content = await fs.readFile(absolutePath, 'utf-8');
  } catch (error) {
    console.error(`Failed to read file for page self object: ${absolutePath}`, error);
    content = `[Could not read file: ${filePath}]`;
  }
 
  // Parse frontmatter
  const { data } = parseFrontmatter(content);
  const fields = buildFieldsFromFrontmatter(data);
 
  // Extract file path relative to workspace
  const relativePath = path.relative(workspacePath, absolutePath);
 
  // Extract file name
  const fileName = path.basename(absolutePath);
 
  // Extract base name (without extension)
  const baseName = path.basename(absolutePath, path.extname(absolutePath));
 
  return {
    content,
    file_path: relativePath,
    file_name: fileName,
    file_base_name: baseName,
    fields,
  };
}
 
/**
 * Build field self object (represents the current field in field context)
 */
export function buildFieldSelfObject(
  fieldKey: string,
  fieldType: string,
  fieldContent: string
): FieldSelfObject {
  return {
    content: fieldContent,
    key: fieldKey,
    type: fieldType,
  };
}
 
/**
 * Build parent page object (represents the parent page in field context)
 */
export async function buildParentPageObject(
  workspacePath: string,
  filePath: string
): Promise<ParentPageObject> {
  const absolutePath = path.isAbsolute(filePath)
    ? filePath
    : path.join(workspacePath, filePath);
 
  // Read file content
  let content = '';
  try {
    content = await fs.readFile(absolutePath, 'utf-8');
  } catch (error) {
    console.error(`Failed to read file for parent page object: ${absolutePath}`, error);
    content = `[Could not read file: ${filePath}]`;
  }
 
  // Parse frontmatter
  const { data } = parseFrontmatter(content);
  const fields = buildFieldsFromFrontmatter(data);
 
  // Extract file path relative to workspace
  const relativePath = path.relative(workspacePath, absolutePath);
 
  // Extract file name
  const fileName = path.basename(absolutePath);
 
  // Extract base name (without extension)
  const baseName = path.basename(absolutePath, path.extname(absolutePath));
 
  return {
    content,
    file_path: relativePath,
    file_name: fileName,
    file_base_name: baseName,
    fields,
  };
}
 
/**
 * Build self object from a file path (legacy - for backward compatibility)
 */
export async function buildSelfObject(
  workspacePath: string,
  filePath: string
): Promise<SelfObject> {
  const absolutePath = path.isAbsolute(filePath)
    ? filePath
    : path.join(workspacePath, filePath);
 
  // Read file content
  let content = '';
  try {
    content = await fs.readFile(absolutePath, 'utf-8');
  } catch (error) {
    console.error(`Failed to read file for self object: ${absolutePath}`, error);
    content = `[Could not read file: ${filePath}]`;
  }
 
  // Extract file path relative to workspace
  const relativePath = path.relative(workspacePath, absolutePath);
 
  // Extract file name
  const fileName = path.basename(absolutePath);
 
  // Extract base name (without extension)
  const baseName = path.basename(absolutePath, path.extname(absolutePath));
 
  return {
    content,
    file_path: relativePath,
    file_name: fileName,
    file_base_name: baseName,
  };
}
 
/**
 * Read a file relative to workspace root
 */
async function funcReadFile(
  filePath: string,
  workspacePath: string
): Promise<string> {
  const absolutePath = path.isAbsolute(filePath)
    ? filePath
    : path.join(workspacePath, filePath);
 
  try {
    return await fs.readFile(absolutePath, 'utf-8');
  } catch {
    return `Could not read: ${filePath}`;
  }
}
 
/**
 * Convert string to uppercase
 */
function funcToUpper(input: string): string {
  return String(input).toUpperCase();
}
 
/**
 * Resolve a nested property path in an object
 * Supports paths like "fields.title.content" or "fields[key].content"
 */
function resolveNestedPath(obj: unknown, path: string): unknown {
  Iif (!obj || typeof obj !== 'object') {
    return undefined;
  }
 
  const parts = path.split('.');
  let current: unknown = obj;
 
  for (const part of parts) {
    if (!current || typeof current !== 'object') {
      return undefined;
    }
 
    // Handle array-like access with brackets (e.g., "fields[key]")
    const bracketMatch = part.match(/^(\w+)\[([^\]]+)\]$/);
    Iif (bracketMatch) {
      const objKey = bracketMatch[1];
      const nestedKey = bracketMatch[2];
      current = (current as Record<string, unknown>)[objKey];
      if (current && typeof current === 'object') {
        current = (current as Record<string, unknown>)[nestedKey];
      } else {
        return undefined;
      }
    } else {
      current = (current as Record<string, unknown>)[part];
    }
  }
 
  return current;
}
 
/**
 * Resolve a variable expression to its value
 */
function resolveVariable(
  expression: string,
  context: VariableContext
): string | unknown {
  const trimmed = expression.trim();
 
  // Split by first dot to get object and property path
  const firstDotIndex = trimmed.indexOf('.');
  Iif (firstDotIndex === -1) {
    return undefined;
  }
 
  const objectName = trimmed.substring(0, firstDotIndex);
  const propertyPath = trimmed.substring(firstDotIndex + 1);
 
  // Handle page context
  if (context.contextType === 'page') {
    if (objectName === 'self') {
      Iif (!context.self) {
        return '';
      }
 
      // Check for simple properties
      if (propertyPath in context.self) {
        return context.self[propertyPath as keyof PageSelfObject];
      }
 
      // Check for nested paths (e.g., "fields.title.content")
      return resolveNestedPath(context.self, propertyPath);
    E} else if (objectName === 'field') {
      return resolveNestedPath(context.field, propertyPath);
    }
  }
 
  // Handle field context
  Eif (context.contextType === 'field') {
    if (objectName === 'self') {
      Iif (!context.self) {
        return '';
      }
 
      // Simple field properties
      Eif (propertyPath in context.self) {
        return context.self[propertyPath as keyof FieldSelfObject];
      }
 
      return '';
    } else if (objectName === 'parent_page') {
      if (!context.parent_page) {
        return '';
      }
 
      // Check for simple properties
      if (propertyPath in context.parent_page) {
        return context.parent_page[propertyPath as keyof ParentPageObject];
      }
 
      // Check for nested paths (e.g., "fields.title.content")
      return resolveNestedPath(context.parent_page, propertyPath);
    E} else if (objectName === 'field') {
      return resolveNestedPath(context.field, propertyPath);
    }
  }
 
  return undefined;
}
 
function isKeyOfSelfObject(value: unknown, context: VariableContext): value is keyof SelfObject {
  // This function is now less useful with our new context types, but kept for potential legacy use
  return typeof value === 'string';
}
 
/**
 * Apply a function to a value
 */
async function applyFunction(
  value: unknown,
  funcExpression: string,
  context: VariableContext
): Promise<unknown> {
  const trimmed = funcExpression.trim();
 
  // Parse function name (e.g., "func.readFile")
  if (!trimmed.startsWith('func.')) {
    throw new Error(`Invalid function expression: ${funcExpression}`);
  }
 
  const funcName = trimmed.substring(5); // Remove "func."
 
  // Convert value to string for function processing
  const stringValue = String(value || '');
 
  // Apply function
  switch (funcName) {
    case 'readFile':
      return await funcReadFile(stringValue, context.workspacePath);
    case 'toUpper':
      return funcToUpper(stringValue);
    default:
      throw new Error(`Unknown function: ${funcName}`);
  }
}
 
/**
 * Process a single variable expression (may include pipes)
 */
async function processExpression(
  expression: string,
  context: VariableContext
): Promise<string> {
  const trimmed = expression.trim();
 
  // Check if expression contains pipe
  Iif (trimmed.includes('|')) {
    const parts = trimmed.split('|').map(p => p.trim());
    const variableExpr = parts[0];
    const functionExprs = parts.slice(1);
 
    // Resolve the variable first
    let value = resolveVariable(variableExpr, context);
 
    // Apply each function in the chain
    for (const funcExpr of functionExprs) {
      value = await applyFunction(value, funcExpr, context);
    }
 
    return String(value || '');
  } else {
    // No pipe, just resolve variable
    const value = resolveVariable(trimmed, context);
    return String(value ?? '');
  }
}
 
/**
 * Process a prompt template and replace all variables
 */
export async function processPromptTemplate(
  templateText: string,
  context: VariableContext
): Promise<string> {
  // Find all {{ ... }} patterns
  const variablePattern = /\{\{([^}]+)\}\}/g;
 
  let result = templateText;
  const matches = Array.from(templateText.matchAll(variablePattern));
 
  // Process each match (in reverse to maintain string positions)
  for (let i = matches.length - 1; i >= 0; i--) {
    const match = matches[i];
    const fullMatch = match[0];
    const expression = match[1];
    const startIndex = match.index!;
 
    try {
      // Process the expression
      const replacement = await processExpression(expression, context);
 
      // Replace in result string
      result = result.substring(0, startIndex) +
               replacement +
               result.substring(startIndex + fullMatch.length);
    } catch (error) {
      console.error(`Error processing variable expression: ${expression}`, error);
      // Leave the variable as-is on error
    }
  }
 
  return result;
}