// Branchwell: open Git hosting. Clone, pull and push over HTTPS; passkey sign-in; commits and branches // are kept or removed by votes. One Worker, one D1 database, one Durable Object per repository. import type { Env } from './env'; import { page, esc, ago, sizeText, markdown, diffHtml, SITE, SECURITY } from './html'; import { handleAuth, currentAccount, canVote, pusherFromBasic, RESERVED, type Account } from './auth'; import { featuresApi, featureVote, WIDGET_JS } from './features'; import { ODOMETER_CSS, ODOMETER_JS, APP_JS } from './static'; import * as C from './content'; import { isText } from './repo'; export { RepoDO } from './repo'; // Every repository lives under an owner: a company account (org) or a person, as owner/project. const OWNER_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/; const PROJ_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/; const FULL_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?\/[a-z0-9][a-z0-9._-]{0,62}$/; const VIEWS = new Set(['tree', 'blob', 'raw', 'commits', 'commit', 'branches']); const GIT_RE = /^\/([a-z0-9][a-z0-9-]{0,39})\/([a-z0-9][a-z0-9._-]{0,62}?)(?:\.git)?\/(info\/refs|git-upload-pack|git-receive-pack)$/; const OLD_GIT_RE = /^\/([a-z0-9][a-z0-9._-]{0,62}?)(?:\.git)?\/(info\/refs|git-upload-pack|git-receive-pack)$/; const json = (b: unknown, s = 200, h: Record = {}) => new Response(JSON.stringify(b), { status: s, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...h } }); // do_name is the storage key. Older repos keep the flat name they were first pushed under. const stub = (env: Env, doName: string) => env.REPO.get(env.REPO.idFromName(doName.toLowerCase())); type RepoRow = { name: string; owner: string; do_name: string; description: string; created_by: string; created_at: number; updated_at: number }; type Org = { handle: string; name: string; domain: string | null; about: string | null; created_at: number }; const asset = (body: string, type: string) => new Response(body, { headers: { 'content-type': type, 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' } }); const APP = ['/assets/app.js']; async function repoRow(env: Env, name: string) { return env.DB.prepare('SELECT name, owner, COALESCE(do_name, name) AS do_name, description, created_by, created_at, updated_at FROM repos WHERE name = ?').bind(name.toLowerCase()).first(); } const orgRow = (env: Env, handle: string) => env.DB.prepare('SELECT handle, name, domain, about, created_at FROM orgs WHERE handle = ?').bind(handle.toLowerCase()).first(); async function myOrgs(env: Env, me: Account) { return (await env.DB.prepare('SELECT o.handle, o.name, o.domain, o.about, o.created_at FROM org_members m JOIN orgs o ON o.handle = m.org WHERE m.account_id = ? ORDER BY o.name').bind(me.id).all()).results; } async function canCreateUnder(env: Env, owner: string, by: Account) { if (owner === by.handle.toLowerCase()) return true; return !!(await env.DB.prepare('SELECT 1 AS x FROM org_members WHERE org = ? AND account_id = ?').bind(owner, by.id).first('x')); } async function createRepo(env: Env, owner: string, project: string, description: string, by: Account): Promise { owner = owner.toLowerCase(); project = project.toLowerCase().replace(/\.git$/, ''); if (!PROJ_RE.test(project) || VIEWS.has(project)) return 'Use 1 to 63 lowercase letters, numbers, dots, dashes or underscores.'; if (!(await canCreateUnder(env, owner, by))) return `You can start projects under your own name, or under a company you belong to. ${owner} isn't one of those.`; const name = owner + '/' + project; if (await repoRow(env, name)) return 'That name is taken.'; if (owner === by.handle.toLowerCase()) { const n = await env.DB.prepare('SELECT COUNT(*) AS n FROM repos WHERE created_by = ? AND owner = ? AND created_at > ?').bind(by.handle, owner, Date.now() - 864e5).first('n'); if ((n || 0) >= 5) return 'You can make 5 projects a day. Try again tomorrow.'; } await env.DB.prepare('INSERT INTO repos (name, owner, do_name, description, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)').bind(name, owner, name, description.slice(0, 300), by.handle, Date.now()).run(); await stub(env, name).init(name); return null; } export default { async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise { const url = new URL(req.url); if (url.hostname === 'www.branchwell.ai') return Response.redirect(SITE + url.pathname + url.search, 301); const path = decodeURIComponent(url.pathname); try { // ---------- Git over HTTPS ---------- const g = url.pathname.match(GIT_RE); if (g) return await git(req, env, ctx, g[1] + '/' + g[2], g[3], url); const og = url.pathname.match(OLD_GIT_RE); if (og) { // Old one-part addresses (branchwell.ai/sunlaid.git) now live at the company's research project. const to = await repoRow(env, og[1].toLowerCase() + '/research'); if (to) return Response.redirect(`${SITE}/${to.name}.git/${og[2]}${url.search}`, 301); return new Response(`Repositories now live under an owner, like https://branchwell.ai/sunlaid/research.git\n`, { status: 404, headers: { 'content-type': 'text/plain' } }); } // ---------- assets and APIs ---------- if (path === '/assets/app.js') return asset(APP_JS, 'text/javascript; charset=utf-8'); if (path === '/assets/visitor-odometer.v1.js') return asset(ODOMETER_JS, 'text/javascript; charset=utf-8'); if (path === '/assets/visitor-odometer.v1.css') return asset(ODOMETER_CSS, 'text/css; charset=utf-8'); if (path === '/widget/features.v1.js') return asset(WIDGET_JS, 'text/javascript; charset=utf-8'); if (path === '/robots.txt') return new Response(`User-agent: *\nAllow: /\nDisallow: /api/\nSitemap: ${SITE}/sitemap.xml\n`, { headers: { 'content-type': 'text/plain' } }); if (path === '/sitemap.xml') return sitemap(env); if (path === '/llms.txt') return new Response(LLMS, { headers: { 'content-type': 'text/plain; charset=utf-8' } }); if (path === '/favicon.ico' || path === '/favicon.svg') return new Response(null, { status: 404 }); if (path.startsWith('/api/auth/')) return await handleAuth(req, env, path.slice(10)); if (path === '/api/features') return await featuresApi(req, env, url); if (path === '/api/feature-vote' && req.method === 'POST') return await featureVote(req, env); if (path === '/api/vote' && req.method === 'POST') return await vote(req, env); if (path === '/api/repos' && req.method === 'POST') return await apiCreateRepo(req, env); if (path === '/api/request') { if (!env.CAREERS) return json({ ok: false, error: 'Unavailable' }, 503); return await env.CAREERS.fetch(new Request('https://careers-intake/api/request', req)); } if (path.startsWith('/api/')) return json({ error: 'Not found' }, 404); // ---------- pages ---------- const me = await currentAccount(req, env); const P = (title: string, body: string, extra: Partial[0]> = {}) => page({ title, body, path: url.pathname, me, scripts: APP, ...extra }); switch (path.replace(/\/$/, '') || '/') { case '/': { const repos = await env.DB.prepare('SELECT COUNT(*) AS n FROM repos').first('n'); const companies = await env.DB.prepare('SELECT COUNT(*) AS n FROM orgs').first('n'); return P('Branchwell: open Git hosting where votes decide', C.home({ repos: repos || 0, companies: companies || 0 }), { head: '' + ORG_LD, description: 'Branchwell hosts open Git repositories. Anyone can pull, anyone signed in can push straight to a branch, and 3 votes keep or remove each commit.' }); } case '/how-to-pull': return P('How to pull', C.howToPull, { current: '/how-to-pull', description: 'Clone and pull any Branchwell repository with plain Git. No account needed.' }); case '/how-to-contribute': return P('How to contribute', C.howToContribute, { current: '/how-to-contribute', description: 'Sign in with a passkey, make a push key and push straight to a branch. No pull requests.' }); case '/rules': return P('How votes work', C.rules, { current: '/rules', description: '3 votes down removes a commit or branch. 3 votes up keeps it for good. Everything else stays.' }); case '/features': return P('New features, voted in', C.features, { current: '/features', description: 'Add a New badge with thumbs up and down to any app. 3 up keeps a feature, 3 down switches it off.' }); case '/careers': return P('Careers', C.careers, { current: '/careers', description: 'Careers at Branchwell. Send us a short request to work with us.' }); case '/privacy': return P('Privacy', C.privacy, { description: 'What Branchwell keeps and what it never does.' }); case '/source': return Response.redirect(SITE + '/branchwell/source', 302); case '/repos': return reposPage(env, P); case '/companies': return companiesPage(env, P); case '/research': return researchPage(env, P); case '/signin': return P('Sign in', signinBody(me), { noindex: true }); case '/account': return me ? accountPage(env, me, P) : Response.redirect(SITE + '/signin?back=/account', 302); case '/new': return P('New project', newRepoBody(me, me ? await myOrgs(env, me) : []), { noindex: true }); case '/feature-vote': return featureVotePage(env, url, me, P); } // ---------- repository pages ---------- const o = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,39})\/?$/); if (o && !RESERVED.has(o[1])) { const r = await ownerPage(env, o[1], me, P); if (r) return r; } const m = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,39})\/([a-z0-9][a-z0-9._-]{0,62}?)(?:\.git)?(?:\/(tree|blob|raw|commits|commit|branches)(?:\/(.*))?)?\/?$/); if (m && !RESERVED.has(m[1])) { const row = await repoRow(env, m[1] + '/' + m[2]); if (row) return await repoPage(env, req, url, me, row, m[3] || '', m[4] ? decodeURIComponent(m[4]) : '', P); } return page({ title: 'Not found', path: url.pathname, me, noindex: true, body: '

