@leed-ai/git-gateway-testkit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -2
  3. package/dist/contract-suite/ancestry-cases.d.ts +4 -0
  4. package/dist/contract-suite/ancestry-cases.js +49 -0
  5. package/dist/contract-suite/ancestry-cases.js.map +1 -0
  6. package/dist/contract-suite/backend-case.d.ts +35 -0
  7. package/dist/contract-suite/backend-case.js +17 -0
  8. package/dist/contract-suite/backend-case.js.map +1 -0
  9. package/dist/contract-suite/backend-contract-suite.d.ts +44 -0
  10. package/dist/contract-suite/backend-contract-suite.js +59 -0
  11. package/dist/contract-suite/backend-contract-suite.js.map +1 -0
  12. package/dist/contract-suite/backend-fixtures.d.ts +25 -0
  13. package/dist/contract-suite/backend-fixtures.js +79 -0
  14. package/dist/contract-suite/backend-fixtures.js.map +1 -0
  15. package/dist/contract-suite/content-cases.d.ts +4 -0
  16. package/dist/contract-suite/content-cases.js +31 -0
  17. package/dist/contract-suite/content-cases.js.map +1 -0
  18. package/dist/contract-suite/lifecycle-cases.d.ts +4 -0
  19. package/dist/contract-suite/lifecycle-cases.js +86 -0
  20. package/dist/contract-suite/lifecycle-cases.js.map +1 -0
  21. package/dist/contract-suite/push-cases.d.ts +4 -0
  22. package/dist/contract-suite/push-cases.js +92 -0
  23. package/dist/contract-suite/push-cases.js.map +1 -0
  24. package/dist/contract-suite/push-helpers.d.ts +17 -0
  25. package/dist/contract-suite/push-helpers.js +47 -0
  26. package/dist/contract-suite/push-helpers.js.map +1 -0
  27. package/dist/contract-suite/read-cases.d.ts +4 -0
  28. package/dist/contract-suite/read-cases.js +186 -0
  29. package/dist/contract-suite/read-cases.js.map +1 -0
  30. package/dist/contract-suite/transport-cases.d.ts +4 -0
  31. package/dist/contract-suite/transport-cases.js +105 -0
  32. package/dist/contract-suite/transport-cases.js.map +1 -0
  33. package/dist/git-binary.d.ts +19 -0
  34. package/dist/git-binary.js +54 -0
  35. package/dist/git-binary.js.map +1 -0
  36. package/dist/git-sandbox.d.ts +33 -0
  37. package/dist/git-sandbox.js +76 -0
  38. package/dist/git-sandbox.js.map +1 -0
  39. package/dist/memory/memory-backend.d.ts +45 -0
  40. package/dist/memory/memory-backend.js +154 -0
  41. package/dist/memory/memory-backend.js.map +1 -0
  42. package/dist/memory/memory-reads.d.ts +9 -0
  43. package/dist/memory/memory-reads.js +39 -0
  44. package/dist/memory/memory-reads.js.map +1 -0
  45. package/dist/memory/memory-repository.d.ts +38 -0
  46. package/dist/memory/memory-repository.js +97 -0
  47. package/dist/memory/memory-repository.js.map +1 -0
  48. package/dist/memory/memory-tokens.d.ts +28 -0
  49. package/dist/memory/memory-tokens.js +59 -0
  50. package/dist/memory/memory-tokens.js.map +1 -0
  51. package/dist/memory/pack-selection.d.ts +30 -0
  52. package/dist/memory/pack-selection.js +104 -0
  53. package/dist/memory/pack-selection.js.map +1 -0
  54. package/dist/memory/receive-pack-service.d.ts +15 -0
  55. package/dist/memory/receive-pack-service.js +126 -0
  56. package/dist/memory/receive-pack-service.js.map +1 -0
  57. package/dist/memory/smart-http-server.d.ts +15 -0
  58. package/dist/memory/smart-http-server.js +65 -0
  59. package/dist/memory/smart-http-server.js.map +1 -0
  60. package/dist/memory/upload-pack-service.d.ts +15 -0
  61. package/dist/memory/upload-pack-service.js +123 -0
  62. package/dist/memory/upload-pack-service.js.map +1 -0
  63. package/dist/node/serve-fetch-handler.d.ts +16 -0
  64. package/dist/node/serve-fetch-handler.js +52 -0
  65. package/dist/node/serve-fetch-handler.js.map +1 -0
  66. package/dist/node/serve-streaming.d.ts +16 -0
  67. package/dist/node/serve-streaming.js +87 -0
  68. package/dist/node/serve-streaming.js.map +1 -0
  69. package/package.json +175 -4
  70. package/src/contract-suite/ancestry-cases.ts +56 -0
  71. package/src/contract-suite/backend-case.ts +53 -0
  72. package/src/contract-suite/backend-contract-suite.ts +89 -0
  73. package/src/contract-suite/backend-fixtures.ts +89 -0
  74. package/src/contract-suite/content-cases.ts +55 -0
  75. package/src/contract-suite/lifecycle-cases.ts +121 -0
  76. package/src/contract-suite/push-cases.ts +123 -0
  77. package/src/contract-suite/push-helpers.ts +63 -0
  78. package/src/contract-suite/read-cases.ts +213 -0
  79. package/src/contract-suite/transport-cases.ts +134 -0
  80. package/src/git-binary.ts +65 -0
  81. package/src/git-sandbox.ts +87 -0
  82. package/src/memory/memory-backend.ts +188 -0
  83. package/src/memory/memory-reads.ts +52 -0
  84. package/src/memory/memory-repository.ts +115 -0
  85. package/src/memory/memory-tokens.ts +64 -0
  86. package/src/memory/pack-selection.ts +127 -0
  87. package/src/memory/receive-pack-service.ts +141 -0
  88. package/src/memory/smart-http-server.ts +78 -0
  89. package/src/memory/upload-pack-service.ts +132 -0
  90. package/src/node/serve-fetch-handler.ts +71 -0
  91. package/src/node/serve-streaming.ts +107 -0
