Skip to content

src/installations.ts

91 lines · 2.8 KB · TypeScript
Raw
import { listOriginInstallations } from './auth.ts'
import { originRequest } from './request.ts'
import { type OriginRepoSummary } from './types.ts'

export { listOriginInstallations }

export async function listOriginInstallationRepos(
	params: {
		pageSize?: number
		pageToken?: string
		installationId?: string
	} = {},
): Promise<{ items: Array<OriginRepoSummary>; nextPageToken: string | null }> {
	const result = await originRequest({
		path: '/installation/repos',
		auth: 'installation',
		installationId: params.installationId,
		query: {
			pageSize: params.pageSize,
			pageToken: params.pageToken,
		},
	})
	if (!result.ok) {
		const message =
			isRecord(result.body) && typeof result.body.message === 'string'
				? result.body.message
				: `HTTP ${String(result.status)}`
		throw new Error(`Failed to list Origin installation repos: ${message}`)
	}
	const payload = isRecord(result.body) ? result.body : {}
	const raw = Array.isArray(payload.repositories) ? payload.repositories : []
	return {
		items: raw.map((item) => slimRepo(asRecord(item))),
		nextPageToken:
			typeof payload.nextPageToken === 'string' && payload.nextPageToken
				? payload.nextPageToken
				: null,
	}
}

/**
 * List Origin App installations for this Origin App (app JWT, no installation token).
 *
 * Use `listOriginInstallationRepos` on this same export module when you need
 * repos the installation can see.
 *
 * @returns `{ items }` of installation summaries (id, target, scopes).
 * @example
 * import listOriginInstallations from 'kody:@kentcdodds/origin/installations'
 * const { items } = await listOriginInstallations()
 * // => { items: [{ id: 'ins_01...', appId: 'app_01...', target: { slug: 'kentcdodds' }, ... }] }
 */
export default async function listInstallations() {
	return await listOriginInstallations()
}

function slimRepo(item: Record<string, unknown>): OriginRepoSummary {
	const owner = isRecord(item.owner) ? item.owner : null
	const mirror = isRecord(item.mirror) ? item.mirror : null
	return {
		id: stringField(item.id) ?? '',
		name: stringField(item.name) ?? '',
		fullName: stringField(item.fullName),
		owner: owner
			? {
					slug: stringField(owner.slug) ?? '',
					id: stringField(owner.id) ?? '',
				}
			: null,
		defaultBranch: stringField(item.defaultBranch),
		cloneUrl: stringField(item.cloneUrl),
		mirror: mirror
			? {
					source: stringField(mirror.source),
					status: stringField(mirror.status),
				}
			: null,
	}
}

function asRecord(value: unknown): Record<string, unknown> {
	return isRecord(value) ? value : {}
}

function isRecord(value: unknown): value is Record<string, unknown> {
	return value !== null && typeof value === 'object' && !Array.isArray(value)
}

function stringField(value: unknown): string | null {
	return typeof value === 'string' && value.length > 0 ? value : null
}