We couldn\'t find that page

It may have moved, or a vote may have removed it.

HomeAll repositories

' }).then404(); } catch (e) { console.error(e); return new Response('Something went wrong on our side. Please try again.', { status: 500 }); } }, }; declare global { interface Response { then404(): Response } } Response.prototype.then404 = function (this: Response) { return new Response(this.body, { status: 404, headers: this.headers }); }; // ---------------- Git ---------------- async function git(req: Request, env: Env, ctx: ExecutionContext, name: string, op: string, url: URL): Promise { name = name.toLowerCase(); const service = op === 'info/refs' ? url.searchParams.get('service') : op; const write = service === 'git-receive-pack'; let pusher: Account | null = null; if (write) { pusher = await pusherFromBasic(req, env); if (!pusher) return new Response('Sign in at https://branchwell.ai/account and make a push key. Use your Branchwell name as the username and the push key as the password.\n', { status: 401, headers: { 'www-authenticate': 'Basic realm="Branchwell"', 'content-type': 'text/plain' } }); } let row = await repoRow(env, name); if (!row) { if (!write || !pusher) return new Response(`Repository ${name} not found on Branchwell.\n`, { status: 404, headers: { 'content-type': 'text/plain' } }); const [owner, project] = name.split('/'); const err = await createRepo(env, owner, project, '', pusher); if (err) return new Response(err + '\n', { status: 403, headers: { 'content-type': 'text/plain' } }); row = await repoRow(env, name); } if (!row) return new Response('Not found\n', { status: 404 }); const target = new URL('https://repo/' + (op === 'info/refs' ? 'info/refs' : op) + url.search); const headers = new Headers({ 'content-type': req.headers.get('content-type') || '' }); headers.set('x-repo', row.name); if (pusher) headers.set('x-pusher', JSON.stringify({ id: pusher.id, handle: pusher.handle })); let body: BodyInit | null = null; if (req.method === 'POST') { let buf = new Uint8Array(await req.arrayBuffer()); if ((req.headers.get('content-encoding') || '').includes('gzip')) buf = new Uint8Array(await new Response(new Blob([buf]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer()); body = buf; } const res = await stub(env, row.do_name).fetch(new Request(target, { method: req.method, headers, body })); if (write && req.method === 'POST') ctx.waitUntil(env.DB.prepare('UPDATE repos SET updated_at = ? WHERE name = ?').bind(Date.now(), name).run()); return res; } // ---------------- APIs ---------------- async function vote(req: Request, env: Env): Promise { if (req.headers.get('origin') !== new URL(req.url).origin) return json({ error: 'Bad origin.' }, 403); const me = await currentAccount(req, env); if (!me) return json({ error: 'Sign in with your passkey to vote.' }, 401); const b = await req.json<{ repo: string; kind: string; target: string; value: number }>().catch(() => null); if (!b || !FULL_RE.test(b.repo || '') || (b.kind !== 'commit' && b.kind !== 'branch') || !b.target) return json({ error: 'Bad vote.' }, 400); const row = await repoRow(env, b.repo); if (!row) return json({ error: 'No such repository.' }, 404); const r = await stub(env, row.do_name).vote(b.kind, String(b.target).slice(0, 120), { id: me.id, handle: me.handle, canVote: canVote(me) }, Number(b.value) || 0); return json(r); } async function apiCreateRepo(req: Request, env: Env): Promise { if (req.headers.get('origin') !== new URL(req.url).origin) return json({ error: 'Bad origin.' }, 403); const me = await currentAccount(req, env); if (!me) return json({ error: 'Sign in first.' }, 401); const b = await req.json<{ owner: string; name: string; description: string }>().catch(() => ({ owner: '', name: '', description: '' })); const owner = String(b.owner || me.handle).toLowerCase(), project = String(b.name || '').toLowerCase(); if (!OWNER_RE.test(owner)) return json({ error: 'Pick who owns it.' }, 400); const err = await createRepo(env, owner, project, String(b.description || ''), me); if (err) return json({ error: err }, 400); return json({ ok: true, name: owner + '/' + project }); } // ---------------- pages ---------------- type PFn = (title: string, body: string, extra?: Record) => Response; async function reposPage(env: Env, P: PFn) { const rows = (await env.DB.prepare('SELECT name, description, created_by, created_at, updated_at FROM repos ORDER BY COALESCE(updated_at, created_at) DESC LIMIT 1000').all<{ name: string; description: string; created_by: string; created_at: number; updated_at: number }>()).results; const list = rows.length ? `${rows.map((r) => ``).join('')}
RepositoryAboutUpdated
${esc(r.name)}${esc(r.description || '')}${ago(r.updated_at || r.created_at)}
` : '

No repositories yet.

'; return P('Repositories', `
Repositories

