Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@tannerlinsley/tanstack-github-dashboard

Track GitHub activity across TanStack factory repositories.

FollowFork

Files

app.ts

143 lines · 13.4 KB · TypeScript
import { createAuthenticatedFetch, packageContext, packageStorage } from 'kody:runtime'

const repos = ['charts', 'tanstack.com', 'redact', 'markdown', 'highlight', 'cli'] as const
const kinds = [
  { key: 'issuesOpened', qualifier: 'is:issue', date: 'created' },
  { key: 'issuesClosed', qualifier: 'is:issue is:closed', date: 'closed' },
  { key: 'prsOpened', qualifier: 'is:pr', date: 'created' },
  { key: 'prsMerged', qualifier: 'is:pr is:merged', date: 'merged' },
] as const

function periods(count: number) {
  const now = new Date()
  return Array.from({ length: count }, (_, i) => {
    const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - count + i + 1, 1))
    const end = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 1))
    const day = (d: Date) => d.toISOString().slice(0, 10)
    end.setUTCDate(end.getUTCDate() - 1)
    return { month: day(start).slice(0, 7), start: day(start), end: day(end) }
  })
}
async function activity(request: Request) {
  const u = new URL(request.url)
  const repo = u.searchParams.get('repo') || 'all'
  const months = Number(u.searchParams.get('months') || 6)
  if ((!repos.includes(repo as typeof repos[number]) && repo !== 'all') || ![3, 6, 12].includes(months)) return Response.json({ error: 'Invalid filters' }, { status: 400 })
  const scope = repo === 'all' ? repos.map(r => `repo:TanStack/${r}`).join(' ') : `repo:TanStack/${repo}`
  const dates = periods(months)
  const fields = dates.flatMap((p, i) => kinds.map(k => {
    const q = `${scope} ${k.qualifier} ${k.date}:${p.start}..${p.end}`
    return `${k.key}_${i}: search(type: ISSUE, query: ${JSON.stringify(q)}) { issueCount }`
  }))
  const recentQuery = `${scope} is:pr is:merged sort:updated-desc`
  fields.push(`recent: search(type: ISSUE, query: ${JSON.stringify(recentQuery)}, first: 20) { nodes { ... on PullRequest { title url number mergedAt repository { nameWithOwner } author { login } } } }`)
  try {
    const github = await createAuthenticatedFetch('github')
    const response = await github('https://api.github.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/vnd.github+json' }, body: JSON.stringify({ query: `query Dashboard { ${fields.join('\n')} }` }) })
    const data: any = await response.json()
    if (!response.ok || data.errors?.length || !data.data) throw new Error(data.errors?.[0]?.message || `GitHub returned ${response.status}`)
    const series = dates.map((p, i) => ({ month: p.month, ...Object.fromEntries(kinds.map(k => [k.key, data.data[`${k.key}_${i}`].issueCount])) }))
    return Response.json({ repo, series, recent: data.data.recent.nodes.filter(Boolean), fetchedAt: new Date().toISOString() }, { headers: { 'Cache-Control': 'no-store' } })
  } catch (error) {
    return Response.json({ error: error instanceof Error ? error.message : 'Could not load GitHub data' }, { status: 502 })
  }
}
async function daily(request: Request) {
  const repo = new URL(request.url).searchParams.get('repo') || ''
  if (!repos.includes(repo as typeof repos[number])) return Response.json({error:'Invalid repository'}, {status:400})
  const now = new Date(), today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
  const days = Array.from({length:30},(_,i)=>new Date(today-(29-i)*86400000).toISOString().slice(0,10))
  const since = `${days[0]}T00:00:00Z`, scope = `repo:TanStack/${repo}`
  const field = (id:string,q:string)=>`${id}: search(type: ISSUE, query: ${JSON.stringify(q)}) { issueCount }`
  const fields=[field('openIssues',`${scope} is:issue is:open`),field('openPrs',`${scope} is:pr is:open`),...days.flatMap((d,i)=>[field(`issues${i}`,`${scope} is:issue created:${d}`),field(`prs${i}`,`${scope} is:pr created:${d}`)])]
  try {
    const github=await createAuthenticatedFetch('github')
    const graph=async(query:string)=>{const response=await github('https://api.github.com/graphql',{method:'POST',headers:{'Content-Type':'application/json',Accept:'application/vnd.github+json'},body:JSON.stringify({query})});const result:any=await response.json();if(!response.ok||result.errors?.length||!result.data)throw new Error(result.errors?.[0]?.message || `GitHub returned ${response.status}`);return result.data}
    const totals=await graph(`query Daily { ${fields.join('\n')} }`)
    const changes:Record<string,{issues:number;prs:number}>={}
    let cursor:string|null=null, pages=0
    do {
      const timeline=`timelineItems(first:100,since:${JSON.stringify(since)},itemTypes:[CLOSED_EVENT,REOPENED_EVENT]) { nodes { __typename ... on ClosedEvent { createdAt } ... on ReopenedEvent { createdAt } } pageInfo { hasNextPage } }`
      const query=`query { search(type: ISSUE, query: ${JSON.stringify(`${scope} updated:>=${days[0]} sort:updated-asc`)}, first: 50${cursor?`, after: ${JSON.stringify(cursor)}`:''}) { issueCount pageInfo { hasNextPage endCursor } nodes { __typename ... on Issue { ${timeline} } ... on PullRequest { ${timeline} } } } }`
      const data=await graph(query), search=data.search
      if(search.issueCount>1000) throw new Error('Too many updated items to reconstruct this history completely.')
      for(const node of search.nodes){
        if(!node?.timelineItems || node.timelineItems.pageInfo.hasNextPage) throw new Error('A GitHub timeline is incomplete.')
        for(const event of node.timelineItems.nodes){
          if(!event?.createdAt || event.createdAt>now.toISOString()) continue
          const day=event.createdAt.slice(0,10), kind=node.__typename==='Issue'?'issues':'prs'
          const entry=changes[day] ||= {issues:0,prs:0}
          entry[kind]+=event.__typename==='ClosedEvent'?-1:1
        }
      }
      cursor=search.pageInfo.hasNextPage?search.pageInfo.endCursor:null
      if(++pages>20) throw new Error('GitHub history exceeded the page limit.')
    } while(cursor)
    let issuesTotal=totals.openIssues.issueCount, prsTotal=totals.openPrs.issueCount
    const series=days.map((day,i)=>({day,issuesCreated:totals[`issues${i}`].issueCount,prsCreated:totals[`prs${i}`].issueCount,issuesTotal:0,prsTotal:0}))
    for(let i=series.length-1;i>=0;i--){const row=series[i];row.issuesTotal=issuesTotal;row.prsTotal=prsTotal;issuesTotal-=row.issuesCreated+(changes[row.day]?.issues||0);prsTotal-=row.prsCreated+(changes[row.day]?.prs||0);if(issuesTotal<0||prsTotal<0)throw new Error('GitHub history could not be reconciled.')}
    return Response.json({repo,series,fetchedAt:new Date().toISOString()},{headers:{'Cache-Control':'no-store'}})
  } catch(e) { return Response.json({error:e instanceof Error?e.message:'Could not load GitHub data'},{status:502}) }
}
type Tracked = { repo: string; number: number; kind: string; evidence: string; source: string; updatedAt: string }
const seeds: Tracked[] = [
  {repo:'redact', number:123, kind:'research', evidence:'Redact R&D reported and delivered the SSR boundary completion experiment.', source:'Redact R&D chat, November 1, 2026', updatedAt:'2026-11-01T21:14:12Z'},
  {repo:'markdown', number:20, kind:'both', evidence:'Markdown factory delivered the autolink change; Markdown R&D independently reviewed its measurements and release evidence.', source:'Markdown factory and R&D chats, November 1, 2026', updatedAt:'2026-11-01T21:23:01Z'},
]
async function tracked(request: Request) {
  const db = packageStorage()
  await db.sql('CREATE TABLE IF NOT EXISTS attribution (repo TEXT NOT NULL, number INTEGER NOT NULL, kind TEXT NOT NULL, evidence TEXT NOT NULL, source TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY(repo, number))')
  if (request.method === 'POST') {
    const origin = request.headers.get('origin')
    if (!origin || origin !== new URL(request.url).origin) return Response.json({error:'Invalid origin'}, {status:403})
    let input: any
    try { input = await request.json() } catch { return Response.json({error:'Invalid request'}, {status:400}) }
    const match = typeof input.url === 'string' && input.url.match(/^https:\/\/github\.com\/TanStack\/(charts|tanstack\.com|redact|markdown|highlight|cli)\/pull\/(\d+)\/?$/i)
    if (!match || !['factory','research','both'].includes(input.kind) || typeof input.evidence !== 'string' || input.evidence.trim().length < 8 || input.evidence.length > 500 || typeof input.source !== 'string' || input.source.trim().length < 4 || input.source.length > 300) return Response.json({error:'Add a supported pull request URL, attribution, evidence, and source.'}, {status:400})
    const repo = match[1].toLowerCase(), number = Number(match[2])
    if (!Number.isSafeInteger(number) || number < 1) return Response.json({error:'Invalid pull request'}, {status:400})
    const github = await createAuthenticatedFetch('github')
    const check = await github(`https://api.github.com/repos/TanStack/${repo}/pulls/${number}`, {headers:{Accept:'application/vnd.github+json'}})
    if (!check.ok) return Response.json({error:'GitHub could not find that pull request.'}, {status:400})
    await db.sql('INSERT INTO attribution (repo, number, kind, evidence, source, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(repo, number) DO UPDATE SET kind=excluded.kind, evidence=excluded.evidence, source=excluded.source, updated_at=excluded.updated_at', [repo,number,input.kind,input.evidence.trim(),input.source.trim(),new Date().toISOString()])
  } else if (request.method !== 'GET') return new Response('Method not allowed', {status:405})
  const result = await db.sql('SELECT repo, number, kind, evidence, source, updated_at FROM attribution ORDER BY updated_at DESC LIMIT 500')
  const custom = result.rows.map((r:any) => ({repo:r.repo,number:r.number,kind:r.kind,evidence:r.evidence,source:r.source,updatedAt:r.updated_at})) as Tracked[]
  const combined = [...custom, ...seeds.filter(s=>!custom.some(c=>c.repo===s.repo && c.number===s.number))]
  const github = await createAuthenticatedFetch('github')
  const items = await Promise.all(combined.map(async item => {
    try {
      const response = await github(`https://api.github.com/repos/TanStack/${item.repo}/pulls/${item.number}`, {headers:{Accept:'application/vnd.github+json'}})
      if (!response.ok) return {...item, status:'unavailable'}
      const pr: any = await response.json()
      return {...item, title:pr.title, url:pr.html_url, status:pr.merged_at ? 'merged' : pr.state === 'closed' ? 'closed' : pr.draft ? 'draft' : 'open', mergedAt:pr.merged_at, githubUpdatedAt:pr.updated_at}
    } catch { return {...item,status:'unavailable'} }
  }))
  return Response.json({items, truncated:result.truncated}, {headers:{'Cache-Control':'no-store'}})
}
async function research(request: Request) {
  const db=packageStorage()
  await db.sql('CREATE TABLE IF NOT EXISTS research_notes (id TEXT PRIMARY KEY, repo TEXT NOT NULL, title TEXT NOT NULL, phase TEXT NOT NULL, progress TEXT NOT NULL, source TEXT NOT NULL, updated_at TEXT NOT NULL)')
  if(request.method === 'POST') {
    if(request.headers.get('origin') !== new URL(request.url).origin) return Response.json({error:'Invalid origin'}, {status:403})
    let x:any; try{x=await request.json()}catch{return Response.json({error:'Invalid request'}, {status:400})}
    if(!repos.includes(x.repo) || !['investigating','testing','ready','blocked','complete'].includes(x.phase) || typeof x.title!=='string' || x.title.trim().length<4 || x.title.length>160 || typeof x.progress!=='string' || x.progress.trim().length<8 || x.progress.length>500 || typeof x.source!=='string' || x.source.trim().length<4 || x.source.length>300) return Response.json({error:'Complete all fields.'},{status:400})
    const id=typeof x.id==='string' && /^[0-9a-f-]{36}$/.test(x.id) ? x.id : crypto.randomUUID()
    await db.sql('INSERT INTO research_notes (id, repo, title, phase, progress, source, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET repo=excluded.repo, title=excluded.title, phase=excluded.phase, progress=excluded.progress, source=excluded.source, updated_at=excluded.updated_at', [id,x.repo,x.title.trim(),x.phase,x.progress.trim(),x.source.trim(),new Date().toISOString()])
  } else if(request.method !== 'GET') return new Response('Method not allowed',{status:405})
  const result=await db.sql('SELECT id, repo, title, phase, progress, source, updated_at FROM research_notes ORDER BY updated_at DESC LIMIT 500')
  return Response.json({items:result.rows,truncated:result.truncated},{headers:{'Cache-Control':'no-store'}})
}
export default {
  async fetch(request: Request) {
    const path = new URL(request.url).pathname
    if (path === '/api/activity') return activity(request)
    if (path === '/api/daily') return daily(request)
    if (path === '/api/research') { try { return await research(request) } catch { return Response.json({error:'Could not load research'}, {status:502}) } }
    if (path === '/api/tracked') { try { return await tracked(request) } catch { return Response.json({error:'Could not load tracked work'}, {status:502}) } }
    if (path !== '/' && path !== '') return new Response('Not found', { status: 404 })
    const ctx = packageContext
    if (!ctx?.clientModuleUrl || !ctx.assetBasePath) return new Response('App assets unavailable', { status: 500 })
    return new Response(`<!doctype html><html lang="en" data-base="${ctx.appBasePath}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>TanStack activity</title><link rel="stylesheet" href="${ctx.assetBasePath}/styles.css"></head><body><div id="root"></div><script type="module" src="${ctx.clientModuleUrl}"></script></body></html>`, { headers: { 'Content-Type': 'text/html; charset=utf-8' } })
  },
}