buildSource

tcmts.core.analyze.buildSource · #gkxyic2s · term · runs anywhere

import type { Piece } from "#codebase/tcmts/core/extract";
import type { SourceFile as ts_SourceFile } from "typescript/ast";

export function buildSource(pieces: Piece[], sf: ts_SourceFile) {
  let text = "";
  const ranges: { fileStart: number; fileEnd: number; outStart: number }[] = [];
  for (const p of pieces) {
    if ("text" in p) text += p.text;
    else {
      ranges.push({ fileStart: p.start, fileEnd: p.end, outStart: text.length });
      text += sf.text.slice(p.start, p.end);
    }
  }
  const map = (pos: number) => {
    for (const r of ranges) if (pos >= r.fileStart && pos <= r.fileEnd) return r.outStart + pos - r.fileStart;
    throw new Error(`position ${pos} outside definition source`);
  };
  return { text, map };
}

uses

used by