Everything here is open

Pull any of these with plain Git. Sign in to push, vote, or start your own.

${list}`, { current: '/repos', description: 'Every repository on Branchwell. All public, all open to pull.' }); } function signinBody(me: Account | null) { if (me) return `

You're signed in as ${esc(me.handle)}

Your account

`; return `
Sign in

Passkeys only

Sign in with your face, fingerprint or device PIN. No passwords and no email.

New here?

Pick a public name. Your device makes a passkey for it.

3 to 30 lowercase letters, numbers or dashes.

`; } async function accountPage(env: Env, me: Account, P: PFn) { const keys = (await env.DB.prepare('SELECT id, name, created_at, last_used FROM push_keys WHERE account_id = ? ORDER BY created_at DESC').bind(me.id).all<{ id: string; name: string; created_at: number; last_used: number }>()).results; const orgs = await myOrgs(env, me); const pks = (await env.DB.prepare('SELECT created_at, last_used FROM passkeys WHERE account_id = ? ORDER BY created_at').bind(me.id).all<{ created_at: number; last_used: number }>()).results; const wait = canVote(me) ? '

You can vote.

' : `

You can vote from ${new Date(me.created_at + 864e5).toUTCString().slice(0, 22)} UTC. New accounts wait a day so votes stay fair.

