@leitwerk-dev/github 0.0.0-bootstrap.0 → 0.2.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 (45) hide show
  1. package/README.md +113 -1
  2. package/dist/LICENSE +13 -0
  3. package/dist/authorization.d.ts +12 -0
  4. package/dist/authorization.d.ts.map +1 -0
  5. package/dist/binding.d.ts +4 -0
  6. package/dist/binding.d.ts.map +1 -0
  7. package/dist/capability.d.ts +8 -0
  8. package/dist/capability.d.ts.map +1 -0
  9. package/dist/chunk-PVE52UFH.js +318 -0
  10. package/dist/chunk-PVE52UFH.js.map +1 -0
  11. package/dist/client.d.ts +111 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/external.d.ts +85 -0
  14. package/dist/external.d.ts.map +1 -0
  15. package/dist/index.d.ts +18 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +809 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/issue-provider.d.ts +8 -0
  20. package/dist/issue-provider.d.ts.map +1 -0
  21. package/dist/issue-watcher.d.ts +19 -0
  22. package/dist/issue-watcher.d.ts.map +1 -0
  23. package/dist/poll-report.d.ts +22 -0
  24. package/dist/poll-report.d.ts.map +1 -0
  25. package/dist/provider.d.ts +6 -0
  26. package/dist/provider.d.ts.map +1 -0
  27. package/dist/testing.d.ts +81 -0
  28. package/dist/testing.d.ts.map +1 -0
  29. package/dist/testing.js +297 -0
  30. package/dist/testing.js.map +1 -0
  31. package/dist/tools.d.ts +5 -0
  32. package/dist/tools.d.ts.map +1 -0
  33. package/package.json +55 -14
  34. package/src/authorization.ts +54 -0
  35. package/src/binding.ts +6 -0
  36. package/src/capability.ts +13 -0
  37. package/src/client.ts +421 -0
  38. package/src/external.ts +139 -0
  39. package/src/index.ts +45 -0
  40. package/src/issue-provider.ts +278 -0
  41. package/src/issue-watcher.ts +30 -0
  42. package/src/poll-report.ts +47 -0
  43. package/src/provider.ts +216 -0
  44. package/src/testing.ts +384 -0
  45. package/src/tools.ts +304 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing.ts"],"sourcesContent":["import { LocalForgeStore, type LocalRepositorySeed } from \"@leitwerk-dev/test-support/local-git\";\nimport { actionableFeedback, authorizedTrigger } from \"./authorization.js\";\nimport type { GitHubClientLike } from \"./capability.js\";\nimport type {\n\tGitHubCheckSummary,\n\tGitHubFeedbackItem,\n\tGitHubIssue,\n\tGitHubLabelEvent,\n\tGitHubProfile,\n\tGitHubPullRequest,\n\tGitHubRelease,\n} from \"./client.js\";\nimport { assertGitHubRepository } from \"./client.js\";\n\nexport interface LocalGitHubRepository {\n\trepository: ReturnType<LocalGitHubAdapter[\"newRepository\"]>;\n\tissues: GitHubIssue[];\n\tpulls: GitHubPullRequest[];\n\tcomments: Record<string, Array<ReturnType<LocalGitHubAdapter[\"newComment\"]>>>;\n\tfeedback: Record<string, GitHubFeedbackItem[]>;\n\tchecks: Record<string, GitHubCheckSummary>;\n\treleases: GitHubRelease[];\n\tassets: Record<string, string>;\n\tlabels: Array<{ id: number; name: string }>;\n\tlabelEvents: Record<string, GitHubLabelEvent[]>;\n\treactions: Record<string, Array<{ id: number; content: string; user: { login: string } }>>;\n\tfeedbackEditors: Record<string, string | null>;\n}\nexport interface LocalGitHubState {\n\tversion: 1;\n\tsequence: number;\n\trepositories: LocalGitHubRepository[];\n\tfailAfterPullRequestWrite: boolean;\n\tmembers: string[];\n\tfailAfterWrite: string | null;\n}\nexport interface LocalGitHubOptions {\n\troot: string;\n\tbaseUrl: string;\n\tnow?: () => number;\n\tnextId?: () => number;\n\tseeds?: LocalRepositorySeed[];\n\tallowedOrganization?: string;\n}\n\n/** Persistent local GitHub with actual commit ancestry and configurable release assets. */\nexport class LocalGitHubAdapter extends LocalForgeStore<LocalGitHubState, LocalGitHubOptions> {\n\tconstructor(options: LocalGitHubOptions) {\n\t\tsuper(options, \"github.json\", {\n\t\t\tversion: 1,\n\t\t\tsequence: 0,\n\t\t\trepositories: [],\n\t\t\tfailAfterPullRequestWrite: false,\n\t\t\tmembers: [],\n\t\t\tfailAfterWrite: null,\n\t\t});\n\t\tthis.state.members ??= [];\n\t\tthis.state.failAfterWrite ??= null;\n\t\tfor (const r of this.state.repositories) {\n\t\t\tr.labels ??= [];\n\t\t\tr.labelEvents ??= {};\n\t\t\tr.reactions ??= {};\n\t\t\tr.feedbackEditors ??= {};\n\t\t}\n\t\tfor (const seed of options.seeds ?? []) this.seed(seed);\n\t}\n\trepo(owner: string, name: string) {\n\t\tconst repo = this.state.repositories.find((r) => r.repository.full_name === `${owner}/${name}`);\n\t\tif (!repo) throw new Error(\"Unknown local GitHub repository\");\n\t\treturn repo;\n\t}\n\tseed(seed: LocalRepositorySeed) {\n\t\tconst existing = this.state.repositories.find(\n\t\t\t(r) => r.repository.full_name === `${seed.owner}/${seed.name}`,\n\t\t);\n\t\tif (existing) return existing;\n\t\tconst repo: LocalGitHubRepository = {\n\t\t\trepository: this.newRepository(seed),\n\t\t\tissues: [],\n\t\t\tpulls: [],\n\t\t\tcomments: {},\n\t\t\tfeedback: {},\n\t\t\tchecks: {},\n\t\t\treleases: [],\n\t\t\tassets: {},\n\t\t\tlabels: [],\n\t\t\tlabelEvents: {},\n\t\t\treactions: {},\n\t\t\tfeedbackEditors: {},\n\t\t};\n\t\tthis.state.repositories.push(repo);\n\t\tthis.save();\n\t\treturn repo;\n\t}\n\tsetChecks(repo: LocalGitHubRepository, summary: GitHubCheckSummary) {\n\t\tthis.git.head(repo.repository.ssh_url, summary.headSha);\n\t\trepo.checks[summary.headSha] = structuredClone(summary);\n\t\tthis.save();\n\t}\n\tpublishRelease(\n\t\trepo: LocalGitHubRepository,\n\t\tinput: {\n\t\t\ttag: string;\n\t\t\tref: string;\n\t\t\tassets: Record<string, string>;\n\t\t\tdraft?: boolean;\n\t\t\tprerelease?: boolean;\n\t\t},\n\t) {\n\t\tconst commit = this.git.head(repo.repository.ssh_url, input.ref);\n\t\tthis.git.run(repo.repository.ssh_url, [\"check-ref-format\", `refs/tags/${input.tag}`]);\n\t\tthis.git.run(repo.repository.ssh_url, [\"tag\", \"--\", input.tag, commit]);\n\t\tconst id = this.id();\n\t\tconst release: GitHubRelease = {\n\t\t\tid,\n\t\t\ttag_name: input.tag,\n\t\t\ttarget_commitish: commit,\n\t\t\tdraft: input.draft ?? false,\n\t\t\tprerelease: input.prerelease ?? false,\n\t\t\thtml_url: `${this.options.baseUrl}/__local`,\n\t\t\tassets: Object.entries(input.assets).map(([name, contents]) => {\n\t\t\t\tconst url = `${this.options.baseUrl}/__local/assets/${this.id()}`;\n\t\t\t\trepo.assets[url] = contents;\n\t\t\t\treturn { name, url, browser_download_url: url };\n\t\t\t}),\n\t\t};\n\t\trepo.releases.unshift(release);\n\t\tthis.save();\n\t\treturn release;\n\t}\n\toverride newRepository(seed: LocalRepositorySeed) {\n\t\treturn { ...super.newRepository(seed), archived: false, has_issues: true };\n\t}\n\tsetMembership(login: string, member: boolean) {\n\t\tthis.state.members = this.state.members.filter(\n\t\t\t(value) => value.toLowerCase() !== login.toLowerCase(),\n\t\t);\n\t\tif (member) this.state.members.push(login);\n\t\tthis.save();\n\t}\n\tfailNextResponse(operation: \"comment\" | \"reply\" | \"reaction\" | \"issue\" | \"label\") {\n\t\tthis.state.failAfterWrite = operation;\n\t\tthis.save();\n\t}\n\tprivate lostResponse(operation: string) {\n\t\tif (this.state.failAfterWrite !== operation) return;\n\t\tthis.state.failAfterWrite = null;\n\t\tthis.save();\n\t\tthrow new Error(`Local GitHub: response lost after ${operation} write`);\n\t}\n\tcreateIssue(\n\t\trepo: LocalGitHubRepository,\n\t\tinput: { title: string; body?: string; author?: string },\n\t) {\n\t\tconst number = this.id();\n\t\tconst issue: GitHubIssue = {\n\t\t\tnumber,\n\t\t\ttitle: input.title,\n\t\t\tbody: input.body ?? \"\",\n\t\t\tstate: \"open\",\n\t\t\thtml_url: `${this.options.baseUrl}/__local#issue-${number}`,\n\t\t\tupdated_at: this.timestamp(),\n\t\t\tuser: { login: input.author ?? \"developer\" },\n\t\t\tlabels: [],\n\t\t};\n\t\trepo.issues.push(issue);\n\t\tthis.save();\n\t\treturn issue;\n\t}\n\tsetIssueLabel(\n\t\trepo: LocalGitHubRepository,\n\t\tnumber: number,\n\t\tname: string,\n\t\tactor: string,\n\t\tpresent = true,\n\t) {\n\t\tconst issue = repo.issues.find((value) => value.number === number);\n\t\tif (!issue) throw new Error(\"Unknown local GitHub issue\");\n\t\tissue.labels = issue.labels.filter((label) => label.name !== name);\n\t\tif (present) issue.labels.push({ id: this.id(), name });\n\t\tconst event: GitHubLabelEvent = {\n\t\t\tid: this.id(),\n\t\t\tevent: present ? \"labeled\" : \"unlabeled\",\n\t\t\tlabel: { name },\n\t\t\tactor: { login: actor },\n\t\t};\n\t\trepo.labelEvents[number] ??= [];\n\t\trepo.labelEvents[number].push(event);\n\t\tissue.updated_at = this.timestamp();\n\t\tthis.save();\n\t\treturn event;\n\t}\n\teditFeedback(\n\t\trepo: LocalGitHubRepository,\n\t\tnumber: number,\n\t\tkind: GitHubFeedbackItem[\"kind\"],\n\t\tid: number,\n\t\tbody: string,\n\t\teditor: string | null,\n\t) {\n\t\tconst item = repo.feedback[number]?.find((value) => value.kind === kind && value.id === id);\n\t\tif (!item) throw new Error(\"Unknown local GitHub feedback\");\n\t\titem.body = body;\n\t\titem.createdAt = this.timestamp();\n\t\trepo.feedbackEditors[`${kind}:${id}`] = editor;\n\t\tthis.save();\n\t}\n\n\tclient(): GitHubClientLike {\n\t\tconst profile: GitHubProfile = {\n\t\t\tapiBaseUrl: this.options.baseUrl,\n\t\t\ttoken: \"\",\n\t\t\tbotLogin: \"leitwerk-bot\",\n\t\t\t...(this.options.allowedOrganization\n\t\t\t\t? { allowedOrganization: this.options.allowedOrganization }\n\t\t\t\t: {}),\n\t\t};\n\t\tconst repo = (owner: string, name: string) => {\n\t\t\tassertGitHubRepository(profile, owner, name);\n\t\t\treturn this.repo(owner, name);\n\t\t};\n\t\tconst client: GitHubClientLike = {\n\t\t\tprofile,\n\t\t\tlistRepositories: async () =>\n\t\t\t\tthis.state.repositories\n\t\t\t\t\t.map((r) => ({ ...r.repository, archived: false, has_issues: true }))\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(r) =>\n\t\t\t\t\t\t\t!profile.allowedOrganization ||\n\t\t\t\t\t\t\tr.owner.login.toLowerCase() === profile.allowedOrganization.toLowerCase(),\n\t\t\t\t\t),\n\t\t\tlistOpenIssues: async (owner, name) =>\n\t\t\t\tstructuredClone(repo(owner, name).issues.filter((i) => i.state === \"open\")),\n\t\t\tlistIssueEvents: async (owner, name, number) =>\n\t\t\t\tstructuredClone(repo(owner, name).labelEvents[number] ?? []),\n\t\t\tisOrganizationMember: async (login) =>\n\t\t\t\t!profile.allowedOrganization ||\n\t\t\t\tthis.state.members.some((member) => member.toLowerCase() === login.toLowerCase()),\n\t\t\tauthorizedTrigger: async (owner, name, number, trigger, done) =>\n\t\t\t\tauthorizedTrigger(client, owner, name, number, trigger, done),\n\t\t\tresolveGitIdentity: async (name) => ({\n\t\t\t\tprovider: \"github\",\n\t\t\t\tprofile: name,\n\t\t\t\tlogin: profile.botLogin,\n\t\t\t\tname: \"Sandbox Developer\",\n\t\t\t\temail: \"developer@sandbox.invalid\",\n\t\t\t}),\n\t\t\tensureLabel: async (owner, name, labelName) => {\n\t\t\t\tconst r = repo(owner, name);\n\t\t\t\tlet label = r.labels.find((value) => value.name === labelName);\n\t\t\t\tif (!label) {\n\t\t\t\t\tlabel = { id: this.id(), name: labelName };\n\t\t\t\t\tr.labels.push(label);\n\t\t\t\t\tthis.save();\n\t\t\t\t\tthis.lostResponse(\"label\");\n\t\t\t\t}\n\t\t\t\treturn structuredClone(label);\n\t\t\t},\n\t\t\tupdateIssue: async (owner, name, number, patch) => {\n\t\t\t\tconst issue = repo(owner, name).issues.find((i) => i.number === number);\n\t\t\t\tif (!issue) throw new Error(\"Unknown local GitHub issue\");\n\t\t\t\tfor (const key of [\"title\", \"body\", \"state\"] as const)\n\t\t\t\t\tif (typeof patch[key] === \"string\") issue[key] = patch[key];\n\t\t\t\tif (Array.isArray(patch.labels))\n\t\t\t\t\tissue.labels = patch.labels.map((value) => ({ id: this.id(), name: String(value) }));\n\t\t\t\tissue.updated_at = this.timestamp();\n\t\t\t\tthis.save();\n\t\t\t\tthis.lostResponse(\"issue\");\n\t\t\t\treturn structuredClone(issue);\n\t\t\t},\n\t\t\tlistFeedbackReactions: async (owner, name, kind, id) =>\n\t\t\t\tstructuredClone(repo(owner, name).reactions[`${kind}:${id}`] ?? []),\n\t\t\taddFeedbackReaction: async (owner, name, kind, id) => {\n\t\t\t\tif (![\"conversation\", \"inline\"].includes(kind))\n\t\t\t\t\tthrow new Error(\"Reviews do not support reactions\");\n\t\t\t\tconst r = repo(owner, name);\n\t\t\t\tr.reactions[`${kind}:${id}`] ??= [];\n\t\t\t\tconst reactions = r.reactions[`${kind}:${id}`];\n\t\t\t\tlet reaction = reactions.find(\n\t\t\t\t\t(r) => r.content === \"eyes\" && r.user.login === profile.botLogin,\n\t\t\t\t);\n\t\t\t\tif (!reaction) {\n\t\t\t\t\treaction = { id: this.id(), content: \"eyes\", user: { login: profile.botLogin } };\n\t\t\t\t\treactions.push(reaction);\n\t\t\t\t\tthis.save();\n\t\t\t\t\tthis.lostResponse(\"reaction\");\n\t\t\t\t}\n\t\t\t\treturn structuredClone(reaction);\n\t\t\t},\n\t\t\tlistFeedbackReplies: async (owner, name, number, kind) =>\n\t\t\t\tkind === \"inline\"\n\t\t\t\t\t? structuredClone(\n\t\t\t\t\t\t\t(repo(owner, name).feedback[number] ?? [])\n\t\t\t\t\t\t\t\t.filter((f) => f.kind === \"inline\")\n\t\t\t\t\t\t\t\t.map((f) => ({ ...f })),\n\t\t\t\t\t\t)\n\t\t\t\t\t: client.listIssueComments(owner, name, number),\n\t\t\treplyFeedback: async (owner, name, number, kind, _id, body) => {\n\t\t\t\tif (kind !== \"inline\") return client.addIssueComment(owner, name, number, body);\n\t\t\t\tconst value = this.addFeedback(repo(owner, name), number, {\n\t\t\t\t\tkind: \"inline\",\n\t\t\t\t\tbody,\n\t\t\t\t\tauthor: profile.botLogin,\n\t\t\t\t});\n\t\t\t\tthis.lostResponse(\"reply\");\n\t\t\t\treturn structuredClone(value);\n\t\t\t},\n\t\t\tlistActionablePullRequestFeedback: async (owner, name, number, signal) =>\n\t\t\t\tactionableFeedback(\n\t\t\t\t\tclient,\n\t\t\t\t\tawait client.listPullRequestFeedback(owner, name, number, signal),\n\t\t\t\t),\n\t\t\tgetIssue: async (owner, name, number) => {\n\t\t\t\tconst issue = repo(owner, name).issues.find((i) => i.number === number);\n\t\t\t\tif (!issue) throw new Error(\"Unknown local GitHub issue\");\n\t\t\t\treturn structuredClone(issue);\n\t\t\t},\n\t\t\tgetCommit: async (owner, name, ref) => ({\n\t\t\t\tsha: this.git.head(repo(owner, name).repository.ssh_url, ref),\n\t\t\t}),\n\t\t\tisAncestor: async (owner, name, ancestor, descendant) =>\n\t\t\t\tthis.git.isAncestor(repo(owner, name).repository.ssh_url, ancestor, descendant),\n\t\t\tlistIssueComments: async (owner, name, number) =>\n\t\t\t\tstructuredClone(repo(owner, name).comments[number] ?? []),\n\t\t\taddIssueComment: async (owner, name, number, body) => {\n\t\t\t\tconst r = repo(owner, name);\n\t\t\t\tif (!r.pulls.some((p) => p.number === number) && !r.issues.some((i) => i.number === number))\n\t\t\t\t\tthrow new Error(\"Unknown local GitHub issue or PR\");\n\t\t\t\tconst value = this.newComment(body);\n\t\t\t\tr.comments[number] ??= [];\n\t\t\t\tr.comments[number].push(value);\n\t\t\t\tthis.save();\n\t\t\t\tthis.lostResponse(\"comment\");\n\t\t\t\treturn structuredClone(value);\n\t\t\t},\n\t\t\tcreatePullRequest: async (owner, name, input) => {\n\t\t\t\tconst r = repo(owner, name);\n\t\t\t\tconst pr = this.newPullRequest(r, input);\n\t\t\t\tr.pulls.push(pr);\n\t\t\t\tconst fail = this.state.failAfterPullRequestWrite;\n\t\t\t\tthis.state.failAfterPullRequestWrite = false;\n\t\t\t\tthis.save();\n\t\t\t\tif (fail) throw new Error(\"Local GitHub: response lost after PR creation\");\n\t\t\t\treturn this.refresh(r, pr);\n\t\t\t},\n\t\t\t...this.pullRequestClient(repo, \"Unknown local GitHub pull request\"),\n\t\t\tlistPullRequestFeedback: async (owner, name, number) =>\n\t\t\t\tstructuredClone([\n\t\t\t\t\t...(repo(owner, name).feedback[number] ?? []).filter((item) => {\n\t\t\t\t\t\tif (!profile.allowedOrganization) return true;\n\t\t\t\t\t\tconst editor = repo(owner, name).feedbackEditors[`${item.kind}:${item.id}`];\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\teditor === undefined ||\n\t\t\t\t\t\t\t(editor !== null &&\n\t\t\t\t\t\t\t\tthis.state.members.some((m) => m.toLowerCase() === editor.toLowerCase()))\n\t\t\t\t\t\t);\n\t\t\t\t\t}),\n\t\t\t\t\t...(repo(owner, name).comments[number] ?? []).map((c) => ({\n\t\t\t\t\t\tkind: \"conversation\" as const,\n\t\t\t\t\t\tid: c.id,\n\t\t\t\t\t\tbody: c.body,\n\t\t\t\t\t\tauthor: c.user.login,\n\t\t\t\t\t\tcreatedAt: c.created_at,\n\t\t\t\t\t})),\n\t\t\t\t]),\n\t\t\tgetCheckSummary: async (owner, name, sha) =>\n\t\t\t\tstructuredClone(\n\t\t\t\t\trepo(owner, name).checks[sha] ?? {\n\t\t\t\t\t\theadSha: sha,\n\t\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\tfailed: [],\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\tlistReleases: async (owner, name) => structuredClone(repo(owner, name).releases),\n\t\t\tdownloadReleaseAsset: async (asset) => {\n\t\t\t\tfor (const r of this.state.repositories)\n\t\t\t\t\tif (r.assets[asset.url] !== undefined) return r.assets[asset.url];\n\t\t\t\tthrow new Error(\"Unknown local GitHub release asset\");\n\t\t\t},\n\t\t};\n\t\treturn client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AAAA,MACF,iBAAiB,OAAO,OAAO,MAAM,QACpC;AAAA,QACC,KAAK,OAAO,IAAI,EAAE,OAAO,GAAG,KAAK;AAAA,UAChC,SAAS;AAAA,UACT,QAAQ;AAAA,UACR,OAAO;AAAA,UACP,QAAQ,CAAC;AAAA,QACV;AAAA,MACD;AAAA,MACD,cAAc,OAAO,OAAO,SAAS,gBAAgB,KAAK,OAAO,IAAI,EAAE,QAAQ;AAAA,MAC/E,sBAAsB,OAAO,UAAU;AACtC,mBAAW,KAAK,KAAK,MAAM;AAC1B,cAAI,EAAE,OAAO,MAAM,GAAG,MAAM,OAAW,QAAO,EAAE,OAAO,MAAM,GAAG;AACjE,cAAM,IAAI,MAAM,oCAAoC;AAAA,MACrD;AAAA,IACD;AACA,WAAO;AAAA,EACR;AACD;","names":["r"]}
