All files / shared source-project.ts

92.6% Statements 213/230
85.54% Branches 148/173
96.42% Functions 27/28
92.64% Lines 189/204

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 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590                                                                                                          82x 82x 82x 82x 82x 82x               20x                   730x 724x   720x 720x 720x 879x 877x 872x 26x 14x 14x   846x   706x       90x 90x       91x 90x 90x       484x                       101x 3x   98x               138x 138x 138x 3818x 3818x   138x       1993x 1991x 1989x 1757x         518x 518x 518x 518x   518x 34018x 34018x   34018x 101x 101x 101x 101x 101x     33917x 1993x 1993x 1993x 1993x     31924x 232x 232x 232x 232x   31692x 3x 3x 3x 3x   31689x 138x 138x 138x 138x   31551x 31551x   518x                     1x       5x 5x   5x 5x 1x 1x       244x 917x 917x 244x 244x 244x 244x   151x 151x 151x 244x 5x   4x                                               152x 152x 152x   152x             152x 249x     152x     152x   152x       152x 150x 150x               152x                   249x 249x 2x 2x   247x       247x         247x 247x 247x                 247x 247x                                       820x 820x                     13x 13x                       902x         902x   13x 13x 5x             13x 13x 5x 8x 5x   13x 13x       83x 2x 2x                     95x 4x               4x     91x 91x 6x               6x   85x 2x               2x   83x 1x               1x   82x                       902x 902x                 902x   889x 902x 95x   794x   889x                 232x 232x 231x                   231x   229x 229x                     229x 229x 229x 229x   229x 229x 229x 229x 902x                   229x       150x 150x 244x 244x   150x                                   150x 150x       150x 150x 150x 150x 14x       150x                  
/**
 * Pure virtual source-project model and local include resolver.
 *
 * This module deliberately has no filesystem, network, React, or Node.js
 * dependencies. It provides the deterministic source view consumed by
 * project-aware static analyzers.
 */
 
export interface SourceProject {
  entryFile: string;
  files: Readonly<Record<string, string>>;
}
 
export interface SourceLocation {
  file: string;
  line: number;
  column?: number;
}
 
export type SourceProjectDiagnosticCode =
  | "INVALID_PATH"
  | "MISSING_ENTRY"
  | "DUPLICATE_PATH"
  | "MISSING_LOCAL_INCLUDE"
  | "INCLUDE_CYCLE"
  | "UNSUPPORTED_CONDITIONAL_INCLUDE";
 
export interface SourceProjectDiagnostic {
  code: SourceProjectDiagnosticCode;
  message: string;
  file?: string;
  line?: number;
  include?: string;
}
 
export interface SourceProjectValidationResult {
  valid: boolean;
  project?: SourceProject;
  errors: SourceProjectDiagnostic[];
}
 
export interface ResolvedSourceProject {
  entryFile: string;
  /** Include-ordered source text. */
  source: string;
  /** One origin for every generated source line. */
  lineOrigins: readonly SourceLocation[];
  /** Entry first, followed by files in DFS expansion order. */
  reachableFiles: readonly string[];
  diagnostics: readonly SourceProjectDiagnostic[];
  complete: boolean;
}
 
const INCLUDE_PATTERN = /^\s*#\s*include\s*"([^"\r\n]+)"/;
const CONDITIONAL_PATTERN = /^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b/;
const CONDITIONAL_START_PATTERN = /^\s*#\s*(if|ifdef|ifndef)\b/;
const CONDITIONAL_END_PATTERN = /^\s*#\s*endif\b/;
const GUARD_IFNDEF_PATTERN = /^\s*#\s*ifndef\s+([A-Za-z_]\w*)\s*$/;
const GUARD_DEFINE_PATTERN = /^\s*#\s*define\s+([A-Za-z_]\w*)\s*$/;
 
function diagnostic(
  code: SourceProjectDiagnosticCode,
  message: string,
  location?: SourceLocation,
  include?: string,
): SourceProjectDiagnostic {
  return {
    code,
    message,
    ...(location ? { file: location.file, line: location.line } : {}),
    ...(include ? { include } : {}),
  };
}
 
