traceCalls

tcmts.cli.web.traceCalls · #hkzyavfe · term · runs on the server

uses node:fs

tcm dev --trace-calls: each call to one of the codebase's functions on the server is a span of its own (fn), inside the call it was made in, so a trace is the whole tree of what ran. The process loads each generated module (.tcm/cache/<hash>.ts) exporting its functions traced (tracedModule): calls between definitions go through that; a call within one definition's own cycle doesn't, nor does a module loaded before this.

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import { HASH_FILE, serverApiHost, tracedModule } from "#codebase/tcmts/cli/web";
import fs from "node:fs";
import { registerHooks } from "node:module";
import path from "node:path";
import { pathToFileURL } from "node:url";

export async function traceCalls(cb: Codebase): Promise<void> {
  const api = await serverApiHost(cb)();
  (globalThis as { __tcmTraceCall?: unknown }).__tcmTraceCall = api.wrapCall;
  const caches = [
    cb.lay.cacheDir,
    fs.existsSync(cb.lay.cacheDir) ? fs.realpathSync(cb.lay.cacheDir) : cb.lay.cacheDir,
  ].map((d) => pathToFileURL(d + path.sep).href);
  registerHooks({
    load(url, context, nextLoad) {
      const loaded = nextLoad(url, context);
      if (
        !caches.some((c) => url.startsWith(c)) ||
        !HASH_FILE.test(url.split("?")[0]!) ||
        loaded.source == null
      )
        return loaded;
      return { ...loaded, source: tracedModule(String(loaded.source)) };
    },
  });
}

uses

used by