@@ -0,0 +1,5 @@
1
+ import { type ExternalWriteLogRepoLike } from "@leitwerk-dev/external-writes";
2
+ import { type ServerExtensionAPI } from "@leitwerk-dev/process-sdk";
3
+ import type { GitHubIntegration } from "./capability.js";
4
+ export declare function registerGitHubTools(api: ServerExtensionAPI, integration: GitHubIntegration, writes: ExternalWriteLogRepoLike): void;
5
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,wBAAwB,EAG7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAKN,KAAK,kBAAkB,EAEvB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAezD,wBAAgB,mBAAmB,CAClC,GAAG,EAAE,kBAAkB,EACvB,WAAW,EAAE,iBAAiB,EAC9B,MAAM,EAAE,wBAAwB,QA8QhC"}
package/package.json CHANGED
@@ -1,16 +1,57 @@
1
1
  {
2
- "name": "@leitwerk-dev/github",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "Registration placeholder only. Not a usable Leitwerk release.",
5
- "license": "Apache-2.0",
6
- "repository": {
7
- "type": "git",
8
- "url": "git+https://github.com/leitwerk-dev/leitwerk.git"
9
- },
10
- "publishConfig": {
11
- "access": "public",
12
- "registry": "https://registry.npmjs.org/",
13
- "tag": "bootstrap",
14
- "provenance": false
15
- }
2
+ "name": "@leitwerk-dev/github",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "leitwerk": {
6
+ "extension": {
7
+ "source": "./src/index.ts",
8
+ "import": "./dist/index.js"
9
+ },
10
+ "discover": false
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "source": "./src/index.ts",
15
+ "import": "./dist/index.js",
16
+ "types": "./dist/index.d.ts"
17
+ },
18
+ "./testing": {
19
+ "source": "./src/testing.ts",
20
+ "import": "./dist/testing.js",
21
+ "types": "./dist/testing.d.ts"
22
+ }
23
+ },
24
+ "scripts": {
25
+ "build": "tsup && tsc -p tsconfig.tsup.json --emitDeclarationOnly"
26
+ },
27
+ "dependencies": {
28
+ "@leitwerk-dev/domain": "0.2.0",
29
+ "@leitwerk-dev/external-writes": "0.2.0",
30
+ "@leitwerk-dev/process-sdk": "0.2.0",
31
+ "@leitwerk-dev/watcher-utils": "0.2.0",
32
+ "@leitwerk-dev/repository-rebase": "0.2.0",
33
+ "@leitwerk-dev/test-support": "0.2.0"
34
+ },
35
+ "devDependencies": {
36
+ "tsup": "^8.5.1",
37
+ "@types/node": "^26.2.0"
38
+ },
39
+ "license": "Apache-2.0",
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "engines": {
44
+ "node": ">=26 <27"
45
+ },
46
+ "files": [
47
+ "dist/**",
48
+ "src/**",
49
+ "!dist/**/*.test.*",
50
+ "!src/**/*.test.ts"
51
+ ],
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "git+https://github.com/leitwerk-dev/leitwerk.git",
55
+ "directory": "extensions/github"
56
+ }
16
57
  }
