From 323d62850dd276c1f5072050b60501c53293b092 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:17:38 -0600 Subject: [PATCH] feat(site[lua]) Show source-bound Lua Core programs why: The Core reader needs the Lua program shape and matrix evidence to display the complete examples run by native CI. what: - Add four programs from the verified public Lua revision. - Bind source, setup, and CI proof to the selected API model revision. - Preserve quickstart and source links across the shared pickers. --- scripts/gen-example-sources.mjs | 6 +- site/src/components/CoreHome.astro | 11 +- site/src/components/CoreShowcase.astro | 23 +-- site/src/data/core-apis.json | 23 +++ site/src/data/core-capabilities.json | 235 +++++++++++++++++++++++ site/src/data/core-example-matrices.json | 50 +++++ site/src/lib/core-apis.ts | 76 ++------ site/src/lib/core-capabilities.ts | 171 +++++++++++++++-- site/src/lib/core-showcase.ts | 20 ++ site/src/lib/example-syntax.ts | 63 ++++++ site/src/pages/index.astro | 3 +- site/test/core-apis.test.ts | 38 +++- site/test/core-capabilities.test.ts | 130 ++++++++++++- 13 files changed, 730 insertions(+), 119 deletions(-) create mode 100644 site/src/data/core-example-matrices.json create mode 100644 site/src/lib/core-showcase.ts create mode 100644 site/src/lib/example-syntax.ts diff --git a/scripts/gen-example-sources.mjs b/scripts/gen-example-sources.mjs index 1c2f86b07..8c9f842d3 100755 --- a/scripts/gen-example-sources.mjs +++ b/scripts/gen-example-sources.mjs @@ -10,7 +10,7 @@ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') const plugin = join(root, 'site/src/plugins/remark-port-code.mjs') const { LANG_TO_PORT, checkoutFor, parseMeta } = await import(`file://${plugin}`) const { landingCacheKey } = await import(`file://${join(root, 'site/src/lib/port-landing.ts')}`) -const { capabilityFiles } = await import(`file://${join(root, 'site/src/lib/core-capabilities.ts')}`) +const { capabilityApplies, capabilityFiles } = await import(`file://${join(root, 'site/src/lib/core-capabilities.ts')}`) const CONTENT = join(root, 'site/src/content/docs') const outArg = process.argv.indexOf('--out') @@ -75,7 +75,9 @@ const CAPABILITIES = JSON.parse(readFileSync(join(root, 'site/src/data/core-capa const choices = [] for (const [owner, capabilities] of Object.entries(CAPABILITIES)) { for (const entry of Object.values(capabilities)) { - for (const files of capabilityFiles(entry)) { + const source = entry.revision && sourceOf(owner, undefined, join(root, `site/src/data/api/${owner}.json`)) + if (!capabilityApplies(entry, source?.revision)) continue + for (const files of capabilityFiles(entry, owner)) { if (files.length > 1) choices.push({ owner, files }) else wanted.set(`${owner}:${files[0]}`, { owner, file: files[0] }) } diff --git a/site/src/components/CoreHome.astro b/site/src/components/CoreHome.astro index da7d5122a..6430c030f 100644 --- a/site/src/components/CoreHome.astro +++ b/site/src/components/CoreHome.astro @@ -1,18 +1,14 @@ --- import { Code } from 'astro-expressive-code/components' +import { coreShowcase } from '../lib/core-showcase' import CoreShowcase from './CoreShowcase.astro' import PackageInstall from './widgets/PackageInstall.astro' import DocCard from './DocCard.astro' import { PORT_BY_SLUG } from '../lib/ports' import { CAPABILITY_GROUPS, coreLead, resolveCoreHome } from '../lib/core-home' -import { portCapabilities, type CapabilityTable } from '../lib/core-capabilities' -import { QUICKSTARTS } from '../lib/quickstarts' import { registryFor } from '../lib/registry' import { proseHref } from '../lib/docs-paths' import { SITE_ROOT } from '../lib/site-root' -import CAPABILITY_TABLE from '../data/core-capabilities.json' -import SOURCES from '../data/example-sources.json' -import type { CachedSource } from '../lib/port-landing' /** * The body of a port's Core Library home, in the order of the Python front @@ -32,8 +28,7 @@ interface Props { const { port, version, cards } = Astro.props as Props const info = PORT_BY_SLUG[port] const home = resolveCoreHome(port, version) -const example = QUICKSTARTS[port]?.complete -const showcase = portCapabilities(port, CAPABILITY_TABLE as CapabilityTable, SOURCES as Record) +const { quickstart, programs } = coreShowcase(port) const released = registryFor(info).version ?? '' const series = /^0\.(\d+)/.exec(released)?.[0] @@ -55,7 +50,7 @@ const rest = (group: keyof typeof CAPABILITY_GROUPS) => home.capabilities[group]

{coreLead(port)}

What it does

-{(example || showcase.length > 0) &&
} +{(quickstart || programs.length > 0) &&
} {/* The installer follows the player (record 0059); the sections to go on to follow it. */}

Install

diff --git a/site/src/components/CoreShowcase.astro b/site/src/components/CoreShowcase.astro index fa9da7776..b413c3b48 100644 --- a/site/src/components/CoreShowcase.astro +++ b/site/src/components/CoreShowcase.astro @@ -2,15 +2,12 @@ import { Code } from 'astro-expressive-code/components' import HomeExample from './HomeExample.astro' import CorePlayer from './core/CorePlayer.astro' -import { CAPABILITIES, capabilityCacheKey, portCapabilities, type CapabilityId, type CapabilityTable } from '../lib/core-capabilities' -import { HOME_VIEWS, QUICKSTARTS, homeProgram } from '../lib/quickstarts' +import { coreShowcase } from '../lib/core-showcase' +import { HOME_VIEWS, homeProgram } from '../lib/quickstarts' import { capabilityExample, markersOnALine, playableCapability } from '../lib/core-player' import { PORT_BY_SLUG } from '../lib/ports' import { apisUsed, CORE_APIS } from '../lib/core-apis' import { buildTarget } from '../lib/versions' -import TABLE from '../data/core-capabilities.json' -import SOURCES from '../data/example-sources.json' -import type { CachedSource } from '../lib/port-landing' import { homeCodeColumns } from '../lib/quickstarts' /** @@ -37,11 +34,7 @@ interface Props { links?: { href: string; label: string }[] } const { port, links = [] } = Astro.props as Props -const quickstart = QUICKSTARTS[port]?.complete -const quickstartCapability = CAPABILITIES.find((item) => item.id === (quickstart?.capability ?? 'typed-graph')) -if (!quickstartCapability) throw new Error(`CoreShowcase: ${port} names an unknown quickstart capability`) -// The quickstart is the panel for its capability, so a port table entry for the same capability is not a second panel: the script selects panels by id. -const programs = portCapabilities(port, TABLE as CapabilityTable, SOURCES as Record).filter((item) => !quickstart || item.id !== quickstartCapability.id) +const { quickstart, capability: quickstartCapability, programs } = coreShowcase(port) const quickstartCode = quickstart ? homeProgram(quickstart, 'full') : '' // A recording of this program, run for real, makes the first capability a player; without one the program stands alone. const player = quickstart ? await playableCapability(port, quickstartCapability.id, quickstartCode) : undefined @@ -52,18 +45,13 @@ const hang = Math.max( ...(quickstart && player ? [markersOnALine(player.capability, HOME_VIEWS.map((view) => homeProgram(quickstart, view)), port)] : []), ...programs.flatMap((item) => { const found = capabilityPlayers.get(item.id) - return found ? [markersOnALine(found.capability, [homeProgram(capabilityExample({ ...item, repository: '', revision: '' }), 'concise')], port)] : [] + return found ? [markersOnALine(found.capability, [homeProgram(capabilityExample(item), 'concise')], port)] : [] }), ) const shown = [ ...(quickstart ? [{ ...quickstartCapability, quickstart: true as const, tmux: undefined as string | undefined }] : []), ...programs.map((item) => ({ ...item, quickstart: false as const })), ] -const cachedSource = (id: CapabilityId) => { - const entry = (TABLE as CapabilityTable)[port]![id]! - const cached = (SOURCES as Record)[capabilityCacheKey(port, entry.file)]! - return { repository: cached.repository, revision: cached.revision } -} const version = buildTarget(process.env).version const apis = new Map(shown.map((item) => [item.id, apisUsed(port, CORE_APIS[port]?.[item.id] ?? [], item.quickstart ? quickstartCode : item.code, version, `${port}/${item.id}`)])) --- @@ -103,9 +91,10 @@ const apis = new Map(shown.map((item) => [item.id, apisUsed(port, CORE_APIS[port style={`--home-code-columns: ${homeCodeColumns(item.code)}`}> {shown.length > 1 &&

{item.label}

} {capabilityPlayers.get(item.id) - ? : } + {item.setupUrl && } {apis.get(item.id)!.shown.length > 0 &&

APIs used

    diff --git a/site/src/data/core-apis.json b/site/src/data/core-apis.json index 9f281a636..9eba2b2bd 100644 --- a/site/src/data/core-apis.json +++ b/site/src/data/core-apis.json @@ -238,5 +238,28 @@ "LibTmux.Snapshot#v:lookupPane", "LibTmux.Snapshot#v:labelText" ] + }, + "lua": { + "typed-graph": [ + "libtmux.Server:new_session", + "libtmux.Session:new_window", + "libtmux.Pane:split" + ], + "watch": [ + "libtmux.Server:observe", + "libtmux.Observation:watch_pane" + ], + "send-keys": [ + "libtmux.Pane:send_text", + "libtmux.Pane:send_keys", + "libtmux.Pane:wait_for_text" + ], + "rename-windows": [ + "libtmux.Window:rename" + ], + "create-windows": [ + "libtmux.Session:new_window", + "libtmux.Window:snapshot" + ] } } diff --git a/site/src/data/core-capabilities.json b/site/src/data/core-capabilities.json index 117df5adf..29cdc07bc 100644 --- a/site/src/data/core-capabilities.json +++ b/site/src/data/core-capabilities.json @@ -431,5 +431,240 @@ } ] } + }, + "lua": { + "watch": { + "file": "examples/api/watch_pane.lua", + "lang": "lua", + "revision": "d8266f22bb7ddace64b597fc35899ab72c71cf9f", + "setup": "examples/api/README.md", + "tmux": "3.7+", + "ci": { + "workflow": ".github/workflows/ci.yml", + "job": "validate", + "step": "Run the ${{ matrix.gate }} gate", + "command": "luajit scripts/check/check.lua \"$CI_GATE\" --lua \"$TEST_LUA\" --nvim \".cache/toolchains/nvim-$CI_NVIM/bin/nvim\" 2>&1 | tee .cache/ci/check.log", + "matrix": { + "output": "matrix", + "cell": { + "name": "Outer current", + "gate": "outer", + "tmux": "3.8" + } + } + }, + "checkedBy": [ + { + "file": "examples/api/manifest.json", + "contains": "\"file\": \"examples/api/watch_pane.lua\",\n \"description\": \"Stream a pane's output from a control-mode observation and wait for typed text to arrive.\",\n \"min_tmux\": \"3.7\",\n \"stdout\": \"output: watched\\n\"\n }" + }, + { + "file": "scripts/check/gates.lua", + "contains": "{ \"mid\", \"integration\", \"package\", \"types\" }" + }, + { + "file": "scripts/check/gates.lua", + "contains": "{ ctx.luajit, \"scripts/package/main.lua\", \"--lua\", ctx.lua }" + }, + { + "file": "scripts/package/package.lua", + "contains": "check_release(work, rocks, lua, rt, cache, options.output, options.public_tag, opts)" + }, + { + "file": "scripts/package/package.lua", + "contains": "M.complete_api_examples(prefix, rt.version, lua, work, opts)" + }, + { + "file": "scripts/package/package.lua", + "contains": "if code ~= 0 then\n refuse(" + }, + { + "file": "scripts/package/package.lua", + "contains": "if output ~= example.stdout then" + }, + { + "file": ".github/workflows/ci.yml", + "contains": "defaults:\n run:\n shell: bash" + }, + { + "file": ".github/workflows/ci.yml", + "contains": "CI_GATE: ${{ matrix.gate }}" + } + ] + }, + "send-keys": { + "file": "examples/api/send_keys.lua", + "lang": "lua", + "revision": "d8266f22bb7ddace64b597fc35899ab72c71cf9f", + "setup": "examples/api/README.md", + "ci": { + "workflow": ".github/workflows/ci.yml", + "job": "validate", + "step": "Run the ${{ matrix.gate }} gate", + "command": "luajit scripts/check/check.lua \"$CI_GATE\" --lua \"$TEST_LUA\" --nvim \".cache/toolchains/nvim-$CI_NVIM/bin/nvim\" 2>&1 | tee .cache/ci/check.log", + "matrix": { + "output": "matrix", + "cell": { + "name": "Outer current", + "gate": "outer", + "tmux": "3.8" + } + } + }, + "checkedBy": [ + { + "file": "examples/api/manifest.json", + "contains": "\"file\": \"examples/api/send_keys.lua\",\n \"description\": \"Send literal text and press Enter in a pane.\",\n \"stdout\": \"lua input ready\\n\"\n }" + }, + { + "file": "scripts/check/gates.lua", + "contains": "{ \"mid\", \"integration\", \"package\", \"types\" }" + }, + { + "file": "scripts/check/gates.lua", + "contains": "{ ctx.luajit, \"scripts/package/main.lua\", \"--lua\", ctx.lua }" + }, + { + "file": "scripts/package/package.lua", + "contains": "check_release(work, rocks, lua, rt, cache, options.output, options.public_tag, opts)" + }, + { + "file": "scripts/package/package.lua", + "contains": "M.complete_api_examples(prefix, rt.version, lua, work, opts)" + }, + { + "file": "scripts/package/package.lua", + "contains": "if code ~= 0 then\n refuse(" + }, + { + "file": "scripts/package/package.lua", + "contains": "if output ~= example.stdout then" + }, + { + "file": ".github/workflows/ci.yml", + "contains": "defaults:\n run:\n shell: bash" + }, + { + "file": ".github/workflows/ci.yml", + "contains": "CI_GATE: ${{ matrix.gate }}" + } + ] + }, + "rename-windows": { + "file": "examples/api/refresh.lua", + "lang": "lua", + "revision": "d8266f22bb7ddace64b597fc35899ab72c71cf9f", + "setup": "examples/api/README.md", + "ci": { + "workflow": ".github/workflows/ci.yml", + "job": "validate", + "step": "Run the ${{ matrix.gate }} gate", + "command": "luajit scripts/check/check.lua \"$CI_GATE\" --lua \"$TEST_LUA\" --nvim \".cache/toolchains/nvim-$CI_NVIM/bin/nvim\" 2>&1 | tee .cache/ci/check.log", + "matrix": { + "output": "matrix", + "cell": { + "name": "Outer current", + "gate": "outer", + "tmux": "3.8" + } + } + }, + "checkedBy": [ + { + "file": "examples/api/manifest.json", + "contains": "\"file\": \"examples/api/refresh.lua\",\n \"description\": \"Read a window again after tmux renamed it, keeping the record read before.\",\n \"stdout\": \"editor build\\n\"\n }" + }, + { + "file": "scripts/check/gates.lua", + "contains": "{ \"mid\", \"integration\", \"package\", \"types\" }" + }, + { + "file": "scripts/check/gates.lua", + "contains": "{ ctx.luajit, \"scripts/package/main.lua\", \"--lua\", ctx.lua }" + }, + { + "file": "scripts/package/package.lua", + "contains": "check_release(work, rocks, lua, rt, cache, options.output, options.public_tag, opts)" + }, + { + "file": "scripts/package/package.lua", + "contains": "M.complete_api_examples(prefix, rt.version, lua, work, opts)" + }, + { + "file": "scripts/package/package.lua", + "contains": "if code ~= 0 then\n refuse(" + }, + { + "file": "scripts/package/package.lua", + "contains": "if output ~= example.stdout then" + }, + { + "file": ".github/workflows/ci.yml", + "contains": "defaults:\n run:\n shell: bash" + }, + { + "file": ".github/workflows/ci.yml", + "contains": "CI_GATE: ${{ matrix.gate }}" + } + ] + }, + "create-windows": { + "file": "examples/api/new_window.lua", + "lang": "lua", + "revision": "d8266f22bb7ddace64b597fc35899ab72c71cf9f", + "setup": "examples/api/README.md", + "ci": { + "workflow": ".github/workflows/ci.yml", + "job": "validate", + "step": "Run the ${{ matrix.gate }} gate", + "command": "luajit scripts/check/check.lua \"$CI_GATE\" --lua \"$TEST_LUA\" --nvim \".cache/toolchains/nvim-$CI_NVIM/bin/nvim\" 2>&1 | tee .cache/ci/check.log", + "matrix": { + "output": "matrix", + "cell": { + "name": "Outer current", + "gate": "outer", + "tmux": "3.8" + } + } + }, + "checkedBy": [ + { + "file": "examples/api/manifest.json", + "contains": "\"file\": \"examples/api/new_window.lua\",\n \"description\": \"Create a named window in a particular session.\",\n \"stdout\": \"window: logs\\n\"\n }" + }, + { + "file": "scripts/check/gates.lua", + "contains": "{ \"mid\", \"integration\", \"package\", \"types\" }" + }, + { + "file": "scripts/check/gates.lua", + "contains": "{ ctx.luajit, \"scripts/package/main.lua\", \"--lua\", ctx.lua }" + }, + { + "file": "scripts/package/package.lua", + "contains": "check_release(work, rocks, lua, rt, cache, options.output, options.public_tag, opts)" + }, + { + "file": "scripts/package/package.lua", + "contains": "M.complete_api_examples(prefix, rt.version, lua, work, opts)" + }, + { + "file": "scripts/package/package.lua", + "contains": "if code ~= 0 then\n refuse(" + }, + { + "file": "scripts/package/package.lua", + "contains": "if output ~= example.stdout then" + }, + { + "file": ".github/workflows/ci.yml", + "contains": "defaults:\n run:\n shell: bash" + }, + { + "file": ".github/workflows/ci.yml", + "contains": "CI_GATE: ${{ matrix.gate }}" + } + ] + } } } diff --git a/site/src/data/core-example-matrices.json b/site/src/data/core-example-matrices.json new file mode 100644 index 000000000..7de650541 --- /dev/null +++ b/site/src/data/core-example-matrices.json @@ -0,0 +1,50 @@ +{ + "lua": { + "revision": "d8266f22bb7ddace64b597fc35899ab72c71cf9f", + "workflow": ".github/workflows/ci.yml", + "inputs": { + ".github/workflows/ci.yml": "737aba66233703f00bf9a6026f404d37d8332f3a93b0d8aaa3dcb638fbccd9bc", + "scripts/ci_plan/ci_plan.lua": "ad2da1b13ae5eb0cc30fc412296524c3bb6d7e10a2e8ab1300ad332624d96877", + "scripts/ci_plan/cli.lua": "ecaac1667b54491a14743465a4244b98faaf3f8bd402248b8d035df56e73ec78", + "scripts/ci_plan/planner.lua": "15b10828b623bb0fce6ec8b98daff3a3edc692c93730d4402b9feff5a471c3e4", + "data/ci-matrix.json": "2d9d685adaeda667e9c490c38042c060f225b6dde3ac55e48a3a197c42bd815d", + "data/tmux-options.json": "8cd54138959ef993684d3173d8e04c2c168a3bd8c6b8f7f1db51509a3ed30d7b", + "scripts/check/check.lua": "7e8783b97aa4fe3c4aa821ac9a9cfb7d252624881feba8ab8e273fac4490e388", + "scripts/check/gates.lua": "e03bfb5620232deb2607c06c1bbd6cd6ebf008feb4650ce823d67a1e5f14f974", + "scripts/package/main.lua": "3a123341da6e9ca69517587a7d498282770ae3f4fc4f6e72f066f3e9ed680125", + "scripts/package/package.lua": "576e47b9a9a4b0c50468110e01d9a2ca9643013074842db8c06e4373f3a95584", + "examples/api/manifest.json": "d9b509cfd097f7ba59fb34617ca7a46b4146d68f81cb9a2257728340b0de4403", + "examples/api/watch_pane.lua": "577d42c85d2e0062afad1e044d861addac8da79bdbdbfeedc32d07a90325b3b4", + "examples/api/send_keys.lua": "8226e47a7ae229aaddf15f8fb21371d50355364ac33054b62b07ce377bc7ed33", + "examples/api/refresh.lua": "7d5bc501b0b294f7a821db60cef28a701d88979807c92408e8ab1d7e03405556", + "examples/api/new_window.lua": "8a0548ce192625281c021b1828f23af504fa03626e15dad8fe4f844ea0e52853", + "examples/api/README.md": "ce99afb6ba1a928112456259eb2206ae2955d7bba8ac4e0a59517c6dedd99442" + }, + "events": { + "pull_request": [ + { + "name": "Outer floor", + "gate": "outer", + "tmux": "3.3a" + }, + { + "name": "Outer current", + "gate": "outer", + "tmux": "3.8" + } + ], + "push": [ + { + "name": "Outer floor", + "gate": "outer", + "tmux": "3.3a" + }, + { + "name": "Outer current", + "gate": "outer", + "tmux": "3.8" + } + ] + } + } +} diff --git a/site/src/lib/core-apis.ts b/site/src/lib/core-apis.ts index 65947a25c..adb304031 100644 --- a/site/src/lib/core-apis.ts +++ b/site/src/lib/core-apis.ts @@ -9,17 +9,27 @@ * the program and holds no standard-library items, because the model holds * none. */ +import { withoutLiterals } from './example-syntax.ts' import DATA from '../data/core-apis.json' +import CAPABILITIES from '../data/core-capabilities.json' +import { capabilityApplies, type CapabilityId, type CapabilityTable } from './core-capabilities.ts' import { API_MODELS, referenceHref } from './api-models.ts' import { PORT_BY_SLUG, referenceUrl } from './ports.ts' /** The language each port's examples are written in. */ -const LANG: Record = { rs: 'rust', go: 'go', ruby: 'ruby', ocaml: 'ocaml', haskell: 'haskell' } +const LANG: Record = { rs: 'rust', go: 'go', ruby: 'ruby', ocaml: 'ocaml', haskell: 'haskell', lua: 'lua' } /** Entries shown before "+N more". */ export const MAX_APIS = 10 -export const CORE_APIS: Readonly>>> = DATA +const table = CAPABILITIES as CapabilityTable +export const CORE_APIS: Readonly>>> = + Object.fromEntries(Object.entries(DATA).map(([port, mapping]) => [ + port, Object.fromEntries(Object.entries(mapping).filter(([id]) => { + const example = table[port]?.[id as CapabilityId] + return !example || capabilityApplies(example, API_MODELS[port]?.revision) + })), + ])) export interface ApiUsed { id: string @@ -37,63 +47,6 @@ export interface ApisUsed { const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') -/** Languages the examples are written in, and what starts a comment or a string in each. */ -const SYNTAX: Record = { - ocaml: { block: ['(*', '*)'], quotes: ['"'] }, - haskell: { line: '--', block: ['{-', '-}'], quotes: ['"'] }, - rust: { line: '//', block: ['/*', '*/'], quotes: ['"'] }, - go: { line: '//', block: ['/*', '*/'], quotes: ['"', '`', "'"] }, - ruby: { line: '#', quotes: ['"', "'"] }, -} - -/** The program with its comments and string literals blanked, so a name in either does not count as a use. */ -export function withoutLiterals(code: string, lang: string): string { - const syntax = SYNTAX[lang] - if (!syntax) throw new Error(`core-apis: no comment and string rules for ${lang}`) - let out = '' - for (let i = 0; i < code.length;) { - const rest = code.slice(i) - const blank = (length: number) => { out += code.slice(i, i + length).replace(/[^\n]/g, ' '); i += length } - if (syntax.line && rest.startsWith(syntax.line)) { - const end = rest.indexOf('\n') - blank(end < 0 ? rest.length : end) - } else if (syntax.block && rest.startsWith(syntax.block[0])) { - let end = rest.indexOf(syntax.block[1], syntax.block[0].length) - if (lang === 'ocaml' || lang === 'haskell') { - let depth = 1 - let at = syntax.block[0].length - while (at < rest.length && depth > 0) { - if (rest.startsWith(syntax.block[0], at)) { depth++; at += syntax.block[0].length } - else if (rest.startsWith(syntax.block[1], at)) { depth--; at += syntax.block[1].length } - else at++ - } - end = depth ? -1 : at - syntax.block[1].length - } - blank(end < 0 ? rest.length : end + syntax.block[1].length) - } else if (syntax.quotes.includes(rest[0]!)) { - const quote = rest[0]! - let j = 1 - // Ruby runs the code in `#{...}` inside a double-quoted string, so a call there is a use. - let interpolated = '' - while (j < rest.length && rest[j] !== quote) { - if (lang === 'ruby' && quote === '"' && rest.startsWith('#{', j)) { - let depth = 0 - let k = j + 1 - for (; k < rest.length; k++) { - if (rest[k] === '{') depth++ - else if (rest[k] === '}' && --depth === 0) break - } - interpolated += ' '.repeat(j - interpolated.length) + rest.slice(j + 2, k) - j = k + 1 - } else j += rest[j] === '\\' && quote !== '`' ? 2 : 1 - } - const length = Math.min(j + 1, rest.length) - if (interpolated) { out += (interpolated + ' ').padEnd(length, ' '); i += length } else blank(length) - } else { out += code[i]; i++ } - } - return out -} - const CALLED = new Set(['method', 'function', 'property']) /** The symbols `ids` name, as the program uses them, in order of first use. */ @@ -108,9 +61,10 @@ export function apisUsed(port: string, ids: readonly string[], code: string, ver const symbol = model.symbols.find((entry) => (entry.publicId ?? entry.id) === id) if (!symbol) throw new Error(`core-apis: ${what} names ${id}, which is not in the ${port} API model`) if (symbol.apiScope === 'internal' || (symbol.product ?? 'core') !== 'core') throw new Error(`core-apis: ${what} names ${id}, which has no core reference page`) - // A call is written `.name(` or `Type::name`; a type or constant is written bare. Comments and strings do not count. + // A method needs its language's call syntax. A type or constant is written bare. const name = escape(symbol.name) - const pattern = CALLED.has(symbol.kind) ? `(?:\\.|::|&:)${name}(?![\\w])` : `(?> +type MatrixEvents = Readonly>> + +interface MatrixProof { + revision: string + workflow: string + inputs: Readonly> + events: MatrixEvents +} + +const matrixProofs: Readonly> = MATRIX_PROOFS + export interface CapabilityEntry { file: string lang: string + /** The source model revision this entry was verified at, when the release pin differs. */ + revision?: string + /** The program's setup instructions at the same revision. */ + setup?: string /** Excerpt anchors. A showcase entry is a whole program, so a recorded anchor is refused. */ from?: string to?: string @@ -72,6 +91,8 @@ export interface CapabilityEntry { * `if` the check accepts, and the plan job must publish it from a step. */ planOutput?: string + /** The required job's planned matrix output and the cell that runs this example. */ + matrix?: { output: string; cell: MatrixCell } } /** Why a wrong exit status or missing expected output fails the CI run. At least one. */ checkedBy: readonly ExitEvidence[] @@ -84,12 +105,32 @@ export type CapabilityTable = Readonly landingCacheKey(owner, 'core' as never, file).replace('/core:', ':') /** Every file an entry relies on, as the paths it may have: the example, then what checks it. */ -export const capabilityFiles = (entry: CapabilityEntry): (readonly string[])[] => [[entry.file], ...entry.checkedBy.map((item) => alternatives(item.file))] +export function capabilityFiles(entry: CapabilityEntry, owner?: string): (readonly string[])[] { + const proof = owner && entry.ci.matrix ? matrixProofs[owner] : undefined + return [ + [entry.file], + ...(entry.setup ? [[entry.setup]] : []), + ...(proof ? Object.keys(proof.inputs).map((file) => [file]) : []), + ...entry.checkedBy.map((item) => alternatives(item.file)), + ] +} + +export const capabilityApplies = (entry: CapabilityEntry, revision: string | undefined): boolean => + entry.revision === undefined || entry.revision === revision /** Problems with an entry's record, empty when it states its evidence. */ export function validateCapability(entry: Partial): string[] { const problems: string[] = [] if (!entry.file) problems.push('names no file') + if (entry.revision !== undefined && !/^[a-f0-9]{40}$/.test(entry.revision)) problems.push('names an invalid source revision') + if (entry.setup !== undefined && !/^[\w.-]+(?:\/[\w.-]+)+\.md$/.test(entry.setup)) problems.push('names no setup guide') + if (entry.ci?.matrix) { + const { output, cell } = entry.ci.matrix + if (!entry.revision || !/^[\w-]+$/.test(output) || !Object.keys(cell).length || + Object.entries(cell).some(([key, value]) => !/^[\w-]+$/.test(key) || !value.trim())) { + problems.push('names no revision-bound matrix cell') + } + } if (entry.from !== undefined || entry.to !== undefined || entry.more !== undefined) problems.push('quotes an excerpt; a showcase entry is a whole program') if (!/^\.github\/workflows\/[\w.-]+\.ya?ml$/.test(entry.ci?.workflow ?? '')) problems.push('names no workflow') if (!entry.ci?.command?.trim()) problems.push('names no CI command') @@ -105,6 +146,27 @@ export function validateCapability(entry: Partial): string[] { /** The most lines a whole program may run; the page shows the file in full. */ export const MAX_PROGRAM_LINES = 150 +/** Inspect the Lua source shown on the page. Keep positions when blanking strings and comments. */ +function luaProgramShape(source: string) { + const code = withoutLiterals(source, 'lua') + const bindings = [...source.matchAll(/^[ \t]*local[ \t]+([A-Za-z_]\w*)[ \t]*=[ \t]*require[ \t]*\(?[ \t]*["'](libtmux(?:\.[A-Za-z_]\w*)*|luv)["']/gm)] + .filter((match) => code.slice(match.index, match.index + match[0].length).trim() !== '') + const calls = code.matchAll(/\b([A-Za-z_]\w*)\.run\s*\(\s*(?:function\s*\(\s*[A-Za-z_]\w*\s*\)|([A-Za-z_]\w*)(?=\s*[),]))/g) + const entry = [...calls].some((call) => { + const before = code.slice(0, call.index) + if (/[.:]\s*$/.test(before)) return false + if (!bindings.some((binding) => binding[2] === 'libtmux.runtime.luv' && binding[1] === call[1] && binding.index < call.index)) return false + const callback = call[2] + return !callback || new RegExp(`^[ \\t]*local\\s+function\\s+${callback}\\s*\\(`, 'm').test(before) + }) + return { + imports: bindings.length > 0, + entry, + usesHelper: /\b(?:dofile|loadfile)\s*\(|\brequire\s*\(?\s*["'](?!(?:libtmux(?:\.[\w_]+)*|luv)["'])/.test(source), + ownsServer: /\bruntime:with_server\(|\bruntime:start_server\([\s\S]*\w+:stop\(/.test(code), + } +} + /** * What a reader needs to paste a program and build it: its imports and its * entry point, with no helper module of the repository. Empty when the file @@ -126,12 +188,19 @@ export function programProblems(lang: string, content: string): string[] { typescript: { imports: /^import /m, entry: /^(?:await |void |main\()|^(?:async )?function main\(/m }, } const rule = rules[lang] + const shape = lang === 'lua' ? luaProgramShape(content) : rule && { + imports: rule.imports.test(content), + entry: rule.entry.test(content), + usesHelper: rule.local?.test(content), + ownsServer: true, + } const problems: string[] = [] - if (!rule) problems.push(`has no completeness rule for ${lang}`) + if (!shape) problems.push(`has no completeness rule for ${lang}`) else { - if (!rule.imports.test(content)) problems.push('has no import lines') - if (!rule.entry.test(content)) problems.push('has no entry point') - if (rule.local?.test(content)) problems.push('uses a helper of the repository') + if (!shape.imports) problems.push('has no import lines') + if (!shape.entry) problems.push('has no entry point') + if (shape.usesHelper) problems.push('uses a helper of the repository') + if (!shape.ownsServer) problems.push('does not own a private server') if (content.trimEnd().split('\n').length > MAX_PROGRAM_LINES) problems.push(`runs past ${MAX_PROGRAM_LINES} lines`) } return [...new Set([...problems, ...hygieneProblems(content)])] @@ -199,7 +268,10 @@ export interface ShownCapability { source: string lang: string file: string + repository: string + revision: string sourceUrl: string + setupUrl?: string ci: CapabilityEntry['ci'] tmux?: string } @@ -215,23 +287,51 @@ export function evidenceProblems(owner: string, item: ExitEvidence, cache: Cache return texts.some((text) => found.cached!.content.includes(text)) ? [] : [`${found.file} holds none of ${texts.map((text) => JSON.stringify(text)).join(' or ')}`] } -/** The capabilities a port shows, in order. An unresolvable anchor or missing cache throws. */ -export function portCapabilities(owner: string, table: CapabilityTable, cache: Cache): ShownCapability[] { +function matrixProblems(owner: string, entry: CapabilityEntry, source: CachedSource, cache: Cache): string[] { + const proof = matrixProofs[owner] + if (!proof || proof.revision !== source.revision || proof.workflow !== entry.ci.workflow) return ['has no matrix proof for its revision'] + const displayed = entry.setup ? [entry.file, entry.setup] : [entry.file] + if ([proof.workflow, ...displayed].some((file) => !proof.inputs[file])) return ['has missing matrix proof input hashes'] + + const digest = (content: string) => createHash('sha256').update(content).digest('hex') + for (const [file, hash] of Object.entries(proof.inputs)) { + const input = cache[capabilityCacheKey(owner, file)] + if (!input || input.revision !== source.revision || input.repository !== source.repository || digest(input.content) !== hash) { + return [`matrix proof source differs for ${file}`] + } + } + const workflow = cache[capabilityCacheKey(owner, proof.workflow)] + if (!workflow || !workflowStep(workflow.content, entry.ci, proof.events)) return ['its example step is not run by the recorded matrix'] + return entry.checkedBy.flatMap((item) => evidenceProblems(owner, item, cache)) +} + +/** The capabilities a port shows, in order. A missing cache or invalid example throws. */ +export function portCapabilities(owner: string, table: CapabilityTable, cache: Cache, revision?: string): ShownCapability[] { return CAPABILITIES.flatMap(({ id, label }): ShownCapability[] => { const entry = table[owner]?.[id] - if (!entry) return [] + if (!entry || !capabilityApplies(entry, revision)) return [] const problems = validateCapability(entry) if (problems.length) throw new Error(`core-capabilities: ${owner}/${id} ${problems.join('; ')}`) const key = capabilityCacheKey(owner, entry.file) const cached = cache[key] if (!cached) throw new Error(`core-capabilities: ${key} is not in the example cache; run node scripts/gen-example-sources.mjs`) + if (entry.revision && capabilityFiles(entry, owner).some((files) => { + const input = files.map((file) => cache[capabilityCacheKey(owner, file)]).find(Boolean) + return !input || input.repository !== cached.repository || input.revision !== revision + })) throw new Error(`core-capabilities: ${owner}/${id} is missing sources at ${revision}`) + if (entry.ci.matrix) { + const problems = matrixProblems(owner, entry, cached, cache) + if (problems.length) throw new Error(`core-capabilities: ${owner}/${id} ${problems.join('; ')}`) + } const code = stripBuildMarkers(cached.content).replace(/\n$/, '') const incomplete = programProblems(entry.lang, code) if (incomplete.length) throw new Error(`core-capabilities: ${owner}/${id} ${incomplete.join('; ')}`) return [{ id, label, lang: entry.lang, file: entry.file, ci: entry.ci, code, source: cached.content.replace(/\n$/, ''), + repository: cached.repository, revision: cached.revision, sourceUrl: `https://github.com/${cached.repository}/blob/${cached.revision}/${entry.file}`, + ...(entry.setup ? { setupUrl: `https://github.com/${cached.repository}/blob/${cached.revision}/${entry.setup}` } : {}), ...(entry.tmux ? { tmux: entry.tmux } : {}), }] }) @@ -242,19 +342,21 @@ export function portCapabilities(owner: string, table: CapabilityTable, cache: C * has one, its working directory, and a `run` that holds the command. A command * that only appears in another step or job does not count. */ -export function workflowStep(workflow: string, ci: CapabilityEntry['ci']): boolean { +export function workflowStep(workflow: string, ci: CapabilityEntry['ci'], events?: MatrixEvents): boolean { const lines = workflow.replaceAll('\r', '').split('\n') const job = jobLines(lines, ci.job) if (!job) return false // A job that may not run, or may fail without failing the workflow, proves nothing. if (job.some((line) => mayNotRun(line) && !plannedRun(lines, job, line, ci))) return false + const cell = ci.matrix && plannedMatrixCell(lines, job, ci.job, ci.matrix, events) + if (ci.matrix && !cell) return false const parsed = jobSteps(job) if (!parsed) return false const { indent, steps } = parsed return steps.some((step) => { const stepName = stepKey(indent, step, 'name') const directory = stepKey(indent, step, 'working-directory') - return !mayNotRunStep(indent, step) + return !mayNotRunStep(indent, step, cell) && (ci.step === undefined || (stepName !== undefined && unquote(stepName) === ci.step)) && (directory === undefined ? ci.directory === undefined : unquote(directory) === ci.directory) && runsCommand(step, ci.command) @@ -297,9 +399,17 @@ const stepKey = (indent: string, step: string[], name: string) => step.map((line new RegExp(`^${indent}(?:- | {2})${name}:\\s*(.+)$`).exec(line)?.[1]).find((value) => value !== undefined) /** Whether a step carries a condition, or may fail without failing the job. */ -function mayNotRunStep(indent: string, step: string[]): boolean { +function mayNotRunStep(indent: string, step: string[], cell?: MatrixCell): boolean { const tolerated = stepKey(indent, step, 'continue-on-error') - return stepKey(indent, step, 'if') !== undefined || (tolerated !== undefined && unquote(tolerated) !== 'false') + if (tolerated !== undefined && unquote(tolerated) !== 'false') return true + const condition = stepKey(indent, step, 'if') + if (condition === undefined) return false + const match = /^matrix\.([\w-]+)\s*(==|!=)\s*(['"])([^'"]+)\3$/.exec( + unquote(condition).replace(/^\$\{\{\s*|\s*\}\}$/g, ''), + ) + const value = match && cell?.[match[1]!] + if (typeof value !== 'string') return true + return match![2] === '==' ? value !== match![4] : value === match![4] } /** @@ -343,10 +453,13 @@ function plannedRun(lines: string[], job: string[], condition: string, ci: Capab if (!flag || !/^[A-Za-z_][\w-]*$/.test(flag)) return false const match = /^ {4}if:\s*['"]?\$?\{?\{?\s*needs\.([\w-]+)\.outputs\.([\w-]+)\s*==\s*'true'\s*\}?\}?['"]?$/.exec(stripComment(condition).trimEnd()) if (!match || match[2] !== flag) return false - const plan = match[1]! + return publishesPlanOutput(lines, job, ci.job, match[1]!, flag) +} + +function publishesPlanOutput(lines: string[], job: string[], name: string, plan: string, flag: string): boolean { const listed = neededJobs(job) - if (!listed.includes(plan) || plan === ci.job) return false - if (!listed.filter((name) => name !== plan).every((name) => alwaysRuns(lines, name, new Set([ci.job])))) return false + if (!listed.includes(plan) || plan === name) return false + if (!listed.filter((other) => other !== plan).every((other) => alwaysRuns(lines, other, new Set([name])))) return false const planned = jobLines(lines, plan) if (!planned || planned.some((line) => /^ {4}needs:/.test(line) || mayNotRun(line))) return false const outputs = planned.findIndex((line) => /^ {4}outputs:\s*$/.test(line)) @@ -365,6 +478,34 @@ function plannedRun(lines: string[], job: string[], condition: string, ci: Capab }) } +/** + * A comparison on a matrix value is useful only with a cell the required + * producer actually plans for both normal CI events. + */ +function plannedMatrixCell( + lines: string[], job: string[], name: string, matrix: NonNullable, events?: MatrixEvents, +): MatrixCell | undefined { + const keys = Object.entries(matrix.cell) + const strategy = job.findIndex((line) => /^ {4}strategy:\s*$/.test(line)) + if (!keys.length || strategy < 0) return undefined + const strategyBody = job.slice(strategy + 1) + const end = strategyBody.findIndex((line) => /^ {0,4}[^\s#]/.test(line)) + const source = strategyBody.slice(0, end < 0 ? undefined : end) + .map((line) => /^ {6}matrix:\s*\$\{\{\s*fromJSON\(needs\.([\w-]+)\.outputs\.([\w-]+)\)\s*\}\}\s*$/.exec(stripComment(line))) + .find(Boolean) + if (!source || source[2] !== matrix.output || !publishesPlanOutput(lines, job, name, source[1]!, source[2]!)) return undefined + const on = lines.findIndex((line) => /^on:\s*$/.test(line)) + if (on < 0) return undefined + const eventLines = lines.slice(on + 1) + const eventEnd = eventLines.findIndex((line) => /^[^\s#]/.test(line)) + const triggers = eventLines.slice(0, eventEnd < 0 ? undefined : eventEnd) + const covered = (['pull_request', 'push'] as const).every((event) => + triggers.some((line) => new RegExp(`^ {2}${event}:`).test(line)) + && events?.[event]?.some((row) => keys.every(([key, value]) => row[key] === value)), + ) + return covered ? matrix.cell : undefined +} + /** Whether a step's `run` holds the command as whole commands, not as a prefix of another or inside a string. */ function runsCommand(step: string[], command: string): boolean { if (!workflowRuns(step.join('\n'), command)) return false diff --git a/site/src/lib/core-showcase.ts b/site/src/lib/core-showcase.ts new file mode 100644 index 000000000..61033211f --- /dev/null +++ b/site/src/lib/core-showcase.ts @@ -0,0 +1,20 @@ +import TABLE from '../data/core-capabilities.json' +import SOURCES from '../data/example-sources.json' +import { API_MODELS } from './api-models' +import { CAPABILITIES, portCapabilities, type CapabilityTable } from './core-capabilities' +import type { CachedSource } from './port-landing' +import { QUICKSTARTS } from './quickstarts' + +/** Which Core programs and CI source links the reader sees for this library revision. */ +export function coreShowcase(port: string, table: CapabilityTable = TABLE as CapabilityTable) { + const revision = API_MODELS[port]?.revision + const programs = portCapabilities(port, table, SOURCES as Record, revision) + const home = QUICKSTARTS[port]?.complete + const capability = CAPABILITIES.find((item) => item.id === (home?.capability ?? 'typed-graph')) + if (!capability) throw new Error(`CoreShowcase: ${port} names an unknown quickstart capability`) + + // A program verified at this revision can replace a quickstart for an older library. + const pin = table[port]?.[capability.id]?.revision + const quickstart = pin && pin === revision && pin !== (home?.libraryRevision ?? home?.sourceRevision) ? undefined : home + return { quickstart, capability, programs: quickstart ? programs.filter((item) => item.id !== capability.id) : programs } +} diff --git a/site/src/lib/example-syntax.ts b/site/src/lib/example-syntax.ts new file mode 100644 index 000000000..bcdac9a35 --- /dev/null +++ b/site/src/lib/example-syntax.ts @@ -0,0 +1,63 @@ +/** Languages the examples are written in, and what starts a comment or a string in each. */ +const SYNTAX: Record = { + ocaml: { block: ['(*', '*)'], quotes: ['"'] }, + haskell: { line: '--', block: ['{-', '-}'], quotes: ['"'] }, + rust: { line: '//', block: ['/*', '*/'], quotes: ['"'] }, + go: { line: '//', block: ['/*', '*/'], quotes: ['"', '`', "'"] }, + ruby: { line: '#', quotes: ['"', "'"] }, + lua: { line: '--', quotes: ['"', "'"] }, +} + +/** The program with its comments and string literals blanked, so a name in either does not count as a use. */ +export function withoutLiterals(code: string, lang: string): string { + const syntax = SYNTAX[lang] + if (!syntax) throw new Error(`core-apis: no comment and string rules for ${lang}`) + let out = '' + for (let i = 0; i < code.length;) { + const rest = code.slice(i) + const blank = (length: number) => { out += code.slice(i, i + length).replace(/[^\n]/g, ' '); i += length } + const block = syntax.block && rest.startsWith(syntax.block[0]) ? syntax.block : undefined + const luaBracket = lang === 'lua' && /^(?:--)?\[(=*)\[/.exec(rest) + if (luaBracket) { + const close = `]${luaBracket[1]}]` + const end = rest.indexOf(close, luaBracket[0].length) + blank(end < 0 ? rest.length : end + close.length) + } else if (syntax.line && rest.startsWith(syntax.line) && !block) { + const end = rest.indexOf('\n') + blank(end < 0 ? rest.length : end) + } else if (block) { + let end = rest.indexOf(block[1], block[0].length) + if (lang === 'ocaml' || lang === 'haskell') { + let depth = 1 + let at = block[0].length + while (at < rest.length && depth > 0) { + if (rest.startsWith(block[0], at)) { depth++; at += block[0].length } + else if (rest.startsWith(block[1], at)) { depth--; at += block[1].length } + else at++ + } + end = depth ? -1 : at - block[1].length + } + blank(end < 0 ? rest.length : end + block[1].length) + } else if (syntax.quotes.includes(rest[0]!)) { + const quote = rest[0]! + let j = 1 + // Ruby runs the code in `#{...}` inside a double-quoted string, so a call there is a use. + let interpolated = '' + while (j < rest.length && rest[j] !== quote) { + if (lang === 'ruby' && quote === '"' && rest.startsWith('#{', j)) { + let depth = 0 + let k = j + 1 + for (; k < rest.length; k++) { + if (rest[k] === '{') depth++ + else if (rest[k] === '}' && --depth === 0) break + } + interpolated += ' '.repeat(j - interpolated.length) + rest.slice(j + 2, k) + j = k + 1 + } else j += rest[j] === '\\' && quote !== '`' ? 2 : 1 + } + const length = Math.min(j + 1, rest.length) + if (interpolated) { out += (interpolated + ' ').padEnd(length, ' '); i += length } else blank(length) + } else { out += code[i]; i++ } + } + return out +} diff --git a/site/src/pages/index.astro b/site/src/pages/index.astro index 2fe7cd278..e19b022d9 100644 --- a/site/src/pages/index.astro +++ b/site/src/pages/index.astro @@ -18,6 +18,7 @@ import { getCollection, render } from 'astro:content' import { DEFAULT_LOCALE } from '../i18n/locales' import { CONTRIBUTE_BRANCH, CONTRIBUTE_REPO, repoPath } from '../i18n/contribute' import { portCapabilities, type CapabilityTable } from '../lib/core-capabilities' +import { API_MODELS } from '../lib/api-models' import type { CachedSource } from '../lib/port-landing' import TABLE from '../data/core-capabilities.json' import SOURCES from '../data/example-sources.json' @@ -48,7 +49,7 @@ const versionSections = versionRootPort ].filter((section) => documentationSectionsFor(versionRootPort.slug).includes(section.route)) : [] // The programs the showcase shows, each with the workflow that runs it. -const ciExamples = versionRootPort ? portCapabilities(versionRootPort.slug, TABLE as CapabilityTable, SOURCES as Record) : [] +const ciExamples = versionRootPort ? portCapabilities(versionRootPort.slug, TABLE as CapabilityTable, SOURCES as Record, API_MODELS[versionRootPort.slug]?.revision) : [] const versionDomains = versionRootPort ? documentationCards(versionRootPort.slug, buildVersion) : [] /** diff --git a/site/test/core-apis.test.ts b/site/test/core-apis.test.ts index 5b9b05543..4e11c569f 100644 --- a/site/test/core-apis.test.ts +++ b/site/test/core-apis.test.ts @@ -1,21 +1,27 @@ import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' -import { apisUsed, callHref, CORE_APIS, MAX_APIS, typeText, withoutLiterals } from '../src/lib/core-apis' +import { apisUsed, callHref, CORE_APIS, MAX_APIS, typeText } from '../src/lib/core-apis' +import { withoutLiterals } from '../src/lib/example-syntax' +import { coreShowcase } from '../src/lib/core-showcase' import { coreRecordingFor } from '../src/lib/core-player' import { portCapabilities, type CapabilityTable } from '../src/lib/core-capabilities' +import { API_MODELS } from '../src/lib/api-models' import { QUICKSTARTS, homeProgram } from '../src/lib/quickstarts' import TABLE from '../src/data/core-capabilities.json' import SOURCES from '../src/data/example-sources.json' import type { CachedSource } from '../src/lib/port-landing' -const capabilityPorts = Object.keys(TABLE).filter((port) => portCapabilities(port, TABLE as CapabilityTable, SOURCES as Record).length > 0) +const capabilityPorts = Object.keys(TABLE).filter((port) => portCapabilities(port, TABLE as CapabilityTable, SOURCES as Record, API_MODELS[port]?.revision).length > 0) const showcasePorts = [...new Set([...capabilityPorts, ...Object.keys(QUICKSTARTS).filter((port) => CORE_APIS[port] !== undefined)])] -const programs = (port: string): Record => ({ - [QUICKSTARTS[port]!.complete!.capability ?? 'typed-graph']: homeProgram(QUICKSTARTS[port]!.complete!, 'full'), - ...Object.fromEntries(portCapabilities(port, TABLE as CapabilityTable, SOURCES as Record).map((item) => [item.id, item.code])), -}) +const programs = (port: string): Record => { + const selected = coreShowcase(port) + return { + ...(selected.quickstart ? { [selected.capability.id]: homeProgram(selected.quickstart, 'full') } : {}), + ...Object.fromEntries(selected.programs.map((item) => [item.id, item.code])), + } +} describe('the APIs a showcase example uses', () => { it('has a list for every example the showcase shows, and none for another', () => { @@ -36,6 +42,23 @@ describe('the APIs a showcase example uses', () => { expect(used.moreHref).toBe(`/${port}/latest/reference/`) }) + it('selects the pinned navigation program when the quickstart uses an older library', () => { + const port = 'ocaml' + const graph = (TABLE as CapabilityTable)[port]!['typed-graph']! + const revision = API_MODELS[port]!.revision + const select = (entry: typeof graph) => coreShowcase(port, { [port]: { 'typed-graph': entry } }) + + const unpinned = { ...graph } + delete unpinned.revision + const fallback = select(unpinned) + expect(fallback.quickstart).toBe(QUICKSTARTS[port]!.complete) + expect(fallback.programs).toEqual([]) + + const selected = select({ ...graph, revision }) + expect(selected.quickstart).toBeUndefined() + expect(selected.programs.map((item) => item.file)).toEqual([graph.file]) + }) + it('lists the Rust quickstart symbols in order of first use', () => { const used = apisUsed('rs', CORE_APIS.rs!['typed-graph']!, programs('rs')['typed-graph']!, 'latest') expect(used.shown.map((item) => item.label)).toEqual([ @@ -116,7 +139,8 @@ describe('the Core player\'s links', () => { elixir: ['System.cmd', 'Session.active_window', 'Ref.from_observation', 'Window.rename!', 'Pane.split!', 'Session.new_window!', 'Pane.send_text!', 'Pane.send_keys!', 'Pane.capture!', 'Window.panes'], fsharp: ['Window.rename', 'Window.activePane', 'Session.newWindow', 'Pane.select', 'Window.select', 'Seq.find'], julia: ['wait_for_text'], - lua: ['tmux', 'Pane:wait_for_text'], + lua: API_MODELS.lua!.symbols.some((symbol) => (symbol.publicId ?? symbol.id) === 'libtmux.Pane:wait_for_text') + ? ['tmux'] : ['tmux', 'Pane:wait_for_text'], } const ports = ['csharp', 'cxx', 'elixir', 'fsharp', 'go', 'java', 'julia', 'kotlin', 'lua', 'powershell', 'py', 'rs', 'ruby', 'scala', 'swift', 'ts'] diff --git a/site/test/core-capabilities.test.ts b/site/test/core-capabilities.test.ts index a19288e3f..9f6c80172 100644 --- a/site/test/core-capabilities.test.ts +++ b/site/test/core-capabilities.test.ts @@ -1,9 +1,10 @@ import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { existsSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import { - alternatives, CAPABILITIES, capabilityCacheKey, capabilityFiles, evidenceProblems, fileProblems, hygieneProblems, MAX_PROGRAM_LINES, portCapabilities, programProblems, setupProblems, validateCapability, workflowStep, + alternatives, CAPABILITIES, capabilityApplies, capabilityCacheKey, capabilityFiles, evidenceProblems, fileProblems, hygieneProblems, MAX_PROGRAM_LINES, portCapabilities, programProblems, setupProblems, validateCapability, workflowStep, type CapabilityEntry, type CapabilityId, type CapabilityTable, } from '../src/lib/core-capabilities' import { LANG_TO_PORT, checkoutFor, parseMeta, readFence } from '../src/plugins/remark-port-code.mjs' @@ -15,9 +16,11 @@ import { registryFor } from '../src/lib/registry' import HOME from '../src/data/home-examples.json' import LANDING from '../src/data/landing-examples.json' import TABLE from '../src/data/core-capabilities.json' +import MATRICES from '../src/data/core-example-matrices.json' import SOURCES from '../src/data/example-sources.json' import { readdirSync, readFileSync, statSync } from 'node:fs' import { join } from 'node:path' +import { cachedExample } from '../../scripts/gen-example-sources.mjs' const table = TABLE as CapabilityTable const LANDING_TABLE = LANDING as LandingTable @@ -29,20 +32,21 @@ const pagesUnder = (dir: string, base = dir): { path: string, text: string }[] = return /\.mdx?$/.test(name) ? [{ path: path.slice(base.length + 1), text: readFileSync(path, 'utf8') }] : [] }) const cache = SOURCES as Record -const entries = Object.entries(table).flatMap(([owner, items]) => +const allEntries = Object.entries(table).flatMap(([owner, items]) => Object.entries(items).map(([id, entry]) => ({ owner, id: id as CapabilityId, entry: entry as CapabilityEntry }))) const model = (owner: string) => JSON.parse(readFileSync(new URL(`../src/data/api/${owner}.json`, import.meta.url), 'utf8')) as { revision: string, repo: string } +const entries = allEntries.filter(({ owner, entry }) => capabilityApplies(entry, model(owner).revision)) const ids = CAPABILITIES.map((capability) => capability.id as string) describe('the capability showcase data', () => { it('names only known ports and capabilities', () => { - for (const { owner, id } of entries) { + for (const { owner, id } of allEntries) { expect(PORT_BY_SLUG[owner], owner).toBeDefined() expect(ids, id).toContain(id) } }) - it.each(entries.map((item) => [`${item.owner}/${item.id}`, item] as const))('%s records the evidence that its result is checked', (_name, { entry }) => { + it.each(allEntries.map((item) => [`${item.owner}/${item.id}`, item] as const))('%s records the evidence that its result is checked', (_name, { entry }) => { expect(validateCapability(entry)).toEqual([]) }) @@ -118,7 +122,7 @@ describe('the capability showcase data', () => { it.each(entries.map((item) => [`${item.owner}/${item.id}`, item] as const))('%s shows a whole program at the revision its API model records', (_name, { owner, entry }) => { const pinned = model(owner) - for (const files of capabilityFiles(entry)) { + for (const files of capabilityFiles(entry, owner)) { const cached = files.map((file) => cache[capabilityCacheKey(owner, file)]).find((found) => found !== undefined) expect(cached, `${files.join(' or ')} is in the example cache`).toBeDefined() expect(cached).toMatchObject({ repository: pinned.repo, revision: pinned.revision }) @@ -139,7 +143,8 @@ describe('the capability showcase data', () => { } // A port whose examples are library functions, not programs, offers none. expect(portCapabilities('ts', table, cache)).toEqual([]) - expect(portCapabilities('lua', table, cache)).toEqual([]) + const launcherRevision = '0395620d362ef75c74cd488f9577afda68922586' + expect(portCapabilities('lua', table, cache, launcherRevision)).toEqual([]) }) it('shows a program without the comments its port\'s tooling reads, and keeps the file for the recording', () => { @@ -186,6 +191,45 @@ describe('the capability showcase data', () => { expect(programProblems('rust', `use a;\nfn main() {}\n${'x\n'.repeat(MAX_PROGRAM_LINES)}`)).toEqual([`runs past ${MAX_PROGRAM_LINES} lines`]) }) + describe('standalone Lua programs with a named callback', () => { + const program = [ + 'local adapter = require("libtmux.runtime.luv")', + 'local function run(runtime)', + ' return runtime:with_server({}, function() return 42 end):await()', + 'end', + ].join('\n') + + it.each([' must(adapter.run(run))', ' print(must(adapter.run(run)))', 'adapter.run(run, {})'])('recognizes %s', (call) => { + expect(programProblems('lua', program + '\n' + call)).toEqual([]) + }) + + it.each([' local adapter = require("libtmux.runtime.luv")', 'local adapter = require "libtmux.runtime.luv"'])('uses the adapter bound by %s', (binding) => { + const source = program.replace('local adapter = require("libtmux.runtime.luv")', binding) + expect(programProblems('lua', source + '\nadapter.run(run)')).toEqual([]) + }) + + it('allows an indented local callback', () => { + expect(programProblems('lua', program.replace('local function run', ' local function run') + '\nadapter.run(run)')).toEqual([]) + }) + + it('requires a private server call in the program', () => { + const mention = program.replace('return runtime:with_server({}, function() return 42 end):await()', '-- runtime:with_server({})') + expect(programProblems('lua', mention + '\nadapter.run(run)')).toContain('does not own a private server') + }) + + it.each([ + '-- adapter.run(run)', + 'other.run(run)', + 'wrapper.adapter.run(run)', + 'wrapper. adapter.run(run)', + 'adapter.run(missing)', + 'local text = [=[\n must(adapter.run(run))\n]=]', + '--[=[\n must(adapter.run(run))\n]=]', + ])('requires a call to the adapter with a defined callback in %s', (text) => { + expect(programProblems('lua', program + '\n' + text)).toContain('has no entry point') + }) + }) + // The fixture is examples/api/capture.rb as libtmux/libtmux-ruby master held it // on 2026-11-02 (commit 20744401ee9f78a131592481e251c6a09ac8f5fa, git blob // f070fac137b166227b34a79e5b4b0de77cf5ee95, last changed by 2156612): the @@ -236,7 +280,7 @@ describe('the capability showcase data', () => { const local = [checkout, `${process.env.HOME}/work/libtmux/libtmux-${owner}`].find((path) => existsSync(`${path}/.git`)) it.skipIf(!local)(`${owner}/${id} runs in that workflow step at that revision`, () => { const workflow = execFileSync('git', ['-C', local!, 'show', `${model(owner).revision}:${entry.ci.workflow}`], { encoding: 'utf8', maxBuffer: 1 << 24 }) - expect(workflowStep(workflow, entry.ci), `${entry.ci.workflow} job ${entry.ci.job} step ${entry.ci.step ?? '(unnamed)'} runs ${entry.ci.command}`).toBe(true) + expect(workflowStep(workflow, entry.ci, MATRICES[owner as keyof typeof MATRICES]?.events), `${entry.ci.workflow} job ${entry.ci.job} step ${entry.ci.step ?? '(unnamed)'} runs ${entry.ci.command}`).toBe(true) }) if (entry.ci.planOutput) { it.skipIf(!local)(`${owner}/${id} is not shown as run once its plan output is not recorded`, () => { @@ -247,6 +291,76 @@ describe('the capability showcase data', () => { } }) +describe('the offline Lua showcase cache', () => { + const revision = model('lua').revision + const files = ['new_window.lua', 'watch_pane.lua', 'send_keys.lua', 'refresh.lua', 'README.md'] + it.runIf(revision === MATRICES.lua.revision).each(files)('rejects edited %s with a valid cache checksum', (name) => { + const file = `examples/api/${name}` + const key = capabilityCacheKey('lua', file) + const source = cache[key]! + const content = (name === 'README.md' ? '# Edited setup\n' : '-- Edited program\n') + source.content + const current = { ...source, content, sha256: createHash('sha256').update(content).digest('hex') } + const loaded = cachedExample({ repository: source.repository, revision, file, checkout: undefined, current }) + expect(loaded).toEqual(current) + expect(() => portCapabilities('lua', table, { ...cache, [key]: loaded }, revision)) + .toThrow(`matrix proof source differs for ${file}`) + }) +}) + +describe('a step in a matrix produced by the CI plan', () => { + const workflow = `name: CI +on: + pull_request: + push: +jobs: + plan: + outputs: + matrix: \${{ steps.plan.outputs.matrix }} + steps: + - id: plan + run: plan-ci + validate: + needs: plan + strategy: + matrix: \${{ fromJSON(needs.plan.outputs.matrix) }} + steps: + - name: Check examples + if: matrix.gate != 'unit' + run: check-examples +` + const selected = { name: 'Examples', gate: 'outer' } + const ci = { + workflow: '.github/workflows/ci.yml', job: 'validate', step: 'Check examples', + command: 'check-examples', matrix: { output: 'matrix', cell: selected }, + } + const plan = { push: [selected], pull_request: [selected] } + it('accepts a condition that is true in an actual cell on both usual events', () => { + expect(workflowStep(workflow, ci, plan)).toBe(true) + expect(workflowStep(workflow.replace("matrix.gate != 'unit'", "${{ matrix.gate == 'outer' }}"), ci, plan)).toBe(true) + }) + + it('refuses a missing proof or a planner that no longer emits that cell', () => { + expect(workflowStep(workflow, ci)).toBe(false) + expect(workflowStep(workflow, ci, { ...plan, pull_request: [{ name: 'Examples', gate: 'unit' }] })).toBe(false) + expect(workflowStep(workflow, ci, { push: [selected] })).toBe(false) + }) + + it.each([ + ["matrix.gate != 'unit'", "matrix.gate == 'unit'"], + ["matrix.gate != 'unit'", "matrix.gate != 'unit' && false"], + [' run: check-examples', ' continue-on-error: true\n run: check-examples'], + [' run: check-examples', ' run: echo check-examples'], + [' - name: Check examples', ' - name: Changed'], + [' pull_request:', ' workflow_dispatch:'], + [' - id: plan', ' - id: other'], + [' - id: plan', ' - id: plan\n if: false'], + [' needs: plan', ' needs: other'], + ['steps.plan.outputs.matrix', 'steps.plan.outputs.missing'], + ])('refuses a workflow with %s changed', (before, after) => { + expect(workflowStep(workflow.replace(before, after), ci, plan)).toBe(false) + }) +}) + describe('the workflow step an entry records', () => { const workflow = `name: ci jobs: @@ -673,7 +787,7 @@ describe('the example gate over what a reader copies', () => { it('shows every capability program as complete and free of the repository', () => { // portCapabilities refuses a program the gate flags, so a build never shows one. - for (const owner of Object.keys(table)) expect(() => portCapabilities(owner, table, cache), owner).not.toThrow() + for (const owner of Object.keys(table)) expect(() => portCapabilities(owner, table, cache, model(owner).revision), owner).not.toThrow() }) }) })