A repo names another repo as a package, and a birth reads the list from config
Misha Kaletsky, 2026-11-25 17:42 UTC · cb7627a721371043f45d6cf2abb30adee0185cbf · parent 0c85e04
7 files changed
- M core/mind-worker/src/config.ts
- M core/mind-worker/src/context/module-resolution.test.ts
- M core/mind-worker/src/context/module-resolution.ts
- M core/mind-worker/src/mind/processor.test.ts
- M core/mind-worker/src/mind/processor.ts
- M core/mind-worker/src/mind/tree.test.ts
- M core/mind-worker/src/mind/tree.ts
M core/mind-worker/src/config.ts
@@ -11,16 +11,18 @@ .string() .regex(/^\/repos\/[a-z0-9][a-z0-9-]*$/, "a repo path: /repos/<name>"); -/** THE REPOS THE MIND IS BORN WITH, and which of them holds its code. */ +/** THE REPOS THAT A DEPLOY NAMES FOR A MIND, and which of them holds its code. */ export const MindRepos = z.object({ - /** At its first wake the mind makes each repo that it does not have yet. One with an `origin` - * is cloned from that public git URL, with its history. One whose `origin` is null is made - * empty and gets its first commit by a push. A later deploy never touches a repo that exists: - * after birth a repo moves by git alone. */ + /** The kernel's repo and the one that holds the mind's code, as a deploy names them at the + * mind's birth. At its first wake the mind makes each one that it does not have yet. One with + * an `origin` is cloned from that public git URL, with its history. One whose `origin` is null + * is made empty and gets its first commit by a push. The mind's other repos are named by the + * entry repo's own package.json, and are made at the same wake (mind/tree.ts `reposNamedIn`). + * A later deploy never touches a repo that exists: after birth a repo moves by git alone. */ repos: z.array(z.object({ path: RepoPath, origin: z.url().nullable() })).min(1), - /** `module` of the repo `repo` answers every request, mail and event. Its relative imports may - * reach into the repos beside it. The mind publishes the newest commits of the repos that it - * loads from whenever one of them moves. */ + /** `module` of the repo `repo` answers every request, mail and event. It names a file of + * another repo as `@repos/<repo>/<path>`. The mind publishes the newest commits of the repos + * that it loads from whenever one of them moves. */ entry: z.object({ repo: RepoPath, module: z.string().min(1) }), }); export type MindRepos = z.infer<typeof MindRepos>;
M core/mind-worker/src/context/module-resolution.test.ts
@@ -27,6 +27,45 @@ }, ); +test("a file of another repo is imported by the repo's name, as code, as a file or as a folder, and is no npm package though package.json lists it", async () => { + const tree = { + "package.json": JSON.stringify({ main: "config/worker.ts" }), + "config/worker.ts": [ + 'import { init } from "@repos/stdlib/init.ts";', + 'import theme from "@repos/stdlib/theme.css";', + 'import files from "@repos/dash/public/";', + "export default { init, theme, files };", + ].join("\n"), + "stdlib/init.ts": 'import { step } from "./step.ts";\nexport const init = step;\n', + "stdlib/step.ts": "export const step = () => {};\n", + "stdlib/theme.css": ":root { color-scheme: light; }\n", + "dash/public/app.js": "console.log('the Dash');\n", + }; + + const { modules } = await resolveModules(tree, options()); + + expect(modules).toMatchObject({ + "config/worker.js": expect.stringContaining('from "../stdlib/init.js"'), + "stdlib/init.js": expect.stringContaining('from "./step.js"'), + "stdlib/theme.css.file.js": expect.stringContaining("color-scheme: light"), + "dash/public.files.js": expect.stringContaining('"app.js"'), + }); +}); + +test("a name under @repos with no such file says so, and one that climbs out of its repo is refused", async () => { + const worker = (specifier: string) => ({ + "package.json": JSON.stringify({ main: "config/worker.ts" }), + "config/worker.ts": `import x from "${specifier}";\nexport default x;\n`, + }); + + await expect(resolveModules(worker("@repos/stdlib/init.ts"), options())).rejects.toThrow( + "config/worker.ts imports @repos/stdlib/init.ts, and there is no such file", + ); + await expect(resolveModules(worker("@repos/stdlib/../../x.ts"), options())).rejects.toThrow( + "config/worker.ts imports @repos/stdlib/../../x.ts, which is no path of a repo", + ); +}); + /** A config whose worker.ts is `worker`, beside one code file in a folder. */ function sourceWith(worker: string) { return {
M core/mind-worker/src/context/module-resolution.ts
@@ -51,6 +51,18 @@ const isRelative = (specifier: string) => specifier.startsWith("./") || specifier.startsWith("../"); +/** A FILE OF ANOTHER REPO OF THE MIND IS NAMED AS A PACKAGE: `@repos/<repo>/<path>`. A repo's + * package.json calls the repo `@repos/<repo>`, and a repo that imports from it lists it under + * "dependencies" as the folder next door (`"@repos/stdlib": "../stdlib"`), which an install on a + * laptop links. Here, in a tree where each repo is a folder at the root (mind/tree.ts), the name + * is the path `<repo>/<path>`. Undefined for any other specifier. */ +const REPOS_SCOPE = "@repos/"; +const pathInRepos = (specifier: string) => + specifier.startsWith(REPOS_SCOPE) ? specifier.slice(REPOS_SCOPE.length) : undefined; +/** Whether a path under `@repos/` stays where it says: no `.` and no `..` in it. */ +const staysInRepos = (path: string) => + path.split("/").every((part) => part !== "." && part !== ".."); + function packageName(specifier: string): string { const parts = specifier.split("/"); return parts.slice(0, specifier.startsWith("@") ? 2 : 1).join("/"); @@ -242,10 +254,12 @@ ].join("\n"); } -/** THE TOP-LEVEL FOLDERS THAT THE CODE REACHED FROM `entry` IMPORTS FROM, each with the first - * file found importing from it. It follows relative imports alone, through the files that - * `source` holds: a folder with no file in `source` is still named, which is how the mind - * learns that the entry's graph needs a repo it has not read yet (mind/tree.ts). */ +/** THE REPOS THAT THE CODE REACHED FROM `entry` IMPORTS FROM, each as its folder at the root of + * `source` and with the first file found importing from it. It follows the imports that name a + * repo (`@repos/<repo>/<path>`) and the relative ones, through the files that `source` holds: a + * repo with no file in `source` is still named, which is how the mind learns that the entry's + * graph needs a repo it has not read yet (mind/tree.ts). A relative import stays in its own + * repo: one that leaves it is refused here, at a publication, with the name to write. */ export function importedTopFolders( source: SourceFiles, entry: string, @@ -259,11 +273,19 @@ const authored = source[path]; if (typeof authored !== "string") continue; const code = /\.m?ts$/.test(path) ? stripTypes(authored, path, where) : authored; + const ownRepo = path.split("/")[0]!; for (const { specifier } of importsOf(code, path, where)) { - if (!isRelative(specifier) || climbsAboveRoot(path, specifier)) continue; - const joined = joinPath(path, specifier); + const named = pathInRepos(specifier); + if (!named && !isRelative(specifier)) continue; + // a name that is no path of a repo is the loader's to refuse (`resolveModules`) + if (named && !staysInRepos(named)) continue; + const joined = named || joinPath(path, specifier); const folder = joined.split("/")[0]!; - if (joined.includes("/") && !folders.has(folder)) folders.set(folder, path); + if (!named && (climbsAboveRoot(path, specifier) || folder !== ownRepo)) + throw new Error( + `${where}: ${path} imports ${specifier}, which is outside its own repo: write ${REPOS_SCOPE}${joined}`, + ); + if (named && !folders.has(folder)) folders.set(folder, path); const file = specifier.endsWith("/") ? undefined : sourceFileAt(source, joined); if (file && !seen.has(file)) { seen.add(file); @@ -343,10 +365,14 @@ const { specifier } = edit; if (specifier.startsWith("cloudflare:")) continue; let target: string; - if (isRelative(specifier)) { - if (climbsAboveRoot(path, specifier)) + const named = pathInRepos(specifier); + if (named || isRelative(specifier)) { + if (named && !staysInRepos(named)) + throw new Error(`${where}: ${path} imports ${specifier}, which is no path of a repo`); + if (!named && climbsAboveRoot(path, specifier)) throw new Error(`${where}: ${path} imports ${specifier}, which is above the source's root`); - const joined = joinPath(path, specifier); + // a repo's name is a path from the root of the tree; a relative one is from this file + const joined = named ? joinPath("", named) : joinPath(path, specifier); const file = specifier.endsWith("/") ? undefined : findSourceFile(joined); if (specifier.endsWith("/")) { target = loadFolder(joined, path, specifier);
M core/mind-worker/src/mind/processor.test.ts
@@ -18,7 +18,7 @@ probed: aConfig, repos: { "/repos/config": { - "worker.ts": `import { init } from "../stdlib/init.ts"; export default class { ready = init(); }`, + "worker.ts": `import { init } from "@repos/stdlib/init.ts"; export default class { ready = init(); }`, }, "/repos/stdlib": { "init.ts": "export const init = () => true;" }, // nothing imports from it: a publication never reads it @@ -174,6 +174,82 @@ ]); }); +test("a birth also makes the repos that the entry repo's package.json names, each cloned from beside where the entry repo came from", async () => { + const mind = mindOf({ + owes: false, + repos: { + "/repos/config": { + "package.json": JSON.stringify({ + main: "worker.ts", + dependencies: { yjs: "13.6.33", "@repos/stdlib": "../stdlib", "@repos/dash": "../dash" }, + }), + }, + }, + }); + const unborn: MindState = { + ...mind.state, + creation: { status: "requested", offset: 2 }, + // what a deploy names: the kernel's repo and the entry repo, each with where it comes from + configured: configuredEvent({ + repos: [ + { path: "/repos/kernel", origin: "https://git.example.org/repos/kernel" }, + { path: "/repos/config", origin: "https://git.example.org/repos/config-template" }, + ], + }).payload as MindState["configured"], + repos: {}, + repoTips: {}, + newestAsking: null, + published: null, + lastPublicationFactOffset: null, + }; + mind.deliver(unborn); + await mind.settled(); + + expect(mind.root.did).toEqual([ + "create /repos/kernel", + "setOrigin /repos/kernel https://git.example.org/repos/kernel", + 'pull /repos/kernel {"remote":"https://git.example.org/repos/kernel"}', + "create /repos/config", + "setOrigin /repos/config https://git.example.org/repos/config-template", + 'pull /repos/config {"remote":"https://git.example.org/repos/config-template"}', + "create /repos/stdlib", + "setOrigin /repos/stdlib https://git.example.org/repos/stdlib", + 'pull /repos/stdlib {"remote":"https://git.example.org/repos/stdlib"}', + "create /repos/dash", + "setOrigin /repos/dash https://git.example.org/repos/dash", + 'pull /repos/dash {"remote":"https://git.example.org/repos/dash"}', + ]); +}); + +test("an entry repo that was cloned from nowhere has its named repos made empty, and a mind that is created fetches nothing for a new name", async () => { + const named = { + "/repos/config": { + "package.json": JSON.stringify({ dependencies: { "@repos/stdlib": "../stdlib" } }), + }, + }; + const empty = mindOf({ owes: false, repos: named }); + empty.deliver({ + ...empty.state, + creation: { status: "requested", offset: 2 }, + configured: configuredEvent({ + repos: [{ path: "/repos/config", origin: null }], + }).payload as MindState["configured"], + repos: {}, + repoTips: {}, + newestAsking: null, + published: null, + lastPublicationFactOffset: null, + }); + await empty.settled(); + expect(empty.root.did).toEqual(["create /repos/config", "create /repos/stdlib"]); + + // after birth a name the mind has no repo for is nobody's to fetch: the publication says so + const alive = mindOf({ owes: false, repos: named }); + alive.deliver(alive.state); + await alive.settled(); + expect(alive.root.did.filter((did) => /^(create|setOrigin|pull) /.test(did))).toEqual([]); +}); + test("a publication keeps the entry module's files after its probe passed and before it appends the pointer", async () => { const mind = mindOf({ owes: true, head: "seed", probed: aConfig }); mind.deliver(mind.state); @@ -821,6 +897,8 @@ return { path: args[0] }; } const got = expression[3]; + if (at === "repos" && Array.isArray(got) && got[0] === "get" && verb === "readFile") + return repos[String(got[1])]?.[String(args[0])] || null; if (at === "repos" && Array.isArray(got) && got[0] === "get") { root.did.push( [verb, got[1], ...args.map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg)))].join(" "),
M core/mind-worker/src/mind/processor.ts
@@ -20,7 +20,13 @@ } from "core-itx"; import { MindContract, type MindState } from "./contract.ts"; import { configPointer, probedConfig, type MindPublisher } from "./publication.ts"; -import { gatheredTree, treeKeyOf, type TreeCommits } from "./tree.ts"; +import { + gatheredTree, + originBeside, + reposNamedIn, + treeKeyOf, + type TreeCommits, +} from "./tree.ts"; // a publication resolves its npm dependencies from esm.sh const PUBLICATION_BUDGET_MS = 60_000; @@ -327,37 +333,47 @@ }); } - /** THE REPOS OF THE CONFIG THAT THE MIND DOES NOT HAVE YET are made, each cloned from its origin - * when the config gives one. A repo that exists is never touched, except for one case: a repo - * with an origin and still no commit is a clone that did not finish, and is tried again, once - * in each incarnation. A clone's pull lands the commit's fact on `/`, which asks for the - * publication. */ + /** THE REPOS THAT THE MIND IS BORN WITH AND DOES NOT HAVE YET are made, and cloned where there + * is somewhere to clone them from. First the repos that the deploy named (the kernel's and the + * entry repo, each with its origin). Then the repos that the entry repo's package.json names + * (tree.ts `reposNamedIn`), each from beside where the entry repo came from (`originBeside`). + * This runs while the mind is being born and never after: a repo that exists is never + * touched, and a created mind fetches nothing. One case is tried again: a repo with an origin + * and still no commit is a clone that did not finish, once in each incarnation. A clone's pull + * lands the commit's fact on `/`, which asks for the publication. */ async #makeMissingRepos(state: MindState): Promise<void> { // one stub a call: a clone outlasts any one of them const call = async (expression: ItxExpression) => { using itx = this.getItx(); return await itx.invoke(expression); }; - for (const { path, origin } of state.configured!.repos) { + // Through the mind's collection, as any caller reaches a repo, and never the repo's own + // facet: a pull goes out through its caller's egress, which is `/`'s `itx.fetch` here, and a + // facet that is called directly has no caller to take one from, so it refuses the pull. + const ofRepo = (path: string, verb: string, ...args: unknown[]): ItxExpression => [ + "itx", + "builtins", + "repos", + ["get", path], + [verb, ...args], + ]; + const make = async (path: string, origin: string | null) => { if (!state.repos[path] && !this.#repoMade.has(path)) { await call(["itx", "builtins", "repos", ["create", path]]); this.#repoMade.add(path); } - if (!origin || state.repoTips[path] || this.#cloneTried.has(path)) continue; + if (!origin || state.repoTips[path] || this.#cloneTried.has(path)) return; this.#cloneTried.add(path); - // Through the mind's collection, as any caller reaches a repo, and never the repo's own - // facet: a pull goes out through its caller's egress, which is `/`'s `itx.fetch` here, and a - // facet that is called directly has no caller to take one from, so it refuses the pull. - const ofRepo = (verb: string, ...args: unknown[]): ItxExpression => [ - "itx", - "builtins", - "repos", - ["get", path], - [verb, ...args], - ]; - await call(ofRepo("setOrigin", origin)); - await call(ofRepo("pull", { remote: origin })); - } + await call(ofRepo(path, "setOrigin", origin)); + await call(ofRepo(path, "pull", { remote: origin })); + }; + const { repos, entry } = state.configured!; + for (const { path, origin } of repos) await make(path, origin); + // the entry repo has its files now, if it was cloned: null from a repo with no commit yet + const packageJson = await call(ofRepo(entry.repo, "readFile", "package.json")); + const entryOrigin = repos.find(({ path }) => path === entry.repo)?.origin || null; + for (const { path, from } of reposNamedIn(typeof packageJson === "string" ? packageJson : null)) + await make(path, originBeside(entryOrigin, from)); } /** THE ROOT'S OWN SUBSCRIPTION ROW names the event types that reach this processor, and a
M core/mind-worker/src/mind/tree.test.ts
@@ -2,15 +2,17 @@ // the tree looks like to the loader, and what it says when a repo it needs is not there. import { expect, test } from "vitest"; import { importedTopFolders, readPackage } from "../context/module-resolution.ts"; -import { gatheredTree, mergedTree, treeKeyOf } from "./tree.ts"; +import { gatheredTree, mergedTree, originBeside, reposNamedIn, treeKeyOf } from "./tree.ts"; test("a publication reads the entry repo and every repo that its imports reach, each at one commit, and no other repo", async () => { const mind = mindWith({ "/repos/config": { - "worker.ts": `import { init } from "../stdlib/init.ts"; import { dashApp } from "../dash/app.ts"; init(dashApp());`, + "worker.ts": `import { init } from "@repos/stdlib/init.ts"; import { dashApp } from "@repos/dash/app.ts"; init(dashApp());`, }, // stdlib's own import reaches a third repo, which the entry never names - "/repos/stdlib": { "init.ts": `import { say } from "../words/say.ts"; export const init = say;` }, + "/repos/stdlib": { + "init.ts": `import { say } from "@repos/words/say.ts"; export const init = say;`, + }, "/repos/dash": { "app.ts": `export const dashApp = () => {};`, "index.html": "<p>the Dash</p>" }, "/repos/words": { "say.ts": `export const say = () => "hello";` }, // nothing imports from the kernel's repo: it is never read @@ -27,7 +29,7 @@ "/repos/words": "words@1", }, files: { - "config/worker.ts": expect.stringContaining("../stdlib/init.ts"), + "config/worker.ts": expect.stringContaining("@repos/stdlib/init.ts"), "stdlib/init.ts": expect.any(String), "dash/app.ts": expect.any(String), // a repo comes whole: a page is one of its files @@ -39,11 +41,13 @@ expect(mind.read).not.toContain("/repos/kernel"); }); -test("the tree's root names the entry module, and takes its npm packages from the entry repo's package.json alone", () => { +test("the tree's root names the entry module, and takes its npm packages from the entry repo's package.json alone: a line that names a repo is no npm package", () => { const tree = mergedTree(CONFIG_WORKER, { "/repos/config": { "worker.ts": "export default class {}", - "package.json": JSON.stringify({ dependencies: { yjs: "13.6.33" } }), + "package.json": JSON.stringify({ + dependencies: { yjs: "13.6.33", "@repos/stdlib": "../stdlib" }, + }), }, "/repos/stdlib": { "init.ts": "export const init = () => {};", @@ -55,12 +59,12 @@ entry: "config/worker.ts", dependencies: { yjs: "13.6.33" }, }); - expect(readPackage(tree, "the mind's code").dependencies).not.toHaveProperty("diff"); + expect(readPackage(tree, "the mind's code").dependencies).toEqual({ yjs: "13.6.33" }); }); test("a repo that the code imports from and that has no commit is refused in words that name the file that imports it", async () => { const mind = mindWith({ - "/repos/config": { "worker.ts": `import { init } from "../stdlib/init.ts"; init();` }, + "/repos/config": { "worker.ts": `import { init } from "@repos/stdlib/init.ts"; init();` }, }); await expect(gatheredTree({ entry: CONFIG_WORKER, ...mind.reads })).rejects.toThrow( @@ -68,6 +72,17 @@ ); }); +test("a relative import that leaves its repo is refused, in words that give the name to write", async () => { + const mind = mindWith({ + "/repos/config": { "worker.ts": `import { init } from "../stdlib/init.ts"; init();` }, + "/repos/stdlib": { "init.ts": `export const init = () => {};` }, + }); + + await expect(gatheredTree({ entry: CONFIG_WORKER, ...mind.reads })).rejects.toThrow( + "config/worker.ts imports ../stdlib/init.ts, which is outside its own repo: write @repos/stdlib/init.ts", + ); +}); + test("an entry repo with no commit is refused as itself", async () => { const mind = mindWith({}); @@ -76,25 +91,58 @@ ); }); -test("the folders that a module's graph imports from are found by reading: code and files, static and dynamic, but no import that is only a type", () => { +test("the repos that a module's graph imports from are found by reading: code and files, static and dynamic, but no import that is only a type", () => { const folders = importedTopFolders( { "config/worker.ts": [ - `import type { Thing } from "../types-only/thing.ts";`, - `import page from "../dash/index.html";`, + `import type { Thing } from "@repos/types-only/thing.ts";`, + `import page from "@repos/dash/index.html";`, `import { helper } from "./helper.ts";`, `export const answer = (thing: Thing) => [page, helper(), thing];`, ].join("\n"), - "config/helper.ts": `export const helper = async () => import("../tasks/app.ts");`, + "config/helper.ts": `export const helper = async () => import("@repos/tasks/app.ts");`, // not reached from the entry: what it imports is nobody's business - "config/unused.ts": `import "../elsewhere/x.ts";`, + "config/unused.ts": `import "@repos/elsewhere/x.ts";`, }, "config/worker.ts", "the mind's code", ); - expect(folders.map(({ folder }) => folder).sort()).toEqual(["config", "dash", "tasks"]); + expect(folders.map(({ folder }) => folder).sort()).toEqual(["dash", "tasks"]); expect(folders).toContainEqual({ folder: "tasks", importedBy: "config/helper.ts" }); +}); + +test("the repos that a package.json names are its dependencies under @repos, each with what its line says of where the repo is", () => { + const packageJson = JSON.stringify({ + main: "worker.ts", + dependencies: { + yjs: "13.6.33", + "@repos/stdlib": "../stdlib", + "@repos/words": "https://git.elsewhere.org/repos/words", + }, + }); + + expect(reposNamedIn(packageJson)).toEqual([ + { path: "/repos/stdlib", from: "../stdlib" }, + { path: "/repos/words", from: "https://git.elsewhere.org/repos/words" }, + ]); + // a repo with no package.json, or one that does not parse, names none: the loader says what is wrong + expect(reposNamedIn(null)).toEqual([]); + expect(reposNamedIn("not JSON")).toEqual([]); +}); + +test("at a birth a named repo comes from beside where the entry repo came from, an address is itself, and with no origin there is nowhere", () => { + const config = "https://git.example.org/repos/config-template"; + + expect(originBeside(config, "../stdlib")).toBe("https://git.example.org/repos/stdlib"); + expect(originBeside(`${config}/`, "../stdlib")).toBe("https://git.example.org/repos/stdlib"); + expect(originBeside(config, "https://git.elsewhere.org/repos/words")).toBe( + "https://git.elsewhere.org/repos/words", + ); + // an entry repo that was cloned from nowhere: its named repos are made empty + expect(originBeside(null, "../stdlib")).toBeNull(); + // what another tool means by a line is not an address + expect(originBeside(config, "link:../stdlib")).toBeNull(); }); test("the same commits have the same key whatever order they are named in, and another commit has another", () => {
M core/mind-worker/src/mind/tree.ts
@@ -1,15 +1,19 @@ // 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`, so `../stdlib/init.ts` in a file of -// `/repos/config` names it, here and in a folder on a laptop where the repos are cloned side by -// side. 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. +// `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`. */ @@ -19,7 +23,8 @@ /** 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. */ + * 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>, @@ -29,7 +34,7 @@ for (const [file, content] of Object.entries(files)) tree[`${folderOf(repoPath)}/${file}`] = content; const own = filesByRepo[entry.repo]?.["package.json"]; - let manifest: { dependencies?: unknown; compatibilityFlags?: unknown } = {}; + let manifest: { dependencies?: Record<string, unknown>; compatibilityFlags?: unknown } = {}; if (typeof own === "string") try { manifest = JSON.parse(own); @@ -38,10 +43,44 @@ } tree["package.json"] = JSON.stringify({ main: entryModuleOf(entry), - dependencies: manifest.dependencies, + 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