`; return P('Your account', `
Your account

${esc(me.handle)}

${wait}

Push keys

Git can't use passkeys, so make a push key for each computer. Use your name as the username and the key as the password.

${keys.length ? `${keys.map((k) => ``).join('')}
${esc(k.name)}
made ${ago(k.created_at)}${k.last_used ? ', used ' + ago(k.last_used) : ', not used yet'}
` : ''}

Passkeys

${pks.length} passkey${pks.length === 1 ? '' : 's'} on this account. Add one for each device you use.

${orgs.length ? `

Your companies

${orgs.map((o) => `${esc(o.name)}`).join(' · ')}

` : ''}

Get started

git clone https://branchwell.ai/sunlaid/research.git

How to contribute · New repository

`, { noindex: true }); } function newRepoBody(me: Account | null, orgs: Org[]) { if (!me) return `

Start a project

Sign in with your passkey first.

Sign in

`; return `
New project

Start a project

Every project is public. Anyone can pull it and anyone signed in can push to it.

Or just push to a new name: git push https://branchwell.ai/${esc(me.handle)}/my-project.git main

`; } async function featureVotePage(env: Env, url: URL, me: Account | null, P: PFn) { const app = (url.searchParams.get('app') || '').toLowerCase(), feature = (url.searchParams.get('feature') || '').toLowerCase(); const f = await env.DB.prepare('SELECT status, up, down FROM features WHERE app = ? AND feature = ?').bind(app, feature).first<{ status: string; up: number; down: number }>(); if (!f) return P('Feature vote', '

We couldn\'t find that feature

', { noindex: true }); const back = encodeURIComponent(url.pathname + url.search); const v = url.searchParams.get('v') === 'down' ? -1 : 1; const body = !me ? `

