@leed-ai/git-gateway-contract 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 (286) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +50 -2
  3. package/dist/behaviour/assertions.d.ts +23 -0
  4. package/dist/behaviour/assertions.js +56 -0
  5. package/dist/behaviour/assertions.js.map +1 -0
  6. package/dist/behaviour/behaviour-case.d.ts +19 -0
  7. package/dist/behaviour/behaviour-case.js +12 -0
  8. package/dist/behaviour/behaviour-case.js.map +1 -0
  9. package/dist/behaviour/behaviour-suite.d.ts +30 -0
  10. package/dist/behaviour/behaviour-suite.js +50 -0
  11. package/dist/behaviour/behaviour-suite.js.map +1 -0
  12. package/dist/behaviour/commit-action-cases.d.ts +4 -0
  13. package/dist/behaviour/commit-action-cases.js +342 -0
  14. package/dist/behaviour/commit-action-cases.js.map +1 -0
  15. package/dist/behaviour/commit-write-cases.d.ts +4 -0
  16. package/dist/behaviour/commit-write-cases.js +234 -0
  17. package/dist/behaviour/commit-write-cases.js.map +1 -0
  18. package/dist/behaviour/fixtures.d.ts +29 -0
  19. package/dist/behaviour/fixtures.js +83 -0
  20. package/dist/behaviour/fixtures.js.map +1 -0
  21. package/dist/behaviour/lifecycle-cases.d.ts +4 -0
  22. package/dist/behaviour/lifecycle-cases.js +158 -0
  23. package/dist/behaviour/lifecycle-cases.js.map +1 -0
  24. package/dist/behaviour/promote-cases.d.ts +4 -0
  25. package/dist/behaviour/promote-cases.js +122 -0
  26. package/dist/behaviour/promote-cases.js.map +1 -0
  27. package/dist/behaviour/read-cases.d.ts +4 -0
  28. package/dist/behaviour/read-cases.js +248 -0
  29. package/dist/behaviour/read-cases.js.map +1 -0
  30. package/dist/behaviour/sync-cases.d.ts +4 -0
  31. package/dist/behaviour/sync-cases.js +205 -0
  32. package/dist/behaviour/sync-cases.js.map +1 -0
  33. package/dist/clock-B3MlpmVY.d.ts +10 -0
  34. package/dist/commit-BEZmeAOl.d.ts +23 -0
  35. package/dist/file-map-CxUveLWz.d.ts +18 -0
  36. package/dist/gateway-config-oVsdTEeK.d.ts +39 -0
  37. package/dist/gateway-error-body-BWzZFAQI.d.ts +214 -0
  38. package/dist/gateway-error.d.ts +30 -0
  39. package/dist/gateway-error.js +63 -0
  40. package/dist/gateway-error.js.map +1 -0
  41. package/dist/git-gateway-VA9Tc5tn.d.ts +358 -0
  42. package/dist/git-gateway.d.ts +2 -0
  43. package/dist/git-gateway.js +65 -0
  44. package/dist/git-gateway.js.map +1 -0
  45. package/dist/health.d.ts +9 -0
  46. package/dist/health.js +18 -0
  47. package/dist/health.js.map +1 -0
  48. package/dist/history-CqvHaUE-.d.ts +20 -0
  49. package/dist/package-name.d.ts +3 -0
  50. package/dist/package-name.js +6 -0
  51. package/dist/package-name.js.map +1 -0
  52. package/dist/proxy/audit-event.d.ts +61 -0
  53. package/dist/proxy/audit-event.js +97 -0
  54. package/dist/proxy/audit-event.js.map +1 -0
  55. package/dist/proxy/branch-rule.d.ts +72 -0
  56. package/dist/proxy/branch-rule.js +106 -0
  57. package/dist/proxy/branch-rule.js.map +1 -0
  58. package/dist/proxy/gateway-hooks.d.ts +58 -0
  59. package/dist/proxy/gateway-hooks.js +0 -0
  60. package/dist/proxy/git-operation.d.ts +17 -0
  61. package/dist/proxy/git-operation.js +32 -0
  62. package/dist/proxy/git-operation.js.map +1 -0
  63. package/dist/proxy/policy-result.d.ts +51 -0
  64. package/dist/proxy/policy-result.js +90 -0
  65. package/dist/proxy/policy-result.js.map +1 -0
  66. package/dist/proxy/principal.d.ts +18 -0
  67. package/dist/proxy/principal.js +32 -0
  68. package/dist/proxy/principal.js.map +1 -0
  69. package/dist/proxy/push-policy-result.d.ts +34 -0
  70. package/dist/proxy/push-policy-result.js +48 -0
  71. package/dist/proxy/push-policy-result.js.map +1 -0
  72. package/dist/proxy/push-policy.d.ts +146 -0
  73. package/dist/proxy/push-policy.js +112 -0
  74. package/dist/proxy/push-policy.js.map +1 -0
  75. package/dist/proxy/request-credential.d.ts +22 -0
  76. package/dist/proxy/request-credential.js +46 -0
  77. package/dist/proxy/request-credential.js.map +1 -0
  78. package/dist/proxy/smart-http-config.d.ts +22 -0
  79. package/dist/proxy/smart-http-config.js +40 -0
  80. package/dist/proxy/smart-http-config.js.map +1 -0
  81. package/dist/reference/apply-actions.d.ts +9 -0
  82. package/dist/reference/apply-actions.js +84 -0
  83. package/dist/reference/apply-actions.js.map +1 -0
  84. package/dist/reference/branch-methods.d.ts +7 -0
  85. package/dist/reference/branch-methods.js +105 -0
  86. package/dist/reference/branch-methods.js.map +1 -0
  87. package/dist/reference/bytes.d.ts +22 -0
  88. package/dist/reference/bytes.js +62 -0
  89. package/dist/reference/bytes.js.map +1 -0
  90. package/dist/reference/clock.d.ts +2 -0
  91. package/dist/reference/clock.js +18 -0
  92. package/dist/reference/clock.js.map +1 -0
  93. package/dist/reference/commit-method.d.ts +5 -0
  94. package/dist/reference/commit-method.js +83 -0
  95. package/dist/reference/commit-method.js.map +1 -0
  96. package/dist/reference/file-map.d.ts +2 -0
  97. package/dist/reference/file-map.js +24 -0
  98. package/dist/reference/file-map.js.map +1 -0
  99. package/dist/reference/hash.d.ts +10 -0
  100. package/dist/reference/hash.js +25 -0
  101. package/dist/reference/hash.js.map +1 -0
  102. package/dist/reference/history.d.ts +2 -0
  103. package/dist/reference/history.js +65 -0
  104. package/dist/reference/history.js.map +1 -0
  105. package/dist/reference/lifecycle-methods.d.ts +9 -0
  106. package/dist/reference/lifecycle-methods.js +48 -0
  107. package/dist/reference/lifecycle-methods.js.map +1 -0
  108. package/dist/reference/read-methods.d.ts +13 -0
  109. package/dist/reference/read-methods.js +68 -0
  110. package/dist/reference/read-methods.js.map +1 -0
  111. package/dist/reference/reference-gateway.d.ts +18 -0
  112. package/dist/reference/reference-gateway.js +35 -0
  113. package/dist/reference/reference-gateway.js.map +1 -0
  114. package/dist/reference/repo-state.d.ts +43 -0
  115. package/dist/reference/repo-state.js +45 -0
  116. package/dist/reference/repo-state.js.map +1 -0
  117. package/dist/reference/run-method.d.ts +13 -0
  118. package/dist/reference/run-method.js +15 -0
  119. package/dist/reference/run-method.js.map +1 -0
  120. package/dist/reference/three-way-merge.d.ts +16 -0
  121. package/dist/reference/three-way-merge.js +45 -0
  122. package/dist/reference/three-way-merge.js.map +1 -0
  123. package/dist/reference/trailer.d.ts +7 -0
  124. package/dist/reference/trailer.js +16 -0
  125. package/dist/reference/trailer.js.map +1 -0
  126. package/dist/reference/tree-index.d.ts +2 -0
  127. package/dist/reference/tree-index.js +66 -0
  128. package/dist/reference/tree-index.js.map +1 -0
  129. package/dist/reference/write-commit.d.ts +15 -0
  130. package/dist/reference/write-commit.js +44 -0
  131. package/dist/reference/write-commit.js.map +1 -0
  132. package/dist/rpc/commit-exists.d.ts +16 -0
  133. package/dist/rpc/commit-exists.js +30 -0
  134. package/dist/rpc/commit-exists.js.map +1 -0
  135. package/dist/rpc/commit.d.ts +172 -0
  136. package/dist/rpc/commit.js +115 -0
  137. package/dist/rpc/commit.js.map +1 -0
  138. package/dist/rpc/list-tree.d.ts +59 -0
  139. package/dist/rpc/list-tree.js +54 -0
  140. package/dist/rpc/list-tree.js.map +1 -0
  141. package/dist/rpc/log.d.ts +35 -0
  142. package/dist/rpc/log.js +41 -0
  143. package/dist/rpc/log.js.map +1 -0
  144. package/dist/rpc/mint-read-token.d.ts +17 -0
  145. package/dist/rpc/mint-read-token.js +36 -0
  146. package/dist/rpc/mint-read-token.js.map +1 -0
  147. package/dist/rpc/promote.d.ts +39 -0
  148. package/dist/rpc/promote.js +69 -0
  149. package/dist/rpc/promote.js.map +1 -0
  150. package/dist/rpc/read-file.d.ts +44 -0
  151. package/dist/rpc/read-file.js +56 -0
  152. package/dist/rpc/read-file.js.map +1 -0
  153. package/dist/rpc/repo-lifecycle.d.ts +39 -0
  154. package/dist/rpc/repo-lifecycle.js +64 -0
  155. package/dist/rpc/repo-lifecycle.js.map +1 -0
  156. package/dist/rpc/resolve-ref.d.ts +15 -0
  157. package/dist/rpc/resolve-ref.js +28 -0
  158. package/dist/rpc/resolve-ref.js.map +1 -0
  159. package/dist/rpc/sync-branch.d.ts +107 -0
  160. package/dist/rpc/sync-branch.js +114 -0
  161. package/dist/rpc/sync-branch.js.map +1 -0
  162. package/dist/schemas/commit-action.d.ts +100 -0
  163. package/dist/schemas/commit-action.js +138 -0
  164. package/dist/schemas/commit-action.js.map +1 -0
  165. package/dist/schemas/commit.d.ts +2 -0
  166. package/dist/schemas/commit.js +24 -0
  167. package/dist/schemas/commit.js.map +1 -0
  168. package/dist/schemas/content-encoding.d.ts +24 -0
  169. package/dist/schemas/content-encoding.js +41 -0
  170. package/dist/schemas/content-encoding.js.map +1 -0
  171. package/dist/schemas/examples.d.ts +38 -0
  172. package/dist/schemas/examples.js +32 -0
  173. package/dist/schemas/examples.js.map +1 -0
  174. package/dist/schemas/gateway-config.d.ts +2 -0
  175. package/dist/schemas/gateway-config.js +72 -0
  176. package/dist/schemas/gateway-config.js.map +1 -0
  177. package/dist/schemas/gateway-error-body.d.ts +2 -0
  178. package/dist/schemas/gateway-error-body.js +188 -0
  179. package/dist/schemas/gateway-error-body.js.map +1 -0
  180. package/dist/schemas/identity.d.ts +21 -0
  181. package/dist/schemas/identity.js +40 -0
  182. package/dist/schemas/identity.js.map +1 -0
  183. package/dist/schemas/names.d.ts +26 -0
  184. package/dist/schemas/names.js +58 -0
  185. package/dist/schemas/names.js.map +1 -0
  186. package/dist/schemas/ref-update.d.ts +10 -0
  187. package/dist/schemas/ref-update.js +25 -0
  188. package/dist/schemas/ref-update.js.map +1 -0
  189. package/dist/schemas/sha.d.ts +8 -0
  190. package/dist/schemas/sha.js +14 -0
  191. package/dist/schemas/sha.js.map +1 -0
  192. package/dist/schemas/tree-entry.d.ts +2 -0
  193. package/dist/schemas/tree-entry.js +62 -0
  194. package/dist/schemas/tree-entry.js.map +1 -0
  195. package/dist/storage/git-remote.d.ts +17 -0
  196. package/dist/storage/git-remote.js +31 -0
  197. package/dist/storage/git-remote.js.map +1 -0
  198. package/dist/storage/storage-backend.d.ts +61 -0
  199. package/dist/storage/storage-backend.js +0 -0
  200. package/dist/storage/storage-errors.d.ts +12 -0
  201. package/dist/storage/storage-errors.js +22 -0
  202. package/dist/storage/storage-errors.js.map +1 -0
  203. package/dist/storage/storage-input.d.ts +7 -0
  204. package/dist/storage/storage-input.js +14 -0
  205. package/dist/storage/storage-input.js.map +1 -0
  206. package/dist/storage/storage-read.d.ts +13 -0
  207. package/dist/storage/storage-read.js +30 -0
  208. package/dist/storage/storage-read.js.map +1 -0
  209. package/dist/storage/storage-repo-info.d.ts +16 -0
  210. package/dist/storage/storage-repo-info.js +30 -0
  211. package/dist/storage/storage-repo-info.js.map +1 -0
  212. package/dist/storage/storage-tree-entry.d.ts +21 -0
  213. package/dist/storage/storage-tree-entry.js +17 -0
  214. package/dist/storage/storage-tree-entry.js.map +1 -0
  215. package/dist/tree-entry-BM_1gou1.d.ts +41 -0
  216. package/dist/tree-index-Bk721Phv.d.ts +14 -0
  217. package/package.json +401 -4
  218. package/src/behaviour/assertions.ts +75 -0
  219. package/src/behaviour/behaviour-case.ts +28 -0
  220. package/src/behaviour/behaviour-suite.ts +76 -0
  221. package/src/behaviour/commit-action-cases.ts +253 -0
  222. package/src/behaviour/commit-write-cases.ts +205 -0
  223. package/src/behaviour/fixtures.ts +103 -0
  224. package/src/behaviour/lifecycle-cases.ts +104 -0
  225. package/src/behaviour/promote-cases.ts +78 -0
  226. package/src/behaviour/read-cases.ts +176 -0
  227. package/src/behaviour/sync-cases.ts +156 -0
  228. package/src/gateway-error.ts +72 -0
  229. package/src/git-gateway.ts +76 -0
  230. package/src/health.ts +26 -0
  231. package/src/package-name.ts +4 -0
  232. package/src/proxy/audit-event.ts +135 -0
  233. package/src/proxy/branch-rule.ts +190 -0
  234. package/src/proxy/gateway-hooks.ts +67 -0
  235. package/src/proxy/git-operation.ts +36 -0
  236. package/src/proxy/policy-result.ts +127 -0
  237. package/src/proxy/principal.ts +81 -0
  238. package/src/proxy/push-policy-result.ts +86 -0
  239. package/src/proxy/push-policy.ts +158 -0
  240. package/src/proxy/request-credential.ts +47 -0
  241. package/src/proxy/smart-http-config.ts +158 -0
  242. package/src/reference/apply-actions.ts +96 -0
  243. package/src/reference/branch-methods.ts +105 -0
  244. package/src/reference/bytes.ts +66 -0
  245. package/src/reference/clock.ts +19 -0
  246. package/src/reference/commit-method.ts +97 -0
  247. package/src/reference/file-map.ts +35 -0
  248. package/src/reference/hash.ts +25 -0
  249. package/src/reference/history.ts +78 -0
  250. package/src/reference/lifecycle-methods.ts +52 -0
  251. package/src/reference/read-methods.ts +87 -0
  252. package/src/reference/reference-gateway.ts +50 -0
  253. package/src/reference/repo-state.ts +83 -0
  254. package/src/reference/run-method.ts +25 -0
  255. package/src/reference/three-way-merge.ts +42 -0
  256. package/src/reference/trailer.ts +18 -0
  257. package/src/reference/tree-index.ts +65 -0
  258. package/src/reference/write-commit.ts +44 -0
  259. package/src/rpc/commit-exists.ts +46 -0
  260. package/src/rpc/commit.ts +156 -0
  261. package/src/rpc/list-tree.ts +78 -0
  262. package/src/rpc/log.ts +51 -0
  263. package/src/rpc/mint-read-token.ts +59 -0
  264. package/src/rpc/promote.ts +72 -0
  265. package/src/rpc/read-file.ts +75 -0
  266. package/src/rpc/repo-lifecycle.ts +103 -0
  267. package/src/rpc/resolve-ref.ts +41 -0
  268. package/src/rpc/sync-branch.ts +149 -0
  269. package/src/schemas/commit-action.ts +157 -0
  270. package/src/schemas/commit.ts +43 -0
  271. package/src/schemas/content-encoding.ts +58 -0
  272. package/src/schemas/examples.ts +24 -0
  273. package/src/schemas/gateway-config.ts +116 -0
  274. package/src/schemas/gateway-error-body.ts +230 -0
  275. package/src/schemas/identity.ts +57 -0
  276. package/src/schemas/names.ts +126 -0
  277. package/src/schemas/ref-update.ts +38 -0
  278. package/src/schemas/sha.ts +20 -0
  279. package/src/schemas/tree-entry.ts +72 -0
  280. package/src/storage/git-remote.ts +58 -0
  281. package/src/storage/storage-backend.ts +65 -0
  282. package/src/storage/storage-errors.ts +24 -0
  283. package/src/storage/storage-input.ts +14 -0
  284. package/src/storage/storage-read.ts +45 -0
  285. package/src/storage/storage-repo-info.ts +46 -0
  286. package/src/storage/storage-tree-entry.ts +20 -0