/** Normalize a relative POSIX path, returning undefined for unsafe paths. */
export function normalizeSourcePath(value: string): string | undefined {
  if (!value || value.includes("\\") || value.includes("\0")) return undefined;
  if (value.startsWith("/") || value.startsWith("//")) return undefined;
 
  const segments = value.split("/");
  const normalized: string[] = [];
  for (const segment of segments) {
    if (!segment) return undefined;
    if (segment === ".") continue;
    if (segment === "..") {
      if (normalized.length === 0) return undefined;
      normalized.pop();
      continue;
    }
    normalized.push(segment);
  }
  return normalized.length > 0 ? normalized.join("/") : undefined;
}
 
function pathDirectory(path: string): string {
  const separator = path.lastIndexOf("/");
  return separator < 0 ? "" : path.slice(0, separator);
}
 
function resolveIncludePath(fromFile: string, include: string): string | undefined {
  if (!include || include.includes("\\") || include.includes("\0")) return undefined;
  const base = pathDirectory(fromFile);
  return normalizeSourcePath(base ? `${base}/${include}` : include);
}
 
function hasOwnProperty(object: object, property: PropertyKey): boolean {
  return Object.getOwnPropertyDescriptor(object, property) !== undefined;
}
 
interface StringMaskState {
  quote: '"' | "'" | null;
  escaped: boolean;
}
 
function maskBlockCommentCharacter(
  source: string,
  index: number,
): { text: string; consumed: number; closed: boolean } {
  if (source[index] === "*" && source[index + 1] === "/") {
    return { text: "  ", consumed: 2, closed: true };
  }
  return {
    text: source[index] === "\n" ? "\n" : " ",
    consumed: 1,
    closed: false,
  };
}
 
function maskLineComment(source: string, start: number): { text: string; nextIndex: number } {
  let nextIndex = start;
  let text = "";
  while (nextIndex < source.length && source[nextIndex] !== "\n") {
    text += " ";
    nextIndex++;
  }
  return { text, nextIndex };
}
 
function advanceStringMask(state: StringMaskState, current: string): StringMaskState {
  if (state.escaped) return { quote: state.quote, escaped: false };
  if (current === "\\") return { quote: state.quote, escaped: true };
  if (current === state.quote) return { quote: null, escaped: false };
  return state;
}
 
/** Replaces comment characters with spaces, keeping every offset and line break of `source`. */
export function maskCommentsPreservingLines(source: string): string {
  const result: string[] = [];
  let inBlockComment = false;
  let stringState: StringMaskState = { quote: null, escaped: false };
  let index = 0;
 
  while (index < source.length) {
    const current = source[index];
    const next = source[index + 1];
 
    if (inBlockComment) {
      const masked = maskBlockCommentCharacter(source, index);
      result.push(masked.text);
      index += masked.consumed;
      inBlockComment = !masked.closed;
      continue;
    }
 
    if (stringState.quote) {
      result.push(current);
      stringState = advanceStringMask(stringState, current);
      index++;
      continue;
    }
 
    if (current === '"' || current === "'") {
      stringState = { quote: current, escaped: false };
      result.push(current);
      index++;
      continue;
    }
    if (current === "/" && next === "*") {
      result.push("  ");
      index += 2;
      inBlockComment = true;
      continue;
    }
    if (current === "/" && next === "/") {
      const masked = maskLineComment(source, index);
      result.push(masked.text);
      index = masked.nextIndex;
      continue;
    }
    result.push(current);
    index++;
  }
  return result.join("");
}
 
interface IncludeGuard {
  ifndefLine: number;
  defineLine: number;
  endifLine: number;
  macro: string;
}
 
function isWhitespace(character: string | undefined): boolean {
  return character === " " || character === "\t" || character === "\r" || character === "\n";
}
 