Sign in with your passkey to vote.

Sign in

` : f.status !== 'new' ? `

${f.status === 'kept' ? 'This feature already got 3 thumbs up. It stays for good.' : 'This feature got 3 thumbs down and is switched off.'}

` : `

3 thumbs up keeps it for good. 3 thumbs down switches it off.

`; return P('Vote on a new feature', `
New feature

${esc(feature.replace(/[-_.]/g, ' '))}

in ${esc(app)}

${body}
`, { noindex: true }); } // ---------------- owners and companies ---------------- type ProjRow = { name: string; description: string; updated_at: number; created_at: number }; const projTable = (rows: ProjRow[], showOwner = false) => rows.length ? `${rows.map((r) => ``).join('')}
${esc(showOwner ? r.name : r.name.split('/')[1])}${r.description ? `
${esc(r.description)}` : ''}
${ago(r.updated_at || r.created_at)}
` : '

No projects yet.

'; async function ownerPage(env: Env, handle: string, me: Account | null, P: PFn): Promise { const org = await orgRow(env, handle); const person = org ? null : await env.DB.prepare('SELECT handle, created_at FROM accounts WHERE handle = ?').bind(handle).first<{ handle: string; created_at: number }>(); if (!org && !person) return null; const rows = (await env.DB.prepare('SELECT name, description, updated_at, created_at FROM repos WHERE owner = ? ORDER BY name').bind(handle).all()).results; const member = !!(me && (await canCreateUnder(env, handle, me))); const title = org ? org.name : handle; const site = org?.domain ? `

${esc(org.domain)}

` : ''; return P(title, `
${org ? 'Company' : 'Person'}

${esc(title)}

${org?.about ? `

${esc(org.about)}

` : ''}${site}

${rows.length} project${rows.length === 1 ? '' : 's'}. Every one is public: pull it with plain Git, push to it once you sign in.

${member ? '' : ''}

Projects

${projTable(rows)}`, { description: org ? `${org.name} on Branchwell: every project, open to pull and to push.` : `${handle} on Branchwell.` }); } async function companiesPage(env: Env, P: PFn) { const orgs = (await env.DB.prepare('SELECT o.handle, o.name, o.domain, o.about, (SELECT COUNT(*) FROM repos r WHERE r.owner = o.handle) AS n FROM orgs o ORDER BY o.name COLLATE NOCASE').all()).results; const cards = orgs.map((o) => `

${esc(o.name)}

${o.domain ? esc(o.domain) + ' · ' : ''}${o.n} project${o.n === 1 ? '' : 's'}

`).join(''); return P('Companies', `
Companies

Every company, in the open

Each company has its own account here, and its projects live inside it. Everything is public: pull any project, or sign in and push.

${cards}
`, { current: '/companies', description: 'Every company on Branchwell, each with its own account and open projects.' }); } async function researchPage(env: Env, P: PFn) { const rows = (await env.DB.prepare("SELECT r.name, o.name AS org, o.domain, r.updated_at, r.created_at FROM repos r JOIN orgs o ON o.handle = r.owner WHERE r.name LIKE '%/research' ORDER BY o.name COLLATE NOCASE").all<{ name: string; org: string; domain: string; updated_at: number; created_at: number }>()).results; const list = `${rows.map((r) => ``).join('')}
CompanyClone
${esc(r.org)}${r.domain ? `
${esc(r.domain)}` : ''}
git clone https://branchwell.ai/${esc(r.name)}.git
`; return P('Research', `
Research

Every company's research

Each company keeps its research in its own project: the full plan behind it, and every public source summarized in plain words with a link to the original. It is all public domain. Pull it, read it, add to it.

