@fabrika/github-app 0.8.1 → 0.9.0-dev.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/github-app",
3
- "version": "0.8.1",
3
+ "version": "0.9.0-dev.2",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -9,12 +9,13 @@
9
9
  },
10
10
  "files": [
11
11
  "src",
12
- "!src/**/__tests__/**"
12
+ "!src/**/__tests__/**",
13
+ "types"
13
14
  ],
14
15
  "exports": {
15
16
  ".": {
16
17
  "bun": "./src/index.ts",
17
- "types": "./src/index.ts",
18
+ "types": "./types/src/index.d.ts",
18
19
  "default": "./src/index.ts"
19
20
  }
20
21
  },
package/src/errors.ts CHANGED
@@ -2,8 +2,16 @@ export function configurationError(): Error {
2
2
  return new Error('GitHub App configuration is invalid')
3
3
  }
4
4
 
5
- export function requestStatusError(status: number): Error {
6
- return new Error(`GitHub App request failed with status ${status}`)
5
+ /** GitHub answered a request with an unexpected status; the message never carries GitHub's response text. */
6
+ export class GitHubRequestError extends Error {
7
+ constructor(readonly status: number) {
8
+ super(`GitHub App request failed with status ${status}`)
9
+ this.name = 'GitHubRequestError'
10
+ }
11
+ }
12
+
13
+ export function requestStatusError(status: number): GitHubRequestError {
14
+ return new GitHubRequestError(status)
7
15
  }
8
16
 
9
17
  export function responseError(): Error {
package/src/index.ts CHANGED
@@ -1,9 +1,14 @@
1
1
  export { GitHubAppClient } from './client'
2
- export { GitHubBranchConflictError, GitHubNotFoundError, GitHubStaleHeadError } from './errors'
2
+ export { GitHubBranchConflictError, GitHubNotFoundError, GitHubRequestError, GitHubStaleHeadError } from './errors'
3
3
  export { buildGitHubAppManifest, exchangeGitHubAppManifestCode } from './manifest'
4
4
  export type {
5
+ GitHubBlobRead,
6
+ GitHubBlobRef,
7
+ GitHubChangedFile,
8
+ GitHubChangedFileStatus,
5
9
  GitHubCommit,
6
10
  GitHubCommitFilesInput,
11
+ GitHubComparison,
7
12
  GitHubCreateBranchInput,
8
13
  GitHubFileChange,
9
14
  GitHubFileRead,
@@ -15,6 +20,8 @@ export type {
15
20
  GitHubTextFile,
16
21
  GitHubTreeEntry,
17
22
  GitHubTreeListing,
23
+ GitHubUnreadablePath,
24
+ GitHubUnreadableReason,
18
25
  } from './repository-types'
19
26
  export { pemToPkcs8 } from './signing'
20
27
  export type {
@@ -32,11 +32,59 @@ export interface GitHubTextFile {
32
32
  readonly content: string
33
33
  }
34
34
 
35
+ /**
36
+ * Why a requested path was not read: `missing` (no such path), `not_a_file` (a directory, symlink or submodule),
37
+ * `too_large` (over the per-file bound), `binary` (not UTF-8), `budget` (past the read's total byte bound).
38
+ */
39
+ export type GitHubUnreadableReason = 'missing' | 'not_a_file' | 'too_large' | 'binary' | 'budget'
40
+
41
+ export interface GitHubUnreadablePath {
42
+ readonly path: string
43
+ readonly reason: GitHubUnreadableReason
44
+ }
45
+
35
46
  export interface GitHubFileRead {
36
47
  readonly commitSha: string
37
48
  readonly files: readonly GitHubTextFile[]
38
- /** Requested paths that do not exist (or are not regular UTF-8 files) at `commitSha`. */
39
- readonly missingPaths: readonly string[]
49
+ /** Requested paths that were not read at `commitSha`, in request order. */
50
+ readonly unreadable: readonly GitHubUnreadablePath[]
51
+ }
52
+
53
+ /** A blob named by a tree listing of the same repository. */
54
+ export interface GitHubBlobRef {
55
+ readonly path: string
56
+ readonly sha: string
57
+ readonly size: number
58
+ }
59
+
60
+ export interface GitHubBlobRead {
61
+ readonly files: readonly GitHubTextFile[]
62
+ /** Blobs that were not read (`too_large`, `budget` or `binary`), in request order. */
63
+ readonly unreadable: readonly GitHubUnreadablePath[]
64
+ }
65
+
66
+ export type GitHubChangedFileStatus = 'added' | 'removed' | 'modified' | 'renamed' | 'copied' | 'changed' | 'unchanged'
67
+
68
+ export interface GitHubChangedFile {
69
+ readonly path: string
70
+ /** The path before a rename or copy. */
71
+ readonly previousPath: string | null
72
+ readonly status: GitHubChangedFileStatus
73
+ readonly additions: number
74
+ readonly deletions: number
75
+ /** The unified diff hunk; null when GitHub omits it (a binary file or a very large change). */
76
+ readonly patch: string | null
77
+ }
78
+
79
+ export interface GitHubComparison {
80
+ readonly baseSha: string
81
+ readonly headSha: string
82
+ /** Commits on head that are not on base. */
83
+ readonly aheadBy: number
84
+ readonly behindBy: number
85
+ readonly files: readonly GitHubChangedFile[]
86
+ /** GitHub lists at most 300 files of a comparison; true when it listed that many, so more may have changed. */
87
+ readonly filesCapped: boolean
40
88
  }
41
89
 
42
90
  export interface GitHubFileChange {
@@ -84,8 +132,14 @@ export interface GitHubRepositoryClient {
84
132
  readRef(branch: string, signal?: AbortSignal): Promise<GitHubRef | null>
85
133
  readTree(commitSha: string, directory?: string, signal?: AbortSignal): Promise<GitHubTreeListing>
86
134
  readFiles(commitSha: string, paths: readonly string[], signal?: AbortSignal): Promise<GitHubFileRead>
135
+ /** Reads listed blobs as text without walking the tree again, within the same per-file and total bounds as `readFiles`. */
136
+ readBlobTexts(blobs: readonly GitHubBlobRef[], signal?: AbortSignal): Promise<GitHubBlobRead>
137
+ /** The changes from the merge base of `baseSha` and `headSha` to `headSha`. */
138
+ compareCommits(baseSha: string, headSha: string, signal?: AbortSignal): Promise<GitHubComparison>
87
139
  /** Idempotent: an existing branch already at `fromSha` is returned; one elsewhere is a conflict. */
88
140
  createBranch(input: GitHubCreateBranchInput): Promise<GitHubRef>
141
+ /** Idempotent: `deleted` is false when the branch did not exist. GitHub closes an open pull request from it. */
142
+ deleteBranch(branch: string, signal?: AbortSignal): Promise<{ readonly deleted: boolean }>
89
143
  /** Creates exactly one commit on top of `expectedHeadSha` and moves the branch to it without force. */
90
144
  commitFiles(input: GitHubCommitFilesInput): Promise<GitHubCommit>
91
145
  openPullRequest(input: GitHubOpenPullRequestInput): Promise<GitHubPullRequestRef>
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod'
2
2
  import { configurationError, responseError } from './errors'
3
- import type { GitHubCommit, GitHubPullRequestRef, GitHubRef, GitHubTreeEntry } from './repository-types'
3
+ import type { GitHubCommit, GitHubComparison, GitHubPullRequestRef, GitHubRef, GitHubTreeEntry } from './repository-types'
4
4
  import { hasAsciiControl } from './validation'
5
5
 
6
6
  export const MAX_TREE_ENTRIES = 5000
@@ -20,6 +20,10 @@ export const MAX_PULL_REQUEST_RESPONSE_BYTES = 1024 * 1024
20
20
  // A commit echoes its message, which existing history does not bound.
21
21
  export const MAX_COMMIT_RESPONSE_BYTES = 1024 * 1024
22
22
  export const MAX_PATH_SEGMENTS = 64
23
+ /** GitHub's own bound on the files of one comparison. */
24
+ export const MAX_COMPARE_FILES = 300
25
+ // Each file of a comparison carries its patch.
26
+ export const MAX_COMPARE_RESPONSE_BYTES = 8 * 1024 * 1024
23
27
 
24
28
  const SHA_PATTERN = /^[a-f0-9]{40}$/
25
29
  const LONE_SURROGATE_PATTERN = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
@@ -137,6 +141,41 @@ export function decodeTextBlob(body: unknown, expectedSha: string, expectedSize:
137
141
  }
138
142
  }
139
143
 
144
+ const comparisonSchema = z.object({
145
+ ahead_by: z.number().int().nonnegative(),
146
+ behind_by: z.number().int().nonnegative(),
147
+ merge_base_commit: z.object({ sha: shaSchema }),
148
+ files: z.array(z.object({
149
+ filename: z.string(),
150
+ previous_filename: z.string().optional(),
151
+ status: z.enum(['added', 'removed', 'modified', 'renamed', 'copied', 'changed', 'unchanged']),
152
+ additions: z.number().int().nonnegative(),
153
+ deletions: z.number().int().nonnegative(),
154
+ patch: z.string().optional(),
155
+ })).max(MAX_COMPARE_FILES).optional(),
156
+ })
157
+
158
+ export function decodeComparison(body: unknown, headSha: string): GitHubComparison {
159
+ const result = comparisonSchema.safeParse(body)
160
+ if (!result.success) throw responseError()
161
+ const files = (result.data.files ?? []).map((file) => ({
162
+ path: file.filename,
163
+ previousPath: file.previous_filename ?? null,
164
+ status: file.status,
165
+ additions: file.additions,
166
+ deletions: file.deletions,
167
+ patch: file.patch ?? null,
168
+ }))
169
+ return {
170
+ baseSha: result.data.merge_base_commit.sha,
171
+ headSha,
172
+ aheadBy: result.data.ahead_by,
173
+ behindBy: result.data.behind_by,
174
+ files,
175
+ filesCapped: files.length === MAX_COMPARE_FILES,
176
+ }
177
+ }
178
+
140
179
  const pullRequestSchema = z.object({ number: z.number().int().positive(), html_url: z.string().url() })
141
180
 
142
181
  export function decodePullRequest(body: unknown, created: boolean): GitHubPullRequestRef {
package/src/repository.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import { configurationError, GitHubBranchConflictError, GitHubNotFoundError, GitHubStaleHeadError, requestStatusError, responseError } from './errors'
2
2
  import type {
3
+ GitHubBlobRead,
4
+ GitHubBlobRef,
3
5
  GitHubCommit,
4
6
  GitHubCommitFilesInput,
7
+ GitHubComparison,
5
8
  GitHubCreateBranchInput,
6
9
  GitHubFileRead,
7
10
  GitHubOpenPullRequestInput,
@@ -11,9 +14,12 @@ import type {
11
14
  GitHubTextFile,
12
15
  GitHubTreeEntry,
13
16
  GitHubTreeListing,
17
+ GitHubUnreadablePath,
18
+ GitHubUnreadableReason,
14
19
  } from './repository-types'
15
20
  import {
16
21
  decodeCommit,
22
+ decodeComparison,
17
23
  decodeCreatedTreeSha,
18
24
  decodePullRequest,
19
25
  decodePullRequestList,
@@ -26,6 +32,7 @@ import {
26
32
  MAX_CHANGED_FILES,
27
33
  MAX_COMMIT_MESSAGE_BYTES,
28
34
  MAX_COMMIT_RESPONSE_BYTES,
35
+ MAX_COMPARE_RESPONSE_BYTES,
29
36
  MAX_FILE_BYTES,
30
37
  MAX_PULL_REQUEST_BODY_BYTES,
31
38
  MAX_PULL_REQUEST_RESPONSE_BYTES,
@@ -54,10 +61,13 @@ export interface RepositoryClientConfig {
54
61
  readonly timeoutMs: number
55
62
  }
56
63
 
64
+ /** Blob reads in flight at once; enough to hide latency, few enough to stay clear of GitHub's secondary rate limits. */
65
+ const BLOB_READ_CONCURRENCY = 6
66
+
57
67
  type RequestResult = { readonly ok: true; readonly body: unknown } | { readonly ok: false; readonly status: number }
58
68
 
59
69
  interface RequestOptions {
60
- readonly method?: 'GET' | 'POST' | 'PATCH'
70
+ readonly method?: 'GET' | 'POST' | 'PATCH' | 'DELETE'
61
71
  readonly body?: unknown
62
72
  readonly signal?: AbortSignal | undefined
63
73
  readonly maxResponseBytes?: number
@@ -79,6 +89,8 @@ export function createRepositoryClient(config: RepositoryClientConfig): GitHubRe
79
89
 
80
90
  class RepositoryClient implements GitHubRepositoryClient {
81
91
  readonly #config: RepositoryClientConfig
92
+ /** Commits and trees this client read, by request path: a sha names immutable content, so one client reads each once. */
93
+ readonly #objects = new Map<string, Promise<unknown>>()
82
94
 
83
95
  constructor(config: RepositoryClientConfig) {
84
96
  this.#config = config
@@ -112,25 +124,74 @@ class RepositoryClient implements GitHubRepositoryClient {
112
124
  for (const path of paths) validatePath(path)
113
125
  const directories = this.#treeWalker((await this.#readCommit(commitSha, signal)).treeSha, signal)
114
126
  const files: GitHubTextFile[] = []
115
- const missingPaths: string[] = []
127
+ const unreadable: GitHubUnreadablePath[] = []
116
128
  let remainingBytes = MAX_READ_BYTES
117
129
  for (const path of paths) {
118
- const entry = await directories.find(path)
119
- // Oversized files, and files past the total read budget, are reported missing like other unreadable paths.
120
- if (entry?.type !== 'blob' || entry.mode === '120000' || entry.size > MAX_FILE_BYTES || entry.size > remainingBytes) {
121
- missingPaths.push(path)
130
+ const entry = readableBlob(await directories.find(path), remainingBytes)
131
+ if (typeof entry === 'string') {
132
+ unreadable.push({ path, reason: entry })
122
133
  continue
123
134
  }
124
135
  const body = await this.#readGitObject(`/git/blobs/${entry.sha}`, signal, MAX_BLOB_RESPONSE_BYTES)
125
136
  const content = decodeTextBlob(body, entry.sha, entry.size)
126
137
  if (content === null) {
127
- missingPaths.push(path)
138
+ unreadable.push({ path, reason: 'binary' })
128
139
  continue
129
140
  }
130
141
  remainingBytes -= entry.size
131
142
  files.push({ path, content })
132
143
  }
133
- return { commitSha, files, missingPaths }
144
+ return { commitSha, files, unreadable }
145
+ }
146
+
147
+ async readBlobTexts(blobs: readonly GitHubBlobRef[], signal?: AbortSignal): Promise<GitHubBlobRead> {
148
+ if (blobs.length === 0 || blobs.length > MAX_READ_PATHS || new Set(blobs.map((blob) => blob.path)).size !== blobs.length) {
149
+ throw configurationError()
150
+ }
151
+ for (const blob of blobs) {
152
+ validatePath(blob.path)
153
+ validateSha(blob.sha)
154
+ if (!Number.isSafeInteger(blob.size) || blob.size < 0) throw configurationError()
155
+ }
156
+ const unreadable = new Map<string, GitHubUnreadableReason>()
157
+ const selected: GitHubBlobRef[] = []
158
+ let remainingBytes = MAX_READ_BYTES
159
+ for (const blob of blobs) {
160
+ if (blob.size > MAX_FILE_BYTES) unreadable.set(blob.path, 'too_large')
161
+ else if (blob.size > remainingBytes) unreadable.set(blob.path, 'budget')
162
+ else {
163
+ remainingBytes -= blob.size
164
+ selected.push(blob)
165
+ }
166
+ }
167
+ const contents = new Map<string, string>()
168
+ for (let start = 0; start < selected.length; start += BLOB_READ_CONCURRENCY) {
169
+ await Promise.all(
170
+ selected.slice(start, start + BLOB_READ_CONCURRENCY).map(async (blob) => {
171
+ const body = await this.#readGitObject(`/git/blobs/${blob.sha}`, signal, MAX_BLOB_RESPONSE_BYTES)
172
+ const content = decodeTextBlob(body, blob.sha, blob.size)
173
+ if (content === null) unreadable.set(blob.path, 'binary')
174
+ else contents.set(blob.path, content)
175
+ }),
176
+ )
177
+ }
178
+ const files: GitHubTextFile[] = []
179
+ const unread: GitHubUnreadablePath[] = []
180
+ for (const blob of blobs) {
181
+ const content = contents.get(blob.path)
182
+ const reason = unreadable.get(blob.path)
183
+ if (content !== undefined) files.push({ path: blob.path, content })
184
+ else if (reason !== undefined) unread.push({ path: blob.path, reason })
185
+ }
186
+ return { files, unreadable: unread }
187
+ }
188
+
189
+ async compareCommits(baseSha: string, headSha: string, signal?: AbortSignal): Promise<GitHubComparison> {
190
+ validateSha(baseSha)
191
+ validateSha(headSha)
192
+ // The changed files ride only on the first page of commits, so one commit per page keeps the rest of the body small.
193
+ const body = await this.#readGitObject(`/compare/${baseSha}...${headSha}?per_page=1`, signal, MAX_COMPARE_RESPONSE_BYTES)
194
+ return decodeComparison(body, headSha)
134
195
  }
135
196
 
136
197
  async createBranch(input: GitHubCreateBranchInput): Promise<GitHubRef> {
@@ -152,6 +213,15 @@ class RepositoryClient implements GitHubRepositoryClient {
152
213
  return requireBranchAt(raced, input.fromSha)
153
214
  }
154
215
 
216
+ async deleteBranch(branch: string, signal?: AbortSignal): Promise<{ readonly deleted: boolean }> {
217
+ validateBranch(branch)
218
+ const result = await this.#request(`/git/refs/heads/${encodeBranch(branch)}`, { method: 'DELETE', signal, expectedFailures: [422] })
219
+ if (result.ok) return { deleted: true }
220
+ // 422 is "Reference does not exist" among other refusals; only an absent branch counts as already deleted.
221
+ if (await this.readRef(branch, signal) !== null) throw requestStatusError(result.status)
222
+ return { deleted: false }
223
+ }
224
+
155
225
  async commitFiles(input: GitHubCommitFilesInput): Promise<GitHubCommit> {
156
226
  validateBranch(input.branch)
157
227
  validateSha(input.expectedHeadSha)
@@ -162,9 +232,11 @@ class RepositoryClient implements GitHubRepositoryClient {
162
232
  const changes = treeChanges(input.changes)
163
233
 
164
234
  // Known limit: REST has no compare-and-swap, so a concurrent reset to an ancestor still lets the non-force PATCH fast-forward.
235
+ const parentRead = this.#readCommit(input.expectedHeadSha, input.signal)
236
+ parentRead.catch(() => undefined)
165
237
  const head = await this.readRef(input.branch, input.signal)
166
238
  if (head?.sha !== input.expectedHeadSha) throw new GitHubStaleHeadError()
167
- const parent = await this.#readCommit(input.expectedHeadSha, input.signal)
239
+ const parent = await parentRead
168
240
  const tree = await this.#resolveModes(changes, parent.treeSha, input.signal)
169
241
 
170
242
  const createdTree = await this.#request('/git/trees', {
@@ -250,7 +322,17 @@ class RepositoryClient implements GitHubRepositoryClient {
250
322
  }
251
323
 
252
324
  /** Reads a commit, tree or blob by sha; GitHub answers 404 or 422 for an unknown one. */
253
- async #readGitObject(path: string, signal: AbortSignal | undefined, maxResponseBytes?: number): Promise<unknown> {
325
+ #readGitObject(path: string, signal: AbortSignal | undefined, maxResponseBytes?: number): Promise<unknown> {
326
+ if (path.startsWith('/git/blobs/')) return this.#fetchGitObject(path, signal, maxResponseBytes)
327
+ const cached = this.#objects.get(path)
328
+ if (cached !== undefined) return cached
329
+ const read = this.#fetchGitObject(path, signal, maxResponseBytes)
330
+ this.#objects.set(path, read)
331
+ read.catch(() => this.#objects.delete(path))
332
+ return read
333
+ }
334
+
335
+ async #fetchGitObject(path: string, signal: AbortSignal | undefined, maxResponseBytes?: number): Promise<unknown> {
254
336
  const result = await this.#request(path, { signal, maxResponseBytes, expectedFailures: [404, 422] })
255
337
  if (!result.ok) throw new GitHubNotFoundError()
256
338
  return result.body
@@ -288,6 +370,7 @@ class RepositoryClient implements GitHubRepositoryClient {
288
370
  if (options.expectedFailures?.includes(response.status) === true) return { ok: false, status: response.status }
289
371
  throw requestStatusError(response.status)
290
372
  }
373
+ if (response.status === 204) return { ok: true, body: null }
291
374
  return { ok: true, body: await readBoundedJson(response, cancellation, options.maxResponseBytes) }
292
375
  } finally {
293
376
  cancellation.dispose()
@@ -334,6 +417,17 @@ class TreeWalker {
334
417
  }
335
418
  }
336
419
 
420
+ type GitHubBlobEntry = Extract<GitHubTreeEntry, { readonly type: 'blob' }>
421
+
422
+ /** The entry when it is a regular file within both bounds, otherwise why it is not read. */
423
+ function readableBlob(entry: GitHubTreeEntry | null, remainingBytes: number): GitHubBlobEntry | GitHubUnreadableReason {
424
+ if (entry === null) return 'missing'
425
+ if (entry.type !== 'blob' || entry.mode === '120000') return 'not_a_file'
426
+ if (entry.size > MAX_FILE_BYTES) return 'too_large'
427
+ if (entry.size > remainingBytes) return 'budget'
428
+ return entry
429
+ }
430
+
337
431
  function requireBranchAt(ref: GitHubRef, sha: string): GitHubRef {
338
432
  if (ref.sha !== sha) throw new GitHubBranchConflictError()
339
433
  return ref
@@ -0,0 +1,39 @@
1
+ import type { GitHubRepositoryClient, GitHubRepositoryOpenRequest } from './repository-types';
2
+ import type { GitHubAppClientConfig, GitHubAppIdentity, GitHubAppInstallation, GitHubAppWebhookConfig, GitHubAppWebhookUpdate, GitHubInstallationToken, GitHubRepositoryTokenRequest } from './types';
3
+ /** GitHub App machine identity. Webhook authentication belongs to the receiving service. */
4
+ export declare class GitHubAppClient {
5
+ private readonly appId;
6
+ private readonly privateKey;
7
+ private readonly apiBaseUrl;
8
+ private readonly fetchImplementation;
9
+ private readonly clock;
10
+ private readonly timeoutMs;
11
+ private constructor();
12
+ /** Validate all configuration and import the RSA key before a credential-owning service boots. */
13
+ static create(config: GitHubAppClientConfig): Promise<GitHubAppClient>;
14
+ /** Read and bind the public identity represented by this client's App credentials. */
15
+ getAuthenticatedApp(signal?: AbortSignal): Promise<GitHubAppIdentity>;
16
+ /** Read the App webhook transport settings without exposing GitHub's masked secret field. */
17
+ getWebhookConfig(signal?: AbortSignal): Promise<GitHubAppWebhookConfig>;
18
+ /** Set the App webhook to JSON over verified TLS and bind GitHub's response to that request. */
19
+ updateWebhookConfig(input: GitHubAppWebhookUpdate): Promise<GitHubAppWebhookConfig>;
20
+ /** Resolve the App installation owned by one organization. A 404 is an expected miss. */
21
+ resolveOrganizationInstallationId(organization: string, signal?: AbortSignal): Promise<number | null>;
22
+ /** Resolve and strictly bind the installation authority owned by one organization. */
23
+ resolveOrganizationInstallation(organization: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null>;
24
+ /** Resolve the App installation for one GitHub repository. A 404 is an expected miss. */
25
+ resolveInstallationId(owner: string, repository: string, signal?: AbortSignal): Promise<number | null>;
26
+ /** Resolve and strictly bind the installation authority that grants one repository. */
27
+ resolveRepositoryInstallation(owner: string, repository: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null>;
28
+ /** Mint a read-only token restricted to one repository in the selected installation. */
29
+ mintRepositoryToken(input: GitHubRepositoryTokenRequest): Promise<GitHubInstallationToken>;
30
+ /**
31
+ * Mint a token restricted to one repository with `contents: write` and `pull_requests: write`,
32
+ * and return a client bound to it. The token never leaves the returned client.
33
+ */
34
+ openRepository(input: GitHubRepositoryOpenRequest): Promise<GitHubRepositoryClient>;
35
+ private mintToken;
36
+ private requestJson;
37
+ private decodeInstallation;
38
+ private now;
39
+ }
@@ -0,0 +1,20 @@
1
+ export declare function configurationError(): Error;
2
+ /** GitHub answered a request with an unexpected status; the message never carries GitHub's response text. */
3
+ export declare class GitHubRequestError extends Error {
4
+ readonly status: number;
5
+ constructor(status: number);
6
+ }
7
+ export declare function requestStatusError(status: number): GitHubRequestError;
8
+ export declare function responseError(): Error;
9
+ /** The branch moved since the caller read it; re-read the head and retry the change on top of it. */
10
+ export declare class GitHubStaleHeadError extends Error {
11
+ constructor();
12
+ }
13
+ /** The branch exists at a different commit than the one it was to be created from. */
14
+ export declare class GitHubBranchConflictError extends Error {
15
+ constructor();
16
+ }
17
+ /** A commit, tree or blob sha the caller named does not exist in the repository. */
18
+ export declare class GitHubNotFoundError extends Error {
19
+ constructor();
20
+ }
@@ -0,0 +1,6 @@
1
+ export { GitHubAppClient } from './client';
2
+ export { GitHubBranchConflictError, GitHubNotFoundError, GitHubRequestError, GitHubStaleHeadError } from './errors';
3
+ export { buildGitHubAppManifest, exchangeGitHubAppManifestCode } from './manifest';
4
+ export type { GitHubBlobRead, GitHubBlobRef, GitHubChangedFile, GitHubChangedFileStatus, GitHubCommit, GitHubCommitFilesInput, GitHubComparison, GitHubCreateBranchInput, GitHubFileChange, GitHubFileRead, GitHubOpenPullRequestInput, GitHubPullRequestRef, GitHubRef, GitHubRepositoryClient, GitHubRepositoryOpenRequest, GitHubTextFile, GitHubTreeEntry, GitHubTreeListing, GitHubUnreadablePath, GitHubUnreadableReason, } from './repository-types';
5
+ export { pemToPkcs8 } from './signing';
6
+ export type { CreatedGitHubApp, GitHubAppClientConfig, GitHubAppFetch, GitHubAppIdentity, GitHubAppInstallation, GitHubAppManifestExchangeOptions, GitHubAppManifestInput, GitHubAppWebhookConfig, GitHubAppWebhookUpdate, GitHubInstallationToken, GitHubRepositoryTokenRequest, } from './types';
@@ -0,0 +1,8 @@
1
+ import type { CreatedGitHubApp, GitHubAppManifestExchangeOptions, GitHubAppManifestInput } from './types';
2
+ /**
3
+ * Build the one App manifest used by Fabrika repository source and MCP authoring. The write permissions serve
4
+ * MCP authoring's branches and pull requests (`openRepository`); deploy tokens are minted with Contents read only.
5
+ */
6
+ export declare function buildGitHubAppManifest(input: GitHubAppManifestInput): Readonly<Record<string, unknown>>;
7
+ /** Exchange a bounded one-time GitHub manifest code without exposing response details. */
8
+ export declare function exchangeGitHubAppManifestCode(code: string, options?: GitHubAppManifestExchangeOptions): Promise<CreatedGitHubApp>;
@@ -0,0 +1,146 @@
1
+ export interface GitHubRef {
2
+ readonly branch: string;
3
+ readonly sha: string;
4
+ }
5
+ export interface GitHubCommit {
6
+ readonly sha: string;
7
+ readonly treeSha: string;
8
+ readonly parents: readonly string[];
9
+ }
10
+ export type GitHubTreeEntry = {
11
+ readonly path: string;
12
+ readonly sha: string;
13
+ } & ({
14
+ readonly type: 'tree';
15
+ readonly mode: '040000';
16
+ } | {
17
+ readonly type: 'blob';
18
+ readonly mode: '100644' | '100755' | '120000';
19
+ readonly size: number;
20
+ } | {
21
+ readonly type: 'commit';
22
+ readonly mode: '160000';
23
+ });
24
+ export interface GitHubTreeListing {
25
+ readonly commitSha: string;
26
+ /** Empty for the root; entries use repository-relative paths. */
27
+ readonly directory: string;
28
+ /** Every entry below `directory`, recursively, up to the client's bound. */
29
+ readonly entries: readonly GitHubTreeEntry[];
30
+ /** True when the bound cut the listing short. */
31
+ readonly truncated: boolean;
32
+ }
33
+ export interface GitHubTextFile {
34
+ readonly path: string;
35
+ readonly content: string;
36
+ }
37
+ /**
38
+ * Why a requested path was not read: `missing` (no such path), `not_a_file` (a directory, symlink or submodule),
39
+ * `too_large` (over the per-file bound), `binary` (not UTF-8), `budget` (past the read's total byte bound).
40
+ */
41
+ export type GitHubUnreadableReason = 'missing' | 'not_a_file' | 'too_large' | 'binary' | 'budget';
42
+ export interface GitHubUnreadablePath {
43
+ readonly path: string;
44
+ readonly reason: GitHubUnreadableReason;
45
+ }
46
+ export interface GitHubFileRead {
47
+ readonly commitSha: string;
48
+ readonly files: readonly GitHubTextFile[];
49
+ /** Requested paths that were not read at `commitSha`, in request order. */
50
+ readonly unreadable: readonly GitHubUnreadablePath[];
51
+ }
52
+ /** A blob named by a tree listing of the same repository. */
53
+ export interface GitHubBlobRef {
54
+ readonly path: string;
55
+ readonly sha: string;
56
+ readonly size: number;
57
+ }
58
+ export interface GitHubBlobRead {
59
+ readonly files: readonly GitHubTextFile[];
60
+ /** Blobs that were not read (`too_large`, `budget` or `binary`), in request order. */
61
+ readonly unreadable: readonly GitHubUnreadablePath[];
62
+ }
63
+ export type GitHubChangedFileStatus = 'added' | 'removed' | 'modified' | 'renamed' | 'copied' | 'changed' | 'unchanged';
64
+ export interface GitHubChangedFile {
65
+ readonly path: string;
66
+ /** The path before a rename or copy. */
67
+ readonly previousPath: string | null;
68
+ readonly status: GitHubChangedFileStatus;
69
+ readonly additions: number;
70
+ readonly deletions: number;
71
+ /** The unified diff hunk; null when GitHub omits it (a binary file or a very large change). */
72
+ readonly patch: string | null;
73
+ }
74
+ export interface GitHubComparison {
75
+ readonly baseSha: string;
76
+ readonly headSha: string;
77
+ /** Commits on head that are not on base. */
78
+ readonly aheadBy: number;
79
+ readonly behindBy: number;
80
+ readonly files: readonly GitHubChangedFile[];
81
+ /** GitHub lists at most 300 files of a comparison; true when it listed that many, so more may have changed. */
82
+ readonly filesCapped: boolean;
83
+ }
84
+ export interface GitHubFileChange {
85
+ readonly path: string;
86
+ /** UTF-8 regular-file contents, or null to delete the path. */
87
+ readonly content: string | null;
88
+ }
89
+ export interface GitHubCreateBranchInput {
90
+ readonly branch: string;
91
+ readonly fromSha: string;
92
+ readonly signal?: AbortSignal;
93
+ }
94
+ export interface GitHubCommitFilesInput {
95
+ readonly branch: string;
96
+ /** The branch head the changes were made against; a different live head fails with `GitHubStaleHeadError`. */
97
+ readonly expectedHeadSha: string;
98
+ readonly message: string;
99
+ readonly author: {
100
+ readonly name: string;
101
+ readonly email: string;
102
+ };
103
+ readonly changes: readonly GitHubFileChange[];
104
+ readonly signal?: AbortSignal;
105
+ }
106
+ export interface GitHubOpenPullRequestInput {
107
+ readonly head: string;
108
+ readonly base: string;
109
+ readonly title: string;
110
+ readonly body: string;
111
+ readonly signal?: AbortSignal;
112
+ }
113
+ export interface GitHubPullRequestRef {
114
+ readonly number: number;
115
+ readonly url: string;
116
+ /** False when an open pull request for the same head and base already existed and was returned instead. */
117
+ readonly created: boolean;
118
+ }
119
+ /**
120
+ * One repository, reached with an installation token restricted to it. The caller (Source) decides
121
+ * which branches it may write; the client only refuses a non-fast-forward or stale update.
122
+ */
123
+ export interface GitHubRepositoryClient {
124
+ readRef(branch: string, signal?: AbortSignal): Promise<GitHubRef | null>;
125
+ readTree(commitSha: string, directory?: string, signal?: AbortSignal): Promise<GitHubTreeListing>;
126
+ readFiles(commitSha: string, paths: readonly string[], signal?: AbortSignal): Promise<GitHubFileRead>;
127
+ /** Reads listed blobs as text without walking the tree again, within the same per-file and total bounds as `readFiles`. */
128
+ readBlobTexts(blobs: readonly GitHubBlobRef[], signal?: AbortSignal): Promise<GitHubBlobRead>;
129
+ /** The changes from the merge base of `baseSha` and `headSha` to `headSha`. */
130
+ compareCommits(baseSha: string, headSha: string, signal?: AbortSignal): Promise<GitHubComparison>;
131
+ /** Idempotent: an existing branch already at `fromSha` is returned; one elsewhere is a conflict. */
132
+ createBranch(input: GitHubCreateBranchInput): Promise<GitHubRef>;
133
+ /** Idempotent: `deleted` is false when the branch did not exist. GitHub closes an open pull request from it. */
134
+ deleteBranch(branch: string, signal?: AbortSignal): Promise<{
135
+ readonly deleted: boolean;
136
+ }>;
137
+ /** Creates exactly one commit on top of `expectedHeadSha` and moves the branch to it without force. */
138
+ commitFiles(input: GitHubCommitFilesInput): Promise<GitHubCommit>;
139
+ openPullRequest(input: GitHubOpenPullRequestInput): Promise<GitHubPullRequestRef>;
140
+ }
141
+ export interface GitHubRepositoryOpenRequest {
142
+ readonly installationId: number;
143
+ readonly owner: string;
144
+ readonly repository: string;
145
+ readonly signal?: AbortSignal;
146
+ }
@@ -0,0 +1,39 @@
1
+ import type { GitHubCommit, GitHubComparison, GitHubPullRequestRef, GitHubRef, GitHubTreeEntry } from './repository-types';
2
+ export declare const MAX_TREE_ENTRIES = 5000;
3
+ export declare const MAX_TREE_RESPONSE_BYTES: number;
4
+ export declare const MAX_READ_PATHS = 100;
5
+ export declare const MAX_FILE_BYTES: number;
6
+ export declare const MAX_READ_BYTES: number;
7
+ export declare const MAX_BLOB_RESPONSE_BYTES: number;
8
+ export declare const MAX_CHANGED_FILES = 256;
9
+ export declare const MAX_CHANGED_BYTES: number;
10
+ export declare const MAX_COMMIT_MESSAGE_BYTES: number;
11
+ export declare const MAX_PULL_REQUEST_TITLE_BYTES = 1024;
12
+ export declare const MAX_PULL_REQUEST_BODY_BYTES: number;
13
+ export declare const MAX_PULL_REQUEST_RESPONSE_BYTES: number;
14
+ export declare const MAX_COMMIT_RESPONSE_BYTES: number;
15
+ export declare const MAX_PATH_SEGMENTS = 64;
16
+ /** GitHub's own bound on the files of one comparison. */
17
+ export declare const MAX_COMPARE_FILES = 300;
18
+ export declare const MAX_COMPARE_RESPONSE_BYTES: number;
19
+ export declare function validateSha(value: string): void;
20
+ /** A subset of `git check-ref-format` that is safe to place in a URL path segment by segment. */
21
+ export declare function validateBranch(value: string): void;
22
+ /** Repository-relative path: no leading, trailing or doubled slash, no `.`/`..` segment, never inside `.git`. */
23
+ export declare function validatePath(value: string): void;
24
+ export declare function validateText(value: string, maxBytes: number, allowEmpty: boolean): void;
25
+ export declare function utf8Length(value: string): number;
26
+ export declare function encodeBranch(branch: string): string;
27
+ export declare function decodeRef(body: unknown, branch: string): GitHubRef;
28
+ export declare function decodeCommit(body: unknown): GitHubCommit;
29
+ export interface DecodedTree {
30
+ readonly entries: readonly GitHubTreeEntry[];
31
+ readonly truncated: boolean;
32
+ }
33
+ export declare function decodeTree(body: unknown, expectedSha: string): DecodedTree;
34
+ export declare function decodeCreatedTreeSha(body: unknown): string;
35
+ /** The blob's bytes as UTF-8 text, or null when they are not valid UTF-8. */
36
+ export declare function decodeTextBlob(body: unknown, expectedSha: string, expectedSize: number): string | null;
37
+ export declare function decodeComparison(body: unknown, headSha: string): GitHubComparison;
38
+ export declare function decodePullRequest(body: unknown, created: boolean): GitHubPullRequestRef;
39
+ export declare function decodePullRequestList(body: unknown): unknown[];
@@ -0,0 +1,12 @@
1
+ import type { GitHubRepositoryClient } from './repository-types';
2
+ import type { GitHubAppFetch, GitHubInstallationToken } from './types';
3
+ export interface RepositoryClientConfig {
4
+ readonly owner: string;
5
+ readonly repository: string;
6
+ readonly token: GitHubInstallationToken;
7
+ readonly now: () => number;
8
+ readonly apiBaseUrl: string;
9
+ readonly fetch: GitHubAppFetch;
10
+ readonly timeoutMs: number;
11
+ }
12
+ export declare function createRepositoryClient(config: RepositoryClientConfig): GitHubRepositoryClient;
@@ -0,0 +1,3 @@
1
+ export declare function signAppJwt(appId: string, privateKey: CryptoKey, clock: () => number): Promise<string>;
2
+ /** Convert a GitHub App PKCS1 or PKCS8 PEM key into PKCS8 DER for WebCrypto. */
3
+ export declare function pemToPkcs8(pem: string): Uint8Array<ArrayBuffer>;
@@ -0,0 +1,11 @@
1
+ export declare const GITHUB_ACCEPT = "application/vnd.github+json";
2
+ export declare const GITHUB_API_VERSION = "2022-11-28";
3
+ export declare const GITHUB_USER_AGENT = "vozka";
4
+ interface RequestCancellation {
5
+ readonly signal: AbortSignal;
6
+ throwIfCancelled(): void;
7
+ dispose(): void;
8
+ }
9
+ export declare function createCancellation(callerSignal: AbortSignal | undefined, timeoutMs: number): RequestCancellation;
10
+ export declare function readBoundedJson(response: Response, cancellation: RequestCancellation, maxResponseBytes?: number): Promise<unknown>;
11
+ export {};
@@ -0,0 +1,79 @@
1
+ export interface GitHubAppClientConfig {
2
+ /** Numeric GitHub App id, kept as a string because it is the JWT issuer. */
3
+ appId: string;
4
+ /** GitHub App RSA private key in PKCS1 or PKCS8 PEM form. */
5
+ privateKeyPem: string;
6
+ /** GitHub API base URL. Defaults to the public GitHub API. */
7
+ apiBaseUrl?: string;
8
+ /** HTTP implementation for the current runtime. */
9
+ fetch?: GitHubAppFetch;
10
+ /** Millisecond Unix clock. */
11
+ now?: () => number;
12
+ /** Upper bound for each GitHub API request, including its response body. */
13
+ timeoutMs?: number;
14
+ }
15
+ export interface GitHubInstallationToken {
16
+ token: string;
17
+ expiresAt: number;
18
+ }
19
+ export interface GitHubAppInstallation {
20
+ readonly id: number;
21
+ readonly accountLogin: string;
22
+ readonly accountType: 'Organization' | 'User';
23
+ readonly repositorySelection: 'all' | 'selected';
24
+ }
25
+ export interface GitHubAppIdentity {
26
+ readonly id: number;
27
+ readonly slug: string;
28
+ readonly htmlUrl: string;
29
+ readonly public: boolean;
30
+ readonly permissions: {
31
+ readonly contents: 'read' | 'write';
32
+ readonly pull_requests?: 'read' | 'write';
33
+ };
34
+ readonly events: readonly string[];
35
+ readonly owner: {
36
+ readonly login: string;
37
+ readonly type: 'Organization' | 'User';
38
+ };
39
+ }
40
+ export interface GitHubAppWebhookConfig {
41
+ readonly url: string;
42
+ readonly contentType: 'json' | 'form';
43
+ readonly insecureSsl: '0' | '1';
44
+ }
45
+ export interface GitHubAppWebhookUpdate {
46
+ readonly url: string;
47
+ readonly secret: string;
48
+ readonly signal?: AbortSignal;
49
+ }
50
+ export interface GitHubRepositoryTokenRequest {
51
+ installationId: number;
52
+ owner: string;
53
+ repository: string;
54
+ signal?: AbortSignal;
55
+ }
56
+ export type GitHubAppFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
57
+ export interface CreatedGitHubApp {
58
+ readonly id: number;
59
+ readonly slug: string;
60
+ readonly htmlUrl: string;
61
+ readonly pem: string;
62
+ readonly webhookSecret: string;
63
+ }
64
+ export interface GitHubAppManifestInput {
65
+ readonly organization: string;
66
+ readonly appName: string;
67
+ readonly homepageUrl: string;
68
+ readonly webhookUrl: string;
69
+ readonly redirectUrl?: string;
70
+ /** Where GitHub sends the installer after an install or an installation update, with `installation_id` and `setup_action`. */
71
+ readonly setupUrl?: string;
72
+ /** GitHub requires a public App when repositories outside its owner organization need it. */
73
+ readonly public: boolean;
74
+ }
75
+ export interface GitHubAppManifestExchangeOptions {
76
+ readonly fetch?: GitHubAppFetch;
77
+ readonly signal?: AbortSignal;
78
+ readonly timeoutMs?: number;
79
+ }
@@ -0,0 +1,69 @@
1
+ import { z } from 'zod';
2
+ import type { GitHubAppIdentity, GitHubAppWebhookConfig } from './types';
3
+ export declare const APP_SLUG_PATTERN: RegExp;
4
+ export declare const appReferenceSchema: z.ZodObject<{
5
+ id: z.ZodNumber;
6
+ slug: z.ZodString;
7
+ html_url: z.ZodString;
8
+ }, "strip", z.ZodTypeAny, {
9
+ id: number;
10
+ slug: string;
11
+ html_url: string;
12
+ }, {
13
+ id: number;
14
+ slug: string;
15
+ html_url: string;
16
+ }>;
17
+ export declare const installationSchema: z.ZodObject<{
18
+ id: z.ZodNumber;
19
+ app_id: z.ZodNumber;
20
+ target_type: z.ZodEnum<["Organization", "User"]>;
21
+ account: z.ZodObject<{
22
+ login: z.ZodString;
23
+ type: z.ZodEnum<["Organization", "User"]>;
24
+ }, "strip", z.ZodTypeAny, {
25
+ type: "Organization" | "User";
26
+ login: string;
27
+ }, {
28
+ type: "Organization" | "User";
29
+ login: string;
30
+ }>;
31
+ repository_selection: z.ZodEnum<["all", "selected"]>;
32
+ }, "strip", z.ZodTypeAny, {
33
+ id: number;
34
+ app_id: number;
35
+ target_type: "Organization" | "User";
36
+ account: {
37
+ type: "Organization" | "User";
38
+ login: string;
39
+ };
40
+ repository_selection: "all" | "selected";
41
+ }, {
42
+ id: number;
43
+ app_id: number;
44
+ target_type: "Organization" | "User";
45
+ account: {
46
+ type: "Organization" | "User";
47
+ login: string;
48
+ };
49
+ repository_selection: "all" | "selected";
50
+ }>;
51
+ export declare const installationTokenSchema: z.ZodObject<{
52
+ token: z.ZodEffects<z.ZodString, string, string>;
53
+ expires_at: z.ZodEffects<z.ZodString, number, string>;
54
+ }, "strip", z.ZodTypeAny, {
55
+ token: string;
56
+ expires_at: number;
57
+ }, {
58
+ token: string;
59
+ expires_at: string;
60
+ }>;
61
+ export declare function normalizeApiBaseUrl(value: string): string;
62
+ export declare function validateRepositoryComponent(value: string): void;
63
+ export declare function normalizeWebhookUrl(value: string): string;
64
+ export declare function validateWebhookSecret(value: string): void;
65
+ export declare function decodeAppIdentity(value: unknown): Omit<GitHubAppIdentity, 'public'> | null;
66
+ export declare function sameAppIdentity(left: Omit<GitHubAppIdentity, 'public'>, right: Omit<GitHubAppIdentity, 'public'>): boolean;
67
+ export declare function decodeWebhookConfig(value: unknown): GitHubAppWebhookConfig | null;
68
+ export declare function hasAsciiControl(value: string): boolean;
69
+ export declare function isPositiveSafeInteger(value: number): boolean;