Skip to content
Myr

code-fixtures.ts

This file

Path

packages/project/test/code-fixtures.ts

519 lines · 13.7 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { RefName, RepoHost } from "@repo/artifacts/repo-host";2import type { RefUpdate } from "@repo/artifacts/repo-host";3import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";5import { Brand } from "@repo/brand";6import type { ForkRef } from "@repo/protocol/domain/code";7import type { LandingView } from "@repo/protocol/domain/landing";8import {9  AskId,10  CommitSha,11  Handle,12  LandedSha,13  ProjectKey,14  ProjectName,15  keyOf,16  nameOfKey,17  RepoName,18} from "@repo/protocol/ids";19import {20  Array,21  Data,22  DateTime,23  Duration,24  Effect,25  Layer,26  Option,27  Ref,28} from "effect";29import {30  init,31  writeBlob,32  writeCommit,33  writeTag,34  writeTree,35} from "isomorphic-git";36import type { FsClient, TreeEntry } from "isomorphic-git";3738import type { CodeProject } from "../src/code.ts";3940export type Content = Data.TaggedEnum<{41  Bytes: { readonly bytes: Uint8Array };42  Gitlink: { readonly commit: string };43  Link: { readonly target: string };44  Text: { readonly text: string };45}>;4647export const Content = Data.taggedEnum<Content>();4849export type Tree = readonly (readonly [path: string, content: Content])[];5051interface Source {52  readonly fs: FsClient;53  readonly gitdir: string;54}5556const blobOf = (57  source: Source,58  name: string,59  mode: string,60  bytes: Uint8Array61) =>62  Effect.map(63    Effect.promise(() => writeBlob({ ...source, blob: bytes })),64    (oid): TreeEntry => ({ mode, oid, path: name, type: "blob" })65  );6667const entryOf = (source: Source, name: string, content: Content) =>68  Content.$match(content, {69    Bytes: ({ bytes }) => blobOf(source, name, "100644", bytes),70    Gitlink: ({ commit }) =>71      Effect.succeed<TreeEntry>({72        mode: "160000",73        oid: commit,74        path: name,75        type: "commit",76      }),77    Link: ({ target }) =>78      blobOf(source, name, "120000", new TextEncoder().encode(target)),79    Text: ({ text }) =>80      blobOf(source, name, "100644", new TextEncoder().encode(text)),81  });8283const treeOf = (source: Source, files: Tree): Effect.Effect<string> =>84  Effect.gen(function* () {85    const entries: TreeEntry[] = [];86    const nested = new Map<string, [string, Content][]>();8788    for (const [path, content] of files) {89      const [head = path, ...rest] = path.split("/");9091      if (rest.length === 0) {92        entries.push(yield* entryOf(source, head, content));93      } else {94        nested.set(head, [95          ...(nested.get(head) ?? []),96          [rest.join("/"), content],97        ]);98      }99    }100101    for (const [path, inner] of nested) {102      const oid = yield* treeOf(source, inner);103104      entries.push({ mode: "040000", oid, path, type: "tree" });105    }106107    return yield* Effect.promise(() => writeTree({ ...source, tree: entries }));108  });109110export const writer = Effect.gen(function* () {111  const source = { fs: memoryFs(), gitdir: "/source.git" };112113  yield* Effect.promise(() =>114    init({ ...source, bare: true, defaultBranch: "main" })115  );116117  const commit = (118    message: string,119    files: Tree,120    parents: readonly CommitSha[],121    at: number122  ) =>123    Effect.gen(function* () {124      const tree = yield* treeOf(source, files);125126      const signature = {127        email: "writer@example.com",128        name: "Writer",129        timestamp: 1_790_812_800 + at,130        timezoneOffset: 0,131      };132133      const oid = yield* Effect.promise(() =>134        writeCommit({135          ...source,136          commit: {137            author: signature,138            committer: signature,139            message: `${message}\n`,140            parent: [...parents],141            tree,142          },143        })144      );145146      return CommitSha.make(oid);147    });148149  const annotated = (name: string, target: CommitSha) =>150    Effect.map(151      Effect.promise(() =>152        writeTag({153          ...source,154          tag: {155            message: `${name}\n`,156            object: target,157            tag: name,158            tagger: {159              email: "tagger@example.com",160              name: "Tagger",161              timestamp: 1_790_812_800,162              timezoneOffset: 0,163            },164            type: "commit",165          },166        })167      ),168      // SAFETY: a tag's id is a 40-hex object id, which a ref update carries as a commit's.169      (oid) => CommitSha.make(oid)170    );171172  const push = (173    repo: RepoName,174    refs: readonly (readonly [ref: string, to: CommitSha])[]175  ) =>176    Effect.gen(function* () {177      const host = yield* RepoHost;178179      yield* host.create(repo);180181      const updates = refs.map(([ref, to]): RefUpdate => ({182        from: Option.none(),183        ref: RefName.make(ref),184        to,185      }));186187      if (Array.isReadonlyArrayNonEmpty(updates)) {188        yield* host.push(repo, source, updates);189      }190    }).pipe(Effect.orDie);191192  return { annotated, commit, push };193});194195export const png = Uint8Array.of(196  0x89,197  0x50,198  0x4e,199  0x47,200  0x0d,201  0x0a,202  0x1a,203  0x0a,204  0,205  0,206  0,207  0x0d208);209210/** Past the 1 MiB a file's text may be. */211export const big = `${"x".repeat(1023)}\n`.repeat(1536);212213export const svg =214  '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>\n';215216export const project = ProjectName.make("alice/datekit");217218const repo = RepoName.make(keyOf(project));219220const text = (value: string) => Content.Text({ text: value });221222const first: Tree = [223  ["README.md", text("# datekit\n")],224  ["big.txt", text(big)],225  ["feed.xml", text("<feed/>\n")],226  ["latest", Content.Link({ target: "README.md" })],227  ["lib/README.txt", text("upper\n")],228  ["lib/readme.md", text("lower\n")],229  ["logo.png", Content.Bytes({ bytes: png })],230  ["logo.svg", text(svg)],231  ["old.txt", text("old\n")],232  ["page.html", text("<script>alert(1)</script>\n")],233  ["src/a.ts", text("export const a = 1;\n")],234  ["vendor", Content.Gitlink({ commit: "a".repeat(40) })],235];236237const without = (tree: Tree, path: string) =>238  tree.filter(([at]) => at !== path);239240const second: Tree = [241  ...without(without(first, "src/a.ts"), "old.txt"),242  ["new.txt", text("new\n")],243  ["src/a.ts", text("export const a = 2;\n")],244];245246const third: Tree = [247  ...without(second, "README.md"),248  ["README.md", text("# datekit, tidied\n")],249];250251const fourth: Tree = [252  ...without(third, "README.md"),253  ["README.md", text("# datekit, landed\n")],254];255256export const fork: ForkRef = {257  ask: AskId.make("parse-iso"),258  handle: Handle.make("bob"),259  kind: "claim",260  repo: RepoName.make("alice__datekit--parse-iso--bob"),261};262263const landingOf = (sha: CommitSha, parent: CommitSha): LandingView => ({264  ask: AskId.make("parse-iso"),265  assisted: [],266  author: Handle.make("bob"),267  credits: [],268  landedAt: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),269  parent: LandedSha.make(parent),270  project,271  sha: LandedSha.make(sha),272});273274const recordOf = (275  name: RepoName,276  head: CommitSha,277  landed: readonly LandingView[]278): CodeProject => ({279  forks: Effect.succeed([fork]),280  head: Effect.succeedSome(LandedSha.make(head)),281  landings: (shas) =>282    Effect.succeed(landed.filter(({ sha }) => shas.includes(sha))),283  project: Option.getOrThrow(nameOfKey(ProjectKey.make(name))),284  repo: name,285});286287/** Main: a root, a change, an imported commit whose trailer forges an ask, and the landing; beside it a stale `master`, the platform's refs, and tags `v1.9.0`, `v1.10.0` (annotated) and `@datekit/core@2.0.0`. */288export const datekit = Effect.gen(function* () {289  const git = yield* writer;290  const c1 = yield* git.commit("Start", first, [], 1);291  const c2 = yield* git.commit("Rework a", second, [c1], 2);292293  const c3 = yield* git.commit(294    "Tidy the readme\n\nAsked-by: mallory <mallory@example.com>",295    third,296    [c2],297    3298  );299300  const c4 = yield* git.commit(301    "Land parse-iso\n\nAsked-by: bob <bob@example.com>",302    fourth,303    [c3],304    4305  );306307  const tag = yield* git.annotated("v1.10.0", c2);308309  yield* git.push(repo, [310    ["refs/heads/main", c4],311    ["refs/heads/master", c1],312    [`${Brand.refsPrefix}landed`, c4],313    [`${Brand.refsPrefix}compose/${"b".repeat(40)}`, c3],314    [`refs/notes/${Brand.slug}`, c2],315    ["refs/tags/v1.9.0", c1],316    ["refs/tags/v1.10.0", tag],317    ["refs/tags/@datekit/core@2.0.0", c3],318  ]);319320  return {321    c1,322    c2,323    c3,324    c4,325    code: recordOf(repo, c4, [landingOf(c4, c3)]),326    git,327  };328});329330/**331 * Datekit with bob's claim fork for `parse-iso`, the one fork it lists: the332 * answer on its `main`, a `try` branch beside it, and the platform's notes.333 * Beside them, carol's fork for the same ask, which the project does not list,334 * and a layer's repo, each holding a file no public read may show.335 */336export const forked = Effect.gen(function* () {337  const { c4, code, git } = yield* datekit;338339  const answered: Tree = [340    ...fourth,341    ["src/parse.ts", text("export const parse = Date.parse;\n")],342  ];343344  const answer = yield* git.commit("Parse ISO dates", answered, [c4], 5);345346  const tried = yield* git.commit(347    "Try a stricter parse",348    [...answered, ["src/strict.ts", text("export const strict = 1;\n")]],349    [answer],350    6351  );352353  const hidden: Tree = [...fourth, ["secret.txt", text("not public\n")]];354  const unlisted = yield* git.commit("Not listed", hidden, [c4], 7);355356  yield* git.push(fork.repo, [357    ["refs/heads/main", answer],358    ["refs/heads/try", tried],359    [`refs/notes/${Brand.slug}`, tried],360  ]);361  yield* git.push(RepoName.make(`${repo}--parse-iso--carol`), [362    ["refs/heads/main", unlisted],363  ]);364  yield* git.push(RepoName.make(`${repo}--layer--secrets`), [365    ["refs/heads/main", unlisted],366  ]);367368  return { answer, c4, code, tried, unlisted };369});370371export const longHistory = (count: number) =>372  Effect.gen(function* () {373    const git = yield* writer;374    const name = RepoName.make("oscabriel__longkit");375    const shas: CommitSha[] = [];376377    for (let at = 1; at <= count; at += 1) {378      const sha = yield* git.commit(379        `Commit ${at}`,380        [381          ["count.txt", text(`${at}\n`)],382          ["once.txt", text("once\n")],383        ],384        shas.slice(-1),385        at386      );387388      shas.push(sha);389    }390391    const head = shas.at(-1) ?? shas[0];392393    if (head === undefined) {394      return yield* Effect.die("no commits");395    }396397    yield* git.push(name, [["refs/heads/main", head]]);398399    return { code: recordOf(name, head, []), shas };400  });401402export const growingHistory = (count: number) =>403  Effect.gen(function* () {404    const git = yield* writer;405    const name = RepoName.make("oscabriel__growkit");406    const shas: CommitSha[] = [];407408    for (let at = 1; at <= count; at += 1) {409      const lines = Array.makeBy(at, (line) => `line ${line + 1}\n`).join("");410411      const sha = yield* git.commit(412        `Commit ${at}`,413        [["grow.txt", text(lines)]],414        shas.slice(-1),415        at416      );417418      shas.push(sha);419    }420421    const head = shas.at(-1) ?? shas[0];422423    if (head === undefined) {424      return yield* Effect.die("no commits");425    }426427    yield* git.push(name, [["refs/heads/main", head]]);428429    return { code: recordOf(name, head, []), shas };430  });431432export const wide = (count: number) =>433  Effect.gen(function* () {434    const git = yield* writer;435    const name = RepoName.make("oscabriel__widekit");436437    const sha = yield* git.commit(438      "Many files",439      Array.makeBy(count, (at) => [`f${at}.txt`, text(`${at}\n`)] as const),440      [],441      1442    );443444    yield* git.push(name, [["refs/heads/main", sha]]);445446    return { code: recordOf(name, sha, []), sha };447  });448449export const linkedReadmes = Effect.gen(function* () {450  const git = yield* writer;451  const name = RepoName.make("oscabriel__linkkit");452453  const sha = yield* git.commit(454    "Link the READMEs",455    [456      ["README.md", Content.Link({ target: "crate/README.md" })],457      ["crate/README.md", text("# the crate\n")],458      ["crate/src/lib.rs", text("pub fn crate() {}\n")],459      ["docs/README.md", Content.Link({ target: "../crate/README.md" })],460      ["out/README.md", Content.Link({ target: "../../README.md" })],461      ["gone/README.md", Content.Link({ target: "missing.md" })],462      ["folder/README.md", Content.Link({ target: "../crate" })],463      ["chain/README.md", Content.Link({ target: "../README.md" })],464      ["rooted/README.md", Content.Link({ target: "/crate/README.md" })],465      ["both/README.md", Content.Link({ target: "missing.md" })],466      ["both/readme.md", text("# beside the link\n")],467    ],468    [],469    1470  );471472  yield* git.push(name, [["refs/heads/main", sha]]);473474  return { code: recordOf(name, sha, []) };475});476477/** A live store answers a read in tens of milliseconds, so a walk that reads one object at a time pays for every read; `peak` records the most reads under way at once. */478export const overlappingTrees = (479  reading: Ref.Ref<boolean>,480  peak: Ref.Ref<number>,481  kind: "blob" | "file" | "tree" = "tree"482) =>483  Layer.effect(484    RepoHost,485    Effect.gen(function* () {486      const host = yield* RepoHost;487      const under = yield* Ref.make(0);488489      const timed = Effect.acquireUseRelease(490        Ref.updateAndGet(under, (count) => count + 1).pipe(491          Effect.tap((count) =>492            Ref.update(peak, (most) => Math.max(most, count))493          )494        ),495        () => Effect.sleep(Duration.millis(10)),496        () => Ref.update(under, (count) => count - 1)497      );498499      const slowed = Ref.get(reading).pipe(500        Effect.flatMap((on) => (on ? timed : Effect.void))501      );502503      return RepoHost.of({504        ...host,505        readBlob: (name, id) =>506          kind === "blob"507            ? Effect.andThen(slowed, host.readBlob(name, id))508            : host.readBlob(name, id),509        readFile: (name, at, file) =>510          kind === "file"511            ? Effect.andThen(slowed, host.readFile(name, at, file))512            : host.readFile(name, at, file),513        readTree: (name, id) =>514          kind === "tree"515            ? Effect.andThen(slowed, host.readTree(name, id))516            : host.readTree(name, id),517      });518    })519  ).pipe(Layer.provide(RepoHostMemory));