${list}`, { current: '/research', description: 'The research behind every company on Branchwell, one open project each. Public domain.' }); } // ---------------- repository views ---------------- const voteBox = (repo: string, kind: string, target: string, up: number, down: number, mine?: number) => `
`; const statusTag = (s?: string) => s ? `${s === 'system' ? 'removal' : esc(s)}` : ''; const MIME: Record = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', pdf: 'application/pdf', json: 'application/json; charset=utf-8', mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg', zip: 'application/zip' }; async function repoPage(env: Env, req: Request, url: URL, me: Account | null, row: RepoRow, view: string, rest: string, P: PFn): Promise { const s = stub(env, row.do_name); const ov = await s.overview(); const branchNames = (ov.branches as { name: string; status: string }[]).filter((b) => b.status !== 'removed').map((b) => b.name); // Split "/" where ref may contain slashes. const split = (x: string) => { const parts = x.split('/').filter((p, i) => p || i === 0); for (let i = parts.length; i > 0; i--) { const ref = parts.slice(0, i).join('/'); if (branchNames.includes(ref)) return { ref, path: parts.slice(i).join('/') }; } return { ref: parts[0] || ov.defaultBranch, path: parts.slice(1).join('/') }; }; const R = esc(row.name); const tabs = (cur: string, ref: string) => ``; const branchPicker = (ref: string, kind: string) => branchNames.length > 1 ? `
` : `${esc(ref)}`; const ownerName = row.name.split('/')[0]; const org = await orgRow(env, ownerName); const head = (title: string) => `

${esc(org?.name || ownerName)} / ${esc(row.name.split('/')[1])}${title}

`; const cloneBox = `
git clone https://branchwell.ai/${R}.git
`; if (ov.empty) { return P(row.name, `
${head('')}Project

${esc(row.name.split('/')[1])}

${esc(row.description || 'This repository is empty. Push the first commit.')}

git clone https://branchwell.ai/${R}.git
cd ${esc(row.name.split('/')[1])}
echo "# ${R}" > README.md
git add README.md
git commit -m "First commit"
git push -u origin main

How to contribute

`); } if (view === '' || view === 'tree') { const { ref, path } = view === '' ? { ref: ov.defaultBranch, path: '' } : split(rest); const t = await s.listTree(ref, path); if (!t) return P('Not found', `${head('')}

That folder isn't on ${esc(ref)}. It may have been removed by a vote.

`, { noindex: true }).then404(); if (t.kind === 'blob') return Response.redirect(`${SITE}/${row.name}/blob/${ref}/${path}`, 302); const crumbs = path.split('/').filter(Boolean).map((p, i, a) => ` / ${esc(p)}`).join(''); const rows = t.entries.map((e) => `${e.dir ? '📁' : '📄'} ${esc(e.name)}${e.dir ? '' : sizeText(e.size)}`).join(''); const readme = t.entries.find((e) => !e.dir && /^readme(\.md|\.markdown|\.txt)?$/i.test(e.name)); let readmeHtml = ''; if (readme) { const b = await s.readBlob(ref, (path ? path + '/' : '') + readme.name); if (b && isText(b.data)) { const dir = path ? path + '/' : ''; const text = new TextDecoder().decode(b.data); readmeHtml = `
${/\.txt$/i.test(readme.name) ? `
${esc(text)}
` : markdown(text, `/${row.name}/blob/${ref}/${dir}`, `/${row.name}/raw/${ref}/${dir}`)}
`; } } const top = view === '' ? `
${esc(org?.name || ownerName)} project

${esc(row.name.split('/')[1])}

${row.description ? `

${esc(row.description)}

` : ''}${cloneBox}

${(ov.commits as { n: number }).n || 0} commit${(ov.commits as { n: number }).n === 1 ? '' : 's'} pushed here · ${(ov.commits as { open: number }).open || 0} open to votes · ${(ov.commits as { removed: number }).removed || 0} removed by votes${ov.updatedAt ? ' · updated ' + ago(ov.updatedAt) : ''}

` : head(crumbs); const last = t.last ? `

Latest: ${esc(t.last.subject)} by ${esc(t.last.author)}, ${ago(t.last.time * 1000)}

` : ''; const extra = view === '' && row.name === 'branchwell/research' ? C.research() : ''; return P(view === '' ? row.name : `${path || ref} · ${row.name}`, `${top}
${tabs('files', ref)}${branchPicker(ref, 'tree')}
${last}${rows}
${readmeHtml}${extra}`, { description: row.description || `The ${row.name} repository on Branchwell. Open to pull and to push.`, noindex: view !== '' }); } if (view === 'blob' || view === 'raw') { const { ref, path } = split(rest); const b = await s.readBlob(ref, path); if (!b) return P('Not found', `${head('')}

