/** * Installed versions of monitored packages. * * `monitored_projects.version` holds the version we look up. When the source * only gave a range (a package.json "^4.17.0" with no lockfile), that is the * low end of the range, which is not necessarily what ships. Such rows carry * `metadata.version_exact = false` and the original spec in * `metadata.version_spec`. They must be shown, exported and reasoned about as * "version unknown", never as the installed version. */ /** What `monitored_projects.metadata` says about the stored version. */ export interface ProjectVersionMeta { /** false when `version` is only the low end of a range. Missing = exact. */ version_exact?: boolean; /** The range as the manifest wrote it, e.g. "^4.17.0" or ">=3.2". */ version_spec?: string; } function metaOf(metadata: unknown): ProjectVersionMeta { return metadata && typeof metadata === 'object' && !Array.isArray(metadata) ? (metadata as ProjectVersionMeta) : {}; } /** * A single release someone could have installed: "4.17.21", "1.0.0-rc.1", * "2.3.1+build.5", "v1.2.3" (Go), and Debian/Ubuntu package versions with an * epoch or a tilde ("1:2.36-9+deb12u3", "3.0.15-1~deb12u1"). Not a range, * placeholder, alias or path: '', '0.0.0', '*', 'latest', '1.x', '^1.2', * '~1.2', '>=1 <2', '1.0 || 2.0', 'workspace:*', 'npm:left-pad@1.3.0', * 'file:../x', '[1.0,2.0)'. */ export function isConcreteVersion(version: string | null | undefined): boolean { // A leading epoch ("1:") is part of a Debian version; any other ':' is not a version. const v = String(version ?? '').trim().replace(/^\d+:(?=\d)/, ''); if (!v || v === '0.0.0') return false; // '~' only after the first digit (Debian's "1~deb12u1"); a leading '~' is a range. if (/[\s,|<>^*:/@\\[\]()=!]/.test(v) || /^~/.test(v)) return false; if (/(?:^|\.)x(?:\.|$)/i.test(v)) return false; if (/^(?:latest|next|dev|master|main|stable|unknown)$/i.test(v)) return false; return /^v?\d/.test(v); } /** The stored version is the installed one: concrete, and not flagged as a range floor. */ export function isVersionKnown(version: string | null | undefined, metadata?: unknown): boolean { return isConcreteVersion(version) && metaOf(metadata).version_exact !== false; } /** The range the source gave, when the version is only its low end. */ export function versionRange(metadata: unknown): string | null { const meta = metaOf(metadata); if (meta.version_exact !== false) return null; const spec = typeof meta.version_spec === 'string' ? meta.version_spec.trim() : ''; return spec || null; } /** * How to show a monitored version: the version itself when it is the installed * one, otherwise "Unknown" (with the manifest's range when there is one). */ export function versionLabel(version: string | null | undefined, metadata?: unknown): string { if (isVersionKnown(version, metadata)) return String(version).trim(); const range = versionRange(metadata); return range ? `Unknown (range ${range})` : 'Unknown'; }