| 1 | #!/usr/bin/env node |
| 2 | // Refresh the checked-in "latest published release" fact from the real GitHub |
| 3 | // release. The fact is mirrored in three places and ALL must move together: |
| 4 | // |
| 5 | // web/data/latest-published-release.json (read by derive-facts.mjs) |
| 6 | // docs/public-surface-facts.json (latestPublishedRelease, which |
| 7 | // names the file above as its |
| 8 | // `sources`) |
| 9 | // docs/cloud-facts/stable.json (release.latest / release_url, |
| 10 | // compared by check-cloud-facts) |
| 11 | // |
| 12 | // web/lib/public-surface-contract.test.ts asserts the first two agree and |
| 13 | // check-cloud-facts.mjs asserts the third, so updating only one turns a stale |
| 14 | // marketing fact into a red Lint & Type Check. web/lib/facts.generated.ts is |
| 15 | // derived from the first file; regenerate it with derive-facts.mjs afterwards. |
| 16 | // |
| 17 | // release.yml's `sync-release-record` job runs this after every publish and |
| 18 | // proposes the result to main as a bot PR, so nobody hand-commits the record. |
| 19 | // |
| 20 | // Facts must be derivable from the repo with no network (derive-facts.mjs reads |
| 21 | // this file, it does not call GitHub), so the file is checked in. Nothing wrote |
| 22 | // it, which is why it drifted: the marketing deploy's post-deploy comparison |
| 23 | // failed on latestPublishedRelease.tag because this said v0.9.10 while the |
| 24 | // published release was v0.9.11. |
| 25 | // |
| 26 | // node web/scripts/sync-latest-release.mjs # write if changed |
| 27 | // node web/scripts/sync-latest-release.mjs --check # exit 1 if stale |
| 28 | // |
| 29 | // --check is the CI form: it makes drift a failing gate at PR time instead of a |
| 30 | // surprise after a production deploy. It only warns while the record is exactly |
| 31 | // one release behind a release published under 24h ago: that is the window in |
| 32 | // which release.yml's sync-release-record PR is waiting to merge, and neither a |
| 33 | // PR author nor an unrelated push to main can fix it. Past 24h, or more than one |
| 34 | // release behind, it fails again. An unreachable or failing GitHub API fails |
| 35 | // --check too: "could not look" is not "current". |
| 36 | // |
| 37 | // A write validates all three files first and then replaces each one through a |
| 38 | // unique temporary file and a rename, so a bad mirror never leaves the first |
| 39 | // file moved on its own and a crash never leaves a half-written JSON file. |
| 40 | |
| 41 | import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; |
| 42 | import { fileURLToPath } from "node:url"; |
| 43 | import { dirname, resolve } from "node:path"; |
| 44 | |
| 45 | const REPO = "codewhale-hq/CodeWhale"; |
| 46 | const here = dirname(fileURLToPath(import.meta.url)); |
| 47 | const target = resolve(here, "..", "data", "latest-published-release.json"); |
| 48 | const mirror = resolve(here, "..", "..", "docs", "public-surface-facts.json"); |
| 49 | const cloudFacts = resolve(here, "..", "..", "docs", "cloud-facts", "stable.json"); |
| 50 | const GRACE_MS = 24 * 60 * 60 * 1000; |
| 51 | const checkOnly = process.argv.includes("--check"); |
| 52 | |
| 53 | const headers = { |
| 54 | accept: "application/vnd.github+json", |
| 55 | "user-agent": "codewhale-facts-sync", |
| 56 | }; |
| 57 | if (process.env.GITHUB_TOKEN) headers.authorization = `Bearer ${process.env.GITHUB_TOKEN}`; |
| 58 | |
| 59 | let release; |
| 60 | try { |
| 61 | const response = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { |
| 62 | headers, |
| 63 | signal: AbortSignal.timeout(30_000), |
| 64 | }); |
| 65 | if (!response.ok) throw new Error(`GitHub returned ${response.status}`); |
| 66 | release = await response.json(); |
| 67 | } catch (error) { |
| 68 | console.error(`[sync-latest-release] could not read the latest release (${error.message}); leaving the files alone.`); |
| 69 | process.exit(1); |
| 70 | } |
| 71 | |
| 72 | function releaseFact(release) { |
| 73 | const tag = String(release.tag_name || ""); |
| 74 | return { |
| 75 | tag, |
| 76 | version: tag.startsWith("v") ? tag.slice(1) : "", |
| 77 | publishedAt: String(release.published_at || ""), |
| 78 | url: `https://github.com/${REPO}/releases/tag/${tag}`, |
| 79 | }; |
| 80 | } |
| 81 | const next = releaseFact(release); |
| 82 | |
| 83 | function releaseAssets(release) { |
| 84 | if (!Array.isArray(release.assets)) return []; |
| 85 | return release.assets |
| 86 | .filter((asset) => asset && (asset.state === undefined || asset.state === "uploaded") && typeof asset.name === "string" |
| 87 | && Number.isSafeInteger(asset.size) && asset.size >= 0) |
| 88 | .map((asset) => ({ |
| 89 | name: asset.name, |
| 90 | size: asset.size, |
| 91 | sha256: typeof asset.digest === "string" && /^sha256:[0-9a-f]{64}$/.test(asset.digest) ? asset.digest.slice(7) : null, |
| 92 | })) |
| 93 | .sort((a, b) => a.name.localeCompare(b.name)); |
| 94 | } |
| 95 | const nextAssets = releaseAssets(release); |
| 96 | |
| 97 | // deriveLatestPublishedRelease() silently returns null on any shape violation, |
| 98 | // which would drop the fact entirely rather than report a bad one. Fail loudly. |
| 99 | if (!next.version || !Number.isFinite(Date.parse(next.publishedAt))) { |
| 100 | console.error(`[sync-latest-release] refusing to write an unusable release fact: ${JSON.stringify(next)}`); |
| 101 | process.exit(1); |
| 102 | } |
| 103 | |
| 104 | const readJson = (path) => { |
| 105 | try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; } |
| 106 | }; |
| 107 | |
| 108 | const current = readJson(target); |
| 109 | const matrix = readJson(mirror); |
| 110 | const currentMirror = matrix?.latestPublishedRelease ?? null; |
| 111 | const cloud = readJson(cloudFacts); |
| 112 | |
| 113 | const differingFields = (record, fact) => |
| 114 | Object.keys(fact).filter((key) => record?.[key] !== fact[key]); |
| 115 | const cloudMatches = (fact) => |
| 116 | cloud?.release?.latest === fact.version && cloud.release.release_url === fact.url; |
| 117 | const allMatch = (fact) => |
| 118 | differingFields(current, fact).length === 0 && differingFields(currentMirror, fact).length === 0 && cloudMatches(fact); |
| 119 | const assetsMatch = () => |
| 120 | typeof current?.readAt === "string" && JSON.stringify(current?.assets) === JSON.stringify(nextAssets); |
| 121 | |
| 122 | // True when `recordedTag` is the published (non-draft, non-prerelease) release |
| 123 | // immediately before `next`, and `next` is younger than GRACE_MS. Any lookup |
| 124 | // failure answers false, so the check stays strict when in doubt. |
| 125 | async function isFreshlyOneBehind(recordedTag) { |
| 126 | const age = Date.now() - Date.parse(next.publishedAt); |
| 127 | if (!recordedTag || recordedTag === next.tag || !(age >= 0 && age < GRACE_MS)) return false; |
| 128 | try { |
| 129 | const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=20`, { |
| 130 | headers, |
| 131 | signal: AbortSignal.timeout(30_000), |
| 132 | }); |
| 133 | if (!res.ok) return false; |
| 134 | const [latest, previous] = (await res.json()) |
| 135 | .filter((r) => !r.draft && !r.prerelease && Number.isFinite(Date.parse(r.published_at))) |
| 136 | .sort((a, b) => Date.parse(b.published_at) - Date.parse(a.published_at)); |
| 137 | return latest?.tag_name === next.tag && previous?.tag_name === recordedTag && allMatch(releaseFact(previous)); |
| 138 | } catch { |
| 139 | return false; |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | if (allMatch(next) && assetsMatch()) { |
| 144 | console.log(`[sync-latest-release] already current at ${next.tag}`); |
| 145 | process.exit(0); |
| 146 | } |
| 147 | |
| 148 | if (checkOnly) { |
| 149 | for (const [path, record] of [[target, current], [mirror, currentMirror]]) { |
| 150 | const fields = differingFields(record, next); |
| 151 | if (fields.length) console.error(`[sync-latest-release] ${path} differs from ${next.tag} in ${fields.join(", ")}.`); |
| 152 | } |
| 153 | if (allMatch(next) && !assetsMatch()) { |
| 154 | console.warn(`[sync-latest-release] warning only: ${target} does not carry the ${nextAssets.length} assets GitHub lists for ${next.tag}. Run: npm --prefix web run sync:latest-release`); |
| 155 | if (process.env.GITHUB_ACTIONS) { |
| 156 | console.log(`::warning title=Release assets drifted::${next.tag} asset list differs from ${target}`); |
| 157 | } |
| 158 | process.exit(0); |
| 159 | } |
| 160 | if (!cloudMatches(next)) { |
| 161 | console.error(`[sync-latest-release] release version or URL in docs/cloud-facts/stable.json differs from ${next.tag}.`); |
| 162 | } |
| 163 | const recorded = current?.tag; |
| 164 | if (await isFreshlyOneBehind(recorded)) { |
| 165 | console.warn( |
| 166 | `[sync-latest-release] warning only: ${next.tag} was published under 24h ago and release.yml's ` + |
| 167 | "sync-release-record job proposes the record as a PR. Merge that; this change does not need to.", |
| 168 | ); |
| 169 | if (process.env.GITHUB_ACTIONS) { |
| 170 | console.log(`::warning title=Release record catching up::${recorded} -> ${next.tag} is pending from release.yml`); |
| 171 | } |
| 172 | process.exit(0); |
| 173 | } |
| 174 | console.error("Run: npm --prefix web run sync:latest-release && node web/scripts/derive-facts.mjs"); |
| 175 | process.exit(1); |
| 176 | } |
| 177 | |
| 178 | const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value); |
| 179 | if (!isRecord(matrix) || (currentMirror !== null && !isRecord(currentMirror))) { |
| 180 | console.error(`[sync-latest-release] could not read ${mirror}; nothing was written.`); |
| 181 | process.exit(1); |
| 182 | } |
| 183 | // stable.json is the unsigned cloud-facts authoring source; only the two |
| 184 | // release pointers move here. yanked/min_supported/notice stay human calls. |
| 185 | if (!isRecord(cloud?.release)) { |
| 186 | console.error(`[sync-latest-release] could not read release in ${cloudFacts}; nothing was written.`); |
| 187 | process.exit(1); |
| 188 | } |
| 189 | |
| 190 | // Preserve every key the matrix carries beyond the four synced fields (notably |
| 191 | // `sources`), so this stays a fact refresh and not a schema rewrite. |
| 192 | matrix.latestPublishedRelease = { ...currentMirror, ...next }; |
| 193 | cloud.release.latest = next.version; |
| 194 | cloud.release.release_url = next.url; |
| 195 | |
| 196 | const staged = [ |
| 197 | [target, { ...next, readAt: new Date().toISOString(), assets: nextAssets }], |
| 198 | [mirror, matrix], |
| 199 | [cloudFacts, cloud], |
| 200 | ].map(([path, value]) => { |
| 201 | const temporary = `${path}.${process.pid}.${Date.now()}.tmp`; |
| 202 | writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx" }); |
| 203 | return [temporary, path]; |
| 204 | }); |
| 205 | try { |
| 206 | for (const [temporary, path] of staged) renameSync(temporary, path); |
| 207 | } finally { |
| 208 | for (const [temporary] of staged) rmSync(temporary, { force: true }); |
| 209 | } |
| 210 | |
| 211 | console.log(`[sync-latest-release] wrote ${next.tag} (${next.publishedAt}) to all three facts`); |
| 212 |