Skip to content
← Public packages

@kody/lineage

Interactive commit-level lines of kody, minus generated noise, as an offline-ready chart.

FollowForkOpen app

Files

handle-github-webhook.ts

65 lines · 2.2 KB · TypeScript
import ingestMissing from './ingest-missing.ts'
import { getRepoSettings } from './storage.ts'

type WebhookInput = {
	request?: {
		headers?: Record<string, string>
		json?: unknown
		body?: string
	}
}

type GithubPushPayload = {
	ref?: string
	before?: string
	after?: string
	repository?: { full_name?: string }
	commits?: Array<{ id?: string }>
}

/**
 * Ingest new main-branch commits from a GitHub push webhook, following the
 * pushed tip's first parents (merged-in branch commits are not ingested).
 * Platform HMAC verification happens before this export runs.
 *
 * @param input - Kody webhook envelope with the GitHub push JSON body
 * @returns Whether the delivery was ignored or which SHAs were ingested
 *
 * @example
 * import handleGithubWebhook from 'kody:@kody/lineage/handle-github-webhook'
 *
 * const result = await handleGithubWebhook({
 *   request: { json: { ref: 'refs/heads/main', commits: [{ id: 'abc' }] } },
 * })
 */
export default async function handleGithubWebhook(input: WebhookInput = {}) {
	const payload = (input.request?.json ?? {}) as GithubPushPayload
	const headers = input.request?.headers ?? {}
	const event = headers['x-github-event'] || headers['X-GitHub-Event']
	if (event && event !== 'push') {
		return { ok: true, ignored: true, reason: `event:${event}` }
	}

	const repo = await getRepoSettings()
	const expectedRef = `refs/heads/${repo.branch}`
	if (payload.ref && payload.ref !== expectedRef) {
		return { ok: true, ignored: true, reason: `ref:${payload.ref}` }
	}

	const remoteName = payload.repository?.full_name
	const expectedName = `${repo.owner}/${repo.repo}`
	if (remoteName && remoteName.toLowerCase() !== expectedName.toLowerCase()) {
		return { ok: true, ignored: true, reason: `repo:${remoteName}` }
	}

	// Walk first parents back from the pushed tip instead of ingesting
	// `payload.commits`: for a merge push that list holds every commit of the
	// merged branch, which would land on the graph at its authoring time.
	const zero = '0'.repeat(40)
	const head = payload.after && payload.after !== zero ? payload.after : null
	if (!head) {
		return ingestMissing({ limit: 10, maxPages: 1 })
	}
	const before = payload.before && payload.before !== zero ? payload.before : null
	return ingestMissing({ head, before, limit: 40 })
}