function isCanonicalGuardEnd(line: string): boolean {
  const directive = line.trim().slice(1).trimStart();
  Iif (!line.trim().startsWith("#") || !directive.startsWith("endif")) return false;
 
  const suffix = directive.slice("endif".length);
  if (suffix.length === 0) return true;
  Iif (!isWhitespace(suffix[0])) return false;
  return suffix.trimStart().startsWith("//");
}
 
function detectIncludeGuard(maskedLines: string[]): IncludeGuard | undefined {
  const nonEmpty = maskedLines
    .map((line, index) => ({ line: line.trim(), index }))
    .filter(({ line }) => line.length > 0);
  const first = nonEmpty[0];
  const second = nonEmpty[1];
  const last = nonEmpty.at(-1);
  if (!first || !second || !last) return undefined;
 
  const ifndef = GUARD_IFNDEF_PATTERN.exec(first.line);
  const define = GUARD_DEFINE_PATTERN.exec(second.line);
  const macro = ifndef?.[1];
  if (!macro || macro !== define?.[1]) return undefined;
  if (!isCanonicalGuardEnd(last.line)) return undefined;
 
  return {
    ifndefLine: first.index,
    defineLine: second.index,
    endifLine: last.index,
    macro,
  };
}
 
function emptyResolvedProject(
  entryFile: string,
  diagnostics: SourceProjectDiagnostic[],
): ResolvedSourceProject {
  return {
    entryFile,
    source: "",
    lineOrigins: [],
    reachableFiles: [],
    diagnostics,
    complete: false,
  };
}
 
/** Validate and normalize all project paths without touching the filesystem. */
export function validateSourceProject(input: SourceProject): SourceProjectValidationResult {
  const errors: SourceProjectDiagnostic[] = [];
  const normalizedFiles: Record<string, string> = Object.create(null) as Record<string, string>;
  const caseFolded = new Map<string, string>();
 
  Iif (!isSourceFileRecord(input?.files)) {
    return {
      valid: false,
      errors: [diagnostic("INVALID_PATH", "Source project files must be a record")],
    };
  }
 
  for (const [rawPath, content] of Object.entries(input.files)) {
    addValidatedSourceFile(rawPath, content, normalizedFiles, caseFolded, errors);
  }
 
  const entryFile = typeof input.entryFile === "string"
    ? normalizeSourcePath(input.entryFile)
    : undefined;
  Iif (!entryFile) {
    errors.push(diagnostic("INVALID_PATH", `Invalid entry file: ${String(input.entryFile)}`));
  } else Iif (!hasOwnProperty(normalizedFiles, entryFile)) {
    errors.push(diagnostic("MISSING_ENTRY", `Entry file is not present in project: ${entryFile}`, { file: entryFile, line: 1 }));
  }
 
  if (errors.length > 0) return { valid: false, errors };
  Iif (!entryFile) return { valid: false, errors };
  return {
    valid: true,
    project: { entryFile, files: normalizedFiles },
    errors: [],
  };
}
 
