iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / mind-worker / src / mind / tree.tsmain at 949894f

// tree.ts — THE MIND'S CODE IS ONE TREE OF SEVERAL REPOS. `/repos` is the module root: the file
// `init.ts` of `/repos/stdlib` is the module `stdlib/init.ts`, and a file of any repo names it
// `@repos/stdlib/init.ts`. That name works on a laptop too: the importing repo's package.json lists
// `"@repos/stdlib": "../stdlib"`, the folder next door, and an install links it. A publication
// reads the entry repo, then each repo that the entry's imports reach, each at one commit. That
// set of commits is what the mind runs.
import { importedTopFolders, type SourceFiles } from "../context/module-resolution.ts";
import { z } from "zod";
import type { MindRepos } from "../config.ts";

/** The commit of each repo in a published tree, by the repo's path. */
export type TreeCommits = Record<string, string>;

const REPOS = "/repos/";
/** The scope under which a repo's package.json names another repo: `@repos/<repo>`. */
const REPOS_SCOPE = "@repos/";
const folderOf = (repoPath: string) => repoPath.slice(REPOS.length);

/** The module that the entry is in the tree: `config/worker.ts`. */
export const entryModuleOf = (entry: MindRepos["entry"]) =>
  `${folderOf(entry.repo)}/${entry.module}`;

/** ONE TREE OUT OF EACH REPO'S FILES, each repo under its own folder, and a `package.json` at the
 *  root that names the entry module. The loader reads that file for the entry and for npm
 *  packages (context/module-resolution.ts `readPackage`): the packages and the compatibility
 *  flags are the entry repo's own, and no other repo's `package.json` counts. A line that names
 *  a repo (`reposNamedIn`) is left out: a repo is no npm package. */
export function mergedTree(
  entry: MindRepos["entry"],
  filesByRepo: Record<string, SourceFiles>,
): SourceFiles {
  const tree: SourceFiles = {};
  for (const [repoPath, files] of Object.entries(filesByRepo))
    for (const [file, content] of Object.entries(files))
      tree[`${folderOf(repoPath)}/${file}`] = content;
  const own = filesByRepo[entry.repo]?.["package.json"];
  let manifest: { dependencies?: Record<string, unknown>; compatibilityFlags?: unknown } = {};
  if (typeof own === "string")
    try {
      manifest = JSON.parse(own);
    } catch (error) {
      throw new Error(`${entry.repo}'s package.json is not valid JSON: ${String(error)}`);
    }
  tree["package.json"] = JSON.stringify({
    main: entryModuleOf(entry),
    dependencies:
      manifest.dependencies &&
      Object.fromEntries(
        Object.entries(manifest.dependencies).filter(([name]) => !name.startsWith(REPOS_SCOPE)),
      ),
    compatibilityFlags: manifest.compatibilityFlags,
  });
  return tree;
}

/** THE REPOS THAT A REPO'S package.json NAMES: each line of "dependencies" whose name is
 *  `@repos/<repo>`, as the mind's path of that repo and what the line says of where the repo is
 *  (`../<repo>`, the folder next door). A file that is not there or is not JSON names none: the
 *  loader says what is wrong with it when it reads it. */
export function reposNamedIn(packageJson: string | null): { path: string; from: string }[] {
  let manifest: { dependencies?: unknown } = {};
  try {
    manifest = JSON.parse(packageJson || "{}") || {};
  } catch {
    return [];
  }
  const lines = z.record(z.string(), z.string()).safeParse(manifest.dependencies);
  if (!lines.success) return [];
  return Object.entries(lines.data)
    .filter(([name]) => /^@repos\/[a-z0-9][a-z0-9-]*$/.test(name))
    .map(([name, from]) => ({ path: REPOS + name.slice(REPOS_SCOPE.length), from }));
}

/** WHERE A NAMED REPO IS CLONED FROM AT A BIRTH: what its line says, read beside the entry repo's
 *  own origin as a path is read beside a folder. `../stdlib` beside
 *  `https://git.example.org/repos/config-template` is `https://git.example.org/repos/stdlib`. An
 *  https address is that address. Null for anything else, and for an entry repo that was cloned
 *  from nowhere: such a repo is made empty, and gets its code by a push. An address is worked out
 *  here and at a birth only. From then on each repo keeps its own origin, and `../stdlib` says
 *  no more than "the repo next door". */
export function originBeside(entryOrigin: string | null, from: string): string | null {
  if (!entryOrigin || !/^(\.\.?\/|https:\/\/)/.test(from)) return null;
  return new URL(from, entryOrigin.replace(/\/?$/, "/")).href.replace(/\/$/, "");
}

/** THE TREE A PUBLICATION LOADS: the entry repo, and every repo that the code reached from the
 *  entry module imports from, found by reading. `commitOf` answers the commit to read of a repo,
 *  or null for a repo that has none. A repo that the code imports from and that has no commit is
 *  an error that names the importing file. */
export async function gatheredTree(input: {
  entry: MindRepos["entry"];
  commitOf: (repoPath: string) => Promise<string | null>;
  filesOf: (repoPath: string, commitOid: string) => Promise<SourceFiles>;
}): Promise<{ files: SourceFiles; commits: TreeCommits }> {
  const { entry } = input;
  const commits: TreeCommits = {};
  const filesByRepo: Record<string, SourceFiles> = {};
  const read = async (repoPath: string, importedBy: string | null) => {
    const commitOid = await input.commitOf(repoPath);
    if (!commitOid)
      throw new Error(
        importedBy
          ? `${importedBy} imports from ${repoPath}, which has no commit on main`
          : `${repoPath} has no commit on main`,
      );
    commits[repoPath] = commitOid;
    filesByRepo[repoPath] = await input.filesOf(repoPath, commitOid);
  };
  await read(entry.repo, null);
  for (;;) {
    const files = mergedTree(entry, filesByRepo);
    const unread = importedTopFolders(files, entryModuleOf(entry), "the mind's code").filter(
      ({ folder }) => !commits[REPOS + folder],
    );
    if (unread.length === 0) return { files, commits };
    for (const { folder, importedBy } of unread) await read(REPOS + folder, importedBy);
  }
}

/** One name for a set of commits, the same for the same set: what a loaded worker is cached by. */
export const treeKeyOf = (commits: TreeCommits) =>
  Object.keys(commits)
    .sort()
    .map((repoPath) => `${folderOf(repoPath)}@${commits[repoPath]}`)
    .join(",");