Skip to content
Myr

Serve a project's refs, trees, paths, files, log and commits over /rpc, and its raw bytes under a sandbox

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- @repo/project/code: one module per read (refs, tree, paths, file, log, commit, revision, raw, cache); the façade delegates, `whyOf` stays 912's stub. Canonical repo only; no payload names a repo. - Revisions (W9-D3): absent/`main` is the record's head; 40 hex is a commit `readCommit` finds; anything else matches a `RepoHost.tags` name exactly, never joined into a ref path, so `../heads/master` and the landed mirror are UnknownRevision. - listRefs reads only tags (peeled), sorted by digit runs, newest first, a release before its own pre-release; forks from the record. Nothing under the platform's refs, notes or a stale master shows. - readTree: folders first then by name; gitlink -> submodule, 120000 -> symlink; README by GitLab's precedence, any case. listPaths walks 8 trees at a time, caps at 50,000, kept by root tree id. - readFile: blob via the tree walk; binary = NUL in the first 8 KiB; text <= 1 MiB else truncated; Artifacts' MEMORY_LIMIT defect (decoded by its code) reads as truncated. - log: first parents from `at`, limit <= 100, `next` when more; with a path, scans <= 200 commits a call comparing the path's entry (mode + id) with the first parent's, `next` resumes the scan; trailers by parseTrailers, `landing` from one `landings` batch. - showCommit: treeDiff (used as is, its readTree routed through the cache) or every file added for a root; submodule sides get no text; > 300 files or past 2 MiB of text -> paths only, truncated. - CodeCache: CodeCacheLive(capacity) over effect's Cache, keyed <repo>:<kind>:<id>; failures, misses and texts over 256 KiB are never kept (an optional `keep` on `through`); one SAFETY'd value assertion, since one cache holds every kind. Provided once in ports.ts (2,000 entries). - Raw (W9-D6): shared pure module (rawHeaders, rawOf, rawRequestOf, rawFor) behind apps/platform/src/raw.ts and a new GET /:project/raw/* route in the web's dev server. nosniff + sandbox CSP on every answer; images as themselves (SVG too), html/xml/text as text/plain, other binary as octet-stream; immutable + etag for a SHA, max-age=60 otherwise; any `..`, `.` or empty segment (before or after decoding), unknown revision, project or path is a bare 404. - Outside the territory, needed by the check: RefName now allows `@` and `+`, so scoped tags (`@changesets/cli@2.27.1`) no longer throw in the memory/local stores or vanish from smart-HTTP listings; 901's façade and W9 contract tests now expect only `why` unbuilt; CodeProject gains `project`. - Tests: packages/project/test/code.test.ts (20), code-raw.test.ts (5) over code-fixtures.ts (repos written object by object: binary, 1.5 MiB, symlink, submodule, annotated and scoped tags, the platform's refs); apps/platform/test/code-reads.test.ts (anonymous /rpc, an extra `repo` key still reads canonical, no code-read payload field is RepoName or `repo`), raw.test.ts (headers with a stale bearer, climbing paths 404, git paths still git). The 250-commit tests carry a 30 s timeout: well under 1 s alone, ~5 s beside every package's tests. - ASSUMPTION: a MEMORY_LIMIT blob's size is unknown, so readFile reports size 0 there.

authored by oscabriel · committed by oscabriel · parent 254268a · Browse files · 21 files+2972 added−103 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

21 files+2972 added−103 removed

  • tests:+1461 added−53 removed
  • other:+1511 added−50 removed

21 files+2972 added−103 removed

