Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions .github/workflows/website.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: Website

# Builds the site in apps/website, every page prerendered to static HTML, with the playground's web builds of the examples and the API reference generated from packages/game's Go doc comments, and deploys it to GitHub Pages. It builds again as this repository's issues change, so the roadmap follows them, and hourly for the NSGo issues under nsgo-dev/nsgo#1047, whose changes cannot trigger a workflow here.
# Builds the site in apps/website, every page prerendered to static HTML, with the playground's web builds of the examples and the API reference generated from packages/game's Go doc comments, and deploys it to GitHub Pages.
on:
push:
branches:
Expand All @@ -24,10 +24,6 @@ on:
- "package.json"
- "bun.lock"
- ".github/workflows/website.yml"
issues:
types: [opened, edited, closed, reopened, deleted, transferred]
schedule:
- cron: "17 * * * *"
workflow_dispatch:

permissions:
Expand Down Expand Up @@ -76,7 +72,6 @@ jobs:
env:
BASE_PATH: ${{ steps.pages.outputs.base_path }}
SITE_ORIGIN: ${{ steps.pages.outputs.origin }}
GITHUB_TOKEN: ${{ github.token }}
run: bun run build
- name: Upload the Pages artifact
if: github.event_name != 'pull_request'
Expand Down
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Contributing