@@ -0,0 +1,54 @@
1
+ import type { GitHubClient, GitHubFeedbackItem, GitHubIssue } from "./client.js";
2
+
3
+ type MembershipClient = Pick<GitHubClient, "profile" | "isOrganizationMember">;
4
+
5
+ export async function authorizedTrigger(
6
+ client: MembershipClient & Pick<GitHubClient, "getIssue" | "listIssueEvents">,
7
+ owner: string,
8
+ repo: string,
9
+ number: number,
10
+ trigger: string,
11
+ done: string,
12
+ ) {
13
+ if (
14
+ client.profile.allowedOrganization &&
15
+ owner.toLowerCase() !== client.profile.allowedOrganization.toLowerCase()
16
+ )
17
+ return null;
18
+ const issue = (await client.getIssue(owner, repo, number)) as GitHubIssue & {
19
+ pull_request?: unknown;
20
+ };
21
+ if (
22
+ issue.pull_request ||
23
+ issue.state !== "open" ||
24
+ !issue.labels.some((label) => label.name === trigger) ||
25
+ issue.labels.some((label) => label.name === done)
26
+ )
27
+ return null;
28
+ const last = (await client.listIssueEvents(owner, repo, number))
29
+ .filter(
30
+ (event) =>
31
+ (event.event === "labeled" || event.event === "unlabeled") && event.label?.name === trigger,
32
+ )
33
+ .sort((a, b) => b.id - a.id)[0];
34
+ if (
35
+ last?.event !== "labeled" ||
36
+ !last.actor?.login ||
37
+ !(await client.isOrganizationMember(last.actor.login))
38
+ )
39
+ return null;
40
+ return { issue, actor: last.actor.login, eventId: last.id };
41
+ }
42
+
43
+ export async function actionableFeedback(client: MembershipClient, feedback: GitHubFeedbackItem[]) {
44
+ const authorized: GitHubFeedbackItem[] = [];
45
+ for (const item of feedback) {
46
+ if (
47
+ item.author.toLowerCase() === client.profile.botLogin.toLowerCase() ||
48
+ item.body.includes("<!-- leitwerk-write:")
49
+ )
50
+ continue;
51
+ if (await client.isOrganizationMember(item.author)) authorized.push(item);
52
+ }
53
+ return authorized;
54
+ }
package/src/binding.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { resolveRepositoryProjectBinding } from "@leitwerk-dev/process-sdk";
2
+
3
+ export type { RepositoryProjectBinding as GitHubProjectBinding } from "@leitwerk-dev/process-sdk";
4
+ export const resolveGitHubProjectBinding = (
5
+ ctx: Parameters<typeof resolveRepositoryProjectBinding>[0],
6
+ ) => resolveRepositoryProjectBinding(ctx, "github");
@@ -0,0 +1,13 @@
1
+ import { createCapabilityToken } from "@leitwerk-dev/process-sdk";
2
+ import type { GitHubClient } from "./client.js";
3
+
4
+ /** Public contract shared by HTTP and local adapters. */
5
+ export type GitHubClientLike = Pick<GitHubClient, keyof GitHubClient>;
6
+
7
+ export interface GitHubIntegration {
8
+ client(profile: string): GitHubClientLike;
9
+ }
10
+
11
+ export const githubIntegration = createCapabilityToken<GitHubIntegration>(
12
+ "@leitwerk-private/github.integration",
13
+ );
package/src/client.ts ADDED
@@ -0,0 +1,421 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import {
3
+ type RepositoryFeedbackItem as GitHubFeedbackItem,
4
+ type RepositoryIssue as GitHubIssue,
5
+ type RepositoryPullRequest as GitHubPullRequest,
6
+ IntegrationHttpError,
7
+ normalizeRepositoryFeedback as normalize,
8
+ RepositoryHttpClient,
9
+ } from "@leitwerk-dev/process-sdk";
10
+
11
+ import { actionableFeedback, authorizedTrigger } from "./authorization.js";
12
+
13
+ export type { GitHubFeedbackItem, GitHubIssue, GitHubPullRequest };
14
+
15
+ export interface GitHubRepository {
16
+ name: string;
17
+ full_name: string;
18
+ owner: { login: string };
19
+ ssh_url: string;
20
+ default_branch: string;
21
+ html_url: string;
22
+ archived: boolean;
23
+ has_issues: boolean;
24
+ }
25
+ export interface GitHubGitIdentity {
26
+ provider: "github";
27
+ profile: string;
28
+ login: string;
29
+ name: string;
30
+ email: string;
31
+ }
32
+ export interface GitHubLabelEvent {
33
+ id: number;
34
+ event: string;
35
+ label?: { name: string };
36
+ actor: { login: string } | null;
37
+ }
38
+
39
+ export interface GitHubProfile {
40
+ apiBaseUrl: string;
41
+ token: string;
42
+ botLogin: string;
43
+ allowedOrganization?: string;
44
+ }
45
+
46
+ export interface GitHubCheckSummary {
47
+ headSha: string;
48
+ status: "pending" | "success" | "failure";
49
+ total: number;
50
+ failed: Array<{
51
+ name: string;
52
+ conclusion: string | null;
53
+ url: string | null;
54
+ }>;
55
+ }
56
+
57
+ export interface GitHubRelease {
58
+ id: number;
59
+ tag_name: string;
60
+ target_commitish: string;
61
+ draft: boolean;
62
+ prerelease: boolean;
63
+ html_url: string;
64
+ assets: Array<{ name: string; url: string; browser_download_url: string }>;
65
+ }
66
+
67
+ export function parseGitHubProfiles(value: unknown): Map<string, GitHubProfile> {
68
+ const profiles = new Map<string, GitHubProfile>();
69
+ for (const [name, raw] of Object.entries(
70
+ asUnknownRecord(asUnknownRecord(value)?.profiles) ?? {},
71
+ )) {
72
+ const config = asUnknownRecord(raw) ?? {};
73
+ const apiBaseUrl =
74
+ typeof config.api_base_url === "string"
75
+ ? config.api_base_url.replace(/\/+$/, "")
76
+ : "https://api.github.com";
77
+ const token = typeof config.token === "string" ? config.token.trim() : "";
78
+ const botLogin = typeof config.bot_login === "string" ? config.bot_login.trim() : "leitwerk";
79
+ if (!/^https:\/\//.test(apiBaseUrl))
80
+ throw new Error(`GitHub profile '${name}' requires an HTTPS api_base_url`);
81
+ if (!token) throw new Error(`GitHub profile '${name}' requires a token`);
82
+ if (!botLogin) throw new Error(`GitHub profile '${name}' requires bot_login`);
83
+ const allowedOrganization = config.allowed_organization;
84
+ if (
85
+ allowedOrganization !== undefined &&
86
+ (typeof allowedOrganization !== "string" || !/^[a-z0-9-]+$/i.test(allowedOrganization))
87
+ ) {
88
+ throw new Error(`GitHub profile '${name}' requires a valid allowed_organization`);
89
+ }
90
+ profiles.set(name, {
91
+ apiBaseUrl,
92
+ token,
93
+ botLogin,
94
+ ...(typeof allowedOrganization === "string"
95
+ ? { allowedOrganization: allowedOrganization.toLowerCase() }
96
+ : {}),
97
+ });
98
+ }
99
+ return profiles;
100
+ }
101
+
102
+ export function assertGitHubRepository(profile: GitHubProfile, owner: string, repo: string): void {
103
+ if (
104
+ !/^[a-z0-9-]+$/i.test(owner) ||
105
+ !/^[a-z0-9_.-]+$/i.test(repo) ||
106
+ repo === "." ||
107
+ repo === ".."
108
+ ) {
109
+ throw new Error("Invalid GitHub repository");
110
+ }
111
+ if (
112
+ profile.allowedOrganization &&
113
+ owner.toLowerCase() !== profile.allowedOrganization.toLowerCase()
114
+ ) {
115
+ throw new Error(`GitHub project must belong to ${profile.allowedOrganization}`);
116
+ }
117
+ }
118
+
119
+ export class GitHubClient extends RepositoryHttpClient {
120
+ constructor(readonly profile: GitHubProfile) {
121
+ super("GitHub", profile.apiBaseUrl, {
122
+ Accept: "application/vnd.github+json",
123
+ Authorization: `Bearer ${profile.token}`,
124
+ "X-GitHub-Api-Version": "2022-11-28",
125
+ });
126
+ }
127
+
128
+ protected override response(path: string, init: RequestInit = {}): Promise<Response> {
129
+ return super.response(path, {
130
+ ...init,
131
+ redirect: "error",
132
+ signal: init.signal ?? AbortSignal.timeout(30_000),
133
+ });
134
+ }
135
+
136
+ protected override repositoryPath(owner: string, repo: string): string {
137
+ assertGitHubRepository(this.profile, owner, repo);
138
+ return super.repositoryPath(owner, repo);
139
+ }
140
+
141
+ async listRepositories() {
142
+ return (
143
+ await this.pages<GitHubRepository>(
144
+ this.profile.allowedOrganization
145
+ ? `/orgs/${this.profile.allowedOrganization}/repos?type=all`
146
+ : "/user/repos?affiliation=owner,collaborator,organization_member",
147
+ )
148
+ ).filter(
149
+ (repo) =>
150
+ (!this.profile.allowedOrganization ||
151
+ repo.owner.login.toLowerCase() === this.profile.allowedOrganization.toLowerCase()) &&
152
+ !repo.archived &&
153
+ repo.has_issues,
154
+ );
155
+ }
156
+ async listOpenIssues(owner: string, repo: string) {
157
+ return (
158
+ await this.pages<GitHubIssue & { pull_request?: unknown }>(
159
+ `${this.repositoryPath(owner, repo)}/issues?state=open`,
160
+ )
161
+ ).filter((issue) => !issue.pull_request);
162
+ }
163
+ listIssueEvents(owner: string, repo: string, number: number) {
164
+ return this.pages<GitHubLabelEvent>(
165
+ `${this.repositoryPath(owner, repo)}/issues/${number}/events`,
166
+ );
167
+ }
168
+ async isOrganizationMember(login: string): Promise<boolean> {
169
+ if (!this.profile.allowedOrganization) return true;
170
+ if (!/^[a-z0-9-]+$/i.test(login)) return false;
171
+ try {
172
+ const response = await this.response(
173
+ `/orgs/${this.profile.allowedOrganization}/members/${encodeURIComponent(login)}`,
174
+ );
175
+ return response.status === 204;
176
+ } catch (error) {
177
+ if (error instanceof IntegrationHttpError) {
178
+ if (error.status === 404) return false;
179
+ throw new Error(`GitHub membership check failed with ${error.status}`);
180
+ }
181
+ throw error;
182
+ }
183
+ }
184
+ async authorizedTrigger(
185
+ owner: string,
186
+ repo: string,
187
+ number: number,
188
+ trigger: string,
189
+ done: string,
190
+ ) {
191
+ return authorizedTrigger(this, owner, repo, number, trigger, done);
192
+ }
193
+ async resolveGitIdentity(profile: string): Promise<GitHubGitIdentity> {
194
+ const user = await this.request<{ login: string; name: string | null; id: number }>("/user");
195
+ if (user.login !== this.profile.botLogin)
196
+ throw new Error("GitHub authenticated user does not match bot_login");
197
+ return {
198
+ provider: "github",
199
+ profile,
200
+ login: user.login,
201
+ name: user.name || user.login,
202
+ email: `${user.id}+${user.login}@users.noreply.github.com`,
203
+ };
204
+ }
205
+ updateIssue(owner: string, repo: string, number: number, patch: Record<string, unknown>) {
206
+ return this.request<GitHubIssue>(`${this.repositoryPath(owner, repo)}/issues/${number}`, {
207
+ method: "PATCH",
208
+ body: JSON.stringify(patch),
209
+ });
210
+ }
211
+ async ensureLabel(owner: string, repo: string, name: string) {
212
+ const labels = await this.pages<{ id: number; name: string }>(
213
+ `${this.repositoryPath(owner, repo)}/labels`,
214
+ );
215
+ return (
216
+ labels.find((label) => label.name === name) ??
217
+ this.request<{ id: number; name: string }>(`${this.repositoryPath(owner, repo)}/labels`, {
218
+ method: "POST",
219
+ body: JSON.stringify({ name, color: "238636" }),
220
+ })
221
+ );
222
+ }
223
+ addFeedbackReaction(owner: string, repo: string, kind: string, id: number) {
224
+ const segment = kind === "inline" ? "pulls/comments" : "issues/comments";
225
+ return this.request(`${this.repositoryPath(owner, repo)}/${segment}/${id}/reactions`, {
226
+ method: "POST",
227
+ body: JSON.stringify({ content: "eyes" }),
228
+ });
229
+ }
230
+ async replyFeedback(
231
+ owner: string,
232
+ repo: string,
233
+ pr: number,
234
+ kind: string,
235
+ id: number,
236
+ body: string,
237
+ ) {
238
+ if (kind === "inline")
239
+ return this.request(
240
+ `${this.repositoryPath(owner, repo)}/pulls/${pr}/comments/${id}/replies`,
241
+ {
242
+ method: "POST",
243
+ body: JSON.stringify({ body }),
244
+ },
245
+ );
246
+ return this.addIssueComment(owner, repo, pr, body);
247
+ }
248
+
249
+ getCommit(owner: string, repo: string, ref: string) {
250
+ return this.request<{ sha: string }>(
251
+ `${this.repositoryPath(owner, repo)}/commits/${encodeURIComponent(ref)}`,
252
+ );
253
+ }
254
+
255
+ async isAncestor(owner: string, repo: string, ancestor: string, descendant: string) {
256
+ const comparison = await this.request<{ status: string }>(
257
+ `${this.repositoryPath(owner, repo)}/compare/${encodeURIComponent(ancestor)}...${encodeURIComponent(descendant)}`,
258
+ );
259
+ return comparison.status === "identical" || comparison.status === "ahead";
260
+ }
261
+
262
+ async listPullRequestFeedback(
263
+ owner: string,
264
+ repo: string,
265
+ number: number,
266
+ signal?: AbortSignal,
267
+ ): Promise<GitHubFeedbackItem[]> {
268
+ const prefix = `${this.repositoryPath(owner, repo)}`;
269
+ const [conversation, reviews, inline] = await Promise.all([
270
+ this.pages<Record<string, unknown>>(`${prefix}/issues/${number}/comments`, signal),
271
+ this.pages<Record<string, unknown>>(`${prefix}/pulls/${number}/reviews`, signal),
272
+ this.pages<Record<string, unknown>>(`${prefix}/pulls/${number}/comments`, signal),
273
+ ]);
274
+
275
+ const candidates = [
276
+ ...conversation.map((item) => ({ kind: "conversation" as const, item })),
277
+ ...reviews.map((item) => ({ kind: "review" as const, item })),
278
+ ...inline.map((item) => ({ kind: "inline" as const, item })),
279
+ ];
280
+ const feedback: GitHubFeedbackItem[] = [];
281
+ const needsProvenance: typeof candidates = [];
282
+ for (const candidate of candidates) {
283
+ const { kind, item } = candidate;
284
+ const normalized = normalize(kind, item);
285
+ if (!normalized) continue;
286
+ const createdAt = typeof item.created_at === "string" ? Date.parse(item.created_at) : NaN;
287
+ const updatedAt = typeof item.updated_at === "string" ? Date.parse(item.updated_at) : NaN;
288
+ if (
289
+ !this.profile.allowedOrganization ||
290
+ (kind !== "review" && Number.isFinite(createdAt) && createdAt === updatedAt)
291
+ ) {
292
+ feedback.push(normalized);
293
+ } else if (typeof item.node_id === "string" && item.node_id) {
294
+ // REST attributes edited bodies to their original author. Reviews also
295
+ // omit edit timestamps, so obtain the body and latest editor together.
296
+ needsProvenance.push(candidate);
297
+ }
298
+ }
299
+ for (let offset = 0; offset < needsProvenance.length; offset += 100) {
300
+ const batch = needsProvenance.slice(offset, offset + 100);
301
+ const response = await this.request<{
302
+ data?: { nodes?: Array<Record<string, unknown> | null> };
303
+ errors?: unknown[];
304
+ }>("/graphql", {
305
+ method: "POST",
306
+ signal,
307
+ body: JSON.stringify({
308
+ query: `query LeitwerkFeedbackProvenance($ids: [ID!]!) {
309
+ nodes(ids: $ids) {
310
+ id __typename
311
+ ... on IssueComment { body createdAt lastEditedAt author { login } editor { login } }
312
+ ... on PullRequestReview { body createdAt submittedAt lastEditedAt author { login } editor { login } }
313
+ ... on PullRequestReviewComment { body createdAt lastEditedAt author { login } editor { login } path line }
314
+ }
315
+ }`,
316
+ variables: { ids: batch.map(({ item }) => item.node_id) },
317
+ }),
318
+ });
319
+ if (response.errors?.length || !Array.isArray(response.data?.nodes)) {
320
+ throw new Error("GitHub feedback provenance lookup failed");
321
+ }
322
+ const snapshots = new Map(
323
+ response.data.nodes.filter((node) => node !== null).map((node) => [node.id, node]),
324
+ );
325
+ for (const { kind, item } of batch) {
326
+ const snapshot = snapshots.get(item.node_id);
327
+ const expectedType = {
328
+ conversation: "IssueComment",
329
+ review: "PullRequestReview",
330
+ inline: "PullRequestReviewComment",
331
+ }[kind];
332
+ if (!snapshot || snapshot.__typename !== expectedType) continue;
333
+ const publishedAt = kind === "review" ? snapshot.submittedAt : snapshot.createdAt;
334
+ if (typeof publishedAt !== "string" || !Number.isFinite(Date.parse(publishedAt))) continue;
335
+ const editedAt = snapshot.lastEditedAt;
336
+ if (editedAt !== null) {
337
+ if (typeof editedAt !== "string" || !Number.isFinite(Date.parse(editedAt))) continue;
338
+ const editor = asUnknownRecord(snapshot.editor)?.login;
339
+ if (typeof editor !== "string" || !(await this.isOrganizationMember(editor))) continue;
340
+ }
341
+ const normalized = normalize(kind, {
342
+ ...snapshot,
343
+ id: item.id,
344
+ user: snapshot.author,
345
+ created_at: editedAt ?? publishedAt,
346
+ });
347
+ if (normalized) feedback.push(normalized);
348
+ }
349
+ }
350
+ return feedback;
351
+ }
352
+
353
+ async getCheckSummary(owner: string, repo: string, headSha: string): Promise<GitHubCheckSummary> {
354
+ const runs: Array<Record<string, unknown>> = [];
355
+ for (let page = 1; ; page++) {
356
+ const response = await this.request<{ check_runs: Array<Record<string, unknown>> }>(
357
+ `${this.repositoryPath(owner, repo)}/commits/${headSha}/check-runs?per_page=100&page=${page}`,
358
+ );
359
+ runs.push(...response.check_runs);
360
+ if (response.check_runs.length < 100) break;
361
+ }
362
+ const terminalSuccess = new Set(["success", "neutral", "skipped"]);
363
+ const failed = runs
364
+ .filter((run) => run.status === "completed" && !terminalSuccess.has(String(run.conclusion)))
365
+ .map((run) => ({
366
+ name: String(run.name ?? "unknown"),
367
+ conclusion: typeof run.conclusion === "string" ? run.conclusion : null,
368
+ url: typeof run.html_url === "string" ? run.html_url : null,
369
+ }));
370
+ const pending = runs.some((run) => run.status !== "completed");
371
+ return {
372
+ headSha,
373
+ status: failed.length ? "failure" : pending || !runs.length ? "pending" : "success",
374
+ total: runs.length,
375
+ failed,
376
+ };
377
+ }
378
+
379
+ /** Human feedback checked against current membership; delivery receipts use raw reads. */
380
+ async listActionablePullRequestFeedback(
381
+ owner: string,
382
+ repo: string,
383
+ number: number,
384
+ signal?: AbortSignal,
385
+ ) {
386
+ return actionableFeedback(
387
+ this,
388
+ await this.listPullRequestFeedback(owner, repo, number, signal),
389
+ );
390
+ }
391
+
392
+ listFeedbackReplies(owner: string, repo: string, pr: number, kind: string) {
393
+ return kind === "inline"
394
+ ? this.pages<Record<string, unknown>>(
395
+ `${this.repositoryPath(owner, repo)}/pulls/${pr}/comments`,
396
+ )
397
+ : this.listIssueComments(owner, repo, pr);
398
+ }
399
+
400
+ listFeedbackReactions(owner: string, repo: string, kind: string, id: number) {
401
+ if (kind !== "inline" && kind !== "conversation")
402
+ throw new Error("Reviews do not support reactions");
403
+ const segment = kind === "inline" ? "pulls/comments" : "issues/comments";
404
+ return this.pages<{ id: number; content: string; user: { login: string } }>(
405
+ `${this.repositoryPath(owner, repo)}/${segment}/${id}/reactions`,
406
+ );
407
+ }
408
+
409
+ listReleases(owner: string, repo: string) {
410
+ return this.pages<GitHubRelease>(`${this.repositoryPath(owner, repo)}/releases`);
411
+ }
412
+
413
+ downloadReleaseAsset(asset: GitHubRelease["assets"][number]): Promise<string> {
414
+ const url = new URL(asset.url);
415
+ if (`${url.protocol}//${url.host}` !== this.profile.apiBaseUrl)
416
+ throw new Error("GitHub release asset URL does not match the configured API origin");
417
+ return this.response(`${url.pathname}${url.search}`, {
418
+ headers: { Accept: "application/octet-stream" },
419
+ }).then((response) => response.text());
420
+ }
421
+ }