function isSourceFileRecord(value: unknown): value is Readonly<Record<string, unknown>> {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
 
function addValidatedSourceFile(
  rawPath: string,
  content: unknown,
  normalizedFiles: Record<string, string>,
  caseFolded: Map<string, string>,
  errors: SourceProjectDiagnostic[],
): void {
  const path = normalizeSourcePath(rawPath);
  if (!path) {
    errors.push(diagnostic("INVALID_PATH", `Invalid source path: ${rawPath}`, { file: rawPath, line: 1 }));
    return;
  }
  Iif (typeof content !== "string") {
    errors.push(diagnostic("INVALID_PATH", `Source content must be a string: ${rawPath}`, { file: rawPath, line: 1 }));
    return;
  }
  Iif (hasOwnProperty(normalizedFiles, path)) {
    errors.push(diagnostic("DUPLICATE_PATH", `Duplicate normalized source path: ${path}`, { file: path, line: 1 }));
    return;
  }
 
  const folded = path.toLocaleLowerCase("en-US");
  const foldedExisting = caseFolded.get(folded);
  Iif (foldedExisting && foldedExisting !== path) {
    errors.push(diagnostic(
      "DUPLICATE_PATH",
      `Case-folded source paths collide: ${foldedExisting} and ${path}`,
      { file: path, line: 1 },
    ));
    return;
  }
 
  caseFolded.set(folded, path);
  normalizedFiles[path] = content;
}
 
interface SourceResolverContext {
  project: SourceProject;
  outputLines: string[];
  lineOrigins: SourceLocation[];
  reachableFiles: string[];
  diagnostics: SourceProjectDiagnostic[];
  expanded: Set<string>;
  stack: string[];
  guardMacros: Set<string>;
  guardByFile: Map<string, IncludeGuard>;
}
 
function addResolvedLine(
  context: SourceResolverContext,
  text: string,
  location: SourceLocation,
): void {
  context.outputLines.push(text);
  context.lineOrigins.push(location);
}
 
function reportIncludeProblem(
  context: SourceResolverContext,
  code: "MISSING_LOCAL_INCLUDE" | "INCLUDE_CYCLE" | "UNSUPPORTED_CONDITIONAL_INCLUDE",
  message: string,
  location?: SourceLocation,
  include?: string,
  sourceLine?: string,
): void {
  context.diagnostics.push(diagnostic(code, message, location, include));
  Eif (location && sourceLine !== undefined) addResolvedLine(context, sourceLine, location);
}
 
function processConditionalDirective(
  context: SourceResolverContext,
  maskedLine: string,
  rawLine: string,
  location: SourceLocation,
  lineIndex: number,
  guard: IncludeGuard | undefined,
  conditionalDepth: number,
): number | undefined {
  const isGuardLine = guard !== undefined && (
    lineIndex === guard.ifndefLine ||
    lineIndex === guard.defineLine ||
    lineIndex === guard.endifLine
  );
  if (isGuardLine || !CONDITIONAL_PATTERN.test(maskedLine)) return undefined;
 
  const startsConditional = CONDITIONAL_START_PATTERN.test(maskedLine);
  if (startsConditional && conditionalDepth === 0) {
    context.diagnostics.push(diagnostic(
      "UNSUPPORTED_CONDITIONAL_INCLUDE",
      "Conditional preprocessing is not evaluated by the source resolver",
      location,
    ));
  }
 
  let nextDepth = conditionalDepth;
  if (CONDITIONAL_END_PATTERN.test(maskedLine)) {
    nextDepth = Math.max(0, conditionalDepth - 1);
  } else if (startsConditional) {
    nextDepth++;
  }
  addResolvedLine(context, rawLine, location);
  return nextDepth;
}
 
function isUnguardedCycle(context: SourceResolverContext, target: string): boolean {
  if (!context.stack.includes(target)) return false;
  const targetGuard = context.guardByFile.get(target);
  return !targetGuard || !context.guardMacros.has(targetGuard.macro);
}
 
function resolveLocalInclude(
  context: SourceResolverContext,
  fromFile: string,
  include: string,
  location: SourceLocation,
  sourceLine: string,
  conditionalDepth: number,
): void {
  if (conditionalDepth > 0) {
    reportIncludeProblem(
      context,
      "UNSUPPORTED_CONDITIONAL_INCLUDE",
      `Conditional local include was not resolved: ${include}`,
      location,
      include,
      sourceLine,
    );
    return;
  }
 
  const target = resolveIncludePath(fromFile, include);
  if (!target) {
    reportIncludeProblem(
      context,
      "MISSING_LOCAL_INCLUDE",
      `Invalid local include path: ${include}`,
      location,
      include,
      sourceLine,
    );
    return;
  }
  if (!hasOwnProperty(context.project.files, target)) {
    reportIncludeProblem(
      context,
      "MISSING_LOCAL_INCLUDE",
      `Local include was not found: ${target}`,
      location,
      include,
      sourceLine,
    );
    return;
  }
  if (isUnguardedCycle(context, target)) {
    reportIncludeProblem(
      context,
      "INCLUDE_CYCLE",
      `Include cycle detected while resolving ${target}`,
      location,
      include,
      sourceLine,
    );
    return;
  }
  expandSourceFile(context, target, location, include);
}
 
function processSourceLine(
  context: SourceResolverContext,
  file: string,
  rawLine: string,
  maskedLine: string,
  lineIndex: number,
  guard: IncludeGuard | undefined,
  conditionalDepth: number,
): number {
  const location: SourceLocation = { file, line: lineIndex + 1 };
  const nextDepth = processConditionalDirective(
    context,
    maskedLine,
    rawLine,
    location,
    lineIndex,
    guard,
    conditionalDepth,
  );
  if (nextDepth !== undefined) return nextDepth;
 
  const include = INCLUDE_PATTERN.exec(maskedLine)?.[1];
  if (include) {
    resolveLocalInclude(context, file, include, location, rawLine, conditionalDepth);
  } else {
    addResolvedLine(context, rawLine, location);
  }
  return conditionalDepth;
}
 
function expandSourceFile(
  context: SourceResolverContext,
  file: string,
  includeLocation?: SourceLocation,
  includeText?: string,
): void {
  const guard = context.guardByFile.get(file);
  if (guard && context.guardMacros.has(guard.macro)) return;
  Iif (context.stack.includes(file)) {
    reportIncludeProblem(
      context,
      "INCLUDE_CYCLE",
      `Include cycle detected while resolving ${file}`,
      includeLocation,
      includeText,
    );
    return;
  }
  if (context.expanded.has(file)) return;
 
  const content = context.project.files[file];
  Iif (content === undefined) {
    reportIncludeProblem(
      context,
      "MISSING_LOCAL_INCLUDE",
      `Local include was not found: ${file}`,
      includeLocation,
      includeText,
    );
    return;
  }
 
  context.expanded.add(file);
  context.reachableFiles.push(file);
  context.stack.push(file);
  if (guard) context.guardMacros.add(guard.macro);
 
  const rawLines = content.split("\n");
  const maskedLines = maskCommentsPreservingLines(content).split("\n");
  let conditionalDepth = 0;
  for (let index = 0; index < rawLines.length; index++) {
    conditionalDepth = processSourceLine(
      context,
      file,
      rawLines[index] ?? "",
      maskedLines[index] ?? "",
      index,
      guard,
      conditionalDepth,
    );
  }
  context.stack.pop();
}
 
function createResolverContext(project: SourceProject): SourceResolverContext {
  const guardByFile = new Map<string, IncludeGuard>();
  for (const [file, content] of Object.entries(project.files)) {
    const guard = detectIncludeGuard(maskCommentsPreservingLines(content).split("\n"));
    if (guard) guardByFile.set(file, guard);
  }
  return {
    project,
    outputLines: [],
    lineOrigins: [],
    reachableFiles: [],
    diagnostics: [],
    expanded: new Set<string>(),
    stack: [],
    guardMacros: new Set<string>(),
    guardByFile,
  };
}
 
/**
 * Resolve only local quoted includes reachable from the entry file.
 * Include expansion is depth-first and each canonical file is emitted once.
 */
export function resolveSourceProject(input: SourceProject): ResolvedSourceProject {
  const validation = validateSourceProject(input);
  Iif (!validation.valid || !validation.project) {
    return emptyResolvedProject(input?.entryFile ?? "", validation.errors);
  }
 
  const project = validation.project;
  const context = createResolverContext(project);
  expandSourceFile(context, project.entryFile);
  const incomplete = context.diagnostics.some(({ code }) =>
    code === "MISSING_LOCAL_INCLUDE" ||
    code === "INCLUDE_CYCLE" ||
    code === "UNSUPPORTED_CONDITIONAL_INCLUDE",
  );
  return {
    entryFile: project.entryFile,
    source: context.outputLines.join("\n"),
    lineOrigins: context.lineOrigins,
    reachableFiles: context.reachableFiles,
    diagnostics: context.diagnostics,
    complete: !incomplete,
  };
}