Skip to content
Open
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
1 change: 1 addition & 0 deletions packages/api-model/src/languages/lua-examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export function attachCompleteLuaExamples(
: `Save the complete program as \`${name}\`. Closing the library connection leaves the daemon running; the launcher owns its lifetime.`,
sourceUrl: url(example.file),
code,
sourcePath: example.file,
},
launcher === undefined
? {
Expand Down
2 changes: 2 additions & 0 deletions packages/api-model/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,8 @@ export interface DocBlock {
outro?: string
/** Source for this complete example, independent of native comment syntax. */
sourceUrl?: string
/** Repository-relative path of a validated complete program. */
sourcePath?: string
}[]
/**
* Citations the docstring defines, as `.. [name] text`.
Expand Down
87 changes: 73 additions & 14 deletions scripts/stage-port-docs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -223,13 +223,45 @@ export function lispReferenceRoutes(symbols) {
return routes
}

export function stagedPortGuides(port, artifact) {
function luaExampleRoutes(artifact, model) {
if (model.repo !== artifact.source.repository || model.revision !== artifact.source.revision) return []
const files = Map.groupBy(artifact.examples ?? [], (file) => file.path)
const targets = Map.groupBy(model.symbols.filter((symbol) =>
symbol.slug && symbol.apiScope !== 'internal' && (symbol.product ?? 'core') === 'core'), (symbol) => symbol.id)
const routes = []
for (const example of artifact.api_examples.examples) {
const sources = files.get(example.file)
if (sources?.length !== 1) continue
const [{ content }] = sources
// The native manifest orders the targets for each complete program.
for (const id of example.symbols) {
const matches = targets.get(id)
if (matches?.length !== 1) continue
const symbol = matches[0]
if (!symbol.doc?.examples?.some((block) =>
block.lang === 'lua' && block.sourcePath === example.file && block.code === content)) continue
routes.push([example.file, `reference/${symbol.slug}`])
break
}
}
return routes
}

export function stagedPortGuides(port, artifact, apiModel) {
const identity = PORTS.find((entry) => entry.slug === port)
const routes = ROUTES[port]
const guides = new Map((artifact.guides ?? []).map((guide) => [guide.path, guide.content]))
const routes = Object.fromEntries(Object.entries(ROUTES[port]).filter(([path, guide]) => !guide.optional || guides.has(path)))
const linkRoutes = Object.fromEntries(Object.entries(routes).map(([sourcePath, guide]) => [sourcePath, [guide.route]]))
const nativeReferenceFiles = new Set()
const nativeDeclarations = new Map()
for (const redirect of sourceGuideRedirectsFor(port)) if (redirect.sourcePath) linkRoutes[redirect.sourcePath] = [redirect.target]
if (port === 'lua' && guides.has('docs/programs.md') && artifact.api_examples?.examples?.length) {
const model = apiModel ?? JSON.parse(readFileSync(join(root, 'site/src/data/api/lua.json'), 'utf8'))
for (const [file, route] of luaExampleRoutes(artifact, model)) {
linkRoutes[file] = [route]
nativeReferenceFiles.add(file)
}
}
if (port === 'haskell') {
const model = JSON.parse(readFileSync(join(root, 'site/src/data/api/haskell.json'), 'utf8'))
if (model.revision !== artifact.source.revision) throw new Error('haskell: guide source differs from the Haskell API model')
Expand Down Expand Up @@ -291,9 +323,13 @@ export function stagedPortGuides(port, artifact) {
if (parent) linkRoutes[`${directory}/${parent.slug}.md#${symbol.name}`] = [`reference/${symbol.slug}`]
}
}
const guides = new Map((artifact.guides ?? []).map((guide) => [guide.path, guide.content]))
const files = new Map()
const descriptions = new Map()
const checkoutGuidePaths = new Set(port === 'lua' ? artifact.checkoutGuidePaths : undefined)
const sourceFor = (path) => ({
repo: artifact.source.repository, path,
...(checkoutGuidePaths.has(path) ? { workingCopy: true } : { ref: artifact.source.revision }),
})
const titles = new Map(Object.entries(routes).map(([path, entry]) => [entry.route, entry.title ?? titleAndBody(guides.get(path) ?? '', path).title]))
for (const [sourcePath, guide] of Object.entries(routes)) {
const { route, product, package: packageId, domain, aliases, equivalence, sidebar } = guide
Expand All @@ -318,7 +354,7 @@ export function stagedPortGuides(port, artifact) {
...(aliases.length ? { aliases } : {}),
...(equivalence ? { equivalence } : {}),
route,
source: { repo: artifact.source.repository, path: sourcePath, ref: artifact.source.revision },
source: sourceFor(sourcePath),
sidebar: sidebar ?? { group: product ? (product === 'mcp' ? 'MCP' : 'Workspace Manager')
: route === 'reference' ? 'API reference' : route.split('/')[0].replace(/^./, (letter) => letter.toUpperCase()) },
}
Expand All @@ -327,7 +363,7 @@ export function stagedPortGuides(port, artifact) {
files.set(`${port}/${route}/index.md`, `---\n${frontmatter}\n---\n\n${rewritten.trim()}\n`)
}
{
const source = { repo: artifact.source.repository, path: Object.keys(routes)[0], ref: artifact.source.revision }
const source = sourceFor(Object.keys(routes)[0])
const writeIndex = (route, title, body, cards = []) => {
const data = { title, description: leadSentence(body) || `${title} for ${identity.packageName}.`, port, route, source, cards,
sidebar: { group: route === 'reference' ? 'API reference' : route[0].toUpperCase() + route.slice(1), label: 'Overview', order: 1 } }
Expand Down Expand Up @@ -412,15 +448,16 @@ function linkDocumenter(content, source) {
}

/** Read the integrated commit even when a contributor's working tree has advanced. */
export function artifactFromRevision(port, checkout, revision) {
export function artifactFromRevision(port, checkout, revision, { allowMissing = false } = {}) {
if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error(`${port.slug}: invalid integrated source revision`)
const git = (...args) => execFileSync('git', ['-C', checkout, ...args], { encoding: 'utf8', stdio: 'pipe' })
try {
git('cat-file', '-e', `${revision}^{commit}`)
} catch (cause) {
throw new Error(`${port.slug}: integrated guides need ${port.repo}@${revision} in ${checkout}. Set LIBTMUX_DOCS_CHECKOUT_${port.slug.toUpperCase()} to a local checkout containing that commit; this check does not fetch.`, { cause })
}
const paths = Object.keys(ROUTES[port.slug])
const routes = ROUTES[port.slug]
const paths = Object.keys(routes)
const blobs = execFileSync('git', ['-C', checkout, 'cat-file', '--batch'], {
input: paths.map((path) => `${revision}:${path}\n`).join(''), maxBuffer: 16 * 1024 * 1024,
stdio: ['pipe', 'pipe', 'pipe'],
Expand All @@ -430,6 +467,10 @@ export function artifactFromRevision(port, checkout, revision) {
for (const path of paths) {
const end = blobs.indexOf(10, offset)
const header = blobs.subarray(offset, end).toString('ascii')
if (end >= offset && (allowMissing || routes[path].optional) && header === `${revision}:${path} missing`) {
offset = end + 1
continue
}
const match = /^[a-f0-9]{40} blob (\d+)$/.exec(header)
const size = match && Number(match[1])
if (end < offset || size === null || !Number.isSafeInteger(size) || size < 0 ||
Expand All @@ -443,11 +484,26 @@ export function artifactFromRevision(port, checkout, revision) {
const readSource = (file) => contents.get(file) ?? git('show', `${revision}:${file}`)
return {
source: { repository: port.repo, revision },
guides: paths.map((path) => {
const content = readSource(path)
return { path, content: port.slug === 'julia' ? expandDocumenter(content, path, readSource) : content }
}),
guides: [...contents].map(([path, content]) => ({
path, content: port.slug === 'julia' ? expandDocumenter(content, path, readSource) : content,
})),
}
}

function luaCheckoutGuides(port, checkout, artifact) {
const { revision } = artifact.source
const pinned = artifactFromRevision(port, checkout, revision, { allowMissing: true })
const contents = new Map(pinned.guides.map(({ path, content }) => [path, content]))
const checkoutGuidePaths = []
for (const { path, content } of artifact.guides ?? []) {
if (!Object.hasOwn(ROUTES.lua, path) || typeof content !== 'string' || contents.get(path) === content) continue
const file = join(checkout, path)
if (!existsSync(file) || readFileSync(file, 'utf8') !== content) {
throw new Error(`lua: exported guide ${path} differs from both ${revision} and ${file}. Regenerate docs/_build/api.json from the selected checkout.`)
}
checkoutGuidePaths.push(path)
}
return checkoutGuidePaths.length ? { ...artifact, checkoutGuidePaths } : artifact
}

export function run() {
Expand Down Expand Up @@ -478,20 +534,23 @@ export function run() {
if (artifact.source.repository !== port.repo || !/^[a-f0-9]{40}$/.test(artifact.source.revision)) {
throw new Error(`${port.slug}: invalid source guide provenance`)
}
let model
if (!port.parentLibrary) {
const model = JSON.parse(readFileSync(join(root, `site/src/data/api/${port.slug}.json`), 'utf8'))
model = JSON.parse(readFileSync(join(root, `site/src/data/api/${port.slug}.json`), 'utf8'))
if (artifact.source.revision !== model.revision) throw new Error(`${port.slug}: guide source ${artifact.source.revision} differs from integrated model ${model.revision}`)
}
const expected = selectedSource
if (expected && artifact.source?.revision !== expected) {
throw new Error(`${port.slug}: expected source ${expected}, artifact records ${artifact.source?.revision}`)
}
const stagingArtifact = port.slug === 'lua' && !cached && !integrated && !fromSource && existsSync(join(checkout, '.git'))
? luaCheckoutGuides(port, checkout, artifact) : artifact
if (!check && (refreshCache || selectedSource)) {
mkdirSync(cacheRoot, { recursive: true })
const content = `${JSON.stringify(artifact, null, 2)}\n`
const content = `${JSON.stringify(stagingArtifact, null, 2)}\n`
if (!existsSync(cachePath) || readFileSync(cachePath, 'utf8') !== content) writeFileSync(cachePath, content)
}
for (const [file, content] of stagedPortGuides(port.slug, artifact)) generated.set(file, content)
for (const [file, content] of stagedPortGuides(port.slug, stagingArtifact, model)) generated.set(file, content)
}

const actual = new Map()
Expand Down
5 changes: 3 additions & 2 deletions site/src/components/SiteFooter.astro
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ interface Props {

const { locale, port, version, pagePath, source, markdownHref, llmsRoot, githubUrl, flush = false, compact = false } = Astro.props
const inventories = inventoryLinks(port, version, pagePath)
const rawSource = source && rawSourceUrl(source)
---

<footer class:list={[!flush && !compact && 'mt-16', 'border-t border-edge']} data-site-footer>
Expand All @@ -52,10 +53,10 @@ const inventories = inventoryLinks(port, version, pagePath)
</>}
<div class:list={[!compact && 'mt-6', 'flex items-start justify-between gap-4', !compact && 'border-t border-edge pt-4', 'opacity-80']}>
<div class="page-source min-w-0 wrap-anywhere">
{source && <>{t(locale, 'footer.source')}: <code>{source.path}</code> &#183; </>}
{source && <>{t(locale, source.workingCopy ? 'footer.checkoutSource' : 'footer.source')}: <code data-working-copy={source.workingCopy ? 'true' : undefined}>{source.path}</code> &#183; </>}
{t(locale, 'footer.machineReadable')}:
{markdownHref && <><a class="muted-link underline" href={markdownHref}>Markdown</a>, </>}
{source && <><a class="muted-link underline" href={rawSourceUrl(source)}>{t(locale, 'footer.rawSource')}</a>, </>}
{rawSource && <><a class="muted-link underline" href={rawSource}>{t(locale, 'footer.rawSource')}</a>, </>}
<a class="muted-link underline" href={`${llmsRoot}docs.json`}>docs.json</a>,
<a class="muted-link underline" href={`${llmsRoot}llms.txt`}>llms.txt</a>,
<a class="muted-link underline" href={`${llmsRoot}llms-full.txt`}>llms-full.txt</a>,
Expand Down
3 changes: 2 additions & 1 deletion site/src/content.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { glob } from 'astro/loaders'
import { defineCollection } from 'astro:content'
import { z } from 'astro/zod'
import { workspaceDocsLoader } from './loaders/workspace-shared.ts'
import { pageSourceSchema } from './lib/markdown-twins.ts'
import { PORTS } from './lib/ports.ts'

/**
Expand Down Expand Up @@ -51,7 +52,7 @@ const docs = defineCollection({
/** Shared task identity for verified counterparts with different routes. */
equivalence: z.string().min(1).optional(),
/** Exact port source backing a staged guide. */
source: z.object({ repo: z.string(), path: z.string(), ref: z.string() }).optional(),
source: pageSourceSchema.optional(),
/** Sidebar placement. */
sidebar: z
.object({
Expand Down
2 changes: 2 additions & 0 deletions site/src/i18n/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export const ui = {
'i18n.editPage': 'Edit this page on GitHub',
'i18n.coverageLink': 'See what else needs translating',
'footer.source': 'Source',
'footer.checkoutSource': 'Checkout source',
'footer.machineReadable': 'Machine-readable',
'footer.rawSource': 'raw source',
},
Expand Down Expand Up @@ -70,6 +71,7 @@ export const ui = {
'i18n.editPage': 'GitHub でこのページを編集する',
'i18n.coverageLink': '他に翻訳が必要なページを見る',
'footer.source': 'ソース',
'footer.checkoutSource': '作業ツリーのソース',
'footer.machineReadable': '機械可読',
'footer.rawSource': '生のソース',
},
Expand Down
2 changes: 1 addition & 1 deletion site/src/layouts/BaseLayout.astro
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ const inventoryPage: InventoryPage = {
scope: portSlug ?? (tmuxVersion ? `tmux@${tmuxVersion}` : 'site'),
product: /^(?:mcp|workspace)(?:\/|$)/.exec(pagePath)?.[0].replace(/\/$/, '') ?? 'core',
identity: inventoryId ?? (pagePath || 'index'),
title, version: portSlug ? target.version : tmuxVersion, source,
title, version: portSlug ? target.version : tmuxVersion, source: source.workingCopy ? undefined : source,
previousScopes: !portSlug && tmuxVersion && pagePath.startsWith(`tmux/${tmuxVersion}/catalog`) ? ['site'] : undefined,
aliases: inventoryAliases, exclude: inventoryExclude || bare ||
Boolean(process.env.LIBTMUX_DOCS_PORT && !inVersionTree) ||
Expand Down
20 changes: 11 additions & 9 deletions site/src/lib/markdown-twins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,20 @@
* loads, applies the same rules as the routes that write twins from source.
*/
import type { ApiModel, ApiSymbol, SourceApiModel } from '@libtmux/api-model'
import { z } from 'astro/zod'
import { CONTRIBUTE_BRANCH, CONTRIBUTE_REPO } from '../i18n/contribute.ts'

/** The file a page is rendered from: a path in a repository, at a ref. */
export interface PageSource {
repo: string
path: string
ref: string
}
const repositoryFile = z.object({ repo: z.string(), path: z.string() })

/** The file a page is rendered from, at a public ref or in the working copy. */
export const pageSourceSchema = z.union([
repositoryFile.extend({ ref: z.string(), workingCopy: z.never().optional() }),
repositoryFile.extend({ workingCopy: z.literal(true), ref: z.never().optional() }),
])
export type PageSource = z.infer<typeof pageSourceSchema>

/** The footer's raw source link. */
export function rawSourceUrl(source: PageSource): string {
return `https://github.com/${source.repo}/raw/${source.ref}/${source.path}`
export function rawSourceUrl(source: PageSource): string | undefined {
return source.workingCopy ? undefined : `https://github.com/${source.repo}/raw/${source.ref}/${source.path}`
}

/** A generated API page's source: its declaration, else the extracted model. */
Expand Down
3 changes: 3 additions & 0 deletions site/src/lib/port-documentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export interface PortSourceGuide {
/** Reader-facing metadata; the native source body and citation stay intact. */
title?: string
description?: string
/** Stage only when the selected native source includes this file. */
optional?: boolean
route: string
aliases: readonly string[]
/** Verified task counterpart; does not create a redirect or change its URL. */
Expand Down Expand Up @@ -430,6 +432,7 @@ const PORT_DOCUMENTATION: Readonly<Record<string, PortDocumentation>> = {
guide('docs/query.md', 'guides/query', 'core', { aliases: ['guides/source/query', 'concepts/queries', 'guides/querying-and-filtering'] }),
guide('docs/snapshots.md', 'guides/snapshots', 'core'),
guide('docs/creation.md', 'guides/creation', 'core'),
guide('docs/programs.md', 'guides/programs', 'core', { optional: true }),
guide('docs/topology.md', 'guides/topology', 'core'),
guide('docs/panes.md', 'guides/panes', 'core', { aliases: ['guides/source/panes', 'topics/pane-interaction', 'guides/capturing-output', 'guides/sending-keys'] }),
guide('docs/control.md', 'guides/control', 'core', { aliases: ['guides/source/control', 'concepts/transports'] }),
Expand Down
4 changes: 3 additions & 1 deletion site/test/core-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ export function routesOf(port: string): Set<string> {
// Staging writes these at build time from the port's repository: each guide, and an overview per section
// the port does not author itself (scripts/stage-port-docs.mjs, stagedSectionsFor).
if (SOURCE_GUIDE_PORTS.includes(port)) {
for (const guide of sourceGuidesFor(port)) for (const route of [guide.route, ...guide.aliases]) routes.add(route)
for (const guide of sourceGuidesFor(port)) {
if (!guide.optional) for (const route of [guide.route, ...guide.aliases]) routes.add(route)
}
for (const section of stagedSectionsFor(port)) routes.add(section)
}
return routes
Expand Down
16 changes: 13 additions & 3 deletions site/test/machine-readable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ function trackedFiles(): Set<string> {

interface Footer {
source?: string
checkoutSource: boolean
markdown?: string
raw?: string
manifest?: string
Expand All @@ -140,8 +141,10 @@ function footerOf(html: string): Footer | undefined {
const links = [...html.matchAll(/<link\b[^>]*>/g)].map((tag) => tag[0])
const alternate = links.find((tag) => value(tag, 'rel') === 'alternate' && value(tag, 'type') === 'text/markdown')
const canonical = links.find((tag) => value(tag, 'rel') === 'canonical')
const code = /<code\b[^>]*>([^<]+)<\/code>/.exec(block)
return {
source: /<code\b[^>]*>([^<]+)<\/code>/.exec(block)?.[1],
source: code?.[1],
checkoutSource: Boolean(code && value(code[0], 'data-working-copy') === 'true'),
markdown: hrefs.find((href) => href.endsWith('.md')),
raw: hrefs.find((href) => href.startsWith('https://github.com/')),
manifest: hrefs.find((href) => href.endsWith('/docs.json')),
Expand All @@ -156,7 +159,12 @@ function footerOf(html: string): Footer | undefined {
describe('machine-readable footer parsing', () => {
it.each(['', ' data-astro-cid-footer'])('reads the source path with code attributes %j', (attributes) => {
const html = `<div class="page-source">Source: <code${attributes}>README.md</code></div>`
expect(footerOf(html)?.source).toBe('README.md')
expect(footerOf(html)).toMatchObject({ source: 'README.md', checkoutSource: false })
})

it('recognizes an explicit working-copy source on the path', () => {
const html = '<div class="page-source">Checkout source: <code data-working-copy="true">README.md</code></div>'
expect(footerOf(html)).toMatchObject({ source: 'README.md', checkoutSource: true })
})
})

Expand Down Expand Up @@ -201,7 +209,9 @@ describe.skipIf(!SITE_BUILT)('machine-readable footer', () => {
}
}
const raw = footer.raw && /^https:\/\/github\.com\/([^/]+\/[^/]+)\/raw\/[^/]+\/(.+)$/.exec(footer.raw)
if (!raw) problems.push(`${page}: raw source ${footer.raw} is not a GitHub raw URL`)
if (footer.checkoutSource) {
if (!footer.source || footer.raw) problems.push(`${page}: invalid checkout source ${footer.source} with raw link ${footer.raw}`)
} else if (!raw) problems.push(`${page}: raw source ${footer.raw} is not a GitHub raw URL`)
else {
if (!REPOS.has(raw[1])) problems.push(`${page}: raw source repository ${raw[1]} is unknown`)
if (footer.source !== raw[2]) problems.push(`${page}: source ${footer.source} differs from raw path ${raw[2]}`)
Expand Down
Loading
Loading