@@ -0,0 +1,66 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import type { ContentEncoding } from '../schemas/content-encoding.ts';
3
+
4
+ const encoder = new TextEncoder();
5
+ const strictDecoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
6
+
7
+ /** UTF-8 bytes of a string. */
8
+ export function utf8(text: string): Uint8Array {
9
+ return encoder.encode(text);
10
+ }
11
+
12
+ /** Standard padded base64 of some bytes. */
13
+ export function toBase64(bytes: Uint8Array): string {
14
+ let binary = '';
15
+ for (const byte of bytes) binary += String.fromCodePoint(byte);
16
+ return btoa(binary);
17
+ }
18
+
19
+ /** The bytes a standard padded base64 string encodes; the caller has validated the string. */
20
+ export function fromBase64(text: string): Uint8Array {
21
+ const binary = atob(text);
22
+ const bytes = new Uint8Array(binary.length);
23
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.codePointAt(index) ?? 0;
24
+ return bytes;
25
+ }
26
+
27
+ /** The bytes of content carried in the given encoding. */
28
+ export function decodeContent(content: string, encoding: ContentEncoding): Uint8Array {
29
+ return encoding === 'base64' ? fromBase64(content) : utf8(content);
30
+ }
31
+
32
+ /**
33
+ * Content for a read: text when asked for and the bytes are valid UTF-8 that round-trips
34
+ * exactly, base64 otherwise.
35
+ */
36
+ export function encodeContent(
37
+ bytes: Uint8Array,
38
+ preferred: ContentEncoding,
39
+ ): { encoding: ContentEncoding; content: string } {
40
+ if (preferred === 'text') {
41
+ try {
42
+ return { encoding: 'text', content: strictDecoder.decode(bytes) };
43
+ } catch {
44
+ // Not valid UTF-8: fall through to base64.
45
+ }
46
+ }
47
+ return { encoding: 'base64', content: toBase64(bytes) };
48
+ }
49
+
50
+ /** True when two byte arrays hold the same bytes. */
51
+ export function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
52
+ if (a.length !== b.length) return false;
53
+ return a.every((byte, index) => byte === b[index]);
54
+ }
55
+
56
+ /** Compares two strings by their UTF-8 bytes, the order git sorts paths in. */
57
+ export function byteOrder(a: string, b: string): number {
58
+ const left = utf8(a);
59
+ const right = utf8(b);
60
+ const length = Math.min(left.length, right.length);
61
+ for (let index = 0; index < length; index += 1) {
62
+ const diff = (left[index] ?? 0) - (right[index] ?? 0);
63
+ if (diff !== 0) return diff;
64
+ }
65
+ return left.length - right.length;
66
+ }
@@ -0,0 +1,19 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ /** A source of the current time. */
4
+ export type Clock = () => Date;
5
+
6
+ /**
7
+ * A deterministic clock for tests: the first call returns `start`, each later call `stepMs`
8
+ * milliseconds after the one before. With it, the reference implementation's ids are the same on
9
+ * every run.
10
+ */
11
+ export function steppingClock(start = '2026-01-01T00:00:00.000Z', stepMs = 1000): Clock {
12
+ let next = Date.parse(start);
13
+ if (Number.isNaN(next)) throw new RangeError(`steppingClock: invalid start time ${start}`);
14
+ return () => {
15
+ const now = new Date(next);
16
+ next += stepMs;
17
+ return now;
18
+ };
19
+ }
@@ -0,0 +1,97 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { RPC_SCHEMAS, type RpcInput, type RpcOutput, type RpcParsedInput } from '../git-gateway.ts';
3
+ import { gatewayError } from '../gateway-error.ts';
4
+ import type { Commit } from '../schemas/commit.ts';
5
+ import { ZERO_SHA } from '../schemas/sha.ts';
6
+ import { applyActions } from './apply-actions.ts';
7
+ import { buildTreeIndex } from './tree-index.ts';
8
+ import { walkHistory } from './history.ts';
9
+ import { lookupIn, requireRepo, withRepoLock, type ReferenceContext, type RepoState } from './repo-state.ts';
10
+ import { runMethod } from './run-method.ts';
11
+ import { appendIdempotencyTrailer } from './trailer.ts';
12
+ import { writeCommit } from './write-commit.ts';
13
+
14
+ type Input = RpcParsedInput<'commit'>;
15
+
16
+ /** The commit carrying `key` within the configured lookback window of the branch, if any. */
17
+ function findReplay(
18
+ context: ReferenceContext,
19
+ repo: RepoState,
20
+ head: string,
21
+ key: string,
22
+ ): Commit | undefined {
23
+ const { maxCommits, maxAgeSeconds } = context.config.idempotency;
24
+ const oldest = new Date(context.now().getTime() - maxAgeSeconds * 1000).toISOString();
25
+ const window = walkHistory(lookupIn(repo), head).slice(0, maxCommits);
26
+ for (const commit of window) {
27
+ if (commit.committer.date < oldest) return undefined;
28
+ if (commit.idempotencyKey === key) return commit;
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ /** The commit the new one builds on: the branch head, the start branch head, or none for a root commit. */
34
+ function baseOf(repo: RepoState, input: Input, head: string | null): string | null {
35
+ if (head !== null) return head;
36
+ if (input.startBranch !== undefined) {
37
+ const start = repo.branches.get(input.startBranch);
38
+ if (start === undefined) {
39
+ throw gatewayError('ref_not_found', `Branch not found: ${input.startBranch}`, {
40
+ ref: input.startBranch,
41
+ });
42
+ }
43
+ return start;
44
+ }
45
+ if (repo.branches.size === 0) return null;
46
+ throw gatewayError('ref_not_found', `Branch not found: ${input.branch}`, { ref: input.branch });
47
+ }
48
+
49
+ async function commitLocked(
50
+ context: ReferenceContext,
51
+ repo: RepoState,
52
+ input: Input,
53
+ ): Promise<RpcOutput<'commit'>> {
54
+ const head = repo.branches.get(input.branch) ?? null;
55
+ if (head !== null) {
56
+ const replay = findReplay(context, repo, head, input.idempotencyKey);
57
+ if (replay !== undefined) return { status: 'replayed', commit: replay };
58
+ }
59
+ if (input.expectedHead !== undefined && input.expectedHead !== head) {
60
+ throw gatewayError('stale_head', `Branch ${input.branch} moved`, {
61
+ branch: input.branch,
62
+ expectedHead: input.expectedHead,
63
+ actualHead: head,
64
+ });
65
+ }
66
+ const base = baseOf(repo, input, head);
67
+ const baseCommit = base === null ? undefined : repo.commits.get(base);
68
+ const files = await applyActions(baseCommit?.files ?? new Map(), input.actions);
69
+ const baseTree = baseCommit?.tree.rootSha ?? (await buildTreeIndex(new Map())).rootSha;
70
+ const nextTree = (await buildTreeIndex(files)).rootSha;
71
+ if (nextTree === baseTree) return { status: 'noop', head };
72
+ const stored = await writeCommit(repo, {
73
+ parents: base === null ? [] : [base],
74
+ files,
75
+ author: input.author,
76
+ committer: input.committer ?? input.author,
77
+ message: appendIdempotencyTrailer(input.message, input.idempotencyKey),
78
+ date: context.now().toISOString(),
79
+ });
80
+ repo.branches.set(input.branch, stored.commit.sha);
81
+ return {
82
+ status: 'committed',
83
+ commit: stored.commit,
84
+ refUpdate: { ref: `refs/heads/${input.branch}`, oldSha: head ?? ZERO_SHA, newSha: stored.commit.sha },
85
+ };
86
+ }
87
+
88
+ /** The reference `commit`: GitLab Commits API rules, idempotency replay, stale-head refusal, no-op detection. */
89
+ export function referenceCommit(
90
+ context: ReferenceContext,
91
+ input: RpcInput<'commit'>,
92
+ ): Promise<RpcOutput<'commit'>> {
93
+ return runMethod(RPC_SCHEMAS.commit, input, async (parsed) => {
94
+ const repo = requireRepo(context, parsed.repo);
95
+ return withRepoLock(repo, () => commitLocked(context, repo, parsed));
96
+ });
97
+ }
@@ -0,0 +1,35 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ /** One file of the in-memory model: its bytes, executable bit and blob id. */
4
+ export interface StoredFile {
5
+ readonly bytes: Uint8Array;
6
+ readonly executable: boolean;
7
+ readonly sha: string;
8
+ }
9
+
10
+ /** A snapshot of a repository: every file by full path. Directories are implied by paths. */
11
+ export type FileMap = ReadonlyMap<string, StoredFile>;
12
+
13
+ /** Every proper parent directory of a path, shallowest first: `a/b/c` → `a`, `a/b`. */
14
+ export function parentDirectories(path: string): string[] {
15
+ const segments = path.split('/');
16
+ return segments.slice(0, -1).map((_, index) => segments.slice(0, index + 1).join('/'));
17
+ }
18
+
19
+ /** True when some file lies beneath `path`, i.e. it is a directory of the snapshot. */
20
+ export function isDirectory(files: FileMap, path: string): boolean {
21
+ const prefix = `${path}/`;
22
+ for (const key of files.keys()) if (key.startsWith(prefix)) return true;
23
+ return false;
24
+ }
25
+
26
+ /** The shallowest parent of `path` that is a file, or undefined when none is. */
27
+ export function fileParent(files: FileMap, path: string): string | undefined {
28
+ return parentDirectories(path).find((parent) => files.has(parent));
29
+ }
30
+
31
+ /** True when two stored files have the same content and mode. */
32
+ export function sameFile(a: StoredFile | undefined, b: StoredFile | undefined): boolean {
33
+ if (a === undefined || b === undefined) return a === b;
34
+ return a.sha === b.sha && a.executable === b.executable;
35
+ }
@@ -0,0 +1,25 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { utf8 } from './bytes.ts';
3
+
4
+ /** Lowercase hex SHA-1 of some bytes, through Web Crypto (Bun, Node, Workers and browsers). */
5
+ export async function sha1Hex(bytes: Uint8Array): Promise<string> {
6
+ const digest = await crypto.subtle.digest('SHA-1', bytes);
7
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
8
+ }
9
+
10
+ /** The git blob id of some bytes: SHA-1 of "blob <size>\0" followed by the bytes. */
11
+ export async function blobSha(bytes: Uint8Array): Promise<string> {
12
+ const header = utf8(`blob ${bytes.length}\0`);
13
+ const object = new Uint8Array(header.length + bytes.length);
14
+ object.set(header);
15
+ object.set(bytes, header.length);
16
+ return sha1Hex(object);
17
+ }
18
+
19
+ /**
20
+ * A deterministic id for a tree or commit of the in-memory model: SHA-1 of the kind and a
21
+ * canonical text form. Equal content gives equal ids; it is not git's object encoding.
22
+ */
23
+ export async function modelSha(kind: 'tree' | 'commit', canonical: string): Promise<string> {
24
+ return sha1Hex(utf8(`${kind}\0${canonical}`));
25
+ }
@@ -0,0 +1,78 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import type { Commit } from '../schemas/commit.ts';
3
+
4
+ /** Looks up a stored commit by id. */
5
+ export type CommitLookup = (sha: string) => Commit | undefined;
6
+
7
+ /** Every commit reachable from `start`, itself included. */
8
+ export function ancestors(lookup: CommitLookup, start: string): Set<string> {
9
+ const seen = new Set<string>();
10
+ const stack = [start];
11
+ for (let sha = stack.pop(); sha !== undefined; sha = stack.pop()) {
12
+ if (seen.has(sha)) continue;
13
+ const commit = lookup(sha);
14
+ if (commit === undefined) continue;
15
+ seen.add(sha);
16
+ stack.push(...commit.parents);
17
+ }
18
+ return seen;
19
+ }
20
+
21
+ /** True when `ancestor` is reachable from `descendant` (a commit contains itself). */
22
+ export function contains(lookup: CommitLookup, descendant: string, ancestor: string): boolean {
23
+ return ancestors(lookup, descendant).has(ancestor);
24
+ }
25
+
26
+ /**
27
+ * History reachable from `start`, newest committer date first, never listing a commit before
28
+ * one of its children; ties go to the commit discovered last (as git log does).
29
+ */
30
+ export function walkHistory(lookup: CommitLookup, start: string): Commit[] {
31
+ const reachable = ancestors(lookup, start);
32
+ const pendingChildren = new Map<string, number>();
33
+ for (const sha of reachable) {
34
+ for (const parent of lookup(sha)?.parents ?? []) {
35
+ pendingChildren.set(parent, (pendingChildren.get(parent) ?? 0) + 1);
36
+ }
37
+ }
38
+ const ordered: Commit[] = [];
39
+ const ready: Commit[] = [];
40
+ const first = lookup(start);
41
+ if (first !== undefined) ready.push(first);
42
+ while (ready.length > 0) {
43
+ let pick = ready.length - 1;
44
+ ready.forEach((candidate, index) => {
45
+ const best = ready[pick];
46
+ if (best !== undefined && candidate.committer.date > best.committer.date) pick = index;
47
+ });
48
+ const [commit] = ready.splice(pick, 1);
49
+ if (commit === undefined) break;
50
+ ordered.push(commit);
51
+ for (const parent of commit.parents) {
52
+ const left = (pendingChildren.get(parent) ?? 1) - 1;
53
+ pendingChildren.set(parent, left);
54
+ const parentCommit = lookup(parent);
55
+ if (left === 0 && parentCommit !== undefined) ready.push(parentCommit);
56
+ }
57
+ }
58
+ return ordered;
59
+ }
60
+
61
+ /**
62
+ * The best common ancestor of two commits: a common ancestor no other common ancestor descends
63
+ * from. When several qualify (criss-cross history) the newest by committer date wins, then the
64
+ * lowest id. Null when the histories are unrelated.
65
+ */
66
+ export function mergeBase(lookup: CommitLookup, a: string, b: string): string | null {
67
+ const fromB = ancestors(lookup, b);
68
+ const common = [...ancestors(lookup, a)].filter((sha) => fromB.has(sha));
69
+ const best = common.filter(
70
+ (candidate) => !common.some((other) => other !== candidate && contains(lookup, other, candidate)),
71
+ );
72
+ const ranked = best.toSorted((x, y) => {
73
+ const dx = lookup(x)?.committer.date ?? '';
74
+ const dy = lookup(y)?.committer.date ?? '';
75
+ return dx === dy ? (x < y ? -1 : 1) : dx > dy ? -1 : 1;
76
+ });
77
+ return ranked[0] ?? null;
78
+ }
@@ -0,0 +1,52 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { RPC_SCHEMAS, type RpcInput, type RpcOutput } from '../git-gateway.ts';
3
+ import { gatewayError } from '../gateway-error.ts';
4
+ import { utf8 } from './bytes.ts';
5
+ import { sha1Hex } from './hash.ts';
6
+ import { remoteUrlOf, requireRepo, type ReferenceContext } from './repo-state.ts';
7
+ import { runMethod } from './run-method.ts';
8
+
9
+ /** The reference `createRepo`. */
10
+ export function referenceCreateRepo(
11
+ context: ReferenceContext,
12
+ input: RpcInput<'createRepo'>,
13
+ ): Promise<RpcOutput<'createRepo'>> {
14
+ return runMethod(RPC_SCHEMAS.createRepo, input, async ({ repo, defaultBranch }) => {
15
+ if (context.repos.has(repo))
16
+ throw gatewayError('repo_exists', `Repository already exists: ${repo}`, { repo });
17
+ const createdAt = context.now().toISOString();
18
+ context.repos.set(repo, {
19
+ name: repo,
20
+ defaultBranch,
21
+ createdAt,
22
+ branches: new Map(),
23
+ commits: new Map(),
24
+ lock: Promise.resolve(),
25
+ });
26
+ return { name: repo, defaultBranch, createdAt, remoteUrl: remoteUrlOf(context.config, repo) };
27
+ });
28
+ }
29
+
30
+ /** The reference `deleteRepo`. */
31
+ export function referenceDeleteRepo(
32
+ context: ReferenceContext,
33
+ input: RpcInput<'deleteRepo'>,
34
+ ): Promise<RpcOutput<'deleteRepo'>> {
35
+ return runMethod(RPC_SCHEMAS.deleteRepo, input, async ({ repo }) => ({
36
+ deleted: context.repos.delete(repo),
37
+ }));
38
+ }
39
+
40
+ /** The reference `mintReadToken`: an opaque, deterministic token (it authorizes nothing in memory). */
41
+ export function referenceMintReadToken(
42
+ context: ReferenceContext,
43
+ input: RpcInput<'mintReadToken'>,
44
+ ): Promise<RpcOutput<'mintReadToken'>> {
45
+ return runMethod(RPC_SCHEMAS.mintReadToken, input, async ({ repo, ttlSeconds }) => {
46
+ requireRepo(context, repo);
47
+ const now = context.now();
48
+ const expiresAt = new Date(now.getTime() + ttlSeconds * 1000).toISOString();
49
+ const token = `ggr_${await sha1Hex(utf8(`${repo}\0${now.toISOString()}\0${expiresAt}`))}`;
50
+ return { token, expiresAt, remoteUrl: remoteUrlOf(context.config, repo) };
51
+ });
52
+ }
@@ -0,0 +1,87 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { RPC_SCHEMAS, type RpcInput, type RpcOutput } from '../git-gateway.ts';
3
+ import { encodeContent } from './bytes.ts';
4
+ import { contains, walkHistory } from './history.ts';
5
+ import {
6
+ lookupIn,
7
+ requireRepo,
8
+ requireRevision,
9
+ resolveRevision,
10
+ type ReferenceContext,
11
+ } from './repo-state.ts';
12
+ import { runMethod } from './run-method.ts';
13
+ import { entriesBeneath } from './tree-index.ts';
14
+
15
+ /** The reference `readFile`. */
16
+ export function referenceReadFile(
17
+ context: ReferenceContext,
18
+ input: RpcInput<'readFile'>,
19
+ ): Promise<RpcOutput<'readFile'>> {
20
+ return runMethod(RPC_SCHEMAS.readFile, input, async ({ repo, ref, path, encoding }) => {
21
+ const stored = requireRevision(requireRepo(context, repo), ref);
22
+ const file = stored.files.get(path);
23
+ if (file === undefined) return null;
24
+ return {
25
+ path,
26
+ commit: stored.commit.sha,
27
+ sha: file.sha,
28
+ size: file.bytes.length,
29
+ executable: file.executable,
30
+ ...encodeContent(file.bytes, encoding),
31
+ };
32
+ });
33
+ }
34
+
35
+ /** The reference `listTree`. */
36
+ export function referenceListTree(
37
+ context: ReferenceContext,
38
+ input: RpcInput<'listTree'>,
39
+ ): Promise<RpcOutput<'listTree'>> {
40
+ return runMethod(RPC_SCHEMAS.listTree, input, async ({ repo, ref, path, recursive }) => {
41
+ const stored = requireRevision(requireRepo(context, repo), ref);
42
+ const dir = path ?? '';
43
+ if (!stored.tree.directories.has(dir)) return null;
44
+ return {
45
+ commit: stored.commit.sha,
46
+ path: path ?? null,
47
+ entries: entriesBeneath(stored.tree, dir, recursive),
48
+ };
49
+ });
50
+ }
51
+
52
+ /** The reference `resolveRef`. */
53
+ export function referenceResolveRef(
54
+ context: ReferenceContext,
55
+ input: RpcInput<'resolveRef'>,
56
+ ): Promise<RpcOutput<'resolveRef'>> {
57
+ return runMethod(RPC_SCHEMAS.resolveRef, input, async ({ repo, ref }) => {
58
+ const stored = resolveRevision(requireRepo(context, repo), ref);
59
+ return stored === undefined ? null : { sha: stored.commit.sha };
60
+ });
61
+ }
62
+
63
+ /** The reference `log`. */
64
+ export function referenceLog(context: ReferenceContext, input: RpcInput<'log'>): Promise<RpcOutput<'log'>> {
65
+ return runMethod(RPC_SCHEMAS.log, input, async ({ repo, ref, limit, offset, since }) => {
66
+ const state = requireRepo(context, repo);
67
+ const start = requireRevision(state, ref);
68
+ const history = walkHistory(lookupIn(state), start.commit.sha).filter(
69
+ (commit) => since === undefined || Date.parse(commit.committer.date) >= Date.parse(since),
70
+ );
71
+ return { commits: history.slice(offset, offset + limit), hasMore: history.length > offset + limit };
72
+ });
73
+ }
74
+
75
+ /** The reference `commitExists`. */
76
+ export function referenceCommitExists(
77
+ context: ReferenceContext,
78
+ input: RpcInput<'commitExists'>,
79
+ ): Promise<RpcOutput<'commitExists'>> {
80
+ return runMethod(RPC_SCHEMAS.commitExists, input, async ({ repo, sha, branch }) => {
81
+ const state = requireRepo(context, repo);
82
+ if (!state.commits.has(sha)) return { exists: false };
83
+ if (branch === undefined) return { exists: true };
84
+ const head = state.branches.get(branch);
85
+ return { exists: head !== undefined && contains(lookupIn(state), head, sha) };
86
+ });
87
+ }
@@ -0,0 +1,50 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import type { GitGateway } from '../git-gateway.ts';
3
+ import { GatewayConfig, type GatewayConfigInput } from '../schemas/gateway-config.ts';
4
+ import { referenceSyncBranch, referencePromote } from './branch-methods.ts';
5
+ import type { Clock } from './clock.ts';
6
+ import { referenceCommit } from './commit-method.ts';
7
+ import { referenceCreateRepo, referenceDeleteRepo, referenceMintReadToken } from './lifecycle-methods.ts';
8
+ import {
9
+ referenceCommitExists,
10
+ referenceListTree,
11
+ referenceLog,
12
+ referenceReadFile,
13
+ referenceResolveRef,
14
+ } from './read-methods.ts';
15
+ import type { ReferenceContext } from './repo-state.ts';
16
+
17
+ /** Options for {@link createReferenceGateway}. */
18
+ export interface ReferenceGatewayOptions {
19
+ /** Gateway configuration; every field has a default. */
20
+ readonly config?: GatewayConfigInput;
21
+ /** Source of commit dates, token expiry and the idempotency window; defaults to the system clock. */
22
+ readonly now?: Clock;
23
+ }
24
+
25
+ /**
26
+ * The in-memory reference implementation of {@link GitGateway}: every rule of the contract on
27
+ * plain objects, no git objects and no I/O. Use it to develop and test consumers before (and
28
+ * alongside) the real gateway, and as the oracle the real gateway is tested against. Blob ids are
29
+ * git's; tree and commit ids are deterministic for a given clock (see `steppingClock`).
30
+ */
31
+ export function createReferenceGateway(options: ReferenceGatewayOptions = {}): GitGateway {
32
+ const context: ReferenceContext = {
33
+ config: GatewayConfig.parse(options.config ?? {}),
34
+ now: options.now ?? (() => new Date()),
35
+ repos: new Map(),
36
+ };
37
+ return {
38
+ commit: (input) => referenceCommit(context, input),
39
+ readFile: (input) => referenceReadFile(context, input),
40
+ listTree: (input) => referenceListTree(context, input),
41
+ resolveRef: (input) => referenceResolveRef(context, input),
42
+ log: (input) => referenceLog(context, input),
43
+ commitExists: (input) => referenceCommitExists(context, input),
44
+ syncBranch: (input) => referenceSyncBranch(context, input),
45
+ promote: (input) => referencePromote(context, input),
46
+ createRepo: (input) => referenceCreateRepo(context, input),
47
+ deleteRepo: (input) => referenceDeleteRepo(context, input),
48
+ mintReadToken: (input) => referenceMintReadToken(context, input),
49
+ };
50
+ }
@@ -0,0 +1,83 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { gatewayError } from '../gateway-error.ts';
3
+ import type { Commit } from '../schemas/commit.ts';
4
+ import type { GatewayConfig } from '../schemas/gateway-config.ts';
5
+ import { Sha } from '../schemas/sha.ts';
6
+ import type { Clock } from './clock.ts';
7
+ import type { FileMap } from './file-map.ts';
8
+ import type { CommitLookup } from './history.ts';
9
+ import type { TreeIndex } from './tree-index.ts';
10
+
11
+ /** A commit of the in-memory model with the snapshot it records. */
12
+ export interface StoredCommit {
13
+ readonly commit: Commit;
14
+ readonly files: FileMap;
15
+ readonly tree: TreeIndex;
16
+ }
17
+
18
+ /** One in-memory repository. */
19
+ export interface RepoState {
20
+ readonly name: string;
21
+ readonly defaultBranch: string;
22
+ readonly createdAt: string;
23
+ readonly branches: Map<string, string>;
24
+ readonly commits: Map<string, StoredCommit>;
25
+ /** Tail of the queue that serializes writes to this repository. */
26
+ lock: Promise<unknown>;
27
+ }
28
+
29
+ /** Everything the reference implementation's methods share. */
30
+ export interface ReferenceContext {
31
+ readonly config: GatewayConfig;
32
+ readonly now: Clock;
33
+ readonly repos: Map<string, RepoState>;
34
+ }
35
+
36
+ /** The repository, or repo_not_found. */
37
+ export function requireRepo(context: ReferenceContext, name: string): RepoState {
38
+ const repo = context.repos.get(name);
39
+ if (repo === undefined)
40
+ throw gatewayError('repo_not_found', `Repository not found: ${name}`, { repo: name });
41
+ return repo;
42
+ }
43
+
44
+ /** A commit lookup over one repository. */
45
+ export function lookupIn(repo: RepoState): CommitLookup {
46
+ return (sha) => repo.commits.get(sha)?.commit;
47
+ }
48
+
49
+ /** The commit a revision names (a commit id, or a branch's head), or undefined. */
50
+ export function resolveRevision(repo: RepoState, revision: string): StoredCommit | undefined {
51
+ const sha = Sha.safeParse(revision).success ? revision : repo.branches.get(revision);
52
+ return sha === undefined ? undefined : repo.commits.get(sha);
53
+ }
54
+
55
+ /** The commit a revision names, or ref_not_found. */
56
+ export function requireRevision(repo: RepoState, revision: string): StoredCommit {
57
+ const stored = resolveRevision(repo, revision);
58
+ if (stored === undefined)
59
+ throw gatewayError('ref_not_found', `Ref not found: ${revision}`, { ref: revision });
60
+ return stored;
61
+ }
62
+
63
+ /** The head of a branch, or ref_not_found. */
64
+ export function requireBranchHead(repo: RepoState, branch: string): string {
65
+ const head = repo.branches.get(branch);
66
+ if (head === undefined) throw gatewayError('ref_not_found', `Branch not found: ${branch}`, { ref: branch });
67
+ return head;
68
+ }
69
+
70
+ /** Runs `work` after every earlier write to the repository has settled, so writes never interleave. */
71
+ export function withRepoLock<T>(repo: RepoState, work: () => Promise<T>): Promise<T> {
72
+ const run = repo.lock.then(work, work);
73
+ repo.lock = run.catch(() => undefined);
74
+ return run;
75
+ }
76
+
77
+ /** The clone URL of a repository under the configured public base URL. */
78
+ export function remoteUrlOf(config: GatewayConfig, repo: string): string {
79
+ // A scan from the end, not /\/+$/, which retries from every slash run (polynomial time).
80
+ let end = config.publicBaseUrl.length;
81
+ while (end > 0 && config.publicBaseUrl.charCodeAt(end - 1) === 47) end -= 1;
82
+ return `${config.publicBaseUrl.slice(0, end)}/${repo}.git`;
83
+ }
@@ -0,0 +1,25 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import type { z } from 'zod';
3
+
4
+ import { invalidInput } from '../gateway-error.ts';
5
+
6
+ /** The input and output schema of one RPC method. */
7
+ export interface MethodSchemas<I extends z.ZodType, O extends z.ZodType> {
8
+ readonly input: I;
9
+ readonly output: O;
10
+ }
11
+
12
+ /**
13
+ * Runs one RPC method the way every implementation must: parse the input (invalid_input on
14
+ * failure), do the work, and parse the result with the output schema, so the reference can never
15
+ * return something its own contract rejects.
16
+ */
17
+ export async function runMethod<I extends z.ZodType, O extends z.ZodType>(
18
+ schemas: MethodSchemas<I, O>,
19
+ input: unknown,
20
+ work: (parsed: z.output<I>) => Promise<z.input<O>>,
21
+ ): Promise<z.output<O>> {
22
+ const parsed = schemas.input.safeParse(input);
23
+ if (!parsed.success) throw invalidInput(parsed.error);
24
+ return schemas.output.parse(await work(parsed.data));
25
+ }
@@ -0,0 +1,42 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { byteOrder } from './bytes.ts';
3
+ import { parentDirectories, sameFile, type FileMap, type StoredFile } from './file-map.ts';
4
+
5
+ /** The result of a file-level three-way merge. */
6
+ export type MergeResult =
7
+ | { readonly kind: 'merged'; readonly files: FileMap }
8
+ | { readonly kind: 'conflict'; readonly paths: readonly string[] };
9
+
10
+ /**
11
+ * Merges two snapshots file by file against their merge base. A path changed on only one side
12
+ * takes that side; a path changed identically on both takes either; a path changed differently on
13
+ * both sides is a conflict, as is a file on one side where the merged result has a directory.
14
+ */
15
+ export function threeWayMerge(base: FileMap, ours: FileMap, theirs: FileMap): MergeResult {
16
+ const merged = new Map<string, StoredFile>();
17
+ const conflicts = new Set<string>();
18
+ const paths = new Set([...base.keys(), ...ours.keys(), ...theirs.keys()]);
19
+ for (const path of paths) {
20
+ const b = base.get(path);
21
+ const o = ours.get(path);
22
+ const t = theirs.get(path);
23
+ let pick: StoredFile | undefined;
24
+ if (sameFile(o, t) || sameFile(t, b)) pick = o;
25
+ else if (sameFile(o, b)) pick = t;
26
+ else {
27
+ conflicts.add(path);
28
+ continue;
29
+ }
30
+ if (pick !== undefined) merged.set(path, pick);
31
+ }
32
+ for (const path of merged.keys()) {
33
+ for (const parent of parentDirectories(path)) {
34
+ if (merged.has(parent) || conflicts.has(parent)) {
35
+ conflicts.add(parent);
36
+ conflicts.add(path);
37
+ }
38
+ }
39
+ }
40
+ if (conflicts.size > 0) return { kind: 'conflict', paths: [...conflicts].toSorted(byteOrder) };
41
+ return { kind: 'merged', files: merged };
42
+ }