Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

github-release.test.ts

108 lines · 6.0 KB · TypeScript
import assert from 'node:assert/strict'
import { registerHooks } from 'node:module'
import { test } from 'node:test'

const STUB = `
const store = globalThis.__factoryStore ??= new Map();
globalThis.__factoryWrites ??= { n: 0 };
export const packageStorage = () => ({
  async get(k) { return store.get(k) ?? null },
  async set(k, v) { globalThis.__factoryWrites.n++; store.set(k, JSON.stringify(v)) },
});
export const packageContext = { appBasePath: '/apps/factory/' };
export async function credential(key) {
  if (key !== 'github' || !globalThis.__githubFetch) throw new Error('credential not mapped');
  return { name: 'github', fetch: globalThis.__githubFetch };
}
export async function credentials() { return [] }
`
registerHooks({
	resolve(spec, ctx, next) {
		if (spec === 'kody:@kody/github/events/ingest') return { url: `data:text/javascript,${encodeURIComponent('export default async () => ({ ok: true, emitted: [] })')}`, shortCircuit: true }
		if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true }
		return next(spec, ctx)
	},
})
const g = globalThis as unknown as { __factoryWrites: { n: number }; __githubFetch?: (u: string) => Promise<Response> }
const { extractReleaseImages, normalizeRelease, safeImageUrl, MAX_RELEASE_IMAGES } = await import('./github-release.ts')
const { default: webhook } = await import('../webhooks/github-release.ts')
const { default: reconcile } = await import('../exports/github-release.ts')
const { upsertProject } = await import('../projects/config.ts')
const { loadReleaseState } = await import('../lib/release-store.ts')

await upsertProject({ id: 'rel', displayName: 'Rel', enabled: true, defaultRunnerId: 'devin', repos: [{ id: 'o__on', repoRef: 'o/on', host: 'github', enabled: true }], sources: { githubRelease: { enabled: true, expectWithinHours: 26 } } })
await upsertProject({ id: 'quiet', displayName: 'Quiet', enabled: true, defaultRunnerId: 'devin', repos: [{ id: 'o__off', repoRef: 'o/off', host: 'github', enabled: true }] })

const BODY = [
	'## New', 'Screens: ![Home (dark)](https://github.com/user-attachments/assets/abc-123 "Home")',
	'![q](https://private-user-images.githubusercontent.com/1/2.png?jwt=x&s=(1))',
	'![evil](https://evil.example/x.png) ![js](javascript:alert(1)) ![http](http://github.com/a.png)',
	'<img alt="Old" src="https://user-images.githubusercontent.com/9/old.png">',
	'<img src=https://raw.githubusercontent.com/o/r/main/a.png>',
	'![dup](https://github.com/user-attachments/assets/abc-123)',
].join('\n')

test('image extraction: allowed hosts only, balanced parens, queries, html img, dedupe', () => {
	const imgs = extractReleaseImages(BODY)
	assert.deepEqual(imgs.map((i) => i.url), [
		'https://github.com/user-attachments/assets/abc-123',
		'https://private-user-images.githubusercontent.com/1/2.png?jwt=x&s=(1)',
		'https://user-images.githubusercontent.com/9/old.png',
		'https://raw.githubusercontent.com/o/r/main/a.png',
	])
	assert.equal(imgs[0]!.alt, 'Home (dark)')
	assert.equal(safeImageUrl('https://github.com.evil.io/a.png'), null)
	const many = Array.from({ length: 15 }, (_, i) => `![x](https://github.com/a/${i}.png)`).join(' ')
	assert.equal(extractReleaseImages(many).length, MAX_RELEASE_IMAGES)
})

const release = (action: string, extra: Record<string, unknown> = {}, repo = 'o/on') => ({
	request: { json: { action, repository: { full_name: repo }, sender: { login: 'bot' }, release: { id: 432583961, tag_name: 'v2026.11.03', name: 'Kody v2026.11.03', html_url: 'https://github.com/o/on/releases/tag/v2026.11.03', target_commitish: 'main', published_at: '2026-11-03T11:03:24Z', body: BODY, ...extra } } },
})

test('normalizer keeps references and a plain snippet only', () => {
	const r = normalizeRelease(release('published').request.json, { projectId: 'rel', repoRef: 'o/on' })!
	assert.equal(r.key, 'o/on#432583961')
	assert.equal(r.actor, 'bot')
	assert.doesNotMatch(r.snippet, /<img|!\[/)
	assert.ok(r.snippet.length <= 500)
})

test('disabled repo returns 501 and writes nothing', async () => {
	const before = g.__factoryWrites.n
	const r = (await webhook(release('published', {}, 'o/off'))) as Record<string, unknown>
	assert.equal(r.ok, false)
	assert.equal(r.status, 501)
	assert.equal(g.__factoryWrites.n, before)
})

test('synthetic release never writes; published dedupes; edited updates; deleted marks state', async () => {
	const before = g.__factoryWrites.n
	const s = (await webhook({ ...release('published'), synthetic: true })) as Record<string, unknown>
	assert.equal(s.wrote, false)
	assert.equal(g.__factoryWrites.n, before)
	assert.equal(((await webhook(release('published'))) as Record<string, unknown>).change, 'created')
	assert.equal(((await webhook(release('published'))) as Record<string, unknown>).change, 'unchanged')
	assert.equal(((await webhook(release('edited', { name: 'Renamed' }))) as Record<string, unknown>).change, 'updated')
	assert.equal(((await webhook(release('deleted', { name: 'Renamed' }))) as Record<string, unknown>).change, 'updated')
	const st = await loadReleaseState()
	assert.equal(st.releases['o/on#432583961']!.externalState, 'deleted')
	assert.equal(st.checkpoints['o/on']!.lastTag, 'v2026.11.03')
})

test('reconcile: dry run, credential missing, overdue only when configured', async () => {
	g.__githubFetch = undefined
	const miss = await reconcile({})
	assert.equal(miss.setup, 'github-credential-missing')
	const calls: string[] = []
	g.__githubFetch = async (u) => { if (u.endsWith('/rate_limit')) return Response.json({}); calls.push(u); return Response.json([release('published').request.json.release, { id: 2, tag_name: 'draft', draft: true }]) }
	const before = g.__factoryWrites.n
	const r = await reconcile({ maxCount: 99 }, { now: new Date('2026-11-05T23:00:00Z') })
	assert.equal(r.maxCount, 20)
	assert.equal(calls.length, 1)
	assert.match(calls[0]!, /^https:\/\/api\.github\.com\/repos\/o\/on\/releases\?per_page=20$/)
	const repo = r.repos[0] as Record<string, unknown>
	assert.equal(repo.overdue, true)
	assert.equal((repo.latest as { tag: string }).tag, 'v2026.11.03')
	assert.equal(g.__factoryWrites.n, before, 'dry run never writes')
})