utils/dep_freshness/parsers/javascript.py
Krzysztof kuhy Rudnicki 2a2f18ca56 Add the shared dependency-freshness gate
"Are we on the newest version?" was not mechanically answerable across these
repos: constraint styles had drifted per-ecosystem and a caret range is
"newest-compatible" by definition, which gives a checker nothing to compare.
This gate makes it answerable and then enforces the answer.

Checks two things at once -- that every dependency carries an exact pin, and
that the pin equals its registry's latest STABLE release -- across pub.dev,
PyPI, npm, crates.io, the Go proxy, kuhyx/utils git tags, and the Flutter /
Node / Python toolchains.

Three deliberate design points:

* Pre-releases are rejected per-ecosystem, because every ecosystem leaks them
  differently and each leak fails GREEN. npm lets a maintainer point
  `dist-tags.latest` at an rc; crates.io's `max_version` includes them; PyPI's
  legacy `info.version` includes yanked releases. Unit-tested with fixtures,
  since an end-to-end run cannot surface a wrong "up to date".

* Offline, the gate serves an expired cache entry and PASSES with a DEGRADED
  banner (exit 3 only under --strict, which is CI). `--no-verify` is banned
  here, so a hook that hard-failed offline would leave no way to commit at all.

* The allowlist has two entry classes. `blocked_by: transitive:<pkg>@<ver>` is
  a predicate that clears itself when upstream moves and must NOT carry a
  date; everything else is discretionary and requires `expires`, capped at 90
  days. Exact pins plus latest-everywhere is provably unsatisfiable when a
  dependency internally constrains a shared transitive, and expiring the
  predicate class on a calendar would turn the gate red for a reason no commit
  could fix. An entry with nothing left to excuse is itself an error.

One hook id, one shim, one shared implementation -- always delegating, so it
cannot fork the way the 250-line cap forked into four ids, two of which were
independent reimplementations.

256 tests, 100% branch coverage on every module of the gate. Also adds the
workflow that runs them, which incidentally gives md_naming's 71 tests their
first CI run.

Not yet installed in any repo: a repo that gets the gate before its deps are
bumped is instantly and permanently red, so the gate and the upgrade land
together, per repo.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 13:00:35 +02:00

73 lines
2.3 KiB
Python

"""`package.json` (+ lockfiles) and `.nvmrc` -> npm dependencies.
`engines.node` and `packageManager` are toolchain declarations rather than
registry packages, and are read as such. `resolutions` / `overrides` get the
same treatment as pub's `dependency_overrides`: reported, because they pin a
transitive nobody is watching.
"""
from __future__ import annotations
import json
from pathlib import Path
from dep_freshness._tables import NPM, TOOLCHAIN
from dep_freshness.models import Dep
from dep_freshness.parsers._lines import index
from dep_freshness.versions import exact_pin
_SECTIONS = (
("dependencies", False, False),
("devDependencies", True, False),
("optionalDependencies", False, False),
("peerDependencies", False, False),
("resolutions", False, True),
("overrides", False, True),
)
_LOCAL_PREFIXES = ("file:", "link:", "workspace:", "git+", "github:", "npm:")
def _load(path: Path) -> dict:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) else {}
def parse_package_json(path: Path) -> list[Dep]:
data = _load(path)
if not data:
return []
lines = index(path)
deps: list[Dep] = []
node = (data.get("engines") or {}).get("node")
if isinstance(node, str):
deps.append(Dep(
ecosystem=TOOLCHAIN, name="node", constraint=node, path=path,
line=lines.get("node", 0), pinned=exact_pin(node), caret_ok=True,
))
for section, is_dev, is_override in _SECTIONS:
for name, spec in (data.get(section) or {}).items():
if not isinstance(spec, str) or spec.startswith(_LOCAL_PREFIXES):
continue
deps.append(Dep(
ecosystem=NPM, name=str(name), constraint=spec, path=path,
line=lines.get(str(name), 0), pinned=exact_pin(spec),
dev=is_dev, override=is_override,
))
return deps
def parse_nvmrc(path: Path) -> list[Dep]:
try:
value = path.read_text(encoding="utf-8").strip().splitlines()[0].strip()
except (OSError, IndexError):
return []
return [Dep(
ecosystem=TOOLCHAIN, name="node", constraint=value, path=path,
line=1, pinned=exact_pin(value),
)]