Files
plan2code/src/web-console/update-check.mjs
T

230 lines
9.2 KiB
JavaScript

// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags --heads` needs no API token and no rate-limited REST
// call, rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The same one snapshot also carries the synthetic
// `install-vX.Y.Z` tags and the branch heads, which the launcher and the
// installer read to pick the ref npx fetches (`chooseReleaseRef()`,
// `installRefForRelease()`). The server starts this at boot and never waits on
// it; the answer, failures included, is cached for an hour so a burst of
// sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
// opening a window nobody asked for.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
// The ref starts the line or follows the sha's whitespace: with `--heads` in the same answer, a
// branch named like `x/refs/tags/v9.9.9` must never read as release 9.9.9.
const TAG_REF = /(?:^|\s)refs\/tags\/v(\d+\.\d+\.\d+)$/;
const SNAPSHOT_LINE = /^([0-9a-f]{40})\s+refs\/(tags|heads)\/(\S+)$/i;
const RELEASE_TAG = /^(install-)?v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote` output, without the `v`.
* Peeled lines (`^{}`), `install-vX.Y.Z` tags, branch heads, pre-releases and
* other tag names never match, so an annotated tag counts once. Null when
* nothing matches. This is the plain-release compatibility API the console
* notice uses: it keeps its own line scan rather than going through
* `parseLsRemoteSnapshot()`, whose stricter sha check and peeled-line
* evidence would change what it has always answered.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
let best = null;
for (const line of text.split(/\r?\n/)) {
const m = TAG_REF.exec(line.trim());
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
}
return best;
}
/**
* One `git ls-remote --tags --heads` answer, parsed: `{ tags, peeledTags,
* installTags, heads }`. `tags` and `installTags` map a version (`X.Y.Z`) to
* the sha its `vX.Y.Z` or `install-vX.Y.Z` ref line names; `peeledTags` maps a
* tag name (`v3.1.2`, `install-v3.1.2`) to the commit on its `^{}` line, which
* only annotated tags have; `heads` maps a branch name to its commit. Shas are
* lowercased. Malformed lines and tags of neither shape are skipped; anything
* but a string gives an empty snapshot.
*/
export function parseLsRemoteSnapshot(text) {
const snapshot = { tags: {}, peeledTags: {}, installTags: {}, heads: {} };
if (typeof text !== "string") return snapshot;
for (const line of text.split(/\r?\n/)) {
const m = SNAPSHOT_LINE.exec(line.trim());
if (!m) continue;
const sha = m[1].toLowerCase();
if (m[2] === "heads") {
snapshot.heads[m[3]] = sha;
continue;
}
const peeled = m[3].endsWith("^{}");
const name = peeled ? m[3].slice(0, -3) : m[3];
const tag = RELEASE_TAG.exec(name);
if (!tag) continue;
if (peeled) snapshot.peeledTags[name] = sha;
else (tag[1] ? snapshot.installTags : snapshot.tags)[tag[2]] = sha;
}
return snapshot;
}
/** Whether the snapshot advertises the tag `name` (`vX.Y.Z` or `install-vX.Y.Z`): its ref line or its peeled line. */
function hasTag(snapshot, name) {
const m = RELEASE_TAG.exec(name);
const refs = (m[1] ? snapshot.installTags : snapshot.tags) || {};
return Object.hasOwn(refs, m[2]) || Object.hasOwn(snapshot.peeledTags || {}, name);
}
/**
* The ref npx should fetch for the logical release `vX.Y.Z` (`X.Y.Z` reads the
* same): `{ releaseRef: "vX.Y.Z", fetchRef: "install-vX.Y.Z", synthetic: true }`
* when the snapshot advertises the slim install tag, `{ releaseRef, fetchRef:
* "vX.Y.Z", synthetic: false }` when it advertises only the plain tag, and
* null when it advertises neither. Chosen by ref name, never by commit; an
* annotated tag's peeled line counts as evidence of its tag.
*/
export function installRefForRelease(version, snapshot) {
if (typeof version !== "string" || !snapshot) return null;
const bare = version.startsWith("v") ? version.slice(1) : version;
if (!SEMVER.test(bare)) return null;
const releaseRef = `v${bare}`;
if (hasTag(snapshot, `install-${releaseRef}`)) return { releaseRef, fetchRef: `install-${releaseRef}`, synthetic: true };
if (hasTag(snapshot, releaseRef)) return { releaseRef, fetchRef: releaseRef, synthetic: false };
return null;
}
/**
* The release a default update installs: always the numerically newest plain
* `vX.Y.Z`, the same release latestTag() reports to the banner, the launcher
* notice and the app, fetched as its slim `install-vX.Y.Z` when that tag
* exists and as the full plain tag when it does not (a release published
* before its install ref, or whose ref publication failed). Never an older
* release because only it has an install tag: that would roll a user back.
* `{ releaseRef, fetchRef, synthetic, version }` with `version` as `X.Y.Z`, or
* null when the snapshot holds no plain release at all.
*/
export function chooseReleaseRef(snapshot) {
if (!snapshot) return null;
const plain = new Set(Object.keys(snapshot.tags || {}));
for (const name of Object.keys(snapshot.peeledTags || {})) {
const m = RELEASE_TAG.exec(name);
if (m && !m[1]) plain.add(m[2]);
}
const version = [...plain].reduce((best, v) => (best === null || compareVersions(v, best) > 0 ? v : best), null);
if (version === null) return null;
const synthetic = hasTag(snapshot, `install-v${version}`);
return { releaseRef: `v${version}`, fetchRef: synthetic ? `install-v${version}` : `v${version}`, synthetic, version };
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
return typeof cached.latest === "string" ? cached.latest : null;
} catch {
return undefined;
}
}
function writeCache(cacheFile, data) {
const tmp = cacheFile + "." + process.pid + ".tmp";
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, cacheFile);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/**
* `git ls-remote --tags --heads` against the repo, one call for the release
* tags, the synthetic install tags and the branch heads: resolves its stdout,
* or null when git is missing, fails, or is still going after `timeoutMs`. No
* shell, no window, no prompt. Readers that want releases only (`latestTag()`)
* skip the head lines.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", "--heads", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],
env,
});
} catch {
return resolve(null);
}
const timer = setTimeout(() => {
try {
child.kill();
} catch {}
done(null);
}, timeoutMs);
timer.unref?.();
let out = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
out += chunk;
});
child.on("error", () => done(null));
child.on("close", (code) => done(code === 0 ? out : null));
});
}
/**
* Whether `installed` is behind the newest release: `{ installed, latest,
* updateAvailable }`, or null when either version is unknown. Reuses a cache
* under an hour old, and caches a failed lookup as `latest: null` so it is
* not retried until the hour is up. Never throws.
*/
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
try {
let latest = readCache(cacheFile, now);
if (latest === undefined) {
latest = latestTag(await run());
writeCache(cacheFile, { checkedAt: now, latest });
}
const order = compareVersions(installed, latest);
if (latest === null || order === null) return null;
return { installed, latest, updateAvailable: order < 0 };
} catch {
return null;
}
}