modified:apps/platform/src/ports.ts+12 added-1 removed
modified:apps/platform/src/raw.ts+8 added-7 removed
added:apps/platform/test/code-reads.test.ts+177 added
1/**2 * The code reads over `/rpc`, as anyone not signed in calls them: datekit's3 * refs, a folder, a file, the log and a commit's changes, read from its4 * canonical repo only. No code read's payload names a repo, so a caller5 * cannot point one at a fork: an extra `repo` key is dropped or refused,6 * and the canonical repo is read either way.7 */8import { describe, expect, it } from "@effect/vitest";9import { Contracts } from "@repo/protocol/contracts";10import { RepoName, RepoPath } from "@repo/protocol/ids";11import { advanceTo } from "@repo/testkit/clock";12import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";13import { Effect, Layer, SchemaAST } from "effect";1415import { Handlers } from "../src/handlers.ts";16import { MemorySessions } from "../src/sessions/memory.ts";17import { seeded, worldOf } from "./handlers.fixtures.ts";18import { origin, rpcClient, served } from "./harness.ts";1920const datekit = aProject({ people: ["bob"] }).pipe(21 withVouches(["bob"]),22 withAsk({ id: "parse-iso", territory: "packages/parser" })23);2425const { project } = datekit;2627/** The platform over datekit's world, seeded: made, pushed to, its ask open. */28const platform = Effect.gen(function* () {29 yield* advanceTo("2026-10-07T12:00:00Z");3031 const world = yield* Layer.build(worldOf([datekit]));3233 yield* seeded(datekit).pipe(Effect.provide(world));3435 const ports = Layer.succeedContext(world);3637 return yield* served(38 Layer.mergeAll(39 Handlers.pipe(Layer.provide(ports)),40 ports,41 MemorySessions.layer({})42 )43 );44});4546/** The contracts that read a project's code. */47const codeReads = [48 "listRefs",49 "readTree",50 "listPaths",51 "readFile",52 "log",53 "showCommit",54 "why",55];5657/** Every field of a payload, nested ones included: its name and its type's AST. */58const fieldsIn = (59 ast: SchemaAST.AST60): readonly (readonly [string, SchemaAST.AST])[] => {61 if (SchemaAST.isObjects(ast)) {62 return ast.propertySignatures.flatMap(({ name, type }) => [63 [String(name), type] as const,64 ...fieldsIn(type),65 ]);66 }6768 return SchemaAST.isUnion(ast) ? ast.types.flatMap(fieldsIn) : [];69};7071describe("the code reads over /rpc", () => {72 it.effect(73 "answer anyone with datekit's refs, its root folder and a file",74 () =>75 Effect.gen(function* () {76 const { handler } = yield* platform;77 const anyone = yield* rpcClient(handler);78 const refs = yield* anyone.listRefs({ project });79 const root = yield* anyone.readTree({ project });8081 const file = yield* anyone.readFile({82 path: RepoPath.make("package.json"),83 project,84 });8586 expect([refs.project, refs.tags]).toStrictEqual([project, []]);87 expect(root.at).toBe(refs.landed);88 expect(root.entries.map(({ name }) => name)).toStrictEqual(89 expect.arrayContaining(["packages", "package.json"])90 );91 expect(file.text).toContain('"name": "datekit"');92 })93 );9495 it.effect("answer anyone with datekit's paths, log and first commit", () =>96 Effect.gen(function* () {97 const { handler } = yield* platform;98 const anyone = yield* rpcClient(handler);99 const { landed } = yield* anyone.listRefs({ project });100 const { commits } = yield* anyone.log({ project });101 const first = commits.at(-1)?.sha ?? "main";102 const paths = yield* anyone.listPaths({ at: first, project });103104 expect([commits[0]?.sha, commits.at(-1)?.subject]).toStrictEqual([105 landed,106 "Start",107 ]);108 expect(paths.paths).toContain("packages/parser/src/parse.ts");109110 const diff = yield* anyone.showCommit({ project, sha: paths.at });111112 expect(113 diff.files.map(({ path, status }) => [path, status])114 ).toStrictEqual(paths.paths.map((path) => [path, "added"]));115 })116 );117118 it.effect(119 "read the canonical repo whatever extra key a payload carries",120 () =>121 Effect.gen(function* () {122 const { handler } = yield* platform;123124 // The wire's request, written as a client would send it, with a125 // `repo` beside the project that no contract has.126 const payload = JSON.stringify({ project, repo: "datekit--me--alice" });127128 const response = yield* Effect.promise(() =>129 handler(130 new Request(`${origin}/rpc`, {131 body: `{"_tag":"Request","id":"1","tag":"readTree","payload":${payload},"headers":[]}`,132 headers: { "content-type": "application/json" },133 method: "POST",134 })135 )136 );137138 const text = yield* Effect.promise(() => response.text());139 const anyone = yield* rpcClient(handler);140 const canonical = yield* anyone.readTree({ project });141142 expect(response.status).toBe(200);143 expect(text).not.toContain("datekit--me--alice");144 expect(text).toContain(canonical.at);145 })146 );147148 it("name no repo in any code read's payload", () => {149 const rpcs = codeReads.map(150 (tag) => [tag, Contracts.requests.get(tag)] as const151 );152153 const fields = rpcs.flatMap(([tag, rpc]) =>154 rpc === undefined155 ? []156 : fieldsIn(rpc.payloadSchema.ast).map(157 ([name, type]) => [tag, name, type] as const158 )159 );160161 expect(162 rpcs.flatMap(([tag, rpc]) => (rpc === undefined ? [tag] : []))163 ).toStrictEqual([]);164 // The check sees a branded field: `readFile`'s path is a `RepoPath`.165 expect(166 fields.some(167 ([tag, name, type]) =>168 tag === "readFile" && name === "path" && type === RepoPath.ast169 )170 ).toBeTruthy();171 expect(172 fields.flatMap(([tag, name, type]) =>173 type === RepoName.ast || name === "repo" ? [`${tag}.${name}`] : []174 )175 ).toStrictEqual([]);176 });177});
added:apps/platform/test/raw.test.ts+167 added
1/**2 * A project's raw files through the platform's fetch handler:3 * `GET /<project>/raw/<rev>/<path…>` answers the bytes with their headers4 * to anyone, a stale bearer token or not; a path that climbs out is a5 * 404; and git's own paths beside it still reach git.6 */7import { describe, expect, it } from "@effect/vitest";8import { RefName, RepoHost } from "@repo/artifacts/repo-host";9import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";10import { Projects } from "@repo/project/projects";11import { RepoName } from "@repo/protocol/ids";12import { Person } from "@repo/protocol/principal";13import { advanceTo } from "@repo/testkit/clock";14import { gitClient } from "@repo/testkit/git-client";15import { aProject } from "@repo/testkit/scenarios";16import { Effect, Layer, Option } from "effect";1718import { Handlers } from "../src/handlers.ts";19import { MemorySessions } from "../src/sessions/memory.ts";20import { worldOf } from "./handlers.fixtures.ts";21import { origin, served } from "./harness.ts";2223const datekit = aProject({ people: [] });2425const { project } = datekit;2627const readme = "# datekit\n\nDates, parsed.\n";2829/**30 * The platform over a world where datekit was made and its first commit,31 * a README and a manifest, pushed to main; and that commit's id.32 */33const platform = Effect.gen(function* () {34 yield* advanceTo("2026-10-07T12:00:00Z");3536 const world = yield* Layer.build(worldOf([datekit]));3738 const first = yield* Effect.gen(function* () {39 const host = yield* RepoHost;40 const api = yield* (yield* Projects).create(project);41 const initializer = Person.make({ handle: datekit.initializer });42 const client = yield* gitClient(memoryFs());4344 yield* api.initProject(initializer, {});4546 const sha = yield* client.commit("Start", [47 ["README.md", readme],48 ["package.json", '{ "name": "datekit" }\n'],49 ]);5051 yield* host.push(RepoName.make(project), client.source, [52 { from: Option.none(), ref: RefName.make("refs/heads/main"), to: sha },53 ]);54 yield* api.recordFirstPush(initializer, sha);5556 return sha;57 }).pipe(Effect.orDie, Effect.provide(world));5859 const ports = Layer.succeedContext(world);6061 const { fetch } = yield* served(62 Layer.mergeAll(63 Handlers.pipe(Layer.provide(ports)),64 ports,65 MemorySessions.layer({})66 )67 );6869 return { fetch, first };70});7172const get = (73 fetch: (request: Request) => Effect.Effect<Response>,74 path: string,75 headers: Record<string, string> = {}76) =>77 Effect.flatMap(78 fetch(new Request(`${origin}${path}`, { headers })),79 (response) =>80 Effect.map(81 Effect.promise(() => response.text()),82 (text) => ({ headers: response.headers, status: response.status, text })83 )84 );8586describe("a project's raw files", () => {87 it.effect(88 "answer anyone with the bytes and their headers, a stale bearer or not",89 () =>90 Effect.gen(function* () {91 const { fetch, first } = yield* platform;92 const path = `/${project}/raw/${first}/README.md`;9394 const answers = yield* Effect.forEach(95 [{}, { authorization: "Bearer not-a-token-the-platform-knows" }],96 (headers) =>97 Effect.map(get(fetch, path, headers), (answer) => ({98 cache: answer.headers.get("cache-control"),99 etag: /^"[0-9a-f]{40}"$/u.test(answer.headers.get("etag") ?? ""),100 nosniff: answer.headers.get("x-content-type-options"),101 sandboxed: (102 answer.headers.get("content-security-policy") ?? ""103 ).includes("sandbox"),104 status: answer.status,105 text: answer.text,106 type: answer.headers.get("content-type"),107 }))108 );109110 expect(answers).toStrictEqual(111 answers.map(() => ({112 cache: "public, max-age=31536000, immutable",113 etag: true,114 nosniff: "nosniff",115 sandboxed: true,116 status: 200,117 text: readme,118 type: "text/plain; charset=utf-8",119 }))120 );121 expect(answers).toHaveLength(2);122123 const main = yield* get(fetch, `/${project}/raw/main/README.md`);124125 expect([main.status, main.headers.get("cache-control")]).toStrictEqual([126 200,127 "public, max-age=60",128 ]);129 })130 );131132 it.effect(133 "is a 404 with no body for a path that climbs out, a missing file or project",134 () =>135 Effect.gen(function* () {136 const { fetch, first } = yield* platform;137138 const answers = yield* Effect.forEach(139 [140 `/${project}/raw/${first}/../../x`,141 `/${project}/raw/${first}/..%2F..%2Fx`,142 `/${project}/raw/${first}/nope.md`,143 `/${project}/raw/v9/README.md`,144 `/nobody/raw/main/README.md`,145 ],146 (path) =>147 Effect.map(get(fetch, path), ({ status, text }) => [status, text])148 );149150 expect(answers).toStrictEqual(answers.map(() => [404, ""]));151 })152 );153154 it.effect("leave git's own paths to git", () =>155 Effect.gen(function* () {156 const { fetch } = yield* platform;157158 const answer = yield* get(159 fetch,160 `/${project}/info/refs?service=git-upload-pack`161 );162163 expect(answer.status).not.toBe(404);164 expect(answer.headers.get("content-security-policy")).toBeNull();165 })166 );167});
modified:apps/platform/test/w9-contracts.test.ts+15 added-17 removed
1/**2 * The code browser's, the people page's and drafting's contracts and3 * routes, wired end to end through the platform's fetch4 * handler before their bodies exist: the policy read answers, each code5 * read reaches the façade (which names the issue that builds it), a draft6 * needs a person, and `/` and a project's raw files have their slots, open7 * to a stale credential as every public path is.4 * handler: the policy read answers, the code reads reach the façade5 * (`why` names the issue that builds it; the others are6 * `code-reads.test.ts`'), a draft needs a person, and `/` and a project's7 * raw files have their routes, open to a stale credential as every public8 * path is (a raw file at no revision is a 404).9 */10import { describe, expect, it } from "@effect/vitest";10import { ProposalId } from "@repo/protocol/ids";11import { ProposalId, RepoPath } from "@repo/protocol/ids";12import { Unauthenticated } from "@repo/protocol/principal";13import { advanceTo } from "@repo/testkit/clock";14import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";15import { Cause, Effect, Exit, Layer, Option } from "effect";
54 unmodified lines
70 Effect.gen(function* () {71 const { handler } = yield* platform;72 const anyone = yield* rpcClient(handler);7373 expect(yield* diedWith(anyone.listRefs({ project }))).toStrictEqual(74 Option.some("not built: 903")75 );76 expect(yield* diedWith(anyone.readTree({ project }))).toStrictEqual(77 Option.some("not built: 903")78 );74 expect(75 yield* diedWith(76 anyone.why({ path: RepoPath.make("package.json"), project })77 )78 ).toStrictEqual(Option.some("not built: 912"));79 })80 );8182 it.effect("refuse a draft to anyone not signed in", () =>
49 unmodified lines
132 homeStale: {133 status: 501,134 text: "not built: 906 (draft model test-model)",135 },136 raw: { status: 501, text: "not built: 903" },137 rawStale: { status: 501, text: "not built: 903" },136 raw: { status: 404, text: "" },137 rawStale: { status: 404, text: "" },138 });139 })140 );141
4 unmodified lines
146 const response = yield* fetch(147 new Request(`${origin}/${project}/raw/info/refs`)148 );149150 expect(response.status).toBe(501);151 expect(yield* Effect.promise(() => response.text())).toBe(152 "not built: 903"153 );150 expect(response.status).toBe(404);151 expect(yield* Effect.promise(() => response.text())).toBe("");152 })153 );154});
modified:apps/web/src/dev/server.ts+50 added-13 removed
1/**2 * The dev world as a fetch handler: `POST /rpc` is an `RpcServer` over3 * `Contracts` with the dev handlers, protocol's `Authenticated` server side4 * over dev tokens (`sessions.ts`) and JSON, as the platform's `/rpc` serves5 * it, over a fresh world the seed has brought to its state. `backend.ts`6 * makes the one an isolate serves; a test makes its own.5 * it, over a fresh world the seed has brought to its state; and6 * `GET /<project>/raw/<rev>/<path…>` answers a project's raw files with7 * the response the platform's `raw.ts` gives (`@repo/project/code/raw`).8 * `backend.ts` makes the one an isolate serves; a test makes its own.9 */10import { RepoHost } from "@repo/artifacts/repo-host";11import { rawFor } from "@repo/project/code/raw";12import { Projects } from "@repo/project/projects";13import { Contracts } from "@repo/protocol/contracts";9import { Layer } from "effect";10import { HttpRouter } from "effect/http";14import { ProjectName } from "@repo/protocol/ids";15import { Context, Effect, Layer, Option, Schema } from "effect";16import { HttpRouter, HttpServerResponse } from "effect/http";17import { RpcSerialization, RpcServer } from "effect/rpc";1819import { devHandlers } from "./handlers.ts";20import { seedDev } from "./seed.ts";
4 unmodified lines
25const seededWorld = Layer.effectDiscard(seedDev).pipe(26 Layer.provideMerge(devWorld)27);2829const decodeProject = Schema.decodeUnknownOption(ProjectName);3031/** `/<project>/raw/<rev>/<path…>`: a project's raw files, as the platform serves them. */32const raw = Layer.unwrap(33 Effect.gen(function* () {34 const services = Context.make(RepoHost, yield* RepoHost).pipe(35 Context.add(Projects, yield* Projects)36 );3738 return HttpRouter.add(39 "GET",40 "/:project/raw/*",41 Effect.gen(function* () {42 const params = yield* HttpRouter.params;4344 return yield* Option.match(decodeProject(params.project), {45 onNone: () =>46 Effect.succeed(HttpServerResponse.empty({ status: 404 })),47 onSome: (project) =>48 rawFor(project, params["*"] ?? "").pipe(49 Effect.provide(services),50 Effect.map(HttpServerResponse.fromWeb)51 ),52 });53 })54 );55 })56);5758/**24 * The contracts at `/rpc` over a fresh, seeded world. `toWebHandler` builds59 * The contracts at `/rpc` and the raw files over a fresh, seeded world. `toWebHandler` builds60 * its layer as soon as it is called, so the world is made and seeded from61 * that moment, and a request that arrives before the seed is done waits for62 * it. `dispose` ends the world.63 */64export const devServer = () =>65 HttpRouter.toWebHandler(66 Layer.merge(31 RpcServer.layerHttp({32 group: Contracts,33 path: "/rpc",34 protocol: "http",35 }).pipe(36 Layer.provide([devHandlers, devSessions, RpcSerialization.layerJson]),37 Layer.provide(seededWorld)38 ),67 RpcServer.layerHttp({68 group: Contracts,69 path: "/rpc",70 protocol: "http",71 }).pipe(72 Layer.provide([devHandlers, devSessions, RpcSerialization.layerJson])73 ),74 raw75 ).pipe(Layer.provide(seededWorld)),76 { disableLogger: true }77 );
modified:packages/artifacts/src/repo-host.ts+8 added-2 removed
24 unmodified lines
25);2627export type BranchName = typeof BranchName.Type;2829/** A full ref name: `refs/heads/main`, `refs/asked/landed`, `refs/notes/commits`. */29/**30 * A full ref name: `refs/heads/main`, `refs/asked/landed`, `refs/notes/commits`,31 * `refs/tags/@changesets/cli@2.27.1` (a scoped package's tag; `@` and `+`32 * are git's as well).33 */34export const RefName = Schema.String.pipe(35 Schema.check(32 Schema.isPattern(/^refs\/(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+$/u)36 Schema.isPattern(37 /^refs\/(?!.*\.\.)[A-Za-z0-9._@+-]+(?:\/[A-Za-z0-9._@+-]+)+$/u38 )39 ),40 Schema.brand("RefName")41);42
198 unmodified lines
modified:packages/project/src/code/cache.ts+114 added-6 removed
1 unmodified line
2 * The code reads' cache: what an object id names never changes, so a read3 * keyed by `<repo>:<kind>:<object id>` (a tree, a blob, a commit, a commit's4 * diff, a blame at a commit) is read once. A `Context.Reference` whose5 * default caches nothing, so every host composes before one is given; the6 * platform gives one held in a layer (no module-level state, principle 6).7 * `main` is never a key: it resolves through the project's record on every6 * platform gives one held in a layer (no module-level state, principle 6),7 * so it lives as long as the isolate. `main` and a tag are never a key:8 * each resolves through the project's record or the repo's tags on every9 * call.10 */10import { Context } from "effect";11import type { Effect } from "effect";11import {12 Cache,13 Context,14 Duration,15 Effect,16 Equal,17 Exit,18 Hash,19 Layer,20 Option,21 Ref,22} from "effect";2324/** The code reads, each kept by its key once read. */25export interface CodeReads {15 /** `read`, or what it gave before for `key`. */26 /**27 * `read`, or what it gave before for `key`. A failure is never kept,28 * and neither is a value `keep` turns down (a large file's text).29 */30 readonly through: <A, E, R>(31 key: string,18 read: Effect.Effect<A, E, R>32 read: Effect.Effect<A, E, R>,33 keep?: (value: A) => boolean34 ) => Effect.Effect<A, E, R>;35}3637export const CodeCache = Context.Reference<CodeReads>("project/CodeCache", {38 defaultValue: () => ({ through: (_key, read) => read }),39});4041/** What one read gave, when it succeeded, and whether it may be kept. */42interface Entry {43 readonly value: Option.Option<unknown>;44 readonly kept: boolean;45}4647/**48 * One read and the key it is kept by: two are the same entry when their49 * keys are, whatever their reads (each a closure of its own).50 */51class Keyed implements Equal.Equal {52 readonly key: string;53 readonly read: Effect.Effect<Entry>;5455 constructor(key: string, read: Effect.Effect<Entry>) {56 this.key = key;57 this.read = read;58 }5960 [Equal.symbol](that: Equal.Equal): boolean {61 return that instanceof Keyed && that.key === this.key;62 }6364 [Hash.symbol](): number {65 return Hash.string(this.key);66 }67}6869const always = () => true;7071/** How long an entry is kept: for good when its read succeeded and may be kept, else not at all. */72const lifeOf = (exit: Exit.Exit<Entry>) =>73 Exit.isSuccess(exit) && exit.value.kept ? Duration.infinity : Duration.zero;7475/**76 * A cache of at most `capacity` reads, the least recently used dropped77 * first. Two calls with one key while the first is under way share its78 * read; a caller whose own read ran gets its exit as it was, and one that79 * waited on a read that failed reads for itself.80 */81export const CodeCacheLive = (capacity: number) =>82 Layer.effect(83 CodeCache,84 Effect.map(85 Cache.makeWith((key: Keyed) => key.read, {86 capacity,87 timeToLive: lifeOf,88 }),89 (cache): CodeReads => ({90 through: <A, E, R>(91 key: string,92 read: Effect.Effect<A, E, R>,93 keep: (value: A) => boolean = always94 ) =>95 Effect.gen(function* () {96 const context = yield* Effect.context<R>();97 const own = yield* Ref.make(Option.none<Exit.Exit<A, E>>());9899 const entry = yield* Cache.get(100 cache,101 new Keyed(102 key,103 Effect.exit(Effect.provideContext(read, context)).pipe(104 Effect.tap((exit) => Ref.set(own, Option.some(exit))),105 Effect.map((exit): Entry => ({106 kept: Exit.isSuccess(exit) && keep(exit.value),107 value: Exit.isSuccess(exit)108 ? Option.some(exit.value)109 : Option.none(),110 }))111 )112 )113 );114115 const ran = yield* Ref.get(own);116117 if (Option.isSome(ran)) {118 return yield* ran.value;119 }120121 if (Option.isNone(entry.value)) {122 return yield* read;123 }124125 // SAFETY: every key names one kind of read (`<repo>:<kind>:<id>`), so the126 // value kept under it is what a read typed as this one gave.127 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one cache holds every kind of read, so its values are typed `unknown`; see SAFETY.128 return entry.value.value as A;129 }),130 })131 )132 );
added:packages/project/src/code/commit.ts+231 added
1/**2 * One commit and what it changed against its first parent (a root commit3 * against the empty tree), through `treeDiff` (`@repo/git/tree-diff`): each4 * file's status, both blob ids, whether it is binary, and its old and new5 * text. At most 300 files and 2 MiB of text in all: past 300 files every6 * file is a path only, and once the text runs past 2 MiB the files after7 * it are; either way the diff says it is `truncated`. The list of changes8 * is kept by the commit's id; the landing is asked for on every call.9 */10import { RepoHost } from "@repo/artifacts/repo-host";11import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";12import { treeDiff } from "@repo/git/tree-diff";13import type { Change } from "@repo/git/tree-diff";14import type { ChangedFile, CommitDiff } from "@repo/protocol/domain/code";15import { BlobSha, TreeSha } from "@repo/protocol/ids";16import type { CommitSha, RepoName } from "@repo/protocol/ids";17import { UnknownCommit } from "@repo/protocol/refusal";18import { Array, Effect, Option, Order } from "effect";1920import type { CodeProject } from "../code.ts";21import { CodeCache } from "./cache.ts";22import { contentsOf } from "./file.ts";23import type { Contents } from "./file.ts";24import { commitViews } from "./log.ts";25import { filesUnder, PATHS_CAP } from "./paths.ts";26import { commitAt } from "./revision.ts";27import { entriesOf, entryAt } from "./tree.ts";2829/** The most files a commit's diff carries text for. */30export const DIFF_FILES = 300;3132/** The most text a commit's diff carries in all: 2 MiB. */33export const DIFF_TEXT = 2 * 1024 * 1024;3435/** A change, and whether each side is a submodule (whose id names no blob here). */36interface Changed extends Change {37 readonly links: { readonly before: boolean; readonly after: boolean };38}3940const isLink = (entry: Option.Option<TreeEntry>) =>41 Option.exists(entry, ({ type }) => type === "commit");4243/** Every file under a root commit's tree, each added. */44const rootChanges = (repo: RepoName, tree: string) =>45 Effect.map(filesUnder(repo, tree, PATHS_CAP), ({ files }) =>46 files.map(({ entry, path }): Changed => ({47 after: BlobSha.make(entry.sha),48 links: { after: entry.type === "commit", before: false },49 path,50 status: "added",51 }))52 );5354/**55 * What changed from `base` to `head`, by `treeDiff` over this repo's trees56 * read through the cache (so the side lookups that follow read none again).57 */58const changesBetween = (repo: RepoName, base: string, head: string) =>59 Effect.gen(function* () {60 const host = yield* RepoHost;6162 const changes = yield* treeDiff(63 repo,64 TreeSha.make(base),65 TreeSha.make(head)66 ).pipe(67 Effect.provideService(68 RepoHost,69 RepoHost.of({70 ...host,71 readTree: (name, id) =>72 name === repo73 ? Effect.asSome(74 Effect.provideService(entriesOf(repo, id), RepoHost, host)75 )76 : host.readTree(name, id),77 })78 )79 );8081 return yield* Effect.forEach(82 changes,83 (change): Effect.Effect<Changed, RepoNotFound, RepoHost> =>84 Effect.map(85 Effect.all([86 entryAt(repo, base, change.path),87 entryAt(repo, head, change.path),88 ]),89 ([before, after]) => ({90 ...change,91 links: { after: isLink(after), before: isLink(before) },92 })93 ),94 { concurrency: 8 }95 );96 });9798const byPath = Order.mapInput(Order.String, (change: Changed) => change.path);99100/** A side's contents, unless it is a submodule or absent. */101const sideOf = (102 repo: RepoName,103 blob: BlobSha | undefined,104 link: boolean105): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>106 blob === undefined || link ? Effect.succeedNone : contentsOf(repo, blob);107108/** A change as a path, its status and its blob ids, with no text. */109const pathOnly = ({ after, before, path, status }: Changed): ChangedFile => {110 const file = { binary: false, path, status };111112 if (before !== undefined && after !== undefined) {113 return { ...file, after, before };114 }115116 if (before !== undefined) {117 return { ...file, before };118 }119120 return after === undefined ? file : { ...file, after };121};122123/** Each change with its text while the budget lasts, and whether any went without. */124const withText = (repo: RepoName, changes: readonly Changed[]) =>125 Effect.gen(function* () {126 if (changes.length > DIFF_FILES) {127 return { files: changes.map(pathOnly), truncated: true };128 }129130 const files: ChangedFile[] = [];131 let budget = DIFF_TEXT;132 let truncated = false;133134 for (const change of changes) {135 if (truncated) {136 files.push(pathOnly(change));137 continue;138 }139140 const before = yield* sideOf(repo, change.before, change.links.before);141 const after = yield* sideOf(repo, change.after, change.links.after);142 const oldText = Option.flatMap(before, ({ text }) => text);143 const newText = Option.flatMap(after, ({ text }) => text);144145 const size =146 Option.getOrElse(147 Option.map(oldText, (text) => text.length),148 () => 0149 ) +150 Option.getOrElse(151 Option.map(newText, (text) => text.length),152 () => 0153 );154155 if (size > budget) {156 truncated = true;157 files.push(pathOnly(change));158 continue;159 }160161 budget -= size;162163 files.push({164 ...pathOnly(change),165 binary:166 Option.exists(before, ({ binary }) => binary) ||167 Option.exists(after, ({ binary }) => binary),168 ...Option.match(oldText, {169 onNone: () => ({}),170 onSome: (text) => ({ oldText: text }),171 }),172 ...Option.match(newText, {173 onNone: () => ({}),174 onSome: (text) => ({ newText: text }),175 }),176 });177 }178179 return { files, truncated };180 });181182/** One commit and the files it changed against its first parent. */183export const commitDiff = (184 project: CodeProject,185 sha: CommitSha186): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>187 Effect.gen(function* () {188 const { repo } = project;189 const cache = yield* CodeCache;190191 const commit = yield* commitAt(repo, sha).pipe(192 Effect.orDie,193 Effect.flatMap(194 Option.match({195 onNone: () => Effect.fail(new UnknownCommit({ sha })),196 onSome: Effect.succeed,197 })198 )199 );200201 const parent = yield* Option.match(202 Option.fromUndefinedOr(commit.parents[0]),203 {204 onNone: () => Effect.succeedNone,205 onSome: (first) => commitAt(repo, first),206 }207 ).pipe(Effect.orDie);208209 const changes = yield* cache210 .through(211 `${repo}:changes:${sha}`,212 Option.match(parent, {213 onNone: () => rootChanges(repo, commit.tree),214 onSome: ({ tree }) => changesBetween(repo, tree, commit.tree),215 })216 )217 .pipe(Effect.orDie);218219 const { files, truncated } = yield* withText(220 repo,221 Array.sort(changes, byPath)222 ).pipe(Effect.orDie);223224 const [view] = yield* commitViews(project, [commit]);225226 if (view === undefined) {227 return yield* Effect.die(`no view of ${sha}`);228 }229230 return { commit: view, files, truncated };231 });
added:packages/project/src/code/file.ts+153 added
1/**2 * One file's contents as a reader sees them: its size, whether it is3 * binary (a NUL in its first 8 KiB, git's own test and `tree-diff.ts`'s),4 * and its text up to 1 MiB; past that, or when Artifacts answers that the5 * blob is too large to hold (`MEMORY_LIMIT`), it is truncated with no text.6 * Kept by the blob's id, unless its text is large.7 */8import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";9import type { RepoNotFound } from "@repo/artifacts/repo-host";10import type { FileView, Rev } from "@repo/protocol/domain/code";11import { BlobSha } from "@repo/protocol/ids";12import type { RepoName, RepoPath } from "@repo/protocol/ids";13import { UnknownPath } from "@repo/protocol/refusal";14import type { UnknownRevision } from "@repo/protocol/refusal";15import { Effect, Option, Schema } from "effect";1617import type { CodeProject } from "../code.ts";18import { CodeCache } from "./cache.ts";19import { commitAt, resolveRev } from "./revision.ts";20import { entryAt } from "./tree.ts";2122/** The most text a file's view carries: 1 MiB. */23export const TEXT_CAP = 1024 * 1024;2425// git's own test: a NUL among the first bytes means the blob is not text.26const SNIFF = 8192;2728/** The largest text a cache entry keeps; a larger one is read again. */29const KEPT_TEXT = 256 * 1024;3031/** Whether `bytes` read as binary: a NUL among the first 8 KiB. */32export const isBinary = (bytes: Uint8Array) =>33 bytes.subarray(0, SNIFF).includes(0);3435/** A file's contents: its text only when it is text and within the cap. */36export interface Contents {37 readonly size: number;38 readonly binary: boolean;39 readonly truncated: boolean;40 readonly text: Option.Option<string>;41}4243/** What Artifacts throws when a blob is too large for the Worker to hold. */44const MemoryLimit = Schema.Struct({ code: Schema.Literal("MEMORY_LIMIT") });4546const isMemoryLimit = Schema.is(MemoryLimit);4748/**49 * `read`, or `tooLarge` when Artifacts said the blob was too large to hold:50 * its binding throws that as a defect, which here is an answer.51 */52export const unlessTooLarge = <A, E, R>(53 read: Effect.Effect<A, E, R>,54 tooLarge: () => A55): Effect.Effect<A, E, R> =>56 Effect.catchDefect(read, (defect) =>57 isMemoryLimit(defect) ? Effect.succeed(tooLarge()) : Effect.die(defect)58 );5960/** `bytes` as a reader sees them. */61export const contentsOfBytes = (bytes: Uint8Array): Contents => {62 const binary = isBinary(bytes);63 const truncated = !binary && bytes.length > TEXT_CAP;6465 return {66 binary,67 size: bytes.length,68 text:69 binary || truncated70 ? Option.none()71 : Option.some(new TextDecoder().decode(bytes)),72 truncated,73 };74};7576/**77 * The blob `blob`'s contents, kept by its id; none when the repo has no78 * blob by it (a submodule's commit).79 */80export const contentsOf = (81 repo: RepoName,82 blob: BlobSha83): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>84 Effect.gen(function* () {85 const cache = yield* CodeCache;8687 return yield* cache.through(88 `${repo}:text:${blob}`,89 unlessTooLarge(90 RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(91 Effect.map(Option.map(contentsOfBytes))92 ),93 () =>94 Option.some({95 binary: false,96 size: 0,97 text: Option.none(),98 truncated: true,99 })100 ),101 (contents) =>102 Option.match(contents, {103 onNone: () => false,104 onSome: ({ text }) =>105 Option.match(text, {106 onNone: () => true,107 onSome: (read) => read.length <= KEPT_TEXT,108 }),109 })110 );111 });112113/** One file at `at`: its text, or that it is binary or too large. */114export const fileView = (115 project: CodeProject,116 at: Option.Option<Rev>,117 path: RepoPath118): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>119 Effect.gen(function* () {120 const commit = yield* resolveRev(project, at);121122 const { tree } = yield* commitAt(project.repo, commit).pipe(123 Effect.flatMap(Effect.fromOption),124 Effect.orDie125 );126127 const entry = yield* entryAt(project.repo, tree, path).pipe(Effect.orDie);128129 if (Option.isNone(entry) || entry.value.type !== "blob") {130 return yield* new UnknownPath({ commit, path });131 }132133 const sha = BlobSha.make(entry.value.sha);134135 const contents = yield* contentsOf(project.repo, sha).pipe(136 Effect.orDie,137 Effect.flatMap(Effect.fromOption),138 Effect.orDie139 );140141 return {142 at: commit,143 binary: contents.binary,144 path,145 sha,146 size: contents.size,147 truncated: contents.truncated,148 ...Option.match(contents.text, {149 onNone: () => ({}),150 onSome: (text) => ({ text }),151 }),152 };153 });
added:packages/project/src/code/log.ts+211 added
1/**2 * The first-parent log from a revision, a page at a time: each commit as a3 * reader sees it (subject, body, trailers, who and when), and `landing`4 * only where the project's record has one, so a trailer in an imported5 * commit never reads as a landing. With a path, only the commits whose6 * first-parent change touched it, scanning at most 200 commits a call;7 * `next` is where the scan stopped, so the next page resumes it.8 */9import { Revision, RepoHost } from "@repo/artifacts/repo-host";10import type {11 Commit,12 RepoNotFound,13 TreeEntry,14} from "@repo/artifacts/repo-host";15import { parseTrailers } from "@repo/git/trailers";16import type { CommitView, Rev } from "@repo/protocol/domain/code";17import type { LandingView } from "@repo/protocol/domain/landing";18import { TreeSha } from "@repo/protocol/ids";19import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";20import type { UnknownRevision } from "@repo/protocol/refusal";21import { DateTime, Effect, Equal, Option } from "effect";2223import type { CodeProject } from "../code.ts";24import { CodeCache } from "./cache.ts";25import { commitAt, resolveRev } from "./revision.ts";26import { entryAt } from "./tree.ts";2728/** The most commits one page holds. */29export const LOG_LIMIT = 100;3031/** The most first-parent commits a path's log scans in one call. */32export const PATH_SCAN = 200;3334/** A commit as a reader sees it, with its landing when it is one. */35export const commitView = (36 commit: Commit,37 landing: Option.Option<LandingView>38): CommitView => {39 const [subject = "", ...rest] = commit.message.split("\n");4041 return {42 author: {43 at: DateTime.fromEpochSeconds(commit.authoredAt),44 email: commit.author.email,45 name: commit.author.name,46 },47 body: rest.join("\n").replace(/^\n+/u, ""),48 committer: {49 at: DateTime.fromEpochSeconds(commit.committedAt),50 email: commit.committer.email,51 name: commit.committer.name,52 },53 parents: commit.parents,54 sha: commit.sha,55 subject,56 trailers: parseTrailers(commit.message).map(({ key, value }) => ({57 key,58 value,59 })),60 tree: TreeSha.make(commit.tree),61 ...Option.match(landing, {62 onNone: () => ({}),63 onSome: (found) => ({ landing: found }),64 }),65 };66};6768/** `commits` as a reader sees them, each landing from one batch of the project's record. */69export const commitViews = (70 project: CodeProject,71 commits: readonly Commit[]72): Effect.Effect<readonly CommitView[]> =>73 Effect.map(74 commits.length === 075 ? Effect.succeed([])76 : project.landings(commits.map(({ sha }) => sha)),77 (landings) => {78 const bySha = new Map<string, LandingView>(79 landings.map((landing) => [landing.sha, landing])80 );8182 return commits.map((commit) =>83 commitView(commit, Option.fromUndefinedOr(bySha.get(commit.sha)))84 );85 }86 );8788/**89 * `count` first-parent commits from `sha`, the first `from` skipped: a90 * commit's history never changes, so the page is kept by its start.91 */92const pageOf = (93 repo: RepoName,94 sha: CommitSha,95 from: number,96 count: number97): Effect.Effect<readonly Commit[], RepoNotFound, RepoHost> =>98 Effect.gen(function* () {99 const cache = yield* CodeCache;100101 return yield* cache.through(102 `${repo}:log:${sha}:${from}:${count}`,103 RepoHost.use((host) =>104 host.log(repo, Revision.Commit({ sha }), count, from)105 )106 );107 });108109/** What sits at `path` in `tree`: its id and mode, or nothing. */110const idAt = (repo: RepoName, tree: string, path: RepoPath) =>111 Effect.map(112 entryAt(repo, tree, path),113 Option.map(({ mode, sha }: TreeEntry) => `${mode} ${sha}`)114 );115116/** A page of the log, and where the next starts when there is more. */117export interface LogPage {118 readonly commits: readonly CommitView[];119 readonly next?: number;120}121122const pageWith = (123 commits: readonly CommitView[],124 next: Option.Option<number>125): LogPage =>126 Option.match(next, {127 onNone: () => ({ commits }),128 onSome: (at) => ({ commits, next: at }),129 });130131/** A page of first-parent commits from `at`, each landing with its record. */132export const logPage = (133 project: CodeProject,134 input: {135 readonly at: Option.Option<Rev>;136 readonly path: Option.Option<RepoPath>;137 readonly from: number;138 readonly limit: number;139 }140): Effect.Effect<LogPage, UnknownRevision, RepoHost> =>141 Effect.gen(function* () {142 const sha = yield* resolveRev(project, input.at);143 const from = Math.max(0, Math.floor(input.from));144 const limit = Math.min(LOG_LIMIT, Math.max(1, Math.floor(input.limit)));145 const { repo } = project;146147 if (Option.isNone(input.path)) {148 const read = yield* pageOf(repo, sha, from, limit + 1).pipe(Effect.orDie);149 const commits = yield* commitViews(project, read.slice(0, limit));150151 return pageWith(152 commits,153 read.length > limit ? Option.some(from + limit) : Option.none()154 );155 }156157 const path = input.path.value;158159 // One past the scan, so the last scanned commit's parent is at hand160 // and whether history goes on is known.161 const scan = yield* pageOf(repo, sha, from, PATH_SCAN + 1).pipe(162 Effect.orDie163 );164165 const scanned = scan.slice(0, PATH_SCAN);166 const touched: Commit[] = [];167168 for (const [at, commit] of scanned.entries()) {169 const parent = Option.fromUndefinedOr(commit.parents[0]);170 const after = Option.fromUndefinedOr(scan[at + 1]);171172 // The log is first parents, so the next commit in it is this one's173 // parent; only past the scan is the parent read on its own.174 const parentCommit = yield* Option.match(parent, {175 onNone: () => Effect.succeedNone,176 onSome: (first) =>177 Option.exists(after, ({ sha: next }) => next === first)178 ? Effect.succeed(after)179 : commitAt(repo, first),180 }).pipe(Effect.orDie);181182 const parentTree = Option.map(parentCommit, ({ tree }) => tree);183184 const now = yield* idAt(repo, commit.tree, path).pipe(Effect.orDie);185186 const before = yield* Option.match(parentTree, {187 onNone: () => Effect.succeedNone,188 onSome: (tree) => idAt(repo, tree, path),189 }).pipe(Effect.orDie);190191 if (!Equal.equals(now, before)) {192 touched.push(commit);193 }194195 if (touched.length === limit) {196 const commits = yield* commitViews(project, touched);197198 return pageWith(199 commits,200 at + 1 < scan.length ? Option.some(from + at + 1) : Option.none()201 );202 }203 }204205 const commits = yield* commitViews(project, touched);206207 return pageWith(208 commits,209 scan.length > PATH_SCAN ? Option.some(from + PATH_SCAN) : Option.none()210 );211 });
added:packages/project/src/code/paths.ts+118 added
1/**2 * Every file of a commit: each blob, symlink and submodule path under its3 * root tree, up to 50,000 (a file tree's sidebar), kept by the root tree's4 * id. The walk reads at most eight trees at once and stops descending once5 * the cap is passed.6 */7import type {8 RepoHost,9 RepoNotFound,10 TreeEntry,11} from "@repo/artifacts/repo-host";12import type { PathList, Rev } from "@repo/protocol/domain/code";13import { RepoPath } from "@repo/protocol/ids";14import type { RepoName } from "@repo/protocol/ids";15import type { UnknownRevision } from "@repo/protocol/refusal";16import type { Option } from "effect";17import { Array, Effect, Order, Ref, Semaphore } from "effect";1819import type { CodeProject } from "../code.ts";20import { CodeCache } from "./cache.ts";21import { commitAt, resolveRev } from "./revision.ts";22import { entriesOf } from "./tree.ts";2324/** The most paths a commit's list holds. */25export const PATHS_CAP = 50_000;2627// Store calls under way at once, however wide or deep the tree.28const STORE_CALLS = 8;2930/** One file under a root tree, with the entry that names it. */31export interface FileAt {32 readonly path: RepoPath;33 readonly entry: TreeEntry;34}3536/**37 * Every file under the tree `root`, in path order; past `cap`, the walk38 * stops and says so.39 */40export const filesUnder = (41 repo: RepoName,42 root: string,43 cap: number44): Effect.Effect<45 { readonly files: readonly FileAt[]; readonly truncated: boolean },46 RepoNotFound,47 RepoHost48> =>49 Effect.gen(function* () {50 const calls = yield* Semaphore.make(STORE_CALLS);51 const seen = yield* Ref.make(0);5253 const walk = (54 prefix: string,55 tree: string56 ): Effect.Effect<readonly FileAt[], RepoNotFound, RepoHost> =>57 Effect.gen(function* () {58 if ((yield* Ref.get(seen)) > cap) {59 return [];60 }6162 const entries = yield* Semaphore.withPermit(63 calls,64 entriesOf(repo, tree)65 );6667 const files = entries68 .filter(({ type }) => type !== "tree")69 .map((entry) => ({70 entry,71 path: RepoPath.make(`${prefix}${entry.name}`),72 }));7374 yield* Ref.update(seen, (count) => count + files.length);7576 const nested = yield* Effect.forEach(77 entries.filter(({ type }) => type === "tree"),78 (entry) => walk(`${prefix}${entry.name}/`, entry.sha),79 { concurrency: "unbounded" }80 );8182 return [...files, ...nested.flat()];83 });8485 const all = Array.sort(86 yield* walk("", root),87 Order.mapInput(Order.String, (file: FileAt) => file.path)88 );8990 return {91 files: all.slice(0, cap),92 truncated: all.length > cap || (yield* Ref.get(seen)) > cap,93 };94 });9596/** Every file path at `at`, up to the cap. */97export const pathList = (98 project: CodeProject,99 at: Option.Option<Rev>100): Effect.Effect<PathList, UnknownRevision, RepoHost> =>101 Effect.gen(function* () {102 const commit = yield* resolveRev(project, at);103 const cache = yield* CodeCache;104105 const { tree } = yield* commitAt(project.repo, commit).pipe(106 Effect.flatMap(Effect.fromOption),107 Effect.orDie108 );109110 const { files, truncated } = yield* cache111 .through(112 `${project.repo}:paths:${tree}`,113 filesUnder(project.repo, tree, PATHS_CAP)114 )115 .pipe(Effect.orDie);116117 return { at: commit, paths: files.map(({ path }) => path), truncated };118 });
added:packages/project/src/code/raw.ts+176 added
1/**2 * A project's raw bytes, `GET /<project>/raw/<rev>/<path…>` (spec W9-D6),3 * as one pure response both the platform (`apps/platform/src/raw.ts`) and4 * the web's dev world serve. Both origins hold a session cookie, so no file5 * may run as script there: every answer carries `nosniff` and a sandboxing6 * CSP, images come back as themselves (an SVG too: an `<img>` never runs7 * its script, and opened on its own the sandbox gives it no script and an8 * opaque origin), markup and every other text as plain text, and anything9 * else binary as bytes to save. A file at a commit's id never changes, so10 * it is cached for good; at a name that moves, for a minute. Anything that11 * is not a file at a revision is a 404 that says nothing of the repo.12 */13import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";14import { Rev } from "@repo/protocol/domain/code";15import { BlobSha, RepoPath } from "@repo/protocol/ids";16import type { ProjectName } from "@repo/protocol/ids";17import { Effect, Option, Schema } from "effect";1819import { codeProjectOf } from "../code.ts";20import type { CodeProject } from "../code.ts";21import { Projects } from "../projects.ts";22import { isBinary, unlessTooLarge } from "./file.ts";23import { commitAt, isFullSha, resolveRev } from "./revision.ts";24import { entryAt, segmentsOf } from "./tree.ts";2526/** What a raw answer may load and do: nothing but its own images and inline styles, sandboxed. */27const SANDBOX =28 "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";2930const IMAGES = new Map([31 ["avif", "image/avif"],32 ["gif", "image/gif"],33 ["ico", "image/x-icon"],34 ["jpeg", "image/jpeg"],35 ["jpg", "image/jpeg"],36 ["png", "image/png"],37 ["svg", "image/svg+xml"],38 ["webp", "image/webp"],39]);4041const TEXT = "text/plain; charset=utf-8";4243/** `path`'s extension, lowercased; none without one. */44const extensionOf = (path: string) => {45 const name = path.slice(path.lastIndexOf("/") + 1);46 const dot = name.lastIndexOf(".");4748 return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();49};5051/**52 * The headers a raw answer for the blob `blob` at `path` carries: its type53 * by extension (an image as itself, anything else as plain text, or as54 * bytes when `binary`), `nosniff` and the sandbox, and a cache for good55 * when `rev` is a commit's id, for a minute when it is a name.56 */57export const rawHeaders = (58 path: RepoPath,59 rev: "sha" | "ref",60 blob: BlobSha,61 binary = false62): Headers => {63 const headers = new Headers({64 "content-security-policy": SANDBOX,65 "content-type":66 IMAGES.get(extensionOf(path)) ??67 (binary ? "application/octet-stream" : TEXT),68 "x-content-type-options": "nosniff",69 });7071 if (rev === "sha") {72 headers.set("cache-control", "public, max-age=31536000, immutable");73 headers.set("etag", `"${blob}"`);74 } else {75 headers.set("cache-control", "public, max-age=60");76 }7778 return headers;79};8081/** A 404 that says nothing of the repo. */82const notFound = () => new Response(null, { status: 404 });8384/** The file `path` at `rev` of the project's canonical repo, as raw bytes. */85export const rawOf = (86 project: CodeProject,87 rev: Rev,88 path: RepoPath89): Effect.Effect<Response, never, RepoHost> =>90 Effect.gen(function* () {91 const commit = yield* resolveRev(project, Option.some(rev));9293 const { tree } = yield* commitAt(project.repo, commit).pipe(94 Effect.flatMap(Effect.fromOption)95 );9697 const entry = yield* entryAt(project.repo, tree, path);9899 if (Option.isNone(entry) || entry.value.type !== "blob") {100 return notFound();101 }102103 const blob = BlobSha.make(entry.value.sha);104105 const bytes = yield* RepoHost.use((host) =>106 host.readBlob(project.repo, ObjectId.make(blob))107 );108109 return Option.match(bytes, {110 onNone: notFound,111 onSome: (read) =>112 new Response(new Uint8Array(read), {113 headers: rawHeaders(114 path,115 isFullSha(rev) ? "sha" : "ref",116 blob,117 isBinary(read)118 ),119 status: 200,120 }),121 });122 }).pipe(123 (read) => unlessTooLarge(read, () => new Response(null, { status: 413 })),124 Effect.catchTags({125 NoSuchElementError: () => Effect.succeed(notFound()),126 RepoNotFound: () => Effect.succeed(notFound()),127 UnknownRevision: () => Effect.succeed(notFound()),128 })129 );130131const decodeRev = Schema.decodeUnknownOption(Rev);132133const decodePath = Schema.decodeUnknownOption(RepoPath);134135const decoded = Option.liftThrowable(decodeURIComponent);136137/**138 * A raw request's revision and path from everything after `raw/`, as the139 * URL carries it: the first segment is the revision (a tag's `/` arrives140 * as `%2F`), the rest the file's path, each decoded once. A path with an141 * empty, `.` or `..` segment, before or after decoding, is none.142 */143export const rawRequestOf = (144 rest: string145): Option.Option<{ readonly rev: Rev; readonly path: RepoPath }> => {146 const slash = rest.indexOf("/");147148 if (slash === -1) {149 return Option.none();150 }151152 return Option.all({153 path: decoded(rest.slice(slash + 1)).pipe(154 Option.filter((path) => Option.isSome(segmentsOf(path))),155 Option.flatMap(decodePath)156 ),157 rev: Option.flatMap(decoded(rest.slice(0, slash)), decodeRev),158 });159};160161/**162 * The answer to `GET /<project>/raw/<rest>`: the project found by its163 * name, then its file. A project never made is a 404 too.164 */165export const rawFor = (166 project: ProjectName,167 rest: string168): Effect.Effect<Response, never, RepoHost | Projects> =>169 Option.match(rawRequestOf(rest), {170 onNone: () => Effect.succeed(notFound()),171 onSome: ({ path, rev }) =>172 Projects.use((projects) => projects.get(project)).pipe(173 Effect.flatMap((api) => rawOf(codeProjectOf(api, project), rev, path)),174 Effect.catchTag("UnknownProject", () => Effect.succeed(notFound()))175 ),176 });
added:packages/project/src/code/refs.ts+112 added
1/**2 * A project's refs as readers see them: main's landed commit (the3 * project's record, never a ref), its tags peeled to their commits (the4 * repo's `tags`) and sorted by version, newest first, and its forks. Only5 * `refs/tags/*` is read: nothing of the platform's own (its landed mirror,6 * compose refs, notes) and no branch but main ever shows.7 */8import { RepoHost } from "@repo/artifacts/repo-host";9import { TagName } from "@repo/protocol/domain/code";10import type { RefsView, TagRef } from "@repo/protocol/domain/code";11import { Array, Effect, Option, Schema } from "effect";1213import type { CodeProject } from "../code.ts";14import { tagNameOf } from "./revision.ts";1516/** A name cut into runs of digits and runs of anything else. */17const runsOf = (name: string) => name.match(/\d+|\D+/gu) ?? [];1819const isDigits = (run: string) => /^\d/u.test(run);2021/** Two strings as written, code point by code point. */22const compareText = (one: string, other: string) => {23 if (one === other) {24 return 0;25 }2627 return one < other ? -1 : 1;28};2930/** Two runs of digits by their value, however long. */31const compareNumbers = (one: string, other: string) => {32 const left = one.replace(/^0+(?=\d)/u, "");33 const right = other.replace(/^0+(?=\d)/u, "");3435 if (left.length !== right.length) {36 return left.length < right.length ? -1 : 1;37 }3839 return compareText(left, right);40};4142/**43 * Tags newest first, by version: runs of digits compare by value, so44 * `v1.10.0` comes before `v1.9.0`, and a release before its own45 * pre-releases (`v1.10.0` before `v1.10.0-beta.1`). Names are otherwise46 * compared as written, so a scoped package's tags stay together.47 */48export const compareTags = (one: string, other: string): number => {49 const left = runsOf(one);50 const right = runsOf(other);5152 for (let at = 0; at < Math.min(left.length, right.length); at += 1) {53 const mine = left[at] ?? "";54 const theirs = right[at] ?? "";5556 const order =57 isDigits(mine) && isDigits(theirs)58 ? compareNumbers(mine, theirs)59 : compareText(mine, theirs);6061 if (order !== 0) {62 return -order;63 }64 }6566 if (left.length === right.length) {67 return 0;68 }6970 // One name runs on past the other: a pre-release (`-beta.1`) is older71 // than its release, anything else newer.72 const longer = left.length > right.length ? left : right;73 const rest = longer[Math.min(left.length, right.length)] ?? "";74 const longerIsNewer = !rest.startsWith("-");75 const leftIsLonger = left.length > right.length;7677 return leftIsLonger === longerIsNewer ? -1 : 1;78};7980const decodeTag = Schema.decodeUnknownOption(TagName);8182/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */83export const refsView = (84 project: CodeProject85): Effect.Effect<RefsView, never, RepoHost> =>86 Effect.gen(function* () {87 const landed = yield* project.head;88 const forks = yield* project.forks;8990 const tags = yield* RepoHost.use((host) => host.tags(project.repo)).pipe(91 Effect.catchTag("RepoNotFound", () => Effect.succeed([]))92 );9394 const named = Array.getSomes(95 tags.map(({ name, sha }) =>96 Option.map(97 Option.flatMap(tagNameOf(name), decodeTag),98 (tag): TagRef => ({ name: tag, sha })99 )100 )101 );102103 return {104 forks,105 project: project.project,106 tags: named.toSorted((one, other) => compareTags(one.name, other.name)),107 ...Option.match(landed, {108 onNone: () => ({}),109 onSome: (sha) => ({ landed: sha }),110 }),111 };112 });
added:packages/project/src/code/revision.ts+99 added
1/**2 * A revision as a reader names it, resolved to the commit it means in the3 * project's canonical repo (spec W9-D3): absent or `main` is main's landed4 * commit, from the project's record and never from a ref; 40 hex digits are5 * that commit, if the repo holds it; anything else is a tag's exact name,6 * found among the repo's tags and never joined into a ref path, so7 * `../heads/x` or a ref of the platform's own names nothing.8 */9import { RepoHost } from "@repo/artifacts/repo-host";10import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";11import type { Rev } from "@repo/protocol/domain/code";12import { CommitSha } from "@repo/protocol/ids";13import type { RepoName } from "@repo/protocol/ids";14import { UnknownRevision } from "@repo/protocol/refusal";15import { Array, Effect, Option } from "effect";1617import type { CodeProject } from "../code.ts";18import { CodeCache } from "./cache.ts";1920/** A full commit id: 40 lowercase hex digits. Short ids are not resolved. */21const FULL_SHA = /^[0-9a-f]{40}$/u;2223/** Whether `rev` names a commit by its full id (and so never moves). */24export const isFullSha = (rev: string) => FULL_SHA.test(rev);2526/** Where every tag's name starts. */27const TAGS = "refs/tags/";2829/** A ref name's tag name, when it is a tag's. */30export const tagNameOf = (ref: string): Option.Option<string> =>31 ref.startsWith(TAGS) ? Option.some(ref.slice(TAGS.length)) : Option.none();3233/**34 * The commit `sha` in `repo`, kept once found. A miss is not kept: the35 * commit may yet be pushed.36 */37export const commitAt = (38 repo: RepoName,39 sha: CommitSha40): Effect.Effect<Option.Option<Commit>, RepoNotFound, RepoHost> =>41 Effect.gen(function* () {42 const cache = yield* CodeCache;4344 return yield* cache45 .through(46 `${repo}:commit:${sha}`,47 RepoHost.use((host) => host.readCommit(repo, sha)).pipe(48 Effect.flatMap(Effect.fromOption)49 )50 )51 .pipe(52 Effect.asSome,53 Effect.catchTag("NoSuchElementError", () => Effect.succeedNone)54 );55 });5657/** The commit `at` names in the project's canonical repo. */58export const resolveRev = (59 project: CodeProject,60 at: Option.Option<Rev>61): Effect.Effect<CommitSha, UnknownRevision, RepoHost> => {62 const rev = Option.getOrElse(at, () => "main");63 const unknown = new UnknownRevision({ rev });6465 if (rev === "main") {66 return Effect.flatMap(project.head, (landed) =>67 Option.match(landed, {68 onNone: () => Effect.fail(unknown),69 onSome: (sha) => Effect.succeed<CommitSha>(sha),70 })71 );72 }7374 if (isFullSha(rev)) {75 const sha = CommitSha.make(rev);7677 return commitAt(project.repo, sha).pipe(78 Effect.catchTag("RepoNotFound", () => Effect.succeedNone),79 Effect.flatMap((found) =>80 Option.isSome(found) ? Effect.succeed(sha) : Effect.fail(unknown)81 )82 );83 }8485 return RepoHost.use((host) => host.tags(project.repo)).pipe(86 Effect.catchTag("RepoNotFound", () => Effect.succeed([])),87 Effect.flatMap((tags) =>88 Option.match(89 Array.findFirst(tags, ({ name }) =>90 Option.contains(tagNameOf(name), rev)91 ),92 {93 onNone: () => Effect.fail(unknown),94 onSome: ({ sha }) => Effect.succeed(sha),95 }96 )97 )98 );99};
added:packages/project/src/code/tree.ts+188 added
1/**2 * Folders of a commit: a tree's entries by its id (kept once read), the3 * entry at a path, walked one segment at a time, and one folder as a4 * reader lists it: folders first, then by name, each entry by its kind,5 * with its README by GitLab's precedence, any case.6 */7import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";8import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";9import type { CodeEntry, Rev, TreeListing } from "@repo/protocol/domain/code";10import { BlobSha, RepoPath } from "@repo/protocol/ids";11import type { CommitSha, RepoName } from "@repo/protocol/ids";12import { UnknownPath } from "@repo/protocol/refusal";13import type { UnknownRevision } from "@repo/protocol/refusal";14import { Array, Effect, Match, Option, Order } from "effect";1516import type { CodeProject } from "../code.ts";17import { CodeCache } from "./cache.ts";18import { commitAt, resolveRev } from "./revision.ts";1920/** The entries of the tree `id`; a tree a commit or a tree names is always there. */21export const entriesOf = (22 repo: RepoName,23 id: string24): Effect.Effect<readonly TreeEntry[], RepoNotFound, RepoHost> =>25 Effect.gen(function* () {26 const cache = yield* CodeCache;2728 return yield* cache.through(29 `${repo}:tree:${id}`,30 RepoHost.use((host) => host.readTree(repo, ObjectId.make(id))).pipe(31 Effect.flatMap(32 Option.match({33 onNone: () => Effect.die(`${repo} has no tree ${id}`),34 onSome: Effect.succeed,35 })36 )37 )38 );39 });4041/** The segments of `path`; none when one is empty, `.` or `..`. */42export const segmentsOf = (path: string): Option.Option<readonly string[]> => {43 const segments = path.split("/");4445 return segments.every(46 (segment) => segment !== "" && segment !== "." && segment !== ".."47 )48 ? Option.some(segments)49 : Option.none();50};5152/** The entry at `path` under the tree `root`, walked one segment at a time. */53export const entryAt = (54 repo: RepoName,55 root: string,56 path: string57): Effect.Effect<Option.Option<TreeEntry>, RepoNotFound, RepoHost> =>58 Option.match(segmentsOf(path), {59 onNone: () => Effect.succeedNone,60 onSome: (segments) =>61 Effect.gen(function* () {62 let tree = root;63 let found: Option.Option<TreeEntry> = Option.none();6465 for (const [at, segment] of segments.entries()) {66 if (at > 0) {67 if (Option.isNone(found) || found.value.type !== "tree") {68 return Option.none();69 }7071 tree = found.value.sha;72 }7374 const entries = yield* entriesOf(repo, tree);7576 found = Array.findFirst(entries, ({ name }) => name === segment);77 }7879 return found;80 }),81 });8283/** What a reader sees an entry as: a gitlink is a submodule, mode 120000 a symlink. */84export const kindOf = (entry: TreeEntry): CodeEntry["type"] =>85 Match.value(entry).pipe(86 Match.when({ type: "tree" }, () => "tree" as const),87 Match.when({ type: "commit" }, () => "submodule" as const),88 Match.when({ mode: "120000" }, () => "symlink" as const),89 Match.orElse(() => "blob" as const)90 );9192/** A file a reader may open: a blob or a symlink, never a folder or a submodule. */93export const isFile = (entry: TreeEntry) => entry.type === "blob";9495/** Folders first, then by name. */96const byKindThenName = Order.combine(97 Order.mapInput(Order.Boolean, (entry: CodeEntry) => entry.type !== "tree"),98 Order.mapInput(Order.String, (entry: CodeEntry) => entry.name)99);100101/** GitLab's README precedence, lowercased. */102const README = [103 "readme.md",104 "readme.markdown",105 "readme.mdown",106 "readme",107 "readme.txt",108 "readme.rst",109];110111const readmeOf = (entries: readonly CodeEntry[]) =>112 Array.findFirst(README, (name) =>113 Array.findFirst(114 entries,115 (entry) => entry.type === "blob" && entry.name.toLowerCase() === name116 )117 ).pipe(Option.map(({ path, sha }) => ({ path, sha: BlobSha.make(sha) })));118119/** The tree `path` names at `commit`, or `UnknownPath`. */120export const folderAt = (121 repo: RepoName,122 commit: CommitSha,123 path: Option.Option<RepoPath>124): Effect.Effect<string, UnknownPath, RepoHost> =>125 Effect.gen(function* () {126 const found = yield* commitAt(repo, commit).pipe(127 Effect.flatMap(Effect.fromOption)128 );129130 if (Option.isNone(path)) {131 return found.tree;132 }133134 const entry = yield* entryAt(repo, found.tree, path.value);135136 if (Option.isNone(entry) || entry.value.type !== "tree") {137 return yield* new UnknownPath({ commit, path: path.value });138 }139140 return entry.value.sha;141 }).pipe(142 Effect.catchTags({143 NoSuchElementError: Effect.die,144 RepoNotFound: Effect.die,145 })146 );147148/** One folder at `at`, folders first, with its README. */149export const listing = (150 project: CodeProject,151 at: Option.Option<Rev>,152 path: Option.Option<RepoPath>153): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>154 Effect.gen(function* () {155 const commit = yield* resolveRev(project, at);156 const tree = yield* folderAt(project.repo, commit, path);157158 const prefix = Option.match(path, {159 onNone: () => "",160 onSome: (folder) => `${folder}/`,161 });162163 const read = yield* entriesOf(project.repo, tree).pipe(Effect.orDie);164165 const entries = Array.sort(166 read.map((entry): CodeEntry => ({167 mode: entry.mode,168 name: entry.name,169 path: RepoPath.make(`${prefix}${entry.name}`),170 sha: entry.sha,171 type: kindOf(entry),172 })),173 byKindThenName174 );175176 return {177 at: commit,178 entries,179 ...Option.match(path, {180 onNone: () => ({}),181 onSome: (folder) => ({ path: folder }),182 }),183 ...Option.match(readmeOf(entries), {184 onNone: () => ({}),185 onSome: (readme) => ({ readme }),186 }),187 };188 });
modified:packages/project/src/code.ts+31 added-21 removed
5 unmodified lines
6 * the web's dev world call these with the `RepoHost` they run on, and7 * consult the project's record only for main's landed commit, its landings8 * and its forks (`CodeProject`). Reads by object id go through `CodeCache`.9 *10 * Stubs until 903 (every read but `whyOf`) and 912 (`whyOf`) land; the11 * signatures are final.10 * Each read lives in its own module under `code/`; `whyOf` is a stub until11 * 912 lands.12 */13import type { RepoHost } from "@repo/artifacts/repo-host";14import type {15 CommitDiff,
20 unmodified lines
36 UnknownRevision,37} from "@repo/protocol/refusal";38import { Effect, Option } from "effect";3940import { commitDiff } from "./code/commit.ts";41import { fileView } from "./code/file.ts";42import { logPage } from "./code/log.ts";43import { pathList } from "./code/paths.ts";44import { refsView } from "./code/refs.ts";45import { listing } from "./code/tree.ts";46import type { ProjectApi } from "./project.ts";4748/** What the code reads take from a project's record, beside its canonical repo. */49export interface CodeProject {50 /** The project, as its refs name it. */51 readonly project: ProjectName;52 /** The project's canonical repo: never a fork's or a layer's. */53 readonly repo: RepoName;54 /** Main's landed commit; none before the first push. */55 readonly head: Effect.Effect<Option.Option<LandedSha>>;
11 unmodified lines
67): CodeProject => ({68 forks: api.forks(),69 head: Effect.map(api.head(), ({ landed }) => Option.fromUndefinedOr(landed)),70 landings: api.landings,71 project,72 repo: RepoName.make(project),73});7475const notBuilt = (issue: string) => Effect.die(`not built: ${issue}`);7677/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */78export const refsOf = (70 _project: CodeProject71): Effect.Effect<RefsView, never, RepoHost> => notBuilt("903");79 project: CodeProject80): Effect.Effect<RefsView, never, RepoHost> => refsView(project);8182/** One folder at `at` (main when none), folders first, with its README. */83export const treeOf = (75 _project: CodeProject,76 _at: Option.Option<Rev>,77 _path: Option.Option<RepoPath>84 project: CodeProject,85 at: Option.Option<Rev>,86 path: Option.Option<RepoPath>87): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>79 notBuilt("903");88 listing(project, at, path);8990/** Every file path at `at`, up to the cap. */91export const pathsOf = (83 _project: CodeProject,84 _at: Option.Option<Rev>85): Effect.Effect<PathList, UnknownRevision, RepoHost> => notBuilt("903");92 project: CodeProject,93 at: Option.Option<Rev>94): Effect.Effect<PathList, UnknownRevision, RepoHost> => pathList(project, at);9596/** One file at `at`: its text, or that it is binary or too large. */97export const fileOf = (89 _project: CodeProject,90 _at: Option.Option<Rev>,91 _path: RepoPath98 project: CodeProject,99 at: Option.Option<Rev>,100 path: RepoPath101): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>93 notBuilt("903");102 fileView(project, at, path);103104/** A page of first-parent commits from `at`, each landing with its record. */105export const logOf = (97 _project: CodeProject,98 _input: {106 project: CodeProject,107 input: {108 readonly at: Option.Option<Rev>;109 readonly path: Option.Option<RepoPath>;110 readonly from: number;111 readonly limit: number;
1 unmodified line
113): Effect.Effect<114 { readonly commits: readonly CommitView[]; readonly next?: number },115 UnknownRevision,116 RepoHost108> => notBuilt("903");117> => logPage(project, input);118119/** One commit and the files it changed against its first parent. */120export const commitOf = (112 _project: CodeProject,113 _sha: CommitSha114): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> => notBuilt("903");121 project: CodeProject,122 sha: CommitSha123): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>124 commitDiff(project, sha);125126/** Why each line of a file at `at` is there. */127export const whyOf = (128 _project: CodeProject,
4 unmodified lines
modified:packages/project/test/code-facade.test.ts+7 added-36 removed
1/**2 * The code façade both handler files call: a project's code read from its3 * canonical repo alone, with main resolved through the project's record.4 * Until 903 and 912 land, each read names the issue that builds it.4 * Until 912 lands, why each line is there names the issue that builds it.5 */6import { describe, expect, it } from "@effect/vitest";7import { RepoHost } from "@repo/artifacts/repo-host";8import type { ProjectApi } from "@repo/project/project";9import {10 CommitSha,11 LandedSha,12 ProjectName,13 RepoPath,14} from "@repo/protocol/ids";9import { LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";10import { untouchable } from "@repo/testkit/untouchable";11import { Cause, Effect, Exit, Option } from "effect";1218import {19 codeProjectOf,20 commitOf,21 fileOf,22 logOf,23 pathsOf,24 refsOf,25 treeOf,26 whyOf,27} from "../src/code.ts";13import { codeProjectOf, whyOf } from "../src/code.ts";14import { CodeCache } from "../src/code/cache.ts";1516const project = ProjectName.make("datekit");1718const landed = LandedSha.make("4".repeat(40));1934const sha = CommitSha.make("4".repeat(40));3520const path = RepoPath.make("README.md");2122/** A project's record, as the façade reads it: only these three. */23const api = untouchable<ProjectApi>("ProjectApi", {
46 unmodified lines
70 expect(yield* cache.through("datekit:tree:x", read)).toBe(2);71 })72 );7390 it.effect("names the issue that builds each read", () =>74 it.effect("names the issue that builds why each line is there", () =>75 Effect.gen(function* () {92 const none = Option.none();9394 expect(95 yield* Effect.all([96 diedWith(refsOf(code)),97 diedWith(treeOf(code, none, none)),98 diedWith(pathsOf(code, none)),99 diedWith(fileOf(code, none, path)),100 diedWith(logOf(code, { at: none, from: 0, limit: 30, path: none })),101 diedWith(commitOf(code, sha)),102 diedWith(whyOf(code, none, path)),103 ])104 ).toStrictEqual([105 ...Array.from({ length: 6 }, () => Option.some("not built: 903")),106 Option.some("not built: 912"),107 ]);76 expect(yield* diedWith(whyOf(code, Option.none(), path))).toStrictEqual(77 Option.some("not built: 912")78 );79 })80 );81});
added:packages/project/test/code-fixtures.ts+395 added
1/**2 * Repos the code reads are tested over, written object by object with3 * isomorphic-git and pushed to the memory repo host: files of every kind4 * (text, binary, too large, a symlink, a submodule), the refs a canonical5 * repo really carries beside main (the landed mirror, a compose ref, the6 * notes, an import's stale `master`), and tags both lightweight and7 * annotated. Each `CodeProject` is fixed: its head, its one landing and its8 * one fork never come from the repo.9 */10import { RefName, RepoHost } from "@repo/artifacts/repo-host";11import type { RefUpdate } from "@repo/artifacts/repo-host";12import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";13import { Brand } from "@repo/brand";14import type { ForkRef } from "@repo/protocol/domain/code";15import type { LandingView } from "@repo/protocol/domain/landing";16import {17 AskId,18 CommitSha,19 Handle,20 LandedSha,21 ProjectName,22 RepoName,23} from "@repo/protocol/ids";24import { Array, Data, DateTime, Effect, Option } from "effect";25import {26 init,27 writeBlob,28 writeCommit,29 writeTag,30 writeTree,31} from "isomorphic-git";32import type { FsClient, TreeEntry } from "isomorphic-git";3334import type { CodeProject } from "../src/code.ts";3536/** A file's content: text, bytes, a symlink's target, or a submodule's commit. */37export type Content = Data.TaggedEnum<{38 Bytes: { readonly bytes: Uint8Array };39 Gitlink: { readonly commit: string };40 Link: { readonly target: string };41 Text: { readonly text: string };42}>;4344export const Content = Data.taggedEnum<Content>();4546/** Paths and what each holds. */47export type Tree = readonly (readonly [path: string, content: Content])[];4849interface Source {50 readonly fs: FsClient;51 readonly gitdir: string;52}5354const blobOf = (55 source: Source,56 name: string,57 mode: string,58 bytes: Uint8Array59) =>60 Effect.map(61 Effect.promise(() => writeBlob({ ...source, blob: bytes })),62 (oid): TreeEntry => ({ mode, oid, path: name, type: "blob" })63 );6465const entryOf = (source: Source, name: string, content: Content) =>66 Content.$match(content, {67 Bytes: ({ bytes }) => blobOf(source, name, "100644", bytes),68 Gitlink: ({ commit }) =>69 Effect.succeed<TreeEntry>({70 mode: "160000",71 oid: commit,72 path: name,73 type: "commit",74 }),75 Link: ({ target }) =>76 blobOf(source, name, "120000", new TextEncoder().encode(target)),77 Text: ({ text }) =>78 blobOf(source, name, "100644", new TextEncoder().encode(text)),79 });8081const treeOf = (source: Source, files: Tree): Effect.Effect<string> =>82 Effect.gen(function* () {83 const entries: TreeEntry[] = [];84 const nested = new Map<string, [string, Content][]>();8586 for (const [path, content] of files) {87 const [head = path, ...rest] = path.split("/");8889 if (rest.length === 0) {90 entries.push(yield* entryOf(source, head, content));91 } else {92 nested.set(head, [93 ...(nested.get(head) ?? []),94 [rest.join("/"), content],95 ]);96 }97 }9899 for (const [path, inner] of nested) {100 const oid = yield* treeOf(source, inner);101102 entries.push({ mode: "040000", oid, path, type: "tree" });103 }104105 return yield* Effect.promise(() => writeTree({ ...source, tree: entries }));106 });107108/**109 * A bare repo in memory that commits are written to and pushed from, each110 * commit's time `at` seconds after 2026-10-01.111 */112export const writer = Effect.gen(function* () {113 const source = { fs: memoryFs(), gitdir: "/source.git" };114115 yield* Effect.promise(() =>116 init({ ...source, bare: true, defaultBranch: "main" })117 );118119 const commit = (120 message: string,121 files: Tree,122 parents: readonly CommitSha[],123 at: number124 ) =>125 Effect.gen(function* () {126 const tree = yield* treeOf(source, files);127128 const signature = {129 email: "writer@example.com",130 name: "Writer",131 timestamp: 1_790_812_800 + at,132 timezoneOffset: 0,133 };134135 const oid = yield* Effect.promise(() =>136 writeCommit({137 ...source,138 commit: {139 author: signature,140 committer: signature,141 message: `${message}\n`,142 parent: [...parents],143 tree,144 },145 })146 );147148 return CommitSha.make(oid);149 });150151 /** An annotated tag object naming `commit`; its id, as a push sends it. */152 const annotated = (name: string, target: CommitSha) =>153 Effect.map(154 Effect.promise(() =>155 writeTag({156 ...source,157 tag: {158 message: `${name}\n`,159 object: target,160 tag: name,161 tagger: {162 email: "tagger@example.com",163 name: "Tagger",164 timestamp: 1_790_812_800,165 timezoneOffset: 0,166 },167 type: "commit",168 },169 })170 ),171 // SAFETY: a tag's id is a 40-hex object id, which a ref update carries as a commit's.172 (oid) => CommitSha.make(oid)173 );174175 /** `repo` made in the host, holding `refs`, each set to its commit. */176 const push = (177 repo: RepoName,178 refs: readonly (readonly [ref: string, to: CommitSha])[]179 ) =>180 Effect.gen(function* () {181 const host = yield* RepoHost;182183 yield* host.create(repo);184185 const updates = refs.map(([ref, to]): RefUpdate => ({186 from: Option.none(),187 ref: RefName.make(ref),188 to,189 }));190191 if (Array.isReadonlyArrayNonEmpty(updates)) {192 yield* host.push(repo, source, updates);193 }194 }).pipe(Effect.orDie);195196 return { annotated, commit, push };197});198199/** A PNG's signature and the start of its header: a NUL in the first bytes. */200export const png = Uint8Array.of(201 0x89,202 0x50,203 0x4e,204 0x47,205 0x0d,206 0x0a,207 0x1a,208 0x0a,209 0,210 0,211 0,212 0x0d213);214215/** 1.5 MiB of text: past the 1 MiB a file's text may be. */216export const big = `${"x".repeat(1023)}\n`.repeat(1536);217218export const svg =219 '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>\n';220221export const project = ProjectName.make("datekit");222223const repo = RepoName.make(project);224225const text = (value: string) => Content.Text({ text: value });226227const first: Tree = [228 ["README.md", text("# datekit\n")],229 ["big.txt", text(big)],230 ["feed.xml", text("<feed/>\n")],231 ["latest", Content.Link({ target: "README.md" })],232 ["lib/README.txt", text("upper\n")],233 ["lib/readme.md", text("lower\n")],234 ["logo.png", Content.Bytes({ bytes: png })],235 ["logo.svg", text(svg)],236 ["old.txt", text("old\n")],237 ["page.html", text("<script>alert(1)</script>\n")],238 ["src/a.ts", text("export const a = 1;\n")],239 ["vendor", Content.Gitlink({ commit: "a".repeat(40) })],240];241242const without = (tree: Tree, path: string) =>243 tree.filter(([at]) => at !== path);244245const second: Tree = [246 ...without(without(first, "src/a.ts"), "old.txt"),247 ["new.txt", text("new\n")],248 ["src/a.ts", text("export const a = 2;\n")],249];250251const third: Tree = [252 ...without(second, "README.md"),253 ["README.md", text("# datekit, tidied\n")],254];255256const fourth: Tree = [257 ...without(third, "README.md"),258 ["README.md", text("# datekit, landed\n")],259];260261/** The claim fork the project's record lists. */262export const fork: ForkRef = {263 ask: AskId.make("parse-iso"),264 handle: Handle.make("bob"),265 kind: "claim",266 repo: RepoName.make("datekit--parse-iso--bob"),267};268269/** The project's one landing, on `sha`. */270const landingOf = (sha: CommitSha, parent: CommitSha): LandingView => ({271 ask: AskId.make("parse-iso"),272 assisted: [],273 author: Handle.make("bob"),274 credits: [],275 landedAt: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),276 parent: LandedSha.make(parent),277 project,278 sha: LandedSha.make(sha),279});280281/** A project's record, fixed: main at `head`, `landed` its only landing. */282const recordOf = (283 name: RepoName,284 head: CommitSha,285 landed: readonly LandingView[]286): CodeProject => ({287 forks: Effect.succeed([fork]),288 head: Effect.succeedSome(LandedSha.make(head)),289 landings: (shas) =>290 Effect.succeed(landed.filter(({ sha }) => shas.includes(sha))),291 project: ProjectName.make(name),292 repo: name,293});294295/**296 * datekit, four commits on main: the root; one that modifies `src/a.ts`,297 * deletes `old.txt` and adds `new.txt`; an imported commit whose trailer298 * forges an ask; and the platform's landing. Beside main: `master` at the299 * root (an import's stale branch), the landed mirror, a compose ref, the300 * notes, and three tags (`v1.9.0` light on the root, `v1.10.0` annotated301 * on the second, `@datekit/core@2.0.0` light on the third).302 */303export const datekit = Effect.gen(function* () {304 const git = yield* writer;305 const c1 = yield* git.commit("Start", first, [], 1);306 const c2 = yield* git.commit("Rework a", second, [c1], 2);307308 const c3 = yield* git.commit(309 "Tidy the readme\n\nAsked-by: mallory <mallory@example.com>",310 third,311 [c2],312 3313 );314315 const c4 = yield* git.commit(316 "Land parse-iso\n\nAsked-by: bob <bob@example.com>",317 fourth,318 [c3],319 4320 );321322 const tag = yield* git.annotated("v1.10.0", c2);323324 yield* git.push(repo, [325 ["refs/heads/main", c4],326 ["refs/heads/master", c1],327 [`${Brand.refsPrefix}landed`, c4],328 [`${Brand.refsPrefix}compose/${"b".repeat(40)}`, c3],329 [`refs/notes/${Brand.slug}`, c2],330 ["refs/tags/v1.9.0", c1],331 ["refs/tags/v1.10.0", tag],332 ["refs/tags/@datekit/core@2.0.0", c3],333 ]);334335 return {336 c1,337 c2,338 c3,339 c4,340 code: recordOf(repo, c4, [landingOf(c4, c3)]),341 };342});343344/**345 * A history of `count` commits: the first adds `once.txt`, and every one346 * after changes only `count.txt`.347 */348export const longHistory = (count: number) =>349 Effect.gen(function* () {350 const git = yield* writer;351 const name = RepoName.make("longkit");352 const shas: CommitSha[] = [];353354 for (let at = 1; at <= count; at += 1) {355 const sha = yield* git.commit(356 `Commit ${at}`,357 [358 ["count.txt", text(`${at}\n`)],359 ["once.txt", text("once\n")],360 ],361 shas.slice(-1),362 at363 );364365 shas.push(sha);366 }367368 const head = shas.at(-1) ?? shas[0];369370 if (head === undefined) {371 return yield* Effect.die("no commits");372 }373374 yield* git.push(name, [["refs/heads/main", head]]);375376 return { code: recordOf(name, head, []), shas };377 });378379/** One root commit of `count` files. */380export const wide = (count: number) =>381 Effect.gen(function* () {382 const git = yield* writer;383 const name = RepoName.make("widekit");384385 const sha = yield* git.commit(386 "Many files",387 Array.makeBy(count, (at) => [`f${at}.txt`, text(`${at}\n`)] as const),388 [],389 1390 );391392 yield* git.push(name, [["refs/heads/main", sha]]);393394 return { code: recordOf(name, sha, []), sha };395 });
added:packages/project/test/code-raw.test.ts+171 added
1/**2 * A project's raw bytes as the platform and the dev world serve them: each3 * file under a sandboxing CSP and `nosniff`, typed by its extension so4 * that only images render as themselves (an SVG under the sandbox), markup5 * comes back as plain text, an immutable cache for a commit's id and a6 * minute for a name that moves, and a 404 with nothing from the repo for7 * anything else.8 */9import { describe, expect, it } from "@effect/vitest";10import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";11import { RepoPath } from "@repo/protocol/ids";12import { Effect, Option } from "effect";1314import { treeOf } from "../src/code.ts";15import { rawOf, rawRequestOf } from "../src/code/raw.ts";16import { datekit, png, svg } from "./code-fixtures.ts";1718const read = (response: Response) =>19 Effect.map(20 Effect.promise(() => response.arrayBuffer()),21 (body) => ({22 body: new Uint8Array(body),23 headers: Object.fromEntries(response.headers.entries()),24 status: response.status,25 })26 );2728describe("a raw file", () => {29 it.effect(30 "at a commit's id is its bytes, sandboxed, unsniffed and cached for good",31 () =>32 Effect.gen(function* () {33 const { c4, code } = yield* datekit;34 const listing = yield* treeOf(code, Option.none(), Option.none());3536 const blob = listing.entries.find(37 ({ name }) => name === "logo.svg"38 )?.sha;3940 const { body, headers, status } = yield* read(41 yield* rawOf(code, c4, RepoPath.make("logo.svg"))42 );4344 expect([status, new TextDecoder().decode(body)]).toStrictEqual([45 200,46 svg,47 ]);48 expect(headers).toMatchObject({49 "cache-control": "public, max-age=31536000, immutable",50 "content-type": "image/svg+xml",51 etag: `"${blob}"`,52 "x-content-type-options": "nosniff",53 });54 expect(headers["content-security-policy"]).toContain("sandbox");55 expect(headers["content-security-policy"]).toContain(56 "default-src 'none'"57 );58 }).pipe(Effect.provide(RepoHostMemory))59 );6061 it.effect("at main or a tag is cached for a minute", () =>62 Effect.gen(function* () {63 const { code } = yield* datekit;6465 const cached = (rev: string) =>66 Effect.map(rawOf(code, rev, RepoPath.make("README.md")), (response) => [67 response.status,68 response.headers.get("cache-control"),69 ]);7071 expect(72 yield* Effect.all([cached("main"), cached("v1.9.0")])73 ).toStrictEqual([74 [200, "public, max-age=60"],75 [200, "public, max-age=60"],76 ]);77 }).pipe(Effect.provide(RepoHostMemory))78 );7980 it.effect(81 "is typed by its extension: images as themselves, markup and the rest as text, binary as bytes",82 () =>83 Effect.gen(function* () {84 const { code } = yield* datekit;8586 const typed = (path: string) =>87 Effect.map(rawOf(code, "main", RepoPath.make(path)), (response) =>88 response.headers.get("content-type")89 );9091 expect(92 yield* Effect.all([93 typed("logo.png"),94 typed("page.html"),95 typed("feed.xml"),96 typed("README.md"),97 ])98 ).toStrictEqual([99 "image/png",100 "text/plain; charset=utf-8",101 "text/plain; charset=utf-8",102 "text/plain; charset=utf-8",103 ]);104105 const image = yield* read(106 yield* rawOf(code, "main", RepoPath.make("logo.png"))107 );108109 expect(image.body).toStrictEqual(png);110 }).pipe(Effect.provide(RepoHostMemory))111 );112113 it.effect(114 "that is missing, a folder, a submodule or at no revision is a 404 with no body",115 () =>116 Effect.gen(function* () {117 const { code } = yield* datekit;118119 const missing = (rev: string, path: string) =>120 Effect.flatMap(rawOf(code, rev, RepoPath.make(path)), read);121122 const answers = yield* Effect.all([123 missing("main", "nope.txt"),124 missing("main", "src"),125 missing("main", "vendor"),126 missing("v9", "README.md"),127 missing("main", "src/../README.md"),128 ]);129130 expect(131 answers.map(({ body, status }) => [status, body.length])132 ).toStrictEqual([133 [404, 0],134 [404, 0],135 [404, 0],136 [404, 0],137 [404, 0],138 ]);139 }).pipe(Effect.provide(RepoHostMemory))140 );141});142143describe("a raw request's path", () => {144 it("is a revision, then a file's path, each decoded once", () => {145 expect(146 [147 "main/README.md",148 "%40datekit%2Fcore%402.0.0/docs/a%20b.md",149 `${"a".repeat(40)}/src/a.ts`,150 "main",151 "main/",152 "main/src//a.ts",153 "main/../x",154 "main/src/%2E%2E/x",155 "main/..%2Fx",156 "main/%E0%A4%A",157 ].map(rawRequestOf)158 ).toStrictEqual([159 Option.some({ path: "README.md", rev: "main" }),160 Option.some({ path: "docs/a b.md", rev: "@datekit/core@2.0.0" }),161 Option.some({ path: "src/a.ts", rev: "a".repeat(40) }),162 Option.none(),163 Option.none(),164 Option.none(),165 Option.none(),166 Option.none(),167 Option.none(),168 Option.none(),169 ]);170 });171});
added:packages/project/test/code.test.ts+529 added
1/**2 * A project's code as readers browse it, read from its canonical repo over3 * the memory repo host, with main, the landings and the forks taken from a4 * fixed project record: refs without the platform's internals, folders and5 * their READMEs, revisions that resolve only to main, a commit or a tag,6 * files within their caps, the first-parent log with its landings, a7 * commit's changes, and reads by object id kept once read.8 */9import { describe, expect, it } from "@effect/vitest";10import { RepoHost } from "@repo/artifacts/repo-host";11import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";12import { Brand } from "@repo/brand";13import { CommitSha, RepoPath } from "@repo/protocol/ids";14import {15 UnknownCommit,16 UnknownPath,17 UnknownRevision,18} from "@repo/protocol/refusal";19import { DateTime, Effect, Exit, Layer, Option, Ref } from "effect";2021import {22 commitOf,23 fileOf,24 logOf,25 pathsOf,26 refsOf,27 treeOf,28} from "../src/code.ts";29import { CodeCacheLive } from "../src/code/cache.ts";30import { compareTags } from "../src/code/refs.ts";31import {32 big,33 datekit,34 fork,35 longHistory,36 project,37 wide,38} from "./code-fixtures.ts";3940const revision = (name: string) => Option.some(name);4142const main = Option.none();4344const path = (text: string) => Option.some(RepoPath.make(text));4546const page = { at: main, from: 0, limit: 30, path: Option.none() };4748/**49 * A history of hundreds of commits, written and pushed in memory: well50 * under a second alone, many times that beside every other package's tests.51 */52const long = { timeout: 30_000 };5354describe("a project's refs", () => {55 it.effect(56 "are main's landed commit, its tags newest first and its forks, and nothing of the platform's own",57 () =>58 Effect.gen(function* () {59 const { c1, c2, c3, c4, code } = yield* datekit;6061 expect(yield* refsOf(code)).toStrictEqual({62 forks: [fork],63 landed: c4,64 project,65 tags: [66 { name: "v1.10.0", sha: c2 },67 { name: "v1.9.0", sha: c1 },68 { name: "@datekit/core@2.0.0", sha: c3 },69 ],70 });71 }).pipe(Effect.provide(RepoHostMemory))72 );7374 it("sort by version, newest first, each package's together", () => {75 expect(76 [77 "v1.9.0",78 "v1.10.0",79 "v1.10.0-beta.1",80 "v2.0.0",81 "@changesets/cli@2.27.1",82 "@changesets/cli@2.3.0",83 "@changesets/apply@1.0.0",84 ].toSorted(compareTags)85 ).toStrictEqual([86 "v2.0.0",87 "v1.10.0",88 "v1.10.0-beta.1",89 "v1.9.0",90 "@changesets/cli@2.27.1",91 "@changesets/cli@2.3.0",92 "@changesets/apply@1.0.0",93 ]);94 });95});9697describe("a folder", () => {98 it.effect(99 "lists folders first, then files by name, each by its kind, with its README",100 () =>101 Effect.gen(function* () {102 const { c4, code } = yield* datekit;103 const listing = yield* treeOf(code, main, Option.none());104105 expect(listing.at).toBe(c4);106 expect(listing.path).toBeUndefined();107 expect(108 listing.entries.map(({ name, path: at, type }) => [name, at, type])109 ).toStrictEqual([110 ["lib", "lib", "tree"],111 ["src", "src", "tree"],112 ["README.md", "README.md", "blob"],113 ["big.txt", "big.txt", "blob"],114 ["feed.xml", "feed.xml", "blob"],115 ["latest", "latest", "symlink"],116 ["logo.png", "logo.png", "blob"],117 ["logo.svg", "logo.svg", "blob"],118 ["new.txt", "new.txt", "blob"],119 ["page.html", "page.html", "blob"],120 ["vendor", "vendor", "submodule"],121 ]);122 expect({123 readme: listing.readme,124 vendor: listing.entries.find(({ name }) => name === "vendor"),125 }).toMatchObject({126 readme: {127 path: "README.md",128 sha: listing.entries.find(({ name }) => name === "README.md")?.sha,129 },130 vendor: { mode: "160000", sha: "a".repeat(40) },131 });132 }).pipe(Effect.provide(RepoHostMemory))133 );134135 it.effect("finds a lowercase readme.md before a README.txt", () =>136 Effect.gen(function* () {137 const { code } = yield* datekit;138 const listing = yield* treeOf(code, main, path("lib"));139140 expect(listing.path).toBe("lib");141 expect(listing.entries.map(({ path: at }) => at)).toStrictEqual([142 "lib/README.txt",143 "lib/readme.md",144 ]);145 expect(listing.readme?.path).toBe("lib/readme.md");146 }).pipe(Effect.provide(RepoHostMemory))147 );148149 it.effect("is UnknownPath when missing, or a file", () =>150 Effect.gen(function* () {151 const { c4, code } = yield* datekit;152153 expect(154 yield* Effect.exit(treeOf(code, main, path("nope")))155 ).toStrictEqual(156 Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("nope") }))157 );158 expect(159 yield* Effect.exit(treeOf(code, main, path("src/a.ts/x")))160 ).toStrictEqual(161 Exit.fail(162 new UnknownPath({ commit: c4, path: RepoPath.make("src/a.ts/x") })163 )164 );165 expect(166 yield* Effect.exit(treeOf(code, main, path("README.md")))167 ).toStrictEqual(168 Exit.fail(169 new UnknownPath({ commit: c4, path: RepoPath.make("README.md") })170 )171 );172 }).pipe(Effect.provide(RepoHostMemory))173 );174});175176describe("a revision", () => {177 it.effect(178 "is main, a commit the repo holds, or a tag by its exact name, peeled",179 () =>180 Effect.gen(function* () {181 const { c1, c2, c3, c4, code } = yield* datekit;182183 const resolved = (rev: string) =>184 Effect.map(185 treeOf(code, revision(rev), Option.none()),186 ({ at: sha }) => sha187 );188189 expect(190 yield* Effect.all([191 resolved("main"),192 resolved(c1),193 resolved("v1.9.0"),194 resolved("v1.10.0"),195 resolved("@datekit/core@2.0.0"),196 ])197 ).toStrictEqual([c4, c1, c1, c2, c3]);198 }).pipe(Effect.provide(RepoHostMemory))199 );200201 it.effect(202 "is UnknownRevision for anything else, a ref path or another branch included",203 () =>204 Effect.gen(function* () {205 const { code } = yield* datekit;206207 const refused = [208 "v9",209 "master",210 "../heads/master",211 "refs/heads/master",212 "refs/tags/v1.9.0",213 `${Brand.refsPrefix}landed`,214 "f".repeat(40),215 "HEAD",216 ];217218 expect(219 yield* Effect.forEach(refused, (rev) =>220 Effect.exit(treeOf(code, revision(rev), Option.none()))221 )222 ).toStrictEqual(223 refused.map((rev) => Exit.fail(new UnknownRevision({ rev })))224 );225 }).pipe(Effect.provide(RepoHostMemory))226 );227});228229describe("a file", () => {230 it.effect("is its text, with its blob id and size", () =>231 Effect.gen(function* () {232 const { c4, code } = yield* datekit;233 const listing = yield* treeOf(code, main, Option.none());234235 expect(236 yield* fileOf(code, main, RepoPath.make("README.md"))237 ).toStrictEqual({238 at: c4,239 binary: false,240 path: "README.md",241 sha: listing.readme?.sha,242 size: 18,243 text: "# datekit, landed\n",244 truncated: false,245 });246 }).pipe(Effect.provide(RepoHostMemory))247 );248249 it.effect("past 1 MiB is truncated, with no text", () =>250 Effect.gen(function* () {251 const { code } = yield* datekit;252 const file = yield* fileOf(code, main, RepoPath.make("big.txt"));253254 expect(file).toMatchObject({255 binary: false,256 size: big.length,257 truncated: true,258 });259 expect(file.text).toBeUndefined();260 }).pipe(Effect.provide(RepoHostMemory))261 );262263 it.effect("with a NUL among its first bytes is binary, with no text", () =>264 Effect.gen(function* () {265 const { code } = yield* datekit;266 const file = yield* fileOf(code, main, RepoPath.make("logo.png"));267268 expect(file).toMatchObject({ binary: true, size: 12, truncated: false });269 expect(file.text).toBeUndefined();270 }).pipe(Effect.provide(RepoHostMemory))271 );272273 it.effect("is UnknownPath for a folder or a missing path", () =>274 Effect.gen(function* () {275 const { c4, code } = yield* datekit;276277 expect(278 yield* Effect.exit(fileOf(code, main, RepoPath.make("src")))279 ).toStrictEqual(280 Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("src") }))281 );282 expect(283 yield* Effect.exit(fileOf(code, main, RepoPath.make("src/b.ts")))284 ).toStrictEqual(285 Exit.fail(286 new UnknownPath({ commit: c4, path: RepoPath.make("src/b.ts") })287 )288 );289 }).pipe(Effect.provide(RepoHostMemory))290 );291});292293describe("every path", () => {294 it.effect("lists each file, symlink and submodule at the revision", () =>295 Effect.gen(function* () {296 const { c1, code } = yield* datekit;297298 expect(yield* pathsOf(code, revision(c1))).toStrictEqual({299 at: c1,300 paths: [301 "README.md",302 "big.txt",303 "feed.xml",304 "latest",305 "lib/README.txt",306 "lib/readme.md",307 "logo.png",308 "logo.svg",309 "old.txt",310 "page.html",311 "src/a.ts",312 "vendor",313 ],314 truncated: false,315 });316 }).pipe(Effect.provide(RepoHostMemory))317 );318});319320describe("the log", () => {321 it.effect(322 "is first parents from the revision, each landing with the platform's record and no other",323 () =>324 Effect.gen(function* () {325 const { c1, c2, c3, c4, code } = yield* datekit;326 const { commits, next } = yield* logOf(code, page);327328 expect(next).toBeUndefined();329 expect(commits.map(({ sha }) => sha)).toStrictEqual([c4, c3, c2, c1]);330331 const [landed, imported] = commits;332333 expect(landed?.landing).toMatchObject({ ask: "parse-iso", sha: c4 });334 expect(imported?.landing).toBeUndefined();335 expect(336 Option.map(Option.fromUndefinedOr(imported), (commit) => ({337 at: DateTime.formatIso(commit.author.at),338 email: commit.author.email,339 name: commit.author.name,340 parents: commit.parents,341 subject: commit.subject,342 trailers: commit.trailers,343 }))344 ).toStrictEqual(345 Option.some({346 at: "2026-10-01T00:00:03.000Z",347 email: "writer@example.com",348 name: "Writer",349 parents: [c2],350 subject: "Tidy the readme",351 trailers: [352 { key: "Asked-by", value: "mallory <mallory@example.com>" },353 ],354 })355 );356 }).pipe(Effect.provide(RepoHostMemory))357 );358359 it.effect(360 "pages 30 at a time, naming where the next page starts",361 () =>362 Effect.gen(function* () {363 const { code, shas } = yield* longHistory(250);364 const first = yield* logOf(code, page);365366 expect(first.commits).toHaveLength(30);367 expect(first.commits[0]?.sha).toBe(shas[249]);368 expect(first.next).toBe(30);369370 const last = yield* logOf(code, { ...page, from: 240 });371372 expect(last.commits.map(({ sha }) => sha)).toStrictEqual(373 shas.slice(0, 10).toReversed()374 );375 expect(last.next).toBeUndefined();376 }).pipe(Effect.provide(RepoHostMemory)),377 long378 );379380 it.effect(381 "for a path, keeps only the commits that changed it, scanning at most 200 a call",382 () =>383 Effect.gen(function* () {384 const { code, shas } = yield* longHistory(250);385 const once = { ...page, path: path("once.txt") };386 const scanned = yield* logOf(code, once);387388 expect(scanned).toStrictEqual({ commits: [], next: 200 });389390 const older = yield* logOf(code, { ...once, from: 200 });391392 expect(older.commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);393 expect(older.next).toBeUndefined();394395 const counted = yield* logOf(code, {396 ...page,397 limit: 3,398 path: path("count.txt"),399 });400401 expect(counted.commits.map(({ sha }) => sha)).toStrictEqual(402 shas.slice(247).toReversed()403 );404 expect(counted.next).toBe(3);405 }).pipe(Effect.provide(RepoHostMemory)),406 long407 );408});409410describe("a commit", () => {411 it.effect("at the root adds every file", () =>412 Effect.gen(function* () {413 const { c1, code } = yield* datekit;414 const diff = yield* commitOf(code, c1);415416 expect([diff.commit.sha, diff.truncated]).toStrictEqual([c1, false]);417 expect(418 diff.files.map(({ path: at, status }) => [at, status])419 ).toStrictEqual(420 (yield* pathsOf(code, revision(c1))).paths.map((at) => [at, "added"])421 );422 expect(423 diff.files.find(({ path: at }) => at === "src/a.ts")424 ).toMatchObject({ binary: false, newText: "export const a = 1;\n" });425426 const logo = diff.files.find(({ path: at }) => at === "logo.png");427428 expect([logo?.binary, logo?.newText]).toStrictEqual([true, undefined]);429 }).pipe(Effect.provide(RepoHostMemory))430 );431432 it.effect(433 "after it shows each change against the first parent, with both blob ids",434 () =>435 Effect.gen(function* () {436 const { c2, code } = yield* datekit;437 const diff = yield* commitOf(code, c2);438439 expect(440 diff.files.map(({ before, after, path: at, status }) => [441 at,442 status,443 before !== undefined,444 after !== undefined,445 ])446 ).toStrictEqual([447 ["new.txt", "added", false, true],448 ["old.txt", "deleted", true, false],449 ["src/a.ts", "modified", true, true],450 ]);451 expect(452 diff.files.find(({ path: at }) => at === "src/a.ts")453 ).toMatchObject({454 newText: "export const a = 2;\n",455 oldText: "export const a = 1;\n",456 });457 expect(diff.commit.landing).toBeUndefined();458 }).pipe(Effect.provide(RepoHostMemory))459 );460461 it.effect(462 "past 300 files lists paths only, truncated",463 () =>464 Effect.gen(function* () {465 const { code, sha } = yield* wide(301);466 const diff = yield* commitOf(code, sha);467468 expect([diff.truncated, diff.files.length]).toStrictEqual([true, 301]);469 expect(470 diff.files.filter(471 ({ newText, oldText }) =>472 newText !== undefined || oldText !== undefined473 )474 ).toStrictEqual([]);475 }).pipe(Effect.provide(RepoHostMemory)),476 long477 );478479 it.effect("the repo does not hold is UnknownCommit", () =>480 Effect.gen(function* () {481 const { code } = yield* datekit;482 const missing = CommitSha.make("f".repeat(40));483484 expect(yield* Effect.exit(commitOf(code, missing))).toStrictEqual(485 Exit.fail(new UnknownCommit({ sha: missing }))486 );487 }).pipe(Effect.provide(RepoHostMemory))488 );489});490491/** The memory store, with each tree id `readTree` is asked for counted in `reads`. */492const countedBy = (reads: Ref.Ref<readonly string[]>) =>493 Layer.effect(494 RepoHost,495 Effect.gen(function* () {496 const host = yield* RepoHost;497498 return RepoHost.of({499 ...host,500 readTree: (name, tree) =>501 Ref.update(reads, (all) => [...all, tree]).pipe(502 Effect.andThen(host.readTree(name, tree))503 ),504 });505 })506 ).pipe(Layer.provide(RepoHostMemory));507508describe("reads by object id", () => {509 it.effect("are kept once read, while main resolves every time", () =>510 Effect.gen(function* () {511 const reads = yield* Ref.make<readonly string[]>([]);512513 yield* Effect.gen(function* () {514 const { code } = yield* datekit;515 const first = yield* treeOf(code, main, Option.none());516 const counted = (yield* Ref.get(reads)).length;517518 expect(counted).toBeGreaterThan(0);519520 const again = yield* treeOf(code, main, Option.none());521522 expect(again).toStrictEqual(first);523 expect(yield* Ref.get(reads)).toHaveLength(counted);524 }).pipe(525 Effect.provide(Layer.merge(countedBy(reads), CodeCacheLive(100)))526 );527 })528 );529});