That file isn't on ${esc(ref)}. It may have been removed by a vote.

`, { noindex: true }).then404(); const ext = (path.split('.').pop() || '').toLowerCase(); if (view === 'raw') { const type = MIME[ext] || (isText(b.data) ? 'text/plain; charset=utf-8' : 'application/octet-stream'); return new Response(b.data, { headers: { 'content-type': type, 'cache-control': 'public, max-age=300', 'content-security-policy': 'sandbox', 'x-content-type-options': 'nosniff', etag: `"${b.sha}"` } }); } const crumbs = path.split('/').map((p, i, a) => i === a.length - 1 ? ` / ${esc(p)}` : ` / ${esc(p)}`).join(''); const raw = `/${R}/raw/${esc(ref)}/${esc(path)}`; let content: string; if (/^(png|jpe?g|gif|webp|avif)$/.test(ext)) content = `
${esc(path)}
`; else if (!isText(b.data)) content = `

This file isn't text (${sizeText(b.data.length)}). Download it.

`; else { const text = new TextDecoder().decode(b.data); const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : ''; if (/^(md|markdown)$/.test(ext) && url.searchParams.get('plain') === null) content = `

Show the source

${markdown(text, `/${row.name}/blob/${ref}/${dir}`, `/${row.name}/raw/${ref}/${dir}`)}
`; else { const lines = text.replace(/\n$/, '').split('\n'); content = `
${lines.slice(0, 20000).map((l, i) => ``).join('')}
${i + 1}${esc(l) || ' '}
`; } } return P(`${path} · ${row.name}`, `${head(crumbs)}
${tabs('files', ref)}Raw ${sizeText(b.data.length)} on ${esc(ref)}
${content}`, { noindex: true }); } if (view === 'commits') { const { ref } = split(rest || ov.defaultBranch); const pageN = Math.max(0, parseInt(url.searchParams.get('page') || '0', 10) || 0); const lg = (await s.log(ref, pageN * 30, 30)) as { commits: unknown[]; more: boolean } | null; if (!lg) return P('Not found', `${head('')}

There's no branch called ${esc(ref)}. It may have been removed by a vote.

`, { noindex: true }).then404(); type CRow = { sha: string; subject: string; author: string; time: number; meta: { status: string; up: number; down: number; pusher: string; pushed_at: number; note: string } | null }; const commits = lg.commits as unknown as CRow[]; const mine: Record = me ? await s.myVotes(me.id, 'commit', commits.filter((c) => c.meta?.status === 'new').map((c) => c.sha)) : {}; const rows = commits.map((c) => { const m = c.meta; const who = m && m.pusher && m.pusher !== 'branchwell' ? `pushed by ${esc(m.pusher)}` : esc(c.author); const v = m && m.status === 'new' ? voteBox(row.name, 'commit', c.sha, m.up, m.down, mine[c.sha]) : m && (m.status === 'kept' || m.status === 'removed') ? `👍 ${m.up} 👎 ${m.down}` : ''; return `${esc(c.subject || '(no message)')} ${statusTag(m?.status)}
${c.sha.slice(0, 8)} ${who}, ${ago(c.time * 1000)}${v}`; }).join(''); const nav = `

${pageN > 0 ? `Newer` : ''}${lg.more ? `Older` : ''}

`; return P(`Commits on ${ref} · ${row.name}`, `${head(' / commits')}
${tabs('commits', ref)}${branchPicker(ref, 'commits')}

New commits are open to votes. 3 down takes one back out; 3 up keeps it for good. How votes work

${rows}
${nav}`, { noindex: true }); } if (view === 'commit') { const info = await s.commitInfo(rest); if (!info) return P('Not found', `${head('')}

We couldn't find that commit.

`, { noindex: true }).then404(); const m = info.meta as { status: string; up: number; down: number; pusher: string; pushed_at: number; note: string; branch: string } | null; const mine = me && m?.status === 'new' ? (await s.myVotes(me.id, 'commit', [info.sha]))[info.sha] : undefined; const voters = (info.voters as { handle: string; value: number }[]); const c = info.commit; const msgBody = c.message.split('\n').slice(1).join('\n').trim(); const diffs = (info.diffs as { path: string; status: string; before: string | null; after: string | null }[]).map((d) => `

${esc(d.path)} ${d.status}