@@ -0,0 +1,105 @@
1
+ import { backendCase } from "./backend-case.js";
2
+ import { fixtureCommit } from "./backend-fixtures.js";
3
+ import { expectAccepted, pushNewBranch, pushRef, seedRepo } from "./push-helpers.js";
4
+ import { assertEqual, assertTrue } from "@leed-ai/git-gateway-contract/behaviour/assertions";
5
+ import { ZERO_SHA } from "@leed-ai/git-gateway-contract/schemas/sha";
6
+ import { sameBytes } from "@leed-ai/git-gateway-contract/reference/bytes";
7
+ import { GitRemote } from "@leed-ai/git-gateway-contract/storage/git-remote";
8
+ import { isCoreError } from "@leed-ai/git-gateway-core/core-error";
9
+ // src/contract-suite/transport-cases.ts
10
+ const GROUP = "transport";
11
+ const sortedShas = (objects) => objects.map((object) => object.sha).toSorted();
12
+ /** Empty repositories, gitRemote, push and fetch over the host's smart-HTTP remote. */
13
+ const transportCases = [
14
+ backendCase(GROUP, "an empty repository has no refs, no history and no files", async (context) => {
15
+ const { backend, repo } = context;
16
+ await backend.createRepo(repo);
17
+ assertEqual(await backend.resolveRef(repo, "main"), null, "resolveRef");
18
+ assertEqual(await backend.log(repo, "main", { limit: 10 }), [], "log");
19
+ assertEqual(await backend.readFile(repo, "main", "README.md"), null, "readFile");
20
+ const reader = await context.client("read");
21
+ assertEqual((await reader.advertisement("git-upload-pack")).refs, [], "upload-pack advertises no refs");
22
+ const writer = await context.client("write");
23
+ assertEqual((await writer.advertisement("git-receive-pack")).refs, [], "receive-pack advertises no refs");
24
+ }),
25
+ backendCase(GROUP, "gitRemote mints a remote whose headers authorize it", async (context) => {
26
+ await context.backend.createRepo(context.repo);
27
+ for (const access of ["read", "write"]) {
28
+ const remote = await context.backend.gitRemote(context.repo, access);
29
+ assertTrue(GitRemote.safeParse(remote).success, `${access} remote is a GitRemote`);
30
+ assertTrue(remote.url.endsWith(".git"), `${access} remote URL ends in .git`);
31
+ assertTrue(!remote.url.includes("@"), `${access} remote URL carries no credential`);
32
+ }
33
+ }),
34
+ backendCase(GROUP, "a push to an empty repository creates the branch", async (context) => {
35
+ const seeded = await seedRepo(context);
36
+ assertEqual(await context.backend.resolveRef(context.repo, "main"), seeded.sha, "resolveRef sees the push");
37
+ const advertised = (await (await context.client("read")).advertisement("git-upload-pack")).refs;
38
+ assertTrue(advertised.some((ref) => ref.name === "refs/heads/main" && ref.sha === seeded.sha), "advertised");
39
+ }),
40
+ backendCase(GROUP, "a fetch returns every pushed object byte for byte", async (context) => {
41
+ const seeded = await seedRepo(context, {
42
+ "a.txt": "a\n",
43
+ "dir/b.txt": "b\n",
44
+ "dir/sub/c.bin": { content: new Uint8Array([
45
+ 0,
46
+ 1,
47
+ 2
48
+ ]) }
49
+ });
50
+ const fetched = await (await context.client("read")).fetchPack({ wants: [seeded.sha] });
51
+ assertEqual(sortedShas(fetched.objects), sortedShas(seeded.objects), "the same object ids");
52
+ for (const object of seeded.objects) {
53
+ const got = fetched.objects.find((candidate) => candidate.sha === object.sha);
54
+ assertTrue(got?.type === object.type && sameBytes(got.data, object.data), `object ${object.sha} round-trips`);
55
+ }
56
+ }),
57
+ backendCase(GROUP, "a fetch with haves leaves out what the client has", async (context) => {
58
+ const first = await seedRepo(context);
59
+ const second = await fixtureCommit({
60
+ "README.md": "# Seed\n",
61
+ "new.txt": "new\n"
62
+ }, [first.sha]);
63
+ expectAccepted(await pushRef(context, "refs/heads/main", first.sha, second.sha, second.objects), "refs/heads/main");
64
+ const fetched = await (await context.client("read")).fetchPack({
65
+ wants: [second.sha],
66
+ haves: [first.sha]
67
+ });
68
+ const got = new Set(fetched.objects.map((object) => object.sha));
69
+ assertTrue(got.has(second.sha), "the new commit is sent");
70
+ assertTrue(!got.has(first.sha), "the had commit is not sent");
71
+ }),
72
+ backendCase(GROUP, "a second branch can point at an existing commit with an empty pack", async (context) => {
73
+ const seeded = await seedRepo(context);
74
+ expectAccepted(await pushRef(context, "refs/heads/staging", ZERO_SHA, seeded.sha), "refs/heads/staging");
75
+ assertEqual(await context.backend.resolveRef(context.repo, "staging"), seeded.sha, "staging");
76
+ }),
77
+ backendCase(GROUP, "a read remote cannot push when the host scopes credentials", async (context) => {
78
+ const seeded = await seedRepo(context);
79
+ if (!context.behaviour.readRemoteCannotPush) return;
80
+ const next = await fixtureCommit({ "x.txt": "x\n" }, [seeded.sha]);
81
+ let pushed = false;
82
+ try {
83
+ pushed = (await (await context.client("read")).push([{
84
+ oldSha: seeded.sha,
85
+ newSha: next.sha,
86
+ ref: "refs/heads/main"
87
+ }], next.objects)).refs.every((ref) => ref.status === "ok");
88
+ } catch (error) {
89
+ assertTrue(isCoreError(error, "remote_error") || isCoreError(error, "remote_http_error"), `refused by the remote, got ${String(error)}`);
90
+ }
91
+ assertTrue(!pushed, "the push did not succeed");
92
+ assertEqual(await context.backend.resolveRef(context.repo, "main"), seeded.sha, "main unchanged");
93
+ }),
94
+ backendCase(GROUP, "pushes from new branches are visible to resolveRef and the advertisement", async (context) => {
95
+ const seeded = await seedRepo(context);
96
+ const feature = await fixtureCommit({ "feature.txt": "f\n" }, [seeded.sha]);
97
+ await pushNewBranch(context, "feature/one", feature);
98
+ assertEqual(await context.backend.resolveRef(context.repo, "refs/heads/feature/one"), feature.sha, "full ref");
99
+ const refs = (await (await context.client("write")).advertisement("git-receive-pack")).refs.map((ref) => ref.name);
100
+ assertTrue(refs.includes("refs/heads/feature/one") && refs.includes("refs/heads/main"), "both branches advertised");
101
+ })
102
+ ];
103
+ export { transportCases };
104
+
105
+ //# sourceMappingURL=transport-cases.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport-cases.js","names":[],"sources":["../../src/contract-suite/transport-cases.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { assertEqual, assertTrue } from '@leed-ai/git-gateway-contract/behaviour/assertions';\nimport { sameBytes } from '@leed-ai/git-gateway-contract/reference/bytes';\nimport { ZERO_SHA } from '@leed-ai/git-gateway-contract/schemas/sha';\nimport { GitRemote } from '@leed-ai/git-gateway-contract/storage/git-remote';\nimport { isCoreError } from '@leed-ai/git-gateway-core/core-error';\n\nimport { backendCase, type BackendCase } from './backend-case.ts';\nimport { fixtureCommit } from './backend-fixtures.ts';\nimport { expectAccepted, pushNewBranch, pushRef, seedRepo } from './push-helpers.ts';\n\nconst GROUP = 'transport';\n\nconst sortedShas = (objects: readonly { sha: string }[]): string[] =>\n objects.map((object) => object.sha).toSorted();\n\n/** Empty repositories, gitRemote, push and fetch over the host's smart-HTTP remote. */\nexport const transportCases: readonly BackendCase[] = [\n backendCase(GROUP, 'an empty repository has no refs, no history and no files', async (context) => {\n const { backend, repo } = context;\n await backend.createRepo(repo);\n assertEqual(await backend.resolveRef(repo, 'main'), null, 'resolveRef');\n assertEqual(await backend.log(repo, 'main', { limit: 10 }), [], 'log');\n assertEqual(await backend.readFile(repo, 'main', 'README.md'), null, 'readFile');\n const reader = await context.client('read');\n assertEqual((await reader.advertisement('git-upload-pack')).refs, [], 'upload-pack advertises no refs');\n const writer = await context.client('write');\n assertEqual((await writer.advertisement('git-receive-pack')).refs, [], 'receive-pack advertises no refs');\n }),\n backendCase(GROUP, 'gitRemote mints a remote whose headers authorize it', async (context) => {\n await context.backend.createRepo(context.repo);\n for (const access of ['read', 'write'] as const) {\n const remote = await context.backend.gitRemote(context.repo, access);\n assertTrue(GitRemote.safeParse(remote).success, `${access} remote is a GitRemote`);\n assertTrue(remote.url.endsWith('.git'), `${access} remote URL ends in .git`);\n assertTrue(!remote.url.includes('@'), `${access} remote URL carries no credential`);\n }\n }),\n backendCase(GROUP, 'a push to an empty repository creates the branch', async (context) => {\n const seeded = await seedRepo(context);\n assertEqual(\n await context.backend.resolveRef(context.repo, 'main'),\n seeded.sha,\n 'resolveRef sees the push',\n );\n const advertised = (await (await context.client('read')).advertisement('git-upload-pack')).refs;\n assertTrue(\n advertised.some((ref) => ref.name === 'refs/heads/main' && ref.sha === seeded.sha),\n 'advertised',\n );\n }),\n backendCase(GROUP, 'a fetch returns every pushed object byte for byte', async (context) => {\n const seeded = await seedRepo(context, {\n 'a.txt': 'a\\n',\n 'dir/b.txt': 'b\\n',\n 'dir/sub/c.bin': { content: new Uint8Array([0, 1, 2]) },\n });\n const fetched = await (await context.client('read')).fetchPack({ wants: [seeded.sha] });\n assertEqual(sortedShas(fetched.objects), sortedShas(seeded.objects), 'the same object ids');\n for (const object of seeded.objects) {\n const got = fetched.objects.find((candidate) => candidate.sha === object.sha);\n assertTrue(\n got?.type === object.type && sameBytes(got.data, object.data),\n `object ${object.sha} round-trips`,\n );\n }\n }),\n backendCase(GROUP, 'a fetch with haves leaves out what the client has', async (context) => {\n const first = await seedRepo(context);\n const second = await fixtureCommit({ 'README.md': '# Seed\\n', 'new.txt': 'new\\n' }, [first.sha]);\n expectAccepted(\n await pushRef(context, 'refs/heads/main', first.sha, second.sha, second.objects),\n 'refs/heads/main',\n );\n const fetched = await (\n await context.client('read')\n ).fetchPack({ wants: [second.sha], haves: [first.sha] });\n const got = new Set(fetched.objects.map((object) => object.sha));\n assertTrue(got.has(second.sha), 'the new commit is sent');\n assertTrue(!got.has(first.sha), 'the had commit is not sent');\n }),\n backendCase(\n GROUP,\n 'a second branch can point at an existing commit with an empty pack',\n async (context) => {\n const seeded = await seedRepo(context);\n expectAccepted(\n await pushRef(context, 'refs/heads/staging', ZERO_SHA, seeded.sha),\n 'refs/heads/staging',\n );\n assertEqual(await context.backend.resolveRef(context.repo, 'staging'), seeded.sha, 'staging');\n },\n ),\n backendCase(GROUP, 'a read remote cannot push when the host scopes credentials', async (context) => {\n const seeded = await seedRepo(context);\n if (!context.behaviour.readRemoteCannotPush) return;\n const next = await fixtureCommit({ 'x.txt': 'x\\n' }, [seeded.sha]);\n let pushed = false;\n try {\n const report = await (\n await context.client('read')\n ).push([{ oldSha: seeded.sha, newSha: next.sha, ref: 'refs/heads/main' }], next.objects);\n pushed = report.refs.every((ref) => ref.status === 'ok');\n } catch (error) {\n assertTrue(\n isCoreError(error, 'remote_error') || isCoreError(error, 'remote_http_error'),\n `refused by the remote, got ${String(error)}`,\n );\n }\n assertTrue(!pushed, 'the push did not succeed');\n assertEqual(await context.backend.resolveRef(context.repo, 'main'), seeded.sha, 'main unchanged');\n }),\n backendCase(\n GROUP,\n 'pushes from new branches are visible to resolveRef and the advertisement',\n async (context) => {\n const seeded = await seedRepo(context);\n const feature = await fixtureCommit({ 'feature.txt': 'f\\n' }, [seeded.sha]);\n await pushNewBranch(context, 'feature/one', feature);\n assertEqual(\n await context.backend.resolveRef(context.repo, 'refs/heads/feature/one'),\n feature.sha,\n 'full ref',\n );\n const refs = (await (await context.client('write')).advertisement('git-receive-pack')).refs.map(\n (ref) => ref.name,\n );\n assertTrue(\n refs.includes('refs/heads/feature/one') && refs.includes('refs/heads/main'),\n 'both branches advertised',\n );\n },\n ),\n];\n"],"mappings":";;;;;;;;;AAWA,MAAM,QAAQ;AAEd,MAAM,cAAc,YAClB,QAAQ,KAAK,WAAW,OAAO,GAAG,CAAC,CAAC,SAAS;;AAG/C,MAAa,iBAAyC;CACpD,YAAY,OAAO,4DAA4D,OAAO,YAAY;EAChG,MAAM,EAAE,SAAS,SAAS;EAC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AAQ,IAAI,IACf;EACA,WACE,KAAK,SAAS,wBAAwB,KAAK,KAAK,SAAS,iBAAiB,GAC1E,0BACF;CACF,CACF;AACF"}
@@ -0,0 +1,19 @@
1
+ import { z } from "zod";
2
+ /** The version of a git binary, parsed from `git --version`. */
3
+ export declare const GitVersion: z.ZodObject<{
4
+ major: z.ZodNumber;
5
+ minor: z.ZodNumber;
6
+ patch: z.ZodNumber;
7
+ raw: z.ZodString;
8
+ }, z.core.$strict>;
9
+ /** The version of a git binary, inferred from {@link GitVersion}. */
10
+ export type GitVersion = z.infer<typeof GitVersion>;
11
+ /** Parses the output of `git --version`; throws on anything else. */
12
+ export declare function parseGitVersion(output: string): GitVersion;
13
+ /** The git binary to drive: `GIT_BINARY` from the environment when set, otherwise `git` on the PATH. */
14
+ export declare function gitBinary(env?: Readonly<Record<string, string | undefined>>): string;
15
+ /** Runs `<binary> --version` and parses the result. */
16
+ export declare function readGitVersion(binary?: string): GitVersion;
17
+ /** True when `version` is at least `major.minor.patch`. */
18
+ export declare function isAtLeast(version: GitVersion, major: number, minor: number, patch?: number): boolean;
19
+ //# sourceMappingURL=git-binary.d.ts.map
@@ -0,0 +1,54 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { z } from "zod";
3
+ // src/git-binary.ts
4
+ /** The version of a git binary, parsed from `git --version`. */
5
+ const GitVersion = z.object({
6
+ major: z.number().int().nonnegative().describe("Major version number, e.g. 2 for git 2.43.0."),
7
+ minor: z.number().int().nonnegative().describe("Minor version number, e.g. 43 for git 2.43.0."),
8
+ patch: z.number().int().nonnegative().describe("Patch version number, e.g. 0 for git 2.43.0; 0 when the binary reports only two parts."),
9
+ raw: z.string().min(1).describe("The version text exactly as git printed it after \"git version\", e.g. \"2.39.5 (Apple Git-154)\".")
10
+ }).strict().meta({
11
+ id: "GitVersion",
12
+ title: "Git version",
13
+ description: "The version of the git binary a conformance run drives, parsed from `git --version`.",
14
+ examples: [{
15
+ major: 2,
16
+ minor: 43,
17
+ patch: 0,
18
+ raw: "2.43.0"
19
+ }]
20
+ });
21
+ const VERSION_PREFIX = "git version ";
22
+ const VERSION_NUMBERS = /^(\d+)\.(\d+)(?:\.(\d+))?(?![\d.]*\d)/;
23
+ /** Parses the output of `git --version`; throws on anything else. */
24
+ function parseGitVersion(output) {
25
+ const line = output.trim();
26
+ const raw = line.startsWith(VERSION_PREFIX) ? line.slice(12) : "";
27
+ const match = line.includes("\n") ? null : VERSION_NUMBERS.exec(raw);
28
+ if (match === null) throw new Error(`not a git --version line: ${JSON.stringify(output)}`);
29
+ const [, major, minor, patch] = match;
30
+ return GitVersion.parse({
31
+ major: Number(major),
32
+ minor: Number(minor),
33
+ patch: Number(patch ?? 0),
34
+ raw
35
+ });
36
+ }
37
+ /** The git binary to drive: `GIT_BINARY` from the environment when set, otherwise `git` on the PATH. */
38
+ function gitBinary(env = process.env) {
39
+ const configured = env["GIT_BINARY"]?.trim();
40
+ return configured === void 0 || configured === "" ? "git" : configured;
41
+ }
42
+ /** Runs `<binary> --version` and parses the result. */
43
+ function readGitVersion(binary = gitBinary()) {
44
+ return parseGitVersion(execFileSync(binary, ["--version"], { encoding: "utf8" }));
45
+ }
46
+ /** True when `version` is at least `major.minor.patch`. */
47
+ function isAtLeast(version, major, minor, patch = 0) {
48
+ if (version.major !== major) return version.major > major;
49
+ if (version.minor !== minor) return version.minor > minor;
50
+ return version.patch >= patch;
51
+ }
52
+ export { GitVersion, gitBinary, isAtLeast, parseGitVersion, readGitVersion };
53
+
54
+ //# sourceMappingURL=git-binary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"git-binary.js","names":[],"sources":["../src/git-binary.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { execFileSync } from 'node:child_process';\n\nimport { z } from 'zod';\n\n/** The version of a git binary, parsed from `git --version`. */\nexport const GitVersion = z\n .object({\n major: z.number().int().nonnegative().describe('Major version number, e.g. 2 for git 2.43.0.'),\n minor: z.number().int().nonnegative().describe('Minor version number, e.g. 43 for git 2.43.0.'),\n patch: z\n .number()\n .int()\n .nonnegative()\n .describe('Patch version number, e.g. 0 for git 2.43.0; 0 when the binary reports only two parts.'),\n raw: z\n .string()\n .min(1)\n .describe(\n 'The version text exactly as git printed it after \"git version\", e.g. \"2.39.5 (Apple Git-154)\".',\n ),\n })\n .strict()\n .meta({\n id: 'GitVersion',\n title: 'Git version',\n description: 'The version of the git binary a conformance run drives, parsed from `git --version`.',\n examples: [{ major: 2, minor: 43, patch: 0, raw: '2.43.0' }],\n });\n\n/** The version of a git binary, inferred from {@link GitVersion}. */\nexport type GitVersion = z.infer<typeof GitVersion>;\n\n// Only the leading numbers are matched; the rest of the line is kept verbatim in `raw`. (A pattern\n// that also matched the suffix, as `\\S*(?:\\s.*)?$`, backtracks in polynomial time.)\nconst VERSION_PREFIX = 'git version ';\nconst VERSION_NUMBERS = /^(\\d+)\\.(\\d+)(?:\\.(\\d+))?(?![\\d.]*\\d)/;\n\n/** Parses the output of `git --version`; throws on anything else. */\nexport function parseGitVersion(output: string): GitVersion {\n const line = output.trim();\n const raw = line.startsWith(VERSION_PREFIX) ? line.slice(VERSION_PREFIX.length) : '';\n const match = line.includes('\\n') ? null : VERSION_NUMBERS.exec(raw);\n if (match === null) throw new Error(`not a git --version line: ${JSON.stringify(output)}`);\n const [, major, minor, patch] = match;\n return GitVersion.parse({ major: Number(major), minor: Number(minor), patch: Number(patch ?? 0), raw });\n}\n\n/** The git binary to drive: `GIT_BINARY` from the environment when set, otherwise `git` on the PATH. */\nexport function gitBinary(env: Readonly<Record<string, string | undefined>> = process.env): string {\n const configured = env['GIT_BINARY']?.trim();\n return configured === undefined || configured === '' ? 'git' : configured;\n}\n\n/** Runs `<binary> --version` and parses the result. */\nexport function readGitVersion(binary: string = gitBinary()): GitVersion {\n return parseGitVersion(execFileSync(binary, ['--version'], { encoding: 'utf8' }));\n}\n\n/** True when `version` is at least `major.minor.patch`. */\nexport function isAtLeast(version: GitVersion, major: number, minor: number, patch = 0): boolean {\n if (version.major !== major) return version.major > major;\n if (version.minor !== minor) return version.minor > minor;\n return version.patch >= patch;\n}\n"],"mappings":";;;;AAMA,MAAa,aAAa,EACvB,OAAO;CACN,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS,8CAA8C;CAC7F,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS,+CAA+C;CAC9F,OAAO,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CACL,YAAY,CAAC,CACb,SAAS,wFAAwF;CACpG,KAAK,EACF,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,SACC,oGACF;AACJ,CAAC,CAAC,CACD,OAAO,CAAC,CACR,KAAK;CACJ,IAAI;CACJ,OAAO;CACP,aAAa;CACb,UAAU,CAAC;EAAE,OAAO;EAAG,OAAO;EAAI,OAAO;EAAG,KAAK;CAAS,CAAC;AAC7D,CAAC;AAOH,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;;AAGxB,SAAgB,gBAAgB,QAA4B;CAC1D,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,MAAM,KAAK,WAAW,cAAc,IAAI,KAAK,MAAM,EAAqB,IAAI;CAClF,MAAM,QAAQ,KAAK,SAAS,IAAI,IAAI,OAAO,gBAAgB,KAAK,GAAG;CACnE,IAAI,UAAU,MAAM,MAAM,IAAI,MAAM,6BAA6B,KAAK,UAAU,MAAM,GAAG;CACzF,MAAM,GAAG,OAAO,OAAO,SAAS;CAChC,OAAO,WAAW,MAAM;EAAE,OAAO,OAAO,KAAK;EAAG,OAAO,OAAO,KAAK;EAAG,OAAO,OAAO,SAAS,CAAC;EAAG;CAAI,CAAC;AACxG;;AAGA,SAAgB,UAAU,MAAoD,QAAQ,KAAa;CACjG,MAAM,aAAa,IAAI,aAAa,EAAE,KAAK;CAC3C,OAAO,eAAe,KAAA,KAAa,eAAe,KAAK,QAAQ;AACjE;;AAGA,SAAgB,eAAe,SAAiB,UAAU,GAAe;CACvE,OAAO,gBAAgB,aAAa,QAAQ,CAAC,WAAW,GAAG,EAAE,UAAU,OAAO,CAAC,CAAC;AAClF;;AAGA,SAAgB,UAAU,SAAqB,OAAe,OAAe,QAAQ,GAAY;CAC/F,IAAI,QAAQ,UAAU,OAAO,OAAO,QAAQ,QAAQ;CACpD,IAAI,QAAQ,UAAU,OAAO,OAAO,QAAQ,QAAQ;CACpD,OAAO,QAAQ,SAAS;AAC1B"}
@@ -0,0 +1,33 @@
1
+ /** What a git invocation produced. */
2
+ export interface GitRun {
3
+ readonly status: number | null;
4
+ readonly stdout: string;
5
+ readonly stderr: string;
6
+ }
7
+ /**
8
+ * A scratch directory where the real git binary (`GIT_BINARY`, or `git` on the PATH) runs isolated
9
+ * from the user's and the system's configuration: the conformance harness drives git clients
10
+ * against a gateway or a backend served on loopback with it. Call {@link dispose} when done.
11
+ */
12
+ export declare class GitSandbox {
13
+ readonly dir: string;
14
+ constructor();
15
+ /**
16
+ * Runs git in `cwd` (default the sandbox) with extra `-c` settings. Asynchronous, so an HTTP
17
+ * server in this process keeps answering while git talks to it.
18
+ */
19
+ run(args: readonly string[], options?: {
20
+ cwd?: string;
21
+ config?: readonly string[];
22
+ }): Promise<GitRun>;
23
+ /** Runs git and returns trimmed stdout, failing on a non-zero exit. */
24
+ ok(args: readonly string[], options?: {
25
+ cwd?: string;
26
+ config?: readonly string[];
27
+ }): Promise<string>;
28
+ /** A path inside the sandbox. */
29
+ path(...parts: string[]): string;
30
+ /** Removes the scratch directory. */
31
+ dispose(): void;
32
+ }
33
+ //# sourceMappingURL=git-sandbox.d.ts.map
@@ -0,0 +1,76 @@
1
+ import { gitBinary } from "./git-binary.js";
2
+ import { spawn } from "node:child_process";
3
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ // src/git-sandbox.ts
7
+ /**
8
+ * A scratch directory where the real git binary (`GIT_BINARY`, or `git` on the PATH) runs isolated
9
+ * from the user's and the system's configuration: the conformance harness drives git clients
10
+ * against a gateway or a backend served on loopback with it. Call {@link dispose} when done.
11
+ */
12
+ var GitSandbox = class {
13
+ dir = mkdtempSync(join(tmpdir(), "git-gateway-testkit-"));
14
+ constructor() {
15
+ writeFileSync(join(this.dir, ".gitconfig"), "[user]\n name = Conformance\n email = conformance@example.com\n[init]\n defaultBranch = main\n");
16
+ }
17
+ /**
18
+ * Runs git in `cwd` (default the sandbox) with extra `-c` settings. Asynchronous, so an HTTP
19
+ * server in this process keeps answering while git talks to it.
20
+ */
21
+ async run(args, options = {}) {
22
+ const config = (options.config ?? []).flatMap((setting) => ["-c", setting]);
23
+ const child = spawn(gitBinary(), [...config, ...args], {
24
+ cwd: options.cwd ?? this.dir,
25
+ env: {
26
+ PATH: process.env["PATH"],
27
+ HOME: this.dir,
28
+ GIT_CONFIG_NOSYSTEM: "1",
29
+ GIT_CONFIG_GLOBAL: join(this.dir, ".gitconfig"),
30
+ GIT_TERMINAL_PROMPT: "0",
31
+ LC_ALL: "C"
32
+ },
33
+ stdio: [
34
+ "ignore",
35
+ "pipe",
36
+ "pipe"
37
+ ]
38
+ });
39
+ let stdout = "";
40
+ let stderr = "";
41
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
42
+ stdout += chunk;
43
+ });
44
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
45
+ stderr += chunk;
46
+ });
47
+ return {
48
+ status: await new Promise((resolve, reject) => {
49
+ child.on("error", reject);
50
+ child.on("close", resolve);
51
+ }),
52
+ stdout,
53
+ stderr
54
+ };
55
+ }
56
+ /** Runs git and returns trimmed stdout, failing on a non-zero exit. */
57
+ async ok(args, options = {}) {
58
+ const result = await this.run(args, options);
59
+ if (result.status !== 0) throw new Error(`git ${args.join(" ")} failed (${result.status}): ${result.stderr}`);
60
+ return result.stdout.trim();
61
+ }
62
+ /** A path inside the sandbox. */
63
+ path(...parts) {
64
+ return join(this.dir, ...parts);
65
+ }
66
+ /** Removes the scratch directory. */
67
+ dispose() {
68
+ rmSync(this.dir, {
69
+ recursive: true,
70
+ force: true
71
+ });
72
+ }
73
+ };
74
+ export { GitSandbox };
75
+
76
+ //# sourceMappingURL=git-sandbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"git-sandbox.js","names":[],"sources":["../src/git-sandbox.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { spawn } from 'node:child_process';\nimport { mkdtempSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nimport { gitBinary } from './git-binary.ts';\n\n/** What a git invocation produced. */\nexport interface GitRun {\n readonly status: number | null;\n readonly stdout: string;\n readonly stderr: string;\n}\n\n/**\n * A scratch directory where the real git binary (`GIT_BINARY`, or `git` on the PATH) runs isolated\n * from the user's and the system's configuration: the conformance harness drives git clients\n * against a gateway or a backend served on loopback with it. Call {@link dispose} when done.\n */\nexport class GitSandbox {\n readonly dir = mkdtempSync(join(tmpdir(), 'git-gateway-testkit-'));\n\n constructor() {\n writeFileSync(\n join(this.dir, '.gitconfig'),\n '[user]\\n\\tname = Conformance\\n\\temail = conformance@example.com\\n[init]\\n\\tdefaultBranch = main\\n',\n );\n }\n\n /**\n * Runs git in `cwd` (default the sandbox) with extra `-c` settings. Asynchronous, so an HTTP\n * server in this process keeps answering while git talks to it.\n */\n async run(\n args: readonly string[],\n options: { cwd?: string; config?: readonly string[] } = {},\n ): Promise<GitRun> {\n const config = (options.config ?? []).flatMap((setting) => ['-c', setting]);\n const child = spawn(gitBinary(), [...config, ...args], {\n cwd: options.cwd ?? this.dir,\n env: {\n PATH: process.env['PATH'],\n HOME: this.dir,\n GIT_CONFIG_NOSYSTEM: '1',\n GIT_CONFIG_GLOBAL: join(this.dir, '.gitconfig'),\n GIT_TERMINAL_PROMPT: '0',\n LC_ALL: 'C',\n },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n child.stdout.setEncoding('utf8').on('data', (chunk: string) => {\n stdout += chunk;\n });\n child.stderr.setEncoding('utf8').on('data', (chunk: string) => {\n stderr += chunk;\n });\n const status = await new Promise<number | null>((resolve, reject) => {\n child.on('error', reject);\n child.on('close', resolve);\n });\n return { status, stdout, stderr };\n }\n\n /** Runs git and returns trimmed stdout, failing on a non-zero exit. */\n async ok(\n args: readonly string[],\n options: { cwd?: string; config?: readonly string[] } = {},\n ): Promise<string> {\n const result = await this.run(args, options);\n if (result.status !== 0)\n throw new Error(`git ${args.join(' ')} failed (${result.status}): ${result.stderr}`);\n return result.stdout.trim();\n }\n\n /** A path inside the sandbox. */\n path(...parts: string[]): string {\n return join(this.dir, ...parts);\n }\n\n /** Removes the scratch directory. */\n dispose(): void {\n rmSync(this.dir, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;;;AAoBA,IAAa,aAAb,MAAwB;CACtB,MAAe,YAAY,KAAK,OAAO,GAAG,sBAAsB,CAAC;CAEjE,cAAc;EACZ,cACE,KAAK,KAAK,KAAK,YAAY,GAC3B,gGACF;CACF;;;;;CAMA,MAAM,IACJ,MACA,UAAwD,CAAC,GACxC;EACjB,MAAM,UAAU,QAAQ,UAAU,CAAC,EAAA,CAAG,SAAS,YAAY,CAAC,MAAM,OAAO,CAAC;EAC1E,MAAM,QAAQ,MAAM,UAAU,GAAG,CAAC,GAAG,QAAQ,GAAG,IAAI,GAAG;GACrD,KAAK,QAAQ,OAAO,KAAK;GACzB,KAAK;IACH,MAAM,QAAQ,IAAI;IAClB,MAAM,KAAK;IACX,qBAAqB;IACrB,mBAAmB,KAAK,KAAK,KAAK,YAAY;IAC9C,qBAAqB;IACrB,QAAQ;GACV;GACA,OAAO;IAAC;IAAU;IAAQ;GAAM;EAClC,CAAC;EACD,IAAI,SAAS;EACb,IAAI,SAAS;EACb,MAAM,OAAO,YAAY,MAAM,CAAC,CAAC,GAAG,SAAS,UAAkB;GAC7D,UAAU;EACZ,CAAC;EACD,MAAM,OAAO,YAAY,MAAM,CAAC,CAAC,GAAG,SAAS,UAAkB;GAC7D,UAAU;EACZ,CAAC;EAKD,OAAO;GAAE,QAAA,MAJY,IAAI,SAAwB,SAAS,WAAW;IACnE,MAAM,GAAG,SAAS,MAAM;IACxB,MAAM,GAAG,SAAS,OAAO;GAC3B,CAAC;GACgB;GAAQ;EAAO;CAClC;;CAGA,MAAM,GACJ,MACA,UAAwD,CAAC,GACxC;EACjB,MAAM,SAAS,MAAM,KAAK,IAAI,MAAM,OAAO;EAC3C,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MAAM,OAAO,KAAK,KAAK,GAAG,EAAE,WAAW,OAAO,OAAO,KAAK,OAAO,QAAQ;EACrF,OAAO,OAAO,OAAO,KAAK;CAC5B;;CAGA,KAAK,GAAG,OAAyB;EAC/B,OAAO,KAAK,KAAK,KAAK,GAAG,KAAK;CAChC;;CAGA,UAAgB;EACd,OAAO,KAAK,KAAK;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACnD;AACF"}
@@ -0,0 +1,45 @@
1
+ import { FetchLike } from "@leed-ai/git-gateway-core/smart-http/git-http-client";
2
+ import { CreateStorageRepoOptions, StorageRepoInfo } from "@leed-ai/git-gateway-contract/storage/storage-repo-info";
3
+ import { GitRemote } from "@leed-ai/git-gateway-contract/storage/git-remote";
4
+ import { Commit } from "@leed-ai/git-gateway-contract/schemas/commit";
5
+ import { StorageLogOptions } from "@leed-ai/git-gateway-contract/storage/storage-read";
6
+ import { StorageTreeEntry } from "@leed-ai/git-gateway-contract/storage/storage-tree-entry";
7
+ import { StorageBackend } from "@leed-ai/git-gateway-contract/storage/storage-backend";
8
+ /** Options of a {@link MemoryBackend}. */
9
+ export interface MemoryBackendOptions {
10
+ /** Base URL of the git remotes it hands out; default "http://memory.git-gateway.invalid". */
11
+ readonly baseUrl?: string;
12
+ /** The clock for creation times and token expiry; default the system clock. */
13
+ readonly now?: () => Date;
14
+ /** Lifetime of the tokens gitRemote() mints, in seconds; default 300. */
15
+ readonly tokenTtlSeconds?: number;
16
+ }
17
+ /**
18
+ * A complete {@link StorageBackend} held in memory, with a real git smart-HTTP server (protocol
19
+ * v0/v1 upload-pack and receive-pack) in {@link handle}, so the git binary and the gateway can
20
+ * push and fetch against it. Serve {@link handle} over HTTP for a git client, or pass
21
+ * {@link fetch} wherever a FetchLike is taken.
22
+ */
23
+ export declare class MemoryBackend implements StorageBackend {
24
+ #private;
25
+ constructor(options?: MemoryBackendOptions);
26
+ /** Sets the base URL of the remotes handed out from now on (e.g. once an HTTP server has a port). */
27
+ setBaseUrl(baseUrl: string): void;
28
+ /** Answers a git smart-HTTP request for one of the repositories. */
29
+ readonly handle: (request: Request) => Promise<Response>;
30
+ /** {@link handle} as a FetchLike, for clients that would otherwise call the network. */
31
+ readonly fetch: FetchLike;
32
+ createRepo(name: string, options?: CreateStorageRepoOptions): Promise<StorageRepoInfo>;
33
+ deleteRepo(name: string): Promise<void>;
34
+ repoInfo(name: string): Promise<StorageRepoInfo | null>;
35
+ resolveRef(name: string, ref: string): Promise<string | null>;
36
+ readCommit(name: string, sha: string): Promise<Commit | null>;
37
+ readTree(name: string, sha: string): Promise<StorageTreeEntry[] | null>;
38
+ readBlob(name: string, sha: string): Promise<Uint8Array | null>;
39
+ readFile(name: string, ref: string, path: string): Promise<Uint8Array | null>;
40
+ log(name: string, ref: string, options: StorageLogOptions): Promise<Commit[]>;
41
+ /** Walks parents from `descendant`; null when either commit is not in the repository. */
42
+ isAncestor(name: string, ancestor: string, descendant: string): Promise<boolean | null>;
43
+ gitRemote(name: string, access: string): Promise<GitRemote>;
44
+ }
45
+ //# sourceMappingURL=memory-backend.d.ts.map
@@ -0,0 +1,154 @@
1
+ import { fileAt, firstParentLog, resolveRevision } from "./memory-reads.js";
2
+ import { MemoryRepository } from "./memory-repository.js";
3
+ import { MemoryTokens } from "./memory-tokens.js";
4
+ import { serveSmartHttp } from "./smart-http-server.js";
5
+ import { Sha } from "@leed-ai/git-gateway-contract/schemas/sha";
6
+ import { CreateStorageRepoOptions, StorageRepoInfo } from "@leed-ai/git-gateway-contract/storage/storage-repo-info";
7
+ import { GitAccess, GitRemote } from "@leed-ai/git-gateway-contract/storage/git-remote";
8
+ import { Commit } from "@leed-ai/git-gateway-contract/schemas/commit";
9
+ import { FilePath, RepoName, Revision } from "@leed-ai/git-gateway-contract/schemas/names";
10
+ import { repoExists, repoNotFound } from "@leed-ai/git-gateway-contract/storage/storage-errors";
11
+ import { parseStorageInput } from "@leed-ai/git-gateway-contract/storage/storage-input";
12
+ import { StorageLogOptions, StorageRef } from "@leed-ai/git-gateway-contract/storage/storage-read";
13
+ import { StorageTreeEntry } from "@leed-ai/git-gateway-contract/storage/storage-tree-entry";
14
+ // src/memory/memory-backend.ts
15
+ const TYPE_OF_MODE = {
16
+ "040000": "tree",
17
+ "160000": "commit"
18
+ };
19
+ /**
20
+ * A complete {@link StorageBackend} held in memory, with a real git smart-HTTP server (protocol
21
+ * v0/v1 upload-pack and receive-pack) in {@link handle}, so the git binary and the gateway can
22
+ * push and fetch against it. Serve {@link handle} over HTTP for a git client, or pass
23
+ * {@link fetch} wherever a FetchLike is taken.
24
+ */
25
+ var MemoryBackend = class {
26
+ #repos = /* @__PURE__ */ new Map();
27
+ #tokens;
28
+ #now;
29
+ #ttl;
30
+ #baseUrl;
31
+ constructor(options = {}) {
32
+ this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
33
+ this.#tokens = new MemoryTokens(this.#now);
34
+ this.#ttl = options.tokenTtlSeconds ?? 300;
35
+ this.#baseUrl = (options.baseUrl ?? "http://memory.git-gateway.invalid").replace(/\/$/, "");
36
+ }
37
+ /** Sets the base URL of the remotes handed out from now on (e.g. once an HTTP server has a port). */
38
+ setBaseUrl(baseUrl) {
39
+ this.#baseUrl = baseUrl.replace(/\/$/, "");
40
+ }
41
+ /** Answers a git smart-HTTP request for one of the repositories. */
42
+ handle = async (request) => serveSmartHttp({
43
+ tokens: this.#tokens,
44
+ repository: (name) => this.#repos.get(name)
45
+ }, request);
46
+ /** {@link handle} as a FetchLike, for clients that would otherwise call the network. */
47
+ fetch = async (request) => this.handle(request);
48
+ async createRepo(name, options = {}) {
49
+ const repo = parseStorageInput(RepoName, name);
50
+ const { defaultBranch } = parseStorageInput(CreateStorageRepoOptions, options);
51
+ if (this.#repos.has(repo)) throw repoExists(repo);
52
+ const created = new MemoryRepository(repo, defaultBranch, this.#now().toISOString());
53
+ this.#repos.set(repo, created);
54
+ return this.#info(created);
55
+ }
56
+ async deleteRepo(name) {
57
+ const repo = parseStorageInput(RepoName, name);
58
+ this.#repos.delete(repo);
59
+ this.#tokens.revokeRepo(repo);
60
+ }
61
+ async repoInfo(name) {
62
+ const repo = this.#repos.get(parseStorageInput(RepoName, name));
63
+ return repo === void 0 ? null : this.#info(repo);
64
+ }
65
+ async resolveRef(name, ref) {
66
+ const repoName = parseStorageInput(RepoName, name);
67
+ const parsed = parseStorageInput(StorageRef, ref);
68
+ return this.#require(repoName).refs.get(parsed.startsWith("refs/") ? parsed : `refs/heads/${parsed}`) ?? null;
69
+ }
70
+ async readCommit(name, sha) {
71
+ const repoName = parseStorageInput(RepoName, name);
72
+ const id = parseStorageInput(Sha, sha);
73
+ const commit = this.#require(repoName).commit(id);
74
+ return commit === null ? null : Commit.parse(commit);
75
+ }
76
+ async readTree(name, sha) {
77
+ const repoName = parseStorageInput(RepoName, name);
78
+ const id = parseStorageInput(Sha, sha);
79
+ const entries = this.#require(repoName).tree(id);
80
+ if (entries === null) return null;
81
+ return entries.map((entry) => StorageTreeEntry.parse({
82
+ ...entry,
83
+ type: entry.mode === "040000" || entry.mode === "160000" ? TYPE_OF_MODE[entry.mode] : "blob"
84
+ }));
85
+ }
86
+ async readBlob(name, sha) {
87
+ const repoName = parseStorageInput(RepoName, name);
88
+ const id = parseStorageInput(Sha, sha);
89
+ const blob = this.#require(repoName).object(id, "blob");
90
+ return blob === null ? null : blob.data.slice();
91
+ }
92
+ async readFile(name, ref, path) {
93
+ const repoName = parseStorageInput(RepoName, name);
94
+ const revision = parseStorageInput(Revision, ref);
95
+ const file = parseStorageInput(FilePath, path);
96
+ const repo = this.#require(repoName);
97
+ const commit = resolveRevision(repo, revision);
98
+ const data = commit === null ? null : fileAt(repo, commit, file);
99
+ return data === null ? null : data.slice();
100
+ }
101
+ async log(name, ref, options) {
102
+ const repoName = parseStorageInput(RepoName, name);
103
+ const revision = parseStorageInput(Revision, ref);
104
+ const { limit, offset } = parseStorageInput(StorageLogOptions, options);
105
+ const repo = this.#require(repoName);
106
+ const start = resolveRevision(repo, revision);
107
+ return start === null ? [] : firstParentLog(repo, start, limit, offset).map((commit) => Commit.parse(commit));
108
+ }
109
+ /** Walks parents from `descendant`; null when either commit is not in the repository. */
110
+ async isAncestor(name, ancestor, descendant) {
111
+ const repoName = parseStorageInput(RepoName, name);
112
+ const older = parseStorageInput(Sha, ancestor);
113
+ const newer = parseStorageInput(Sha, descendant);
114
+ const repo = this.#require(repoName);
115
+ if (repo.commit(older) === null || repo.commit(newer) === null) return null;
116
+ const seen = /* @__PURE__ */ new Set([newer]);
117
+ const queue = [newer];
118
+ for (let sha = queue.shift(); sha !== void 0; sha = queue.shift()) {
119
+ if (sha === older) return true;
120
+ for (const parent of repo.commit(sha)?.parents ?? []) if (!seen.has(parent)) {
121
+ seen.add(parent);
122
+ queue.push(parent);
123
+ }
124
+ }
125
+ return false;
126
+ }
127
+ async gitRemote(name, access) {
128
+ const repoName = parseStorageInput(RepoName, name);
129
+ const level = parseStorageInput(GitAccess, access);
130
+ const repo = this.#require(repoName);
131
+ const minted = this.#tokens.mint(repo.name, level, this.#ttl);
132
+ return GitRemote.parse({
133
+ url: `${this.#baseUrl}/${repo.name}.git`,
134
+ headers: { Authorization: `Bearer ${minted.token}` },
135
+ expiresAt: minted.expiresAt.toISOString()
136
+ });
137
+ }
138
+ /** The repository `repo` (already parsed with RepoName, as every other argument must be first). */
139
+ #require(repo) {
140
+ const found = this.#repos.get(repo);
141
+ if (found === void 0) throw repoNotFound(repo);
142
+ return found;
143
+ }
144
+ #info(repo) {
145
+ return StorageRepoInfo.parse({
146
+ name: repo.name,
147
+ defaultBranch: repo.defaultBranch,
148
+ createdAt: repo.createdAt
149
+ });
150
+ }
151
+ };
152
+ export { MemoryBackend };
153
+
154
+ //# sourceMappingURL=memory-backend.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-backend.js","names":[],"sources":["../../src/memory/memory-backend.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { Commit } from '@leed-ai/git-gateway-contract/schemas/commit';\nimport { FilePath, RepoName, Revision } from '@leed-ai/git-gateway-contract/schemas/names';\nimport { Sha } from '@leed-ai/git-gateway-contract/schemas/sha';\nimport { GitAccess, GitRemote } from '@leed-ai/git-gateway-contract/storage/git-remote';\nimport type { StorageBackend } from '@leed-ai/git-gateway-contract/storage/storage-backend';\nimport { repoExists, repoNotFound } from '@leed-ai/git-gateway-contract/storage/storage-errors';\nimport { parseStorageInput } from '@leed-ai/git-gateway-contract/storage/storage-input';\nimport { StorageLogOptions, StorageRef } from '@leed-ai/git-gateway-contract/storage/storage-read';\nimport {\n CreateStorageRepoOptions,\n StorageRepoInfo,\n} from '@leed-ai/git-gateway-contract/storage/storage-repo-info';\nimport { StorageTreeEntry } from '@leed-ai/git-gateway-contract/storage/storage-tree-entry';\nimport type { FetchLike } from '@leed-ai/git-gateway-core/smart-http/git-http-client';\n\nimport { fileAt, firstParentLog, resolveRevision } from './memory-reads.ts';\nimport { MemoryRepository } from './memory-repository.ts';\nimport { MemoryTokens } from './memory-tokens.ts';\nimport { serveSmartHttp } from './smart-http-server.ts';\n\n/** Options of a {@link MemoryBackend}. */\nexport interface MemoryBackendOptions {\n /** Base URL of the git remotes it hands out; default \"http://memory.git-gateway.invalid\". */\n readonly baseUrl?: string;\n /** The clock for creation times and token expiry; default the system clock. */\n readonly now?: () => Date;\n /** Lifetime of the tokens gitRemote() mints, in seconds; default 300. */\n readonly tokenTtlSeconds?: number;\n}\n\nconst TYPE_OF_MODE = { '040000': 'tree', '160000': 'commit' } as const;\n\n/**\n * A complete {@link StorageBackend} held in memory, with a real git smart-HTTP server (protocol\n * v0/v1 upload-pack and receive-pack) in {@link handle}, so the git binary and the gateway can\n * push and fetch against it. Serve {@link handle} over HTTP for a git client, or pass\n * {@link fetch} wherever a FetchLike is taken.\n */\nexport class MemoryBackend implements StorageBackend {\n readonly #repos = new Map<string, MemoryRepository>();\n readonly #tokens: MemoryTokens;\n readonly #now: () => Date;\n readonly #ttl: number;\n #baseUrl: string;\n\n constructor(options: MemoryBackendOptions = {}) {\n this.#now = options.now ?? (() => new Date());\n this.#tokens = new MemoryTokens(this.#now);\n this.#ttl = options.tokenTtlSeconds ?? 300;\n this.#baseUrl = (options.baseUrl ?? 'http://memory.git-gateway.invalid').replace(/\\/$/, '');\n }\n\n /** Sets the base URL of the remotes handed out from now on (e.g. once an HTTP server has a port). */\n setBaseUrl(baseUrl: string): void {\n this.#baseUrl = baseUrl.replace(/\\/$/, '');\n }\n\n /** Answers a git smart-HTTP request for one of the repositories. */\n readonly handle = async (request: Request): Promise<Response> =>\n serveSmartHttp({ tokens: this.#tokens, repository: (name) => this.#repos.get(name) }, request);\n\n /** {@link handle} as a FetchLike, for clients that would otherwise call the network. */\n readonly fetch: FetchLike = async (request) => this.handle(request);\n\n async createRepo(name: string, options: CreateStorageRepoOptions = {}): Promise<StorageRepoInfo> {\n const repo = parseStorageInput(RepoName, name);\n const { defaultBranch } = parseStorageInput(CreateStorageRepoOptions, options);\n if (this.#repos.has(repo)) throw repoExists(repo);\n const created = new MemoryRepository(repo, defaultBranch, this.#now().toISOString());\n this.#repos.set(repo, created);\n return this.#info(created);\n }\n\n async deleteRepo(name: string): Promise<void> {\n const repo = parseStorageInput(RepoName, name);\n this.#repos.delete(repo);\n this.#tokens.revokeRepo(repo);\n }\n\n async repoInfo(name: string): Promise<StorageRepoInfo | null> {\n const repo = this.#repos.get(parseStorageInput(RepoName, name));\n return repo === undefined ? null : this.#info(repo);\n }\n\n async resolveRef(name: string, ref: string): Promise<string | null> {\n const repoName = parseStorageInput(RepoName, name);\n const parsed = parseStorageInput(StorageRef, ref);\n const repo = this.#require(repoName);\n return repo.refs.get(parsed.startsWith('refs/') ? parsed : `refs/heads/${parsed}`) ?? null;\n }\n\n async readCommit(name: string, sha: string): Promise<Commit | null> {\n const repoName = parseStorageInput(RepoName, name);\n const id = parseStorageInput(Sha, sha);\n const commit = this.#require(repoName).commit(id);\n return commit === null ? null : Commit.parse(commit);\n }\n\n async readTree(name: string, sha: string): Promise<StorageTreeEntry[] | null> {\n const repoName = parseStorageInput(RepoName, name);\n const id = parseStorageInput(Sha, sha);\n const entries = this.#require(repoName).tree(id);\n if (entries === null) return null;\n return entries.map((entry) =>\n StorageTreeEntry.parse({\n ...entry,\n type: entry.mode === '040000' || entry.mode === '160000' ? TYPE_OF_MODE[entry.mode] : 'blob',\n }),\n );\n }\n\n async readBlob(name: string, sha: string): Promise<Uint8Array | null> {\n const repoName = parseStorageInput(RepoName, name);\n const id = parseStorageInput(Sha, sha);\n const blob = this.#require(repoName).object(id, 'blob');\n return blob === null ? null : blob.data.slice();\n }\n\n async readFile(name: string, ref: string, path: string): Promise<Uint8Array | null> {\n const repoName = parseStorageInput(RepoName, name);\n const revision = parseStorageInput(Revision, ref);\n const file = parseStorageInput(FilePath, path);\n const repo = this.#require(repoName);\n const commit = resolveRevision(repo, revision);\n const data = commit === null ? null : fileAt(repo, commit, file);\n return data === null ? null : data.slice();\n }\n\n async log(name: string, ref: string, options: StorageLogOptions): Promise<Commit[]> {\n const repoName = parseStorageInput(RepoName, name);\n const revision = parseStorageInput(Revision, ref);\n const { limit, offset } = parseStorageInput(StorageLogOptions, options);\n const repo = this.#require(repoName);\n const start = resolveRevision(repo, revision);\n return start === null\n ? []\n : firstParentLog(repo, start, limit, offset).map((commit) => Commit.parse(commit));\n }\n\n /** Walks parents from `descendant`; null when either commit is not in the repository. */\n async isAncestor(name: string, ancestor: string, descendant: string): Promise<boolean | null> {\n const repoName = parseStorageInput(RepoName, name);\n const older = parseStorageInput(Sha, ancestor);\n const newer = parseStorageInput(Sha, descendant);\n const repo = this.#require(repoName);\n if (repo.commit(older) === null || repo.commit(newer) === null) return null;\n const seen = new Set([newer]);\n const queue = [newer];\n for (let sha = queue.shift(); sha !== undefined; sha = queue.shift()) {\n if (sha === older) return true;\n for (const parent of repo.commit(sha)?.parents ?? []) {\n if (!seen.has(parent)) {\n seen.add(parent);\n queue.push(parent);\n }\n }\n }\n return false;\n }\n\n async gitRemote(name: string, access: string): Promise<GitRemote> {\n const repoName = parseStorageInput(RepoName, name);\n const level = parseStorageInput(GitAccess, access);\n const repo = this.#require(repoName);\n const minted = this.#tokens.mint(repo.name, level, this.#ttl);\n return GitRemote.parse({\n url: `${this.#baseUrl}/${repo.name}.git`,\n headers: { Authorization: `Bearer ${minted.token}` },\n expiresAt: minted.expiresAt.toISOString(),\n });\n }\n\n /** The repository `repo` (already parsed with RepoName, as every other argument must be first). */\n #require(repo: string): MemoryRepository {\n const found = this.#repos.get(repo);\n if (found === undefined) throw repoNotFound(repo);\n return found;\n }\n\n #info(repo: MemoryRepository): StorageRepoInfo {\n return StorageRepoInfo.parse({\n name: repo.name,\n defaultBranch: repo.defaultBranch,\n createdAt: repo.createdAt,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA+BA,MAAM,eAAe;CAAE,UAAU;CAAQ,UAAU;AAAS;;;;;;;AAQ5D,IAAa,gBAAb,MAAqD;CACnD,yBAAkB,IAAI,IAA8B;CACpD;CACA;CACA;CACA;CAEA,YAAY,UAAgC,CAAC,GAAG;EAC9C,KAAK,OAAO,QAAQ,8BAAc,IAAI,KAAK;EAC3C,KAAK,UAAU,IAAI,aAAa,KAAK,IAAI;EACzC,KAAK,OAAO,QAAQ,mBAAmB;EACvC,KAAK,YAAY,QAAQ,WAAW,oCAAA,CAAqC,QAAQ,OAAO,EAAE;CAC5F;;CAGA,WAAW,SAAu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AAU,KAAA,GAAW,MAAM,aAAa,IAAI;EAChD,OAAO;CACT;CAEA,MAAM,MAAyC;EAC7C,OAAO,gBAAgB,MAAM;GAC3B,MAAM,KAAK;GACX,eAAe,KAAK;GACpB,WAAW,KAAK;EAClB,CAAC;CACH;AACF"}
@@ -0,0 +1,9 @@
1
+ import { MemoryRepository } from "./memory-repository.js";
2
+ import { Commit } from "@leed-ai/git-gateway-contract/schemas/commit";
3
+ /** The commit a revision names: a commit id as is, otherwise the branch "refs/heads/<name>". */
4
+ export declare function resolveRevision(repo: MemoryRepository, revision: string): string | null;
5
+ /** The blob at `path` beneath a commit's tree, or null when there is no file there. */
6
+ export declare function fileAt(repo: MemoryRepository, commitSha: string, path: string): Uint8Array | null;
7
+ /** The first-parent chain from a commit, newest first: `offset` skipped, then up to `limit`. */
8
+ export declare function firstParentLog(repo: MemoryRepository, start: string, limit: number, offset: number): Commit[];
9
+ //# sourceMappingURL=memory-reads.d.ts.map
@@ -0,0 +1,39 @@
1
+ // src/memory/memory-reads.ts
2
+ const SHA = /^[0-9a-f]{40}$/;
3
+ /** The commit a revision names: a commit id as is, otherwise the branch "refs/heads/<name>". */
4
+ function resolveRevision(repo, revision) {
5
+ if (SHA.test(revision)) return repo.object(revision, "commit") === null ? null : revision;
6
+ return repo.refs.get(`refs/heads/${revision}`) ?? null;
7
+ }
8
+ /** The blob at `path` beneath a commit's tree, or null when there is no file there. */
9
+ function fileAt(repo, commitSha, path) {
10
+ const commit = repo.commit(commitSha);
11
+ if (commit === null) return null;
12
+ let tree = commit.tree;
13
+ const segments = path.split("/");
14
+ for (const [index, segment] of segments.entries()) {
15
+ const entry = repo.tree(tree)?.find((candidate) => candidate.name === segment);
16
+ if (entry === void 0) return null;
17
+ if (index === segments.length - 1) return entry.mode === "040000" || entry.mode === "160000" ? null : repo.object(entry.sha, "blob")?.data ?? null;
18
+ if (entry.mode !== "040000") return null;
19
+ tree = entry.sha;
20
+ }
21
+ return null;
22
+ }
23
+ /** The first-parent chain from a commit, newest first: `offset` skipped, then up to `limit`. */
24
+ function firstParentLog(repo, start, limit, offset) {
25
+ const out = [];
26
+ let index = 0;
27
+ let next = start;
28
+ while (next !== void 0 && out.length < limit) {
29
+ const commit = repo.commit(next);
30
+ if (commit === null) break;
31
+ if (index >= offset) out.push(commit);
32
+ index += 1;
33
+ next = commit.parents[0];
34
+ }
35
+ return out;
36
+ }
37
+ export { fileAt, firstParentLog, resolveRevision };
38
+
39
+ //# sourceMappingURL=memory-reads.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-reads.js","names":[],"sources":["../../src/memory/memory-reads.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { Commit } from '@leed-ai/git-gateway-contract/schemas/commit';\n\nimport type { MemoryRepository } from './memory-repository.ts';\n\nconst SHA = /^[0-9a-f]{40}$/;\n\n/** The commit a revision names: a commit id as is, otherwise the branch \"refs/heads/<name>\". */\nexport function resolveRevision(repo: MemoryRepository, revision: string): string | null {\n if (SHA.test(revision)) return repo.object(revision, 'commit') === null ? null : revision;\n return repo.refs.get(`refs/heads/${revision}`) ?? null;\n}\n\n/** The blob at `path` beneath a commit's tree, or null when there is no file there. */\nexport function fileAt(repo: MemoryRepository, commitSha: string, path: string): Uint8Array | null {\n const commit = repo.commit(commitSha);\n if (commit === null) return null;\n let tree = commit.tree;\n const segments = path.split('/');\n for (const [index, segment] of segments.entries()) {\n const entry = repo.tree(tree)?.find((candidate) => candidate.name === segment);\n if (entry === undefined) return null;\n if (index === segments.length - 1) {\n return entry.mode === '040000' || entry.mode === '160000'\n ? null\n : (repo.object(entry.sha, 'blob')?.data ?? null);\n }\n if (entry.mode !== '040000') return null;\n tree = entry.sha;\n }\n return null;\n}\n\n/** The first-parent chain from a commit, newest first: `offset` skipped, then up to `limit`. */\nexport function firstParentLog(\n repo: MemoryRepository,\n start: string,\n limit: number,\n offset: number,\n): Commit[] {\n const out: Commit[] = [];\n let index = 0;\n let next: string | undefined = start;\n while (next !== undefined && out.length < limit) {\n const commit = repo.commit(next);\n if (commit === null) break;\n if (index >= offset) out.push(commit);\n index += 1;\n next = commit.parents[0];\n }\n return out;\n}\n"],"mappings":";AAKA,MAAM,MAAM;;AAGZ,SAAgB,gBAAgB,MAAwB,UAAiC;CACvF,IAAI,IAAI,KAAK,QAAQ,GAAG,OAAO,KAAK,OAAO,UAAU,QAAQ,MAAM,OAAO,OAAO;CACjF,OAAO,KAAK,KAAK,IAAI,cAAc,UAAU,KAAK;AACpD;;AAGA,SAAgB,OAAO,MAAwB,WAAmB,MAAiC;CACjG,MAAM,SAAS,KAAK,OAAO,SAAS;CACpC,IAAI,WAAW,MAAM,OAAO;CAC5B,IAAI,OAAO,OAAO;CAClB,MAAM,WAAW,KAAK,MAAM,GAAG;CAC/B,KAAK,MAAM,CAAC,OAAO,YAAY,SAAS,QAAQ,GAAG;EACjD,MAAM,QAAQ,KAAK,KAAK,IAAI,CAAC,EAAE,MAAM,cAAc,UAAU,SAAS,OAAO;EAC7E,IAAI,UAAU,KAAA,GAAW,OAAO;EAChC,IAAI,UAAU,SAAS,SAAS,GAC9B,OAAO,MAAM,SAAS,YAAY,MAAM,SAAS,WAC7C,OACC,KAAK,OAAO,MAAM,KAAK,MAAM,CAAC,EAAE,QAAQ;EAE/C,IAAI,MAAM,SAAS,UAAU,OAAO;EACpC,OAAO,MAAM;CACf;CACA,OAAO;AACT;;AAGA,SAAgB,eACd,MACA,OACA,OACA,QACU;CACV,MAAM,MAAgB,CAAC;CACvB,IAAI,QAAQ;CACZ,IAAI,OAA2B;CAC/B,OAAO,SAAS,KAAA,KAAa,IAAI,SAAS,OAAO;EAC/C,MAAM,SAAS,KAAK,OAAO,IAAI;EAC/B,IAAI,WAAW,MAAM;EACrB,IAAI,SAAS,QAAQ,IAAI,KAAK,MAAM;EACpC,SAAS;EACT,OAAO,OAAO,QAAQ;CACxB;CACA,OAAO;AACT"}