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
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,15 @@ Edit one YAML file per service or provider. Start with [Linear](catalog/services

`bun run verify` checks generated source, rebuilds the distribution, runs the type checker, and tests under Bun and Node.js. Use `bun run test` for a fresh build and the Bun suite. Use `bun run test:built` or `bun run test:node` after an explicit build to exercise the existing distribution. CI runs the full verification, checks distribution freshness, and smoke-tests an installed package.

Run `bun run import:reference /path/to/reference-checkout` to reproduce the import from the pinned revision. Supply a full commit SHA as a second argument to update the source revision, then review the changed definitions and regenerate the exports.
Preview a reference update before importing it. Pass a local checkout and a full Git commit SHA.

```sh
bun run preview:reference /path/to/reference-checkout <full-commit-sha> --json
```

Omit `--json` for a text report. The command prints changed field paths and conflicts and leaves both checkouts untouched. Exit `0` means no conflicts, `2` means conflicts need review, and `1` means the comparison could not run. Pass `--as-of YYYY-MM-DD --max-age-days N` together to report how long ago sources were reviewed.

Resolve any conflicts separately, then pass the same SHA to `bun run import:reference /path/to/reference-checkout <full-commit-sha>`. Omit the SHA to reproduce the pinned import. Review the changed definitions and regenerate the exports.

The importer checks every candidate before writing. A removed upstream entry or a collision with a local ID stops the import. Resolve the affected entries in a separate catalog change. An upstream display-name change follows the source when the local name matches its old source name. Local name overrides are preserved. Keep the old Git objects available when names differ so the importer can tell the two cases apart.

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"scripts": {
"build": "bun scripts/build.mjs",
"import:reference": "bun scripts/import-reference.mjs",
"preview:reference": "bun scripts/preview-reference.mjs",
"generate": "bun scripts/generate.mjs",
"generate:check": "bun scripts/generate.mjs --check",
"typecheck": "tsc",
Expand Down
38 changes: 38 additions & 0 deletions scripts/preview-reference.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { parseArgs } from "node:util"
import { readReferenceInputs } from "./reference-import.mjs"
import { previewReferenceUpdate, renderReferencePreviewText } from "./reference-preview.mjs"

try {
const { values, positionals } = parseArgs({
allowPositionals: true,
options: {
json: { type: "boolean" },
"as-of": { type: "string" },
"max-age-days": { type: "string" },
},
})
const [checkout, revision] = positionals
if (positionals.length !== 2 || !checkout || !/^[a-f0-9]{40}$/u.test(revision)) {
throw new Error("Expected a reference checkout and full commit SHA")
}

const asOf = values["as-of"]
const threshold = values["max-age-days"]
let age
if (asOf !== undefined || threshold !== undefined) {
if (asOf === undefined || threshold === undefined || threshold.trim() === "") {
throw new Error("Both review-age options are required")
}
age = { asOf, maxAgeDays: Number(threshold) }
}

const catalog = new URL("../catalog/", import.meta.url)
const inputs = await readReferenceInputs({ checkout, revision, catalog, offline: true })
const report = previewReferenceUpdate(inputs, { revision, age })
console.log(values.json ? JSON.stringify(report, null, 2) : renderReferencePreviewText(report))
process.exitCode = report.conflicts.length === 0 ? 0 : 2
} catch {
// Git and YAML errors can include input values.
console.error("Preview failed. Check the arguments, catalog structure, and available Git objects.")
process.exitCode = 1
}
13 changes: 10 additions & 3 deletions scripts/reference-import.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,16 @@ async function readCatalogFolder(catalog, folder) {
}

/** Read the committed upstream and local snapshots without changing either checkout. */
export async function readReferenceInputs({ checkout, revision, catalog }) {
export async function readReferenceInputs({ checkout, revision, catalog, offline = false }) {
if (!checkout || !fullRevision.test(revision)) throw new Error("Expected a reference checkout and full commit SHA")
const git = (...args) => execFileSync("git", ["-C", checkout, ...args], { encoding: "utf8" })
const gitOptions = {
encoding: "utf8",
...(offline ? {
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env, GIT_NO_LAZY_FETCH: "1", GIT_OPTIONAL_LOCKS: "0" },
} : {}),
}
const git = (...args) => execFileSync("git", ["-C", checkout, ...args], gitOptions)
const sourceFolders = { checked: "services", providers: "providers" }
const tree = git("ls-tree", "-rz", "--name-only", revision, "catalog/checked", "catalog/providers")
const upstream = tree.split("\0").filter(path => path.endsWith(".yaml")).sort().map(path => {
Expand Down Expand Up @@ -180,7 +187,7 @@ export async function readReferenceInputs({ checkout, revision, catalog }) {
if (reference === undefined || definition.name === candidate.input.name) continue
checkReference(reference, record)
const result = spawnSync("git", ["-C", checkout, "show", `${reference.revision}:${reference.path}`],
{ encoding: "utf8" })
gitOptions)
if (result.error !== undefined) throw result.error
if (result.status === 0) {
previous.push({ folder: record.folder, file: record.file, input: parseDefinition(record, result.stdout) })
Expand Down
130 changes: 130 additions & 0 deletions scripts/reference-preview.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { parse } from "yaml"
import { planReferenceUpdate } from "./reference-import.mjs"

const groups = ["endpoints", "credential-schema", "capabilities", "settings", "provenance", "other"]
const keyFor = ({ folder, file }) => `${folder}/${file}`
const isObject = value => value !== null && typeof value === "object"
const pathLabel = key => /^(?:[a-zA-Z][a-zA-Z0-9_-]{0,63}|[0-9]{1,6})$/u.test(key) ? key : "[field]"

function pathsOf(before, after, prefix = "") {
if (Object.is(before, after)) return []
if (prefix === "reference" && before === undefined) before = {}
if (isObject(before) && isObject(after) && Array.isArray(before) === Array.isArray(after)) {
const keys = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort()
return keys.flatMap(key => pathsOf(
Object.hasOwn(before, key) ? before[key] : undefined,
Object.hasOwn(after, key) ? after[key] : undefined,
prefix === "" ? pathLabel(key) : `${prefix}.${pathLabel(key)}`,
))
}
return [prefix]
}

function groupFor(path) {
if (/^reference\.(?:revision|path|sources)(?:\.|$)/u.test(path)) return "provenance"
if (/^reference\.(?:settings|gaps)(?:\.|$)/u.test(path)) return "settings"
if (/^reference\.credentials(?:\.|$)|\.(?:accepts|send)(?:\.|$)/u.test(path)) return "credential-schema"
if (/\.(?:url|base|base_url|discover|authorization_url|token_url)$/u.test(path) ||
path === "reference.surfaces.api.description") return "endpoints"
if (/^(?:reference\.)?(?:surfaces|speaks|models|endpoints|auth)(?:\.|$)/u.test(path)) return "capabilities"
return "other"
}

function summarizeFields(before, after) {
const fields = Object.fromEntries(groups.map(group => [group, []]))
for (const path of [...new Set(pathsOf(before, after))].sort()) fields[groupFor(path)].push(path)
return fields
}

const millisecondsPerDay = 86_400_000
function utcDay(value) {
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/u.test(value)) {
throw new Error("Expected a UTC calendar date")
}
const parsed = new Date(`${value}T00:00:00.000Z`)
if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value) {
throw new Error("Expected a valid UTC calendar date")
}
return parsed.getTime() / millisecondsPerDay
}

function sourceAgeFor(upstream, { asOf, maxAgeDays }) {
const day = utcDay(asOf)
if (!Number.isFinite(maxAgeDays) || maxAgeDays < 0) throw new Error("Expected a nonnegative review-age threshold")
const sources = [...upstream].sort((left, right) => {
const a = keyFor(left)
const b = keyFor(right)
return a < b ? -1 : a > b ? 1 : 0
}).flatMap(({ folder, file, input }) =>
Object.keys(input.sources).sort().map(section => {
const { read } = input.sources[section]
const ageDays = day - utcDay(read)
const status = ageDays < 0 ? "future-dated" : ageDays > maxAgeDays ? "older-than-threshold" : "recent"
return { folder, file, section: pathLabel(section), read, ageDays, status }
}))
return { asOf, maxAgeDays, sources }
}

export function previewReferenceUpdate(inputs, { revision, age } = {}) {
if (typeof revision !== "string" || !/^[a-f0-9]{40}$/u.test(revision)) {
throw new Error("Expected a full reference revision")
}
if (inputs.upstream.some(record => record.revision !== revision)) {
throw new Error("Upstream records must match the reviewed revision")
}
const plan = planReferenceUpdate(inputs)
const local = new Map(inputs.current.map(record => [keyFor(record), record.source]))
const changes = plan.changes.map(({ folder, file, action, contents }) => {
const source = local.get(keyFor({ folder, file }))
return {
folder,
id: file.slice(0, -5),
action,
fields: summarizeFields(source === undefined ? {} : parse(source), parse(contents)),
}
})
const conflicts = plan.conflicts.map(({ folder, file, code, runtime, existingFolder }) => ({
folder,
id: file.slice(0, -5),
code,
...(runtime === undefined ? {} : { runtime }),
...(existingFolder === undefined ? {} : { existingFolder }),
}))
const notices = plan.notices.map(({ folder, file, code }) => ({ folder, id: file.slice(0, -5), code }))
return {
revision,
changes,
conflicts,
notices,
...(age === undefined ? {} : { sourceAge: sourceAgeFor(inputs.upstream, age) }),
}
}

export function renderReferencePreviewText(report) {
const lines = [
`Reference ${report.revision}`,
`${report.changes.length} changes, ${report.conflicts.length} conflicts, ${report.notices.length} notices`,
]
for (const { folder, id, action, fields } of report.changes) {
lines.push(`${action} ${folder}/${id}`)
for (const group of groups) {
if (fields[group].length > 0) lines.push(` ${group}: ${fields[group].join(", ")}`)
}
}
for (const { folder, id, code, runtime, existingFolder } of report.conflicts) {
const detail = existingFolder !== undefined ? ` (existing in ${existingFolder})`
: runtime ? " (runtime overlay)" : ""
lines.push(`${folder}/${id} ${code}${detail}`)
}
for (const { folder, id, code } of report.notices) {
lines.push(`${folder}/${id} ${code}`)
}
if (report.sourceAge !== undefined) {
const { asOf, maxAgeDays, sources } = report.sourceAge
lines.push(`Source review age as of ${asOf} with a ${maxAgeDays}-day threshold`)
for (const { folder, file, section, read, ageDays, status } of sources) {
lines.push(`${folder}/${file} ${section} ${read} ${ageDays} days ${status}`)
}
}
return lines.join("\n")
}
Loading