${d.before === null || d.after === null ? '

Not a text file.

' : diffHtml(d.before, d.after)}
`).join(''); const more = info.files.length > info.diffs.length ? `

${info.files.length - info.diffs.length} more files changed.

` : ''; const noteLine = m?.status === 'removed' ? `
This commit was voted down and taken back out of ${esc(m.branch)}: ${esc(m.note || '')}.
` : m?.status === 'system' ? `
Branchwell made this commit to take ${esc((m.note || '').slice(0, 8))} back out after 3 votes down.
` : ''; return P(`${c.message.split('\n')[0]} · ${row.name}`, `${head(` / commits / ${info.sha.slice(0, 8)}`)}

${esc(c.message.split('\n')[0] || '(no message)')} ${statusTag(m?.status)}

${msgBody ? `
${esc(msgBody)}
` : ''}

${m && m.pusher !== 'branchwell' ? `Pushed by ${esc(m.pusher)} to ${esc(m.branch)} ${ago(m.pushed_at)} · ` : ''}written by ${esc(c.author.replace(/\s*<.*$/, ''))} · ${info.sha}${c.parents.length ? ` · parent ${c.parents[0].slice(0, 8)}` : ''}

${noteLine}${m?.status === 'new' ? `
${voteBox(row.name, 'commit', info.sha, m.up, m.down, mine)}
` : ''} ${voters.length ? `

Votes: ${voters.map((v) => `${esc(v.handle)} ${v.value > 0 ? '👍' : '👎'}`).join(', ')}

` : ''}

${info.files.length} file${info.files.length === 1 ? '' : 's'} changed

${diffs}${more}

Browse files at this commit

`, { noindex: true }); } if (view === 'branches') { type BRow = { name: string; status: string; up: number; down: number; created_by: string; created_at: number; removed_at: number; last_sha: string }; const all = ov.branches as unknown as BRow[]; const mine: Record = me ? await s.myVotes(me.id, 'branch', all.filter((b) => b.status === 'new').map((b) => b.name)) : {}; const rows = all.map((b) => `${b.status === 'removed' ? `${esc(b.name)}` : `${esc(b.name)}`} ${b.name === ov.defaultBranch ? 'main branch' : statusTag(b.status)}
opened by ${esc(b.created_by || 'unknown')} ${ago(b.created_at)}${b.removed_at ? ', removed ' + ago(b.removed_at) : ''} ${b.status === 'new' && b.name !== ov.defaultBranch ? voteBox(row.name, 'branch', b.name, b.up, b.down, mine[b.name]) : b.status === 'removed' || b.name === ov.defaultBranch ? '' : `👍 ${b.up} 👎 ${b.down}`}`).join(''); return P(`Branches · ${row.name}`, `${head(' / branches')}
${tabs('branches', ov.defaultBranch)}

Anyone can open a branch: git push origin HEAD:your-idea. 3 votes down removes a branch; 3 up keeps it. The main branch always stays.

${rows}
`, { noindex: true }); } return new Response('Not found', { status: 404 }); } async function sitemap(env: Env) { const rows = (await env.DB.prepare('SELECT name FROM repos ORDER BY name LIMIT 5000').all<{ name: string }>()).results; const orgs = (await env.DB.prepare('SELECT handle FROM orgs ORDER BY handle').all<{ handle: string }>()).results; const urls = ['/', '/companies', '/research', '/repos', '/how-to-pull', '/how-to-contribute', '/rules', '/features', '/careers', '/privacy', ...orgs.map((o) => '/' + o.handle), ...rows.map((r) => '/' + r.name)]; return new Response(`\n${urls.map((u) => `${SITE}${u}`).join('')}`, { headers: { 'content-type': 'application/xml' } }); } const ORG_LD = ``; const LLMS = `# Branchwell > Open Git hosting. Anyone can pull. Anyone signed in (passkeys only) can push straight to a branch. No pull requests, no reviews. 3 votes down removes a commit or branch; 3 votes up keeps it for good. - Clone: git clone https://branchwell.ai//.git - Companies (each has its own account and projects): ${SITE}/companies - Research, one project per company (public domain sources): ${SITE}/research - How to pull: ${SITE}/how-to-pull - How to contribute: ${SITE}/how-to-contribute - How votes work: ${SITE}/rules - New-feature votes for apps: ${SITE}/features - Source code: ${SITE}/branchwell/source `; void SECURITY;