Contributions are welcome: bug fixes, new packages from the [roadmap](https://game.nsgo.dev/roadmap/), examples, documentation, and website improvements.
Contributions are welcome: bug fixes, new packages, examples, documentation, and website improvements.

## Repository layout

Expand Down Expand Up @@ -74,7 +74,7 @@ The site is [TanStack Start](https://tanstack.com/start) and React, every page p

## Pull requests

1. **Keep PRs focused.** One issue or cohesive change per pull request. Before starting a large feature, open an issue or comment on the existing roadmap issue to align on the API.
1. **Keep PRs focused.** One issue or cohesive change per pull request. Before starting a large feature, open an issue to align on the API.
2. **Verify locally before opening.** Ensure `gofmt -l` outputs nothing, `go tool nsgo test ./...` passes, and `go tool nsgo check` passes for your targets. For `docs/` or `apps/website/` changes, ensure `bun run build` exits `0`.
3. **Link the issue.** Include `Fixes #<number>` (or `Refs #<number>` for partial work) in the pull request description.
4. **Add a changelog fragment.** A change to `packages/`, `examples/` or `template/` adds a file to `changelog.d/` instead of editing `CHANGELOG.md`, as [changelog.d/README.md](changelog.d/README.md) describes. An internal change takes the `skip-changelog` label instead.
Expand Down
169 changes: 121 additions & 48 deletions README.md

Large diffs are not rendered by default.

277 changes: 4 additions & 273 deletions apps/website/plugins/content.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Build-time content: the docs from the repository's Markdown in each language, the API reference from the Go packages' doc comments, the home page's Go snippets, the playground's example sources, and the roadmap from GitHub's API. Each is a virtual module the routes import, so the pages carry the result and nothing is read from the repository or fetched from GitHub in the browser.
// Build-time content: the docs from the repository's Markdown in each language, the API reference from the Go packages' doc comments, the home page's Go snippets, and the playground's example sources. Each is a virtual module the routes import, so the pages carry the result and nothing is read from the repository in the browser.

import { execFile } from 'node:child_process'
import { readdir, readFile, stat } from 'node:fs/promises'
Expand All @@ -13,18 +13,16 @@ import { codeToHtml } from 'shiki'
import { type Plugin as UnifiedPlugin, unified } from 'unified'
import type { Plugin } from 'vite'
import { PLAYGROUND_BUILDS, PLAYGROUND_IDS, type PlaygroundId, isPlaygroundId } from '../src/content/playground.ts'
import type { ApiPackage, ApiReference, ApiSummary, DocHeading, DocPackage, DocPage, DocSummary, PackageStatus, PlaygroundExample, PlaygroundFile, PlaygroundSource, Roadmap, RoadmapGroup, RoadmapIssue, RoadmapStage, Snippet } from '../src/content/types'
import type { ApiPackage, ApiReference, ApiSummary, DocHeading, DocPackage, DocPage, DocSummary, PackageStatus, PlaygroundExample, PlaygroundFile, PlaygroundSource, Snippet } from '../src/content/types'
import { LANGS, type Lang, NON_DEFAULT_LANGS } from '../src/locales.ts'
import { loadSite, toTraditional } from './site.ts'

const REPO = 'nsgo-dev/game'
const PLAN = { repo: 'nsgo-dev/nsgo', number: 1047 }
const SNIPPETS: Snippet['id'][] = ['game', 'loop', 'sprite', 'sound']
const THEMES = { light: 'github-light', dark: 'github-dark' } as const

const modules = {
'virtual:snippets': loadSnippetsModule,
'virtual:roadmap': loadRoadmapModule,
'virtual:playground': loadPlaygroundModule,
'virtual:site': loadSiteModule,
} as const
Expand All @@ -50,8 +48,7 @@ interface Context {

export function siteContent(): Plugin {
let ctx: Context | undefined
// The client and server builds both load each module; the roadmap is fetched, and the API reference generated, once for both.
const cache = new Map<ModuleId, Promise<string>>()
// The client and server builds both load the API reference; generate it once for both.
let api: Promise<ApiBuild> | undefined
// The docs are rendered once for the client and server builds, and again after a Markdown file changes.
let docs: Promise<DocsBuild> | undefined
Expand Down Expand Up @@ -81,7 +78,6 @@ export function siteContent(): Plugin {
configureServer(server) {
server.watcher.on('add', (file) => {
if (!ctx || path.basename(file) !== 'nsgo.json' || !file.startsWith(path.join(ctx.publicDir, PLAYGROUND_BUILDS))) return
cache.delete('virtual:playground')
for (const environment of Object.values(server.environments)) {
const mod = environment.moduleGraph.getModuleById('\0virtual:playground')
if (mod) environment.moduleGraph.invalidateModule(mod)
Expand Down Expand Up @@ -163,12 +159,7 @@ export function siteContent(): Plugin {
if (moduleId === 'virtual:snippets') {
for (const snippet of SNIPPETS) this.addWatchFile(path.join(ctx.snippetsDir, `${snippet}.go.txt`))
}
let code = cache.get(moduleId)
if (!code || moduleId !== 'virtual:roadmap') {
code = modules[moduleId](ctx)
cache.set(moduleId, code)
}
return code
return modules[moduleId](ctx)
},
}
}
Expand Down Expand Up @@ -536,263 +527,3 @@ async function loadPlaygroundSource(ctx: Context, id: PlaygroundId): Promise<str
}
return `export const files = ${JSON.stringify(source.files)}`
}

// ---- Roadmap ----

// The roadmap is the issue tree under the plan, read with GitHub's GraphQL API: the plan's sub-issues are its stages, a stage's sub-issues its areas, and everything below an area is listed under it. A level of the tree is one request for up to 100 issues, so a build takes a handful of requests rather than one per issue. GraphQL needs a token; without GITHUB_TOKEN a local build shows the roadmap as unavailable.

const GRAPHQL_URL = 'https://api.github.com/graphql'
// Up to 100 issues a request asks for the sub-issues of, and up to 100 sub-issues for each: 10,000 nodes, well inside GitHub's limit of 500,000.
const PAGE = 100

const ISSUE_FIELDS = `fragment IssueFields on Issue { id number title state url repository { nameWithOwner } subIssuesSummary { total } }`
const SUB_ISSUES = `subIssues(first: ${PAGE}) { pageInfo { hasNextPage endCursor } nodes { ...IssueFields } }`

interface GqlPageInfo {
hasNextPage: boolean
endCursor: string | null
}

interface GqlIssue {
id: string
number: number
title: string
state: 'OPEN' | 'CLOSED'
url: string
repository: { nameWithOwner: string }
subIssuesSummary: { total: number }
}

interface GqlConnection<T> {
pageInfo: GqlPageInfo
nodes: T[]
}

type GqlStage = GqlIssue & { body: string; subIssues: GqlConnection<GqlIssue> }

// TreeNode is an issue of the plan's tree with the sub-issues read so far.
interface TreeNode {
id: string
issue: RoadmapIssue
// total is how many sub-issues GitHub says the issue has.
total: number
children: TreeNode[]
}

async function loadRoadmapModule(): Promise<string> {
let roadmap: Roadmap
try {
roadmap = await fetchRoadmap()
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
// A deploy must not replace the roadmap with an empty one; a local build goes on without it.
if (process.env.CI) throw new Error(`roadmap: ${reason}`)
console.warn(`[roadmap] skipped: ${reason}`)
roadmap = { status: 'unavailable', reason }
}
return `export const roadmap = ${JSON.stringify(roadmap)}`
}

async function fetchRoadmap(): Promise<Roadmap> {
const token = process.env.GITHUB_TOKEN
if (!token) throw new Error('GITHUB_TOKEN is not set, and GitHub’s GraphQL API needs a token')
const client = new GraphQL(token)
const [stages, gameIssues] = await Promise.all([fetchTree(client), fetchGameIssues(client)])
const planned = new Set<string>()
const roadmapStages = stages.map((stage, index) => {
const built = buildStage(stage, index)
for (const node of descendants(stage.node)) planned.add(issueKey(node.issue))
return built
})
const unplanned = gameIssues.filter((issue) => !planned.has(issueKey(issue))).sort((a, b) => a.number - b.number)
console.info(`[roadmap] ${client.requests} GraphQL requests; ${roadmapStages.map((s) => `stage ${s.number} ${s.closed}/${s.open + s.closed}`).join(', ')}; ${unplanned.length} unplanned`)
return { status: 'ok', fetchedAt: new Date().toISOString(), stages: roadmapStages, unplanned }
}

// fetchTree reads the plan's stages with their bodies and two levels below them in one request, then each further level, a request per 100 issues that have sub-issues.
async function fetchTree(client: GraphQL): Promise<{ node: TreeNode; body: string }[]> {
const data = await client.query<{ repository: { issue: { subIssues: GqlConnection<GqlStage> } | null } }>(
`query($owner: String!, $name: String!, $number: Int!) {
repository(owner: $owner, name: $name) {
issue(number: $number) {
subIssues(first: ${PAGE}) { pageInfo { hasNextPage endCursor } nodes { ...IssueFields body ${SUB_ISSUES} } }
}
}
}
${ISSUE_FIELDS}`,
{ owner: PLAN.repo.split('/')[0], name: PLAN.repo.split('/')[1], number: PLAN.number },
)
const plan = data.repository.issue
if (!plan) throw new Error(`${PLAN.repo}#${PLAN.number} was not found`)
if (plan.subIssues.pageInfo.hasNextPage) throw new Error(`${PLAN.repo}#${PLAN.number} has more than ${PAGE} stages`)
// Issues whose sub-issues are still to be read, and those with more pages of them.
let pending: TreeNode[] = []
const more: { node: TreeNode; after: string }[] = []
const attach = (node: TreeNode, connection: GqlConnection<GqlIssue>) => {
for (const raw of connection.nodes) {
const child = treeNode(raw)
node.children.push(child)
if (child.total > 0) pending.push(child)
}
if (connection.pageInfo.hasNextPage && connection.pageInfo.endCursor) more.push({ node, after: connection.pageInfo.endCursor })
}
const stages = plan.subIssues.nodes.map((raw) => {
const node = treeNode(raw)
attach(node, raw.subIssues)
return { node, body: raw.body }
})
while (pending.length || more.length) {
const level = pending
pending = []
for (let i = 0; i < level.length; i += PAGE) {
const batch = level.slice(i, i + PAGE)
const result = await client.query<{ nodes: ({ id: string; subIssues: GqlConnection<GqlIssue> } | null)[] }>(
`query($ids: [ID!]!) { nodes(ids: $ids) { ... on Issue { id ${SUB_ISSUES} } } }
${ISSUE_FIELDS}`,
{ ids: batch.map((node) => node.id) },
)
result.nodes.forEach((raw, j) => {
if (raw) attach(batch[j]!, raw.subIssues)
})
}
// An issue with more than 100 sub-issues reads the rest a page at a time.
for (const { node, after } of more.splice(0)) {
const result = await client.query<{ node: { subIssues: GqlConnection<GqlIssue> } | null }>(
`query($id: ID!, $after: String!) { node(id: $id) { ... on Issue { subIssues(first: ${PAGE}, after: $after) { pageInfo { hasNextPage endCursor } nodes { ...IssueFields } } } } }
${ISSUE_FIELDS}`,
{ id: node.id, after },
)
if (result.node) attach(node, result.node.subIssues)
}
}
return stages
}

// fetchGameIssues reads every issue of the game's repository, to list those in no stage.
async function fetchGameIssues(client: GraphQL): Promise<RoadmapIssue[]> {
const [owner, name] = REPO.split('/')
const issues: RoadmapIssue[] = []
let after: string | null = null
do {
const data: { repository: { issues: GqlConnection<Omit<GqlIssue, 'id' | 'subIssuesSummary'>> } } = await client.query(
`query($owner: String!, $name: String!, $after: String) {
repository(owner: $owner, name: $name) {
issues(first: ${PAGE}, after: $after, orderBy: { field: CREATED_AT, direction: ASC }) {
pageInfo { hasNextPage endCursor }
nodes { number title state url repository { nameWithOwner } }
}
}
}`,
{ owner, name, after },
)
const page = data.repository.issues
for (const raw of page.nodes) issues.push(toIssue(raw))
after = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null
} while (after)
return issues
}

function treeNode(raw: GqlIssue): TreeNode {
return { id: raw.id, issue: toIssue(raw), total: raw.subIssuesSummary.total, children: [] }
}

function toIssue(raw: Pick<GqlIssue, 'number' | 'title' | 'state' | 'url' | 'repository'>): RoadmapIssue {
return { repo: raw.repository.nameWithOwner, number: raw.number, title: raw.title, state: raw.state === 'CLOSED' ? 'closed' : 'open', url: raw.url }
}

function issueKey(issue: RoadmapIssue): string {
return `${issue.repo}#${issue.number}`
}

// descendants lists the issues below node, depth first in GitHub's order.
function descendants(node: TreeNode): TreeNode[] {
return node.children.flatMap((child) => [child, ...descendants(child)])
}

const STAGE_TITLE = /^Games stage (\d+):\s*(.+)$/i

// buildStage turns a stage's subtree into areas: each sub-issue with sub-issues of its own is an area listing everything below it, and the rest share one group after them.
function buildStage({ node, body }: { node: TreeNode; body: string }, index: number): RoadmapStage {
const match = STAGE_TITLE.exec(node.issue.title)
const title = match ? match[2]! : node.issue.title
const stage: RoadmapStage = {
number: match ? Number(match[1]) : index + 1,
title: title.charAt(0).toUpperCase() + title.slice(1),
description: stageDescription(body),
url: node.issue.url,
groups: [],
open: 0,
closed: 0,
}
const single: RoadmapGroup = { epic: null, area: '', items: [], open: 0, closed: 0 }
for (const child of node.children) {
if (child.children.length === 0) {
single.items.push({ ...child.issue, depth: 0 })
single[child.issue.state]++
continue
}
const group: RoadmapGroup = { epic: child.issue, area: areaName(child.issue.title), items: [], open: 0, closed: 0 }
group[child.issue.state]++
const visit = (parent: TreeNode, depth: 0 | 1) => {
for (const item of parent.children) {
group.items.push({ ...item.issue, depth })
group[item.issue.state]++
visit(item, 1)
}
}
visit(child, 0)
stage.groups.push(group)
}
if (single.items.length) stage.groups.push(single)
for (const group of stage.groups) {
stage.open += group.open
stage.closed += group.closed
}
return stage
}

// areaName is an epic's title up to its colon, without a leading tag such as "[Feature]": "Input: named actions…" is Input.
function areaName(title: string): string {
const untagged = title.replace(/^\[[^\]]*\]\s*/, '')
const colon = untagged.indexOf(':')
return colon > 0 ? untagged.slice(0, colon) : untagged
}

// stageDescription is the first paragraph of the stage issue's Context section, or of its body, without the sentence naming the plan it belongs to.
function stageDescription(body: string): string {
const text = body.replace(/\r\n/g, '\n')
const context = /^#{1,6}\s*Context\s*\n([\s\S]*?)(?=^#{1,6}\s|$(?![\s\S]))/im.exec(text)
const paragraphs = (context ? context[1]! : text).split(/\n\s*\n/).map((p) => p.trim().replace(/\s*\n\s*/g, ' '))
const first = paragraphs.find((p) => p && !p.startsWith('#')) ?? ''
return first
.replace(/^A stage of [\w/-]*#\d+\.\s*/i, '')
.replace(/`([^`]*)`/g, '$1')
.replace(/\*\*([^*]+)\*\*/g, '$1')
}

class GraphQL {
requests = 0
constructor(private readonly token: string) {}

async query<T>(query: string, variables: Record<string, unknown>): Promise<T> {
this.requests++
const res = await fetch(GRAPHQL_URL, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
'Content-Type': 'application/json',
'User-Agent': 'game-website-build',
},
body: JSON.stringify({ query, variables }),
signal: AbortSignal.timeout(30_000),
})
if (!res.ok) {
const hint = res.status === 403 || res.status === 429 ? ' (rate limited)' : ''
throw new Error(`GraphQL answered ${res.status} ${res.statusText}${hint}`)
}
const json = (await res.json()) as { data?: T; errors?: { message: string }[] }
if (json.errors?.length) throw new Error(`GraphQL: ${json.errors.map((e) => e.message).join('; ')}`)
if (!json.data) throw new Error('GraphQL answered without data')
return json.data
}
}
5 changes: 3 additions & 2 deletions apps/website/plugins/llms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,14 @@ export function buildLlms(pages: readonly LlmsPage[], site: string): { index: st
const index = `${[
'# NSGo Game',
`> ${copy.site.description}`,
`NSGo Game is early and its APIs will change: read the packages' source, \`go list -m -f '{{.Dir}}' github.com/nsgo-dev/game/packages/game\`, before relying on a signature. Each page below is a page of the site; ${site}${LLMS_FULL} holds their Markdown in full.`,
`NSGo Game v0.1.0 ships both stable and experimental packages (see API Stability). Read the packages' source, \`go list -m -f '{{.Dir}}' github.com/nsgo-dev/game/packages/game\`, before relying on a signature. Each page below is a page of the site; ${site}${LLMS_FULL} holds their Markdown in full.`,
...sections,
[
'## Optional',
'',
`- [NSGo for language models](${NSGO_LLMS_URL}): the docs of the UI engine the game layer runs on`,
`- [Roadmap](${site}roadmap/): what is planned and what is done, by stage`,
`- [API reference](${site}docs/api/): every exported identifier of the game packages`,
`- [Showcase](${site}showcase/): games, official examples and starter templates`,
`- [Changelog](${CHANGELOG_URL})`,
`- [Source](${GITHUB_URL})`,
].join('\n'),
Expand Down
Loading