From bc4e199ca9348134451c7b3477ffc766e9be17ae Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:03:32 +0000 Subject: [PATCH 1/7] Make a release one pull request merge. Prepare release opens release/X.Y.Z for a person to merge. Merging publishes to npm and JSR with OIDC, then tags vX.Y.Z from the changelog. Co-authored-by: ProxyMesh AI --- .cursor/skills/release/SKILL.md | 44 ++- .github/workflows/prepare-release.yml | 39 ++ .github/workflows/publish.yml | 139 +++---- .github/workflows/release-on-merge.yml | 63 ++- CHANGELOG.md | 7 + README.md | 2 + RELEASING.md | 48 +++ scripts/create-release-pr.mjs | 524 +++++++++++++++++++------ scripts/release.test.mjs | 134 +++++++ 9 files changed, 725 insertions(+), 275 deletions(-) create mode 100644 .github/workflows/prepare-release.yml create mode 100644 CHANGELOG.md create mode 100644 RELEASING.md create mode 100644 scripts/release.test.mjs diff --git a/.cursor/skills/release/SKILL.md b/.cursor/skills/release/SKILL.md index ed5631a..4bccabc 100644 --- a/.cursor/skills/release/SKILL.md +++ b/.cursor/skills/release/SKILL.md @@ -1,49 +1,53 @@ --- name: release description: >- - Bumps package.json and jsr.json, pushes branch release/VERSION, opens a PR to - main with auto-merge, and relies on CI to publish a GitHub release after merge. - Use when the user invokes /release or /release VERSION, asks for a release PR, - or wants to ship a new semver version. + Opens a release/X.Y.Z pull request that bumps package.json, jsr.json, and + package-lock.json and moves the CHANGELOG Unreleased section. Merge is + manual. After merge, CI publishes to npm and JSR and tags vX.Y.Z. Use when + the user invokes /release or /release VERSION, asks for a release PR, or + wants to ship a new semver version. --- # Release (`/release` [VERSION]) -In chat, users may type **`/release`** (patch bump) or **`/release 1.2.3`** (explicit semver). Treat that as this workflow. +In chat, users may type **`/release`** (patch bump), **`/release minor`**, **`/release major`**, or **`/release 1.2.3`**. See `RELEASING.md` for what CI runs and the owner setup. Do not publish, tag, or merge unless the user asks. ## Goal -Cut a **release PR** from `release/` → `main` with version bumps in `package.json` and `jsr.json`. Optional **VERSION** defaults to **patch bump** from the current `package.json` version. +Cut a **release PR** from `release/` → `main`. Optional **VERSION** defaults to a **patch** bump of `package.json`. ## Preconditions -- Clean git working tree (no uncommitted changes). -- `git` and [`gh`](https://cli.github.com/) installed and authenticated (`gh auth login`). -- Repo default branch is `main`. -- Remote branch `release/` must not already exist. +- Clean git working tree. +- `git` and `gh` installed and authenticated. +- Default branch is `main`. +- Remote branch `release/` does not already exist. +- `CHANGELOG.md` has a `## Unreleased` section. Put the release notes there first. ## Steps -1. **Resolve VERSION** (if the user did not pass one): read `package.json` `version`, bump **patch** (e.g. `0.2.1` → `0.2.2`). -2. **Run the automation script** from the repo root (preferred): +1. Resolve VERSION: explicit `X.Y.Z`, or `patch` / `minor` / `major`. Omitted means patch. +2. From the repo root: ```bash npm run release:pr -- [VERSION] ``` - Or: `node scripts/create-release-pr.mjs [VERSION]`. Omit `[VERSION]` for patch bump. + Or: `node scripts/create-release-pr.mjs [VERSION]`. -3. If the script cannot enable auto-merge, tell the user to merge the PR manually once CI passes. +3. The script bumps `package.json`, `jsr.json`, and the root `package-lock.json` versions, moves `## Unreleased` to `## VERSION - YYYY-MM-DD`, pushes `release/VERSION`, and opens a PR titled `Release VERSION`. +4. Tell the user to merge the PR after **Release check** passes. -## After merge +Actions → **Prepare release** opens the same pull request. Approve workflow runs on that PR if GitHub asks. -Merging into `main` triggers `.github/workflows/release-on-merge.yml`, which creates GitHub release tag `v-` and release notes. That **published** release runs `publish.yml` (npm + JSR). +## After merge -## Tag convention +Merging into `main` runs `.github/workflows/publish.yml`. It publishes to npm and JSR with OIDC, then creates tag `vVERSION` (for example `0.4.1` → `v0.4.1`) and a GitHub Release from the changelog section. -GitHub release tag: `v-${VERSION}` (e.g. `0.2.2` → tag `v-0.2.2`), matching `publish.yml` expectations. +Tags through `v-0.4.0` keep the `v-` prefix. Leave those tags in place. ## Do not -- Commit unrelated files (e.g. stray `site/` or local-only dirs) on the release branch. -- Bump only one of `package.json` / `jsr.json`; both must match for publish. +- Commit unrelated files on the release branch. +- Bump one version manifest and leave the others behind. `package.json`, `jsr.json`, and `package-lock.json` must match. +- Enable auto-merge on the release pull request. diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml new file mode 100644 index 0000000..2fd3c08 --- /dev/null +++ b/.github/workflows/prepare-release.yml @@ -0,0 +1,39 @@ +name: Prepare release + +on: + workflow_dispatch: + inputs: + version: + description: "X.Y.Z, or patch, minor, or major" + required: true + type: string + +concurrency: + group: prepare-release + cancel-in-progress: false + +permissions: {} + +jobs: + prepare: + runs-on: ubuntu-24.04 + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + persist-credentials: true + + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false + + - name: Open release pull request + env: + RELEASE_VERSION: ${{ inputs.version }} + PREPARE_FROM_CHECKOUT: "1" + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: node scripts/create-release-pr.mjs diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 832bc5f..b7298ab 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,113 +1,62 @@ name: Publish +# A push to main lets the release environment limit deployments to main. +# The merge commit is that push. Detect the release pull request from it. on: - release: - types: [published] - workflow_dispatch: - # GitHub does not start new workflow runs for events caused by the default - # GITHUB_TOKEN (e.g. gh release create in another workflow). After - # "Release on merge" creates a release, trigger publish here instead. - workflow_run: - workflows: [Release on merge] - types: [completed] + push: + branches: + - main + +concurrency: + group: publish-${{ github.ref }} + cancel-in-progress: false + +permissions: {} jobs: - publish: - if: >- - github.event_name != 'workflow_run' || - github.event.workflow_run.conclusion == 'success' + gate: runs-on: ubuntu-24.04 - # Explicit job permissions: org default token scopes must not block OIDC. - # actions: write is required for setup-node's npm cache save (contents: read alone - # can restore but not reserve/write caches → "token has no writable scopes"). + outputs: + publish: ${{ steps.detect.outputs.publish }} permissions: contents: read - actions: write - id-token: write + pull-requests: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ github.event_name == 'workflow_run' && 'main' || github.event_name == 'release' && github.ref || 'main' }} + persist-credentials: false - - name: Decide whether to publish - id: gate - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - set -euo pipefail - if [[ "${{ github.event_name }}" != "workflow_run" ]]; then - echo "publish=true" >> "${GITHUB_OUTPUT}" - exit 0 - fi - VERSION="$(node -p "require('./package.json').version")" - TAG="v-${VERSION}" - if gh release view "${TAG}" --repo "${{ github.repository }}" >/dev/null 2>&1; then - echo "publish=true" >> "${GITHUB_OUTPUT}" - else - echo "No GitHub release ${TAG} yet (or release job was skipped); skipping publish." - echo "publish=false" >> "${GITHUB_OUTPUT}" - fi - - # Omit registry-url: setup-node otherwise sets NODE_AUTH_TOKEN to a placeholder and npm publish uses that instead of OIDC. - # Node 24 ships npm 11.x (≥11.5.1 in current LTS line). Node 22’s npm is 10.x; Corepack `prepare npm@11` does not replace - # the toolcache `npm` binary on GitHub-hosted runners, so `npm publish` stayed on 10.x and OIDC trusted publishing never ran. - - name: Setup Node - if: steps.gate.outputs.publish == 'true' - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 - cache: npm - - - name: Assert npm supports trusted publishing (OIDC) - if: steps.gate.outputs.publish == 'true' - run: | - set -euo pipefail - ver="$(npm --version)" - echo "npm ${ver}" - node -e " - const v = process.argv[1].split('.').map(Number); - const ok = v[0] > 11 || (v[0] === 11 && (v[1] > 5 || (v[1] === 5 && (v[2] || 0) >= 1))); - if (!ok) { console.error('npm ' + process.argv[1] + ' < 11.5.1; trusted publishing OIDC requires npm >= 11.5.1'); process.exit(1); } - " "$ver" - - - name: Ensure versions match - if: steps.gate.outputs.publish == 'true' - shell: bash - run: | - set -euo pipefail - PKG_VERSION="$(node -p "require('./package.json').version")" - JSR_VERSION="$(node -p "require('./jsr.json').version")" - TAG_NAME="${{ github.event.release.tag_name }}" - if [[ -z "$TAG_NAME" ]]; then - TAG_NAME="v-${PKG_VERSION}" - fi - if [[ "$PKG_VERSION" != "$JSR_VERSION" ]]; then - echo "Version mismatch: package.json=$PKG_VERSION, jsr.json=$JSR_VERSION" - exit 1 - fi - if [[ "$TAG_NAME" != "v$PKG_VERSION" && "$TAG_NAME" != "$PKG_VERSION" && "$TAG_NAME" != "v-${PKG_VERSION}" ]]; then - echo "Release tag '$TAG_NAME' does not match version '$PKG_VERSION' (expected '$PKG_VERSION', 'v$PKG_VERSION', or 'v-${PKG_VERSION}')." - exit 1 - fi + package-manager-cache: false - - name: Install dependencies - if: steps.gate.outputs.publish == 'true' - run: npm install --ignore-scripts --no-package-lock + - id: detect + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: node scripts/create-release-pr.mjs --detect - # If NODE_AUTH_TOKEN / NPM_TOKEN are set to empty or a placeholder (repo/org Variables, - # or setup-node + registry-url), npm prefers them over OIDC and fails with ENEEDAUTH. - - name: Publish to npm - if: steps.gate.outputs.publish == 'true' - run: | - set -euo pipefail - if [[ -z "${ACTIONS_ID_TOKEN_REQUEST_URL:-}" || -z "${ACTIONS_ID_TOKEN_REQUEST_TOKEN:-}" ]]; then - echo "::error::GitHub OIDC is unavailable (missing ACTIONS_ID_TOKEN_*). Check job permissions id-token: write and repo Settings → Actions → Workflow permissions." - exit 1 - fi - unset NODE_AUTH_TOKEN NPM_TOKEN - npm publish --access public --provenance + publish: + needs: gate + if: success() && needs.gate.outputs.publish == 'true' + runs-on: ubuntu-24.04 + environment: release + permissions: + contents: write + id-token: write + pull-requests: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - - name: Publish to JSR - if: steps.gate.outputs.publish == 'true' - run: npx jsr publish + # Omit registry-url. setup-node would set NODE_AUTH_TOKEN and npm would skip OIDC. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false + - name: Publish to npm and JSR + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: node scripts/create-release-pr.mjs --publish diff --git a/.github/workflows/release-on-merge.yml b/.github/workflows/release-on-merge.yml index e22a1ac..589c1cf 100644 --- a/.github/workflows/release-on-merge.yml +++ b/.github/workflows/release-on-merge.yml @@ -1,53 +1,34 @@ -name: Release on merge - -# When a release/* PR merges into main, create a GitHub release (tag v-). -# Events from GITHUB_TOKEN do not start other workflows; publish.yml is triggered via -# workflow_run when this workflow completes (see publish.yml). +# Checks a release pull request before merge. publish.yml publishes after the merge reaches main. +name: Release check on: pull_request: - types: [closed] - branches: - - main - -concurrency: - group: release-on-merge-${{ github.event.pull_request.number }} - cancel-in-progress: false -permissions: - contents: write +permissions: {} jobs: - github-release: - if: >- - github.event.pull_request.merged == true && - startsWith(github.head_ref, 'release/') && - github.event.pull_request.head.repo.full_name == github.repository + check: + name: Release check runs-on: ubuntu-24.04 + permissions: + contents: read steps: - - name: Checkout merge commit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ github.event.pull_request.merge_commit_sha }} + persist-credentials: false - - name: Read version - id: ver - run: | - VERSION="$(node -p "require('./package.json').version")" - echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false - - name: Create GitHub release + - name: Check version and changelog env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - set -euo pipefail - VERSION="${{ steps.ver.outputs.version }}" - TAG="v-${VERSION}" - if gh release view "${TAG}" --repo "${{ github.repository }}" >/dev/null 2>&1; then - echo "Release ${TAG} already exists; skipping." - exit 0 - fi - gh release create "${TAG}" \ - --repo "${{ github.repository }}" \ - --title "${VERSION}" \ - --generate-notes + RELEASE_HEAD_REF: ${{ github.head_ref }} + run: node scripts/create-release-pr.mjs --check + + - name: Test the release helper + run: node --test scripts/release.test.mjs + + - name: Build package + run: npm pack --ignore-scripts --pack-destination "${RUNNER_TEMP}" diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e14c1f8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## Unreleased + +## 0.4.0 - 2026-11-02 + +Tagged `v-0.4.0`. Notes are on that GitHub Release. diff --git a/README.md b/README.md index 8f062c6..1f27934 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ Extensions for JavaScript HTTP libraries to support **sending and receiving custom proxy headers** during HTTPS CONNECT tunneling. +See [RELEASING.md](RELEASING.md) to publish a new version. + ## The Problem When making HTTPS requests through a proxy, the connection is established via a CONNECT tunnel. During this process: diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..2ae0705 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,48 @@ +# Releasing + +## Cut a release + +1. Add notes under `## Unreleased` in `CHANGELOG.md`. +2. Run Actions → **Prepare release**. Set `version` to `X.Y.Z`, or to `patch`, `minor`, or `major`. +3. The workflow pushes `release/X.Y.Z` and opens a pull request titled `Release X.Y.Z`. The body is the new changelog section. Merge it after **Release check** passes. +4. If the pull request shows **Approve workflows to run**, approve it. A pull request opened with the Actions token waits for that approval before checks start. + +From a clone: + +```bash +npm run release:pr -- X.Y.Z +``` + +`patch`, `minor`, and `major` work too. Omit the argument for a patch bump. Push the branch to this repository. + +## What runs + +**Prepare release** creates `release/X.Y.Z` from `main`, sets the version in `package.json`, `jsr.json`, and the root `package-lock.json` fields, and moves `## Unreleased` to `## X.Y.Z - YYYY-MM-DD`. + +**Release check** runs on pull requests. On `release/X.Y.Z` the branch name, version manifests, and a dated changelog section must match, and `npm pack` must succeed. Other pull requests check that the manifests match and that `## Unreleased` exists. + +**Publish** runs when a push to `main` is the merge of a `release/X.Y.Z` pull request from this repository. It publishes to npm (`npm publish --access public --provenance`, GitHub OIDC) and JSR (`npx jsr publish`, GitHub OIDC), then creates tag `vX.Y.Z` and a GitHub Release whose notes are that changelog section. The job uses the `release` environment. Other pushes to `main` stop at the gate. + +Re-run **Publish** on that commit if it fails after the registry has accepted the version. A re-run skips a registry that already has this commit and skips an existing tag. If the version is on npm or JSR from another commit, the job fails and leaves the tag uncreated. + +### Tags + +New tags are `vX.Y.Z` (for example `v0.4.1`). + +Tags through `0.4.0` used a hyphen: `v-0.2.0` through `v-0.4.0`. Those tags stay as they are. + +## One-time owner setup + +Do this before the next release. This change does not create a tag or publish a package. + +1. Create a GitHub Environment named `release` (Settings → Environments). Publish runs on a push to `main`, so a deployment-branch rule can limit it to `main`. Required reviewers are optional. +2. npm already uses trusted publishing. Add a publisher for the environment. A saved publisher cannot be edited, so add a second one: + - Package `javascript-proxy-headers` on npmjs.com → Settings → Trusted Publisher → Add + - Organization `proxymesh`, repository `javascript-proxy-headers`, workflow filename `publish.yml` + - Environment name `release` + - Allow direct `npm publish`. Publishers created after 3 Sep 2026 default to staged publish, and this workflow runs `npm publish`. + - The new publisher must complete a publish within 2 days or it expires. Keep the current publisher until that publish succeeds, then delete the old one. +3. Confirm `@proxymesh/javascript-proxy-headers` on JSR is linked to `proxymesh/javascript-proxy-headers`. That link is JSR trusted publishing. JSR has no environment field and no token in this workflow. +4. Under Settings → Actions → General, allow GitHub Actions to create and approve pull requests. Prepare release needs that to open the pull request. +5. After the publisher with environment `release` has published once, delete repository secrets `NPM_TOKEN`, `NODE_AUTH_TOKEN`, and `JSR_TOKEN` if they are present. The publish job unsets them so a leftover token cannot take precedence over OIDC. +6. If branch protection still requires **Release on merge**, drop that check. Require **Release check** so a release pull request with a mismatched version or changelog cannot merge. diff --git a/scripts/create-release-pr.mjs b/scripts/create-release-pr.mjs index 363a8b6..4d6f3e8 100644 --- a/scripts/create-release-pr.mjs +++ b/scripts/create-release-pr.mjs @@ -1,168 +1,454 @@ #!/usr/bin/env node /** - * Bumps package.json + jsr.json, opens release/VERSION → main PR, enables auto-merge. - * Usage: node scripts/create-release-pr.mjs [VERSION] - * If VERSION is omitted, bumps the patch segment of the current package.json version. + * Release helper. + * node scripts/create-release-pr.mjs [X.Y.Z|patch|minor|major] + * node scripts/create-release-pr.mjs --check + * node scripts/create-release-pr.mjs --detect + * node scripts/create-release-pr.mjs --publish + * + * Omit the version to bump the patch number. The pull request is left for a person to merge. */ -import { execFileSync, execSync } from "node:child_process"; -import { readFileSync, writeFileSync } from "node:fs"; +import { execFileSync, spawnSync } from "node:child_process"; +import { appendFileSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -const repoRoot = join(dirname(fileURLToPath(import.meta.url)), ".."); +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; -function sh(cmd, inherit = false) { - return execSync(cmd, { - cwd: repoRoot, - encoding: "utf8", - stdio: inherit ? "inherit" : "pipe", - }).trim(); +function git(args) { + return execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim(); } -function gh(args, inherit = false) { - if (inherit) { - execFileSync("gh", args, { cwd: repoRoot, stdio: "inherit" }); - return ""; - } - return execFileSync("gh", args, { cwd: repoRoot, encoding: "utf8" }).trim(); +function gh(args) { + return execFileSync("gh", args, { cwd: root, encoding: "utf8" }).trim(); } -function ensureCleanWorkingTree() { - const out = sh("git status --porcelain"); - if (out) { - throw new Error( - "Working tree is not clean. Commit or stash changes before running this script.", - ); - } +function parseSemver(value) { + const match = SEMVER.exec(String(value).trim()); + if (!match) throw new Error(`Version must be X.Y.Z (got ${JSON.stringify(value)}).`); + return [Number(match[1]), Number(match[2]), Number(match[3])]; } -function refExists(ref) { - try { - execSync(`git rev-parse --verify --quiet "${ref}"`, { - cwd: repoRoot, - stdio: "ignore", - }); - return true; - } catch { - return false; - } +export function resolveVersion(current, input) { + const raw = (input ?? "").trim(); + const spec = raw === "" ? "patch" : raw; + const [major, minor, patch] = parseSemver(current); + if (spec === "major") return `${major + 1}.0.0`; + if (spec === "minor") return `${major}.${minor + 1}.0`; + if (spec === "patch") return `${major}.${minor}.${patch + 1}`; + const [nextMajor, nextMinor, nextPatch] = parseSemver(spec); + const greater = nextMajor > major + || (nextMajor === major && nextMinor > minor) + || (nextMajor === major && nextMinor === minor && nextPatch > patch); + if (!greater) throw new Error(`New version must be greater than ${current} (got ${spec}).`); + return spec; } -function remoteHeadsHas(branch) { - const out = sh(`git ls-remote --heads origin "${branch}"`); - return out.length > 0; +function validDate(value) { + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); + if (!match) return false; + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const date = new Date(Date.UTC(year, month - 1, day)); + return date.getUTCFullYear() === year + && date.getUTCMonth() === month - 1 + && date.getUTCDate() === day; } -function parseSemver(v) { - const m = String(v).match(/^(\d+)\.(\d+)\.(\d+)$/); - if (!m) { - throw new Error(`VERSION must be semver X.Y.Z (got ${JSON.stringify(v)})`); - } - return [Number(m[1]), Number(m[2]), Number(m[3])]; +function headingPattern(version) { + parseSemver(version); + return new RegExp(`^## ${version.replaceAll(".", "\\.")} - (\\d{4}-\\d{2}-\\d{2})\\s*$`); } -function bumpPatch(version) { - const [a, b, c] = parseSemver(version); - return `${a}.${b}.${c + 1}`; +function trimBlankLines(lines) { + let start = 0; + let end = lines.length; + while (start < end && lines[start].trim() === "") start += 1; + while (end > start && lines[end - 1].trim() === "") end -= 1; + return lines.slice(start, end); } -function cmpVersion(a, b) { - const pa = parseSemver(a); - const pb = parseSemver(b); - for (let i = 0; i < 3; i++) { - if (pa[i] > pb[i]) return 1; - if (pa[i] < pb[i]) return -1; +export function moveUnreleased(markdown, version, date) { + if (!validDate(date)) throw new Error(`Invalid release date ${date}.`); + const pattern = headingPattern(version); + const lines = markdown.replace(/\r\n/g, "\n").replace(/^\uFEFF/, "").split("\n"); + if (lines.some((line) => pattern.test(line))) { + throw new Error(`CHANGELOG.md already has a ${version} section.`); + } + const start = lines.findIndex((line) => /^## Unreleased\s*$/.test(line)); + if (start < 0) throw new Error("CHANGELOG.md is missing a ## Unreleased section."); + let end = lines.length; + for (let i = start + 1; i < lines.length; i += 1) { + if (lines[i].startsWith("## ")) { + end = i; + break; + } } - return 0; + const header = trimBlankLines(lines.slice(0, start)); + const body = trimBlankLines(lines.slice(start + 1, end)); + let restStart = end; + while (restStart < lines.length && lines[restStart].trim() === "") restStart += 1; + const rest = lines.slice(restStart); + const out = []; + if (header.length) out.push(...header, ""); + out.push("## Unreleased", "", `## ${version} - ${date}`); + if (body.length) out.push("", ...body); + if (rest.length) out.push("", ...rest); + return `${out.join("\n").replace(/\n+$/, "")}\n`; } -function readJson(path) { - return JSON.parse(readFileSync(path, "utf8")); +export function extractSection(markdown, version) { + const pattern = headingPattern(version); + const lines = markdown.replace(/\r\n/g, "\n").split("\n"); + const start = lines.findIndex((line) => pattern.test(line)); + if (start < 0) throw new Error(`CHANGELOG.md is missing a dated ${version} section.`); + const found = lines[start].match(pattern); + if (!validDate(found[1])) throw new Error(`CHANGELOG date for ${version} is invalid: ${found[1]}.`); + let end = lines.length; + for (let i = start + 1; i < lines.length; i += 1) { + if (lines[i].startsWith("## ")) { + end = i; + break; + } + } + return `${lines.slice(start, end).join("\n").trim()}\n`; } -function writeJson(path, obj) { - writeFileSync(path, `${JSON.stringify(obj, null, 2)}\n`, "utf8"); +export function readVersions(dir) { + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const jsr = JSON.parse(readFileSync(join(dir, "jsr.json"), "utf8")); + const lock = JSON.parse(readFileSync(join(dir, "package-lock.json"), "utf8")); + return { + package: pkg.version, + jsr: jsr.version, + lock: lock.version, + lockPackage: lock.packages[""].version, + packageName: pkg.name, + jsrName: jsr.name, + }; } -function main() { - process.chdir(repoRoot); +export function requireVersion(versions, expected) { + const pkg = versions.package; + if (pkg !== versions.jsr || pkg !== versions.lock || pkg !== versions.lockPackage) { + throw new Error( + `Version mismatch: package.json=${pkg}, jsr.json=${versions.jsr}, package-lock.json=${versions.lock}, packages[""]=${versions.lockPackage}`, + ); + } + parseSemver(pkg); + if (expected !== undefined && pkg !== expected) { + throw new Error(`Version ${pkg} does not match ${expected}.`); + } +} - const arg = process.argv[2]; - const pkgPath = join(repoRoot, "package.json"); - const jsrPath = join(repoRoot, "jsr.json"); +function replaceVersionFields(path, from, to, count, exact) { + const needle = `"version": "${from}"`; + const next = `"version": "${to}"`; + let text = readFileSync(path, "utf8"); + const total = text.split(needle).length - 1; + if (exact && total !== count) { + throw new Error(`${path} has ${total} ${needle} fields, expected ${count}.`); + } + if (!exact && total < count) { + throw new Error(`${path} has ${total} ${needle} fields, expected at least ${count}.`); + } + let start = 0; + for (let i = 0; i < count; i += 1) { + const index = text.indexOf(needle, start); + text = `${text.slice(0, index)}${next}${text.slice(index + needle.length)}`; + start = index + next.length; + } + writeFileSync(path, text); +} - ensureCleanWorkingTree(); +// The first two package-lock version fields are this package. Later copies are dependencies. +export function writeVersions(dir, from, to) { + replaceVersionFields(join(dir, "package.json"), from, to, 1, true); + replaceVersionFields(join(dir, "jsr.json"), from, to, 1, true); + replaceVersionFields(join(dir, "package-lock.json"), from, to, 2, false); + requireVersion(readVersions(dir), to); +} - const pkg = readJson(pkgPath); - const current = pkg.version; - const target = arg ? String(arg).trim() : bumpPatch(current); +function changelogText() { + return readFileSync(join(root, "CHANGELOG.md"), "utf8"); +} - parseSemver(target); - if (cmpVersion(target, current) <= 0) { - throw new Error( - `New version must be greater than current ${current} (got ${target})`, - ); +function check() { + const changelog = changelogText(); + if (!changelog.split("\n").some((line) => /^## Unreleased\s*$/.test(line))) { + throw new Error("CHANGELOG.md is missing a ## Unreleased section."); } + const versions = readVersions(root); + const branch = (process.env.RELEASE_HEAD_REF || git(["branch", "--show-current"])).trim(); + if (branch.startsWith("release/")) { + const version = branch.slice("release/".length); + if (!SEMVER.test(version)) throw new Error(`Release branch must be release/X.Y.Z (got ${branch}).`); + requireVersion(versions, version); + extractSection(changelog, version); + console.log(`Release check passed for ${version}.`); + return; + } + requireVersion(versions); + console.log(`Version manifests match at ${versions.package}.`); +} - sh("git fetch origin main", true); - sh("git checkout main", true); - sh("git pull --ff-only origin main", true); - - const branch = `release/${target}`; - if (refExists(`refs/heads/${branch}`)) { - throw new Error( - `Local branch ${branch} already exists. Delete it or pick another version.`, - ); +function mergedReleasePull() { + const sha = process.env.GITHUB_SHA; + const repository = process.env.GITHUB_REPOSITORY; + if (!sha || !repository) throw new Error("GITHUB_SHA and GITHUB_REPOSITORY are required."); + const head = git(["rev-parse", "HEAD"]); + if (head !== sha) throw new Error(`Checkout is ${head}, expected ${sha}.`); + const pulls = JSON.parse(gh([ + "api", + `repos/${repository}/commits/${sha}/pulls`, + "-H", + "Accept: application/vnd.github+json", + ])); + const releases = pulls.filter((pr) => { + const ref = pr.head.ref; + return pr.merged_at + && pr.base.ref === "main" + && ref.startsWith("release/") + && SEMVER.test(ref.slice("release/".length)); + }); + const ours = releases.filter((pr) => pr.head.repo && pr.head.repo.full_name === repository); + if (releases.length > 0 && ours.length === 0) { + const other = releases[0].head.repo ? releases[0].head.repo.full_name : "another repository"; + throw new Error(`Release pull requests must come from ${repository} (got ${other}).`); } - if (remoteHeadsHas(branch)) { - throw new Error( - `Remote branch origin/${branch} already exists. Delete it or pick another version.`, - ); + if (ours.length > 1) throw new Error(`Commit ${sha} matches multiple release pull requests.`); + return ours[0] || null; +} + +function npmGitHead(name, version) { + const spec = `${name}@${version}`; + const result = spawnSync("npm", ["view", spec, "gitHead", "--json"], { cwd: root, encoding: "utf8" }); + const output = `${result.stdout || ""}\n${result.stderr || ""}`; + if (result.status !== 0) { + if (output.includes("E404")) return { exists: false, gitHead: null }; + throw new Error(`npm view ${spec} failed: ${output.trim()}`); } + const text = (result.stdout || "").trim(); + if (!text) return { exists: true, gitHead: null }; + const parsed = JSON.parse(text); + return { exists: true, gitHead: typeof parsed === "string" ? parsed : null }; +} - sh(`git checkout -b "${branch}"`, true); +async function jsrHasVersion(name, version) { + const response = await fetch(`https://jsr.io/${name}/meta.json`); + if (response.status === 404) return false; + if (!response.ok) throw new Error(`JSR meta for ${name} returned ${response.status}.`); + const body = await response.json(); + return Object.hasOwn(body.versions, version); +} - pkg.version = target; - writeJson(pkgPath, pkg); +function tagExists(repository, tag) { + const result = spawnSync("gh", ["api", `repos/${repository}/git/ref/tags/${tag}`], { + cwd: root, + encoding: "utf8", + }); + if (result.status === 0) return true; + const output = `${result.stdout || ""}\n${result.stderr || ""}`; + if (output.includes("404")) return false; + throw new Error(`Could not read tag ${tag}: ${output.trim()}`); +} - const jsr = readJson(jsrPath); - jsr.version = target; - writeJson(jsrPath, jsr); +function createGitHubRelease(repository, tag, version, sha, notes) { + const notesPath = join(tmpdir(), `release-notes-${version}.md`); + writeFileSync(notesPath, notes.endsWith("\n") ? notes : `${notes}\n`); + if (!tagExists(repository, tag)) { + execFileSync("gh", [ + "release", "create", tag, + "--repo", repository, + "--target", sha, + "--title", version, + "--notes-file", notesPath, + ], { cwd: root, stdio: "inherit" }); + return; + } + const existing = spawnSync("gh", ["release", "view", tag, "--repo", repository], { + cwd: root, + encoding: "utf8", + }); + if (existing.status === 0) { + console.log(`GitHub Release ${tag} already exists.`); + return; + } + const payload = join(tmpdir(), `release-${version}.json`); + writeFileSync(payload, JSON.stringify({ + tag_name: tag, + target_commitish: sha, + name: version, + body: notes, + })); + execFileSync("gh", [ + "api", "--method", "POST", `repos/${repository}/releases`, "--input", payload, + ], { cwd: root, stdio: "inherit" }); +} - sh(`git add package.json jsr.json`, true); - sh(`git commit -m "chore(release): bump version to ${target}"`, true); - sh(`git push -u origin "${branch}"`, true); +function detect() { + const pr = mergedReleasePull(); + const file = process.env.GITHUB_OUTPUT; + if (!pr) { + if (file) appendFileSync(file, "publish=false\n"); + console.log("Not a merged release pull request."); + return; + } + const version = pr.head.ref.slice("release/".length); + requireVersion(readVersions(root), version); + extractSection(changelogText(), version); + if (file) appendFileSync(file, `publish=true\nversion=${version}\n`); + console.log(`Will publish ${version} from pull request #${pr.number}.`); +} - const body = [ - "Automated release PR.", - "", - `- Bumps \`package.json\` and \`jsr.json\` to **${target}**`, - `- Merging publishes GitHub release \`v-${target}\` and triggers npm/JSR publish (see \`.github/workflows/\`).`, - ].join("\n"); +async function publish() { + const pr = mergedReleasePull(); + if (!pr) throw new Error("Publish expected a merged release pull request."); + const version = pr.head.ref.slice("release/".length); + const versions = readVersions(root); + requireVersion(versions, version); + const notes = extractSection(changelogText(), version); + const sha = process.env.GITHUB_SHA; + const repository = process.env.GITHUB_REPOSITORY; + const tag = `v${version}`; + const npmInfo = npmGitHead(versions.packageName, version); + const jsrHas = await jsrHasVersion(versions.jsrName, version); + if (npmInfo.exists && npmInfo.gitHead !== sha) { + throw new Error( + `${versions.packageName}@${version} is already on npm (gitHead ${npmInfo.gitHead || "missing"}, this commit ${sha}). Refusing to publish.`, + ); + } + if (jsrHas && !(npmInfo.exists && npmInfo.gitHead === sha)) { + throw new Error(`${versions.jsrName}@${version} is already on JSR. Refusing to publish.`); + } + const publishNpm = !npmInfo.exists; + const publishJsr = !jsrHas; + if (tagExists(repository, tag) && (publishNpm || publishJsr)) { + throw new Error(`Tag ${tag} already exists and ${version} is not fully published from ${sha}. Refusing to publish.`); + } + if (publishNpm || publishJsr) { + if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL || !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) { + throw new Error("GitHub OIDC is unavailable. The publish job needs id-token: write."); + } + } + // A NODE_AUTH_TOKEN or NPM_TOKEN, even an empty one, makes npm skip OIDC. + const env = { ...process.env }; + delete env.NODE_AUTH_TOKEN; + delete env.NPM_TOKEN; + delete env.JSR_TOKEN; + if (publishNpm) { + const npmVersion = execFileSync("npm", ["--version"], { cwd: root, encoding: "utf8" }).trim(); + const [major, minor, patch] = npmVersion.split(".").map(Number); + const npmOk = major > 11 || (major === 11 && (minor > 5 || (minor === 5 && patch >= 1))); + if (!npmOk) throw new Error(`npm ${npmVersion} is older than 11.5.1, which trusted publishing requires.`); + console.log(`Publishing ${versions.packageName}@${version} to npm.`); + execFileSync("npm", ["publish", "--access", "public", "--provenance"], { cwd: root, stdio: "inherit", env }); + } else { + console.log(`npm already has ${versions.packageName}@${version} from this commit.`); + } + if (publishJsr) { + console.log(`Publishing ${versions.jsrName}@${version} to JSR.`); + execFileSync("npx", ["--yes", "jsr", "publish"], { cwd: root, stdio: "inherit", env }); + } else { + console.log(`JSR already has ${versions.jsrName}@${version}.`); + } + createGitHubRelease(repository, tag, version, sha, notes); +} - const prUrl = gh([ - "pr", - "create", - "--base", - "main", - "--head", - branch, - "--title", - `Release ${target}`, - "--body", - body, - ]); +function prepare(input) { + if (process.env.PREPARE_FROM_CHECKOUT === "1") { + const currentBranch = git(["branch", "--show-current"]); + if (currentBranch !== "main") throw new Error(`Expected checkout on main, found ${currentBranch || "detached HEAD"}.`); + execFileSync("git", ["config", "user.name", "github-actions[bot]"], { cwd: root }); + execFileSync("git", ["config", "user.email", "41898282+github-actions[bot]@users.noreply.github.com"], { cwd: root }); + } else { + const status = git(["status", "--porcelain"]); + if (status) throw new Error("Working tree is not clean. Commit or stash changes before running this script."); + execFileSync("git", ["fetch", "origin", "main"], { cwd: root, stdio: "inherit" }); + execFileSync("git", ["checkout", "main"], { cwd: root, stdio: "inherit" }); + execFileSync("git", ["pull", "--ff-only", "origin", "main"], { cwd: root, stdio: "inherit" }); + } - console.log(prUrl); + const current = readVersions(root); + requireVersion(current); + const version = resolveVersion(current.package, input); + const branch = `release/${version}`; + const local = spawnSync("git", ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], { cwd: root }); + if (local.status === 0) throw new Error(`Local branch ${branch} already exists.`); + if (git(["ls-remote", "--heads", "origin", branch])) { + throw new Error(`Remote branch origin/${branch} already exists.`); + } + let created = false; + let pushed = false; try { - gh(["pr", "merge", prUrl, "--auto", "--merge"], true); - console.log("Auto-merge enabled; PR will merge when required checks pass."); - } catch { - console.warn( - "\nCould not enable auto-merge (repo may not allow it, or checks are pending). Merge the PR manually when ready.", + execFileSync("git", ["checkout", "-b", branch], { cwd: root, stdio: "inherit" }); + created = true; + writeVersions(root, current.package, version); + const changelogPath = join(root, "CHANGELOG.md"); + const updated = moveUnreleased( + readFileSync(changelogPath, "utf8"), + version, + new Date().toISOString().slice(0, 10), ); + writeFileSync(changelogPath, updated); + const section = extractSection(updated, version); + execFileSync("git", ["add", "package.json", "jsr.json", "package-lock.json", "CHANGELOG.md"], { cwd: root }); + execFileSync("git", ["commit", "-m", `chore(release): bump version to ${version}`], { + cwd: root, + stdio: "inherit", + }); + execFileSync("git", ["push", "--set-upstream", "origin", branch], { cwd: root, stdio: "inherit" }); + pushed = true; + const body = join(tmpdir(), `release-pr-${version}.md`); + writeFileSync(body, section); + const url = gh([ + "pr", "create", + "--base", "main", + "--head", branch, + "--title", `Release ${version}`, + "--body-file", body, + ]); + console.log(url); + console.log("Merge the pull request after Release check passes."); + } catch (error) { + if (created && !pushed) { + spawnSync("git", ["checkout", "-f", "main"], { cwd: root }); + spawnSync("git", ["branch", "-D", branch], { cwd: root }); + } + if (pushed) console.error(`Pushed ${branch}. The pull request was not created.`); + throw error; } } -main(); +async function main() { + const command = process.argv[2]; + if (command === "--check") { + check(); + return; + } + if (command === "--detect") { + detect(); + return; + } + if (command === "--publish") { + await publish(); + return; + } + if (command && command.startsWith("--")) throw new Error(`Unknown command ${command}.`); + prepare(command ?? process.env.RELEASE_VERSION); +} + +const invoked = process.argv[1] + && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); +if (invoked) { + main().catch((error) => { + const message = error instanceof Error ? error.message : String(error); + if (process.env.GITHUB_ACTIONS) console.error(`::error::${message}`); + else console.error(message); + process.exit(1); + }); +} diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs new file mode 100644 index 0000000..47a0723 --- /dev/null +++ b/scripts/release.test.mjs @@ -0,0 +1,134 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { cpSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + extractSection, + moveUnreleased, + readVersions, + requireVersion, + resolveVersion, + writeVersions, +} from "./create-release-pr.mjs"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); + +test("resolveVersion bumps and rejects older versions", () => { + assert.equal(resolveVersion("1.2.3", ""), "1.2.4"); + assert.equal(resolveVersion("1.2.3", "patch"), "1.2.4"); + assert.equal(resolveVersion("1.2.3", "minor"), "1.3.0"); + assert.equal(resolveVersion("1.2.3", "major"), "2.0.0"); + assert.equal(resolveVersion("1.2.3", "1.2.4"), "1.2.4"); + assert.throws(() => resolveVersion("1.2.3", "1.2.3"), /greater than/); + assert.throws(() => resolveVersion("1.2.3", "v1.2.4"), /X\.Y\.Z/); +}); + +test("moveUnreleased keeps older sections and the empty heading", () => { + const source = [ + "# Changelog", + "", + "## Unreleased", + "", + "- Ship the release flow.", + "", + "## 0.4.0 - 2026-11-02", + "", + "- Older.", + "", + ].join("\n"); + const moved = moveUnreleased(source, "0.4.1", "2026-11-12"); + assert.equal(moved, [ + "# Changelog", + "", + "## Unreleased", + "", + "## 0.4.1 - 2026-11-12", + "", + "- Ship the release flow.", + "", + "## 0.4.0 - 2026-11-02", + "", + "- Older.", + "", + ].join("\n")); + assert.equal(extractSection(moved, "0.4.1"), [ + "## 0.4.1 - 2026-11-12", + "", + "- Ship the release flow.", + "", + ].join("\n")); + assert.throws(() => moveUnreleased(moved, "0.4.1", "2026-11-12"), /already has/); + assert.throws(() => moveUnreleased(source, "0.4.1", "2026-02-31"), /Invalid release date/); +}); + +test("moveUnreleased accepts an empty Unreleased section", () => { + const source = "# Changelog\r\n\r\n## Unreleased\r\n\r\n## 0.4.0 - 2026-11-02\r\n\r\n- Older.\r\n"; + const moved = moveUnreleased(source, "0.5.0", "2026-12-01"); + assert.equal(moved.includes("\r"), false); + assert.match(moved, /^# Changelog\n\n## Unreleased\n\n## 0\.5\.0 - 2026-12-01\n\n## 0\.4\.0 - 2026-11-02\n\n- Older\.\n$/); +}); + +test("writeVersions updates only this package in the lockfile", () => { + const dir = mkdtempSync(join(tmpdir(), "release-versions-")); + try { + for (const name of ["package.json", "jsr.json", "package-lock.json"]) { + cpSync(join(root, name), join(dir, name)); + } + const from = readVersions(dir).package; + const to = resolveVersion(from, "patch"); + const packageBefore = readFileSync(join(dir, "package.json"), "utf8"); + const jsrBefore = readFileSync(join(dir, "jsr.json"), "utf8"); + const lockBefore = readFileSync(join(dir, "package-lock.json"), "utf8"); + const needle = `"version": "${from}"`; + const beforeCount = lockBefore.split(needle).length - 1; + writeVersions(dir, from, to); + assert.equal( + readFileSync(join(dir, "package.json"), "utf8"), + packageBefore.replace(needle, `"version": "${to}"`), + ); + assert.equal( + readFileSync(join(dir, "jsr.json"), "utf8"), + jsrBefore.replace(needle, `"version": "${to}"`), + ); + let expectedLock = lockBefore; + for (let i = 0; i < 2; i += 1) expectedLock = expectedLock.replace(needle, `"version": "${to}"`); + const lockAfter = readFileSync(join(dir, "package-lock.json"), "utf8"); + assert.equal(lockAfter, expectedLock); + assert.equal(lockAfter.split(needle).length - 1, beforeCount - 2); + requireVersion(readVersions(dir), to); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("check accepts the working tree and rejects a mismatched release branch", () => { + const version = readVersions(root).package; + const ok = spawnSync("node", ["scripts/create-release-pr.mjs", "--check"], { + cwd: root, + encoding: "utf8", + }); + assert.equal(ok.status, 0, ok.stderr); + const release = spawnSync("node", ["scripts/create-release-pr.mjs", "--check"], { + cwd: root, + encoding: "utf8", + env: { ...process.env, RELEASE_HEAD_REF: `release/${version}` }, + }); + assert.equal(release.status, 0, release.stderr); + const mismatch = spawnSync("node", ["scripts/create-release-pr.mjs", "--check"], { + cwd: root, + encoding: "utf8", + env: { ...process.env, RELEASE_HEAD_REF: "release/9.9.9" }, + }); + assert.equal(mismatch.status, 1); + assert.match(mismatch.stderr, /does not match 9\.9\.9/); + const named = spawnSync("node", ["scripts/create-release-pr.mjs", "--check"], { + cwd: root, + encoding: "utf8", + env: { ...process.env, RELEASE_HEAD_REF: "release/not-a-version" }, + }); + assert.equal(named.status, 1); + assert.match(named.stderr, /release\/X\.Y\.Z/); +}); From 48ccd87f0096d3176b5ec837d4fa2d3e9b1f3842 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:21:12 +0000 Subject: [PATCH 2/7] Shrink the release helper and publish from the workflow. npm version bumps the package manifests, scripts/release.mjs only moves the changelog and checks it, and the publish workflow calls npm and jsr directly. Co-authored-by: ProxyMesh AI --- .cursor/skills/release/SKILL.md | 37 +- .github/workflows/prepare-release.yml | 68 ++- .github/workflows/publish.yml | 69 ++- ...release-on-merge.yml => release-check.yml} | 7 +- RELEASING.md | 39 +- package.json | 1 - scripts/create-release-pr.mjs | 454 ------------------ scripts/release.mjs | 147 ++++++ scripts/release.test.mjs | 115 +---- 9 files changed, 312 insertions(+), 625 deletions(-) rename .github/workflows/{release-on-merge.yml => release-check.yml} (75%) delete mode 100644 scripts/create-release-pr.mjs create mode 100644 scripts/release.mjs diff --git a/.cursor/skills/release/SKILL.md b/.cursor/skills/release/SKILL.md index 4bccabc..542a2c8 100644 --- a/.cursor/skills/release/SKILL.md +++ b/.cursor/skills/release/SKILL.md @@ -1,28 +1,21 @@ --- name: release description: >- - Opens a release/X.Y.Z pull request that bumps package.json, jsr.json, and - package-lock.json and moves the CHANGELOG Unreleased section. Merge is - manual. After merge, CI publishes to npm and JSR and tags vX.Y.Z. Use when - the user invokes /release or /release VERSION, asks for a release PR, or - wants to ship a new semver version. + Opens a release/X.Y.Z pull request with Prepare release. Merge is manual. + After merge, CI publishes to npm and JSR and tags vX.Y.Z. Use when the user + invokes /release or /release VERSION, asks for a release PR, or wants to ship + a new semver version. --- # Release (`/release` [VERSION]) -In chat, users may type **`/release`** (patch bump), **`/release minor`**, **`/release major`**, or **`/release 1.2.3`**. See `RELEASING.md` for what CI runs and the owner setup. Do not publish, tag, or merge unless the user asks. - -## Goal - -Cut a **release PR** from `release/` → `main`. Optional **VERSION** defaults to a **patch** bump of `package.json`. +In chat, users may type **`/release`** (patch bump), **`/release minor`**, **`/release major`**, or **`/release 1.2.3`**. See `RELEASING.md`. Do not publish, tag, or merge unless the user asks. ## Preconditions -- Clean git working tree. -- `git` and `gh` installed and authenticated. -- Default branch is `main`. -- Remote branch `release/` does not already exist. -- `CHANGELOG.md` has a `## Unreleased` section. Put the release notes there first. +- Notes are under `## Unreleased` in `CHANGELOG.md`. +- `gh` is authenticated. +- The workflow runs from `main`. ## Steps @@ -30,24 +23,18 @@ Cut a **release PR** from `release/` → `main`. Optional **VERSION** d 2. From the repo root: ```bash - npm run release:pr -- [VERSION] + gh workflow run "Prepare release" --ref main -f version=VERSION ``` - Or: `node scripts/create-release-pr.mjs [VERSION]`. - -3. The script bumps `package.json`, `jsr.json`, and the root `package-lock.json` versions, moves `## Unreleased` to `## VERSION - YYYY-MM-DD`, pushes `release/VERSION`, and opens a PR titled `Release VERSION`. -4. Tell the user to merge the PR after **Release check** passes. - -Actions → **Prepare release** opens the same pull request. Approve workflow runs on that PR if GitHub asks. +3. Tell the user to merge the pull request after they have looked at the diff. Prepare release runs the version, changelog, and `npm pack` checks before it pushes, because a pull request it opens does not start `pull_request` workflows. If GitHub shows **Approve workflows to run**, the user approves that so the other checks can run. ## After merge -Merging into `main` runs `.github/workflows/publish.yml`. It publishes to npm and JSR with OIDC, then creates tag `vVERSION` (for example `0.4.1` → `v0.4.1`) and a GitHub Release from the changelog section. +`.github/workflows/publish.yml` publishes to npm and JSR with OIDC, then creates tag `vVERSION` (for example `0.4.1` → `v0.4.1`) and a GitHub Release from the changelog section. Tags through `v-0.4.0` keep the `v-` prefix. Leave those tags in place. ## Do not -- Commit unrelated files on the release branch. -- Bump one version manifest and leave the others behind. `package.json`, `jsr.json`, and `package-lock.json` must match. - Enable auto-merge on the release pull request. +- Publish or tag from a workstation. diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index 2fd3c08..5428cdc 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -17,10 +17,14 @@ permissions: {} jobs: prepare: runs-on: ubuntu-24.04 + timeout-minutes: 15 permissions: contents: write pull-requests: write steps: + - name: Require main + run: test "$GITHUB_REF" = "refs/heads/main" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: main @@ -31,9 +35,67 @@ jobs: node-version: 24 package-manager-cache: false - - name: Open release pull request + - id: version env: RELEASE_VERSION: ${{ inputs.version }} - PREPARE_FROM_CHECKOUT: "1" + run: echo "version=$(node scripts/release.mjs plan)" >> "$GITHUB_OUTPUT" + + - name: Bump package version + env: + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: npm version "$RELEASE_VERSION" --no-git-tag-version + + - name: Set jsr.json version + env: + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: | + node --input-type=module <<'EOF' + import { readFileSync, writeFileSync } from "node:fs"; + const path = "jsr.json"; + const version = process.env.RELEASE_VERSION; + const text = readFileSync(path, "utf8"); + const next = text.replace(/"version": "[^"]+"/, `"version": "${version}"`); + if (next === text) { + console.error("jsr.json has no version field"); + process.exit(1); + } + writeFileSync(path, next); + EOF + + - name: Move changelog section + run: node scripts/release.mjs changelog + + - name: Create release branch + env: + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: git checkout -b "release/${RELEASE_VERSION}" + + - name: Check release + run: node scripts/release.mjs check + + - name: Build package + run: npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP" + + - name: Commit and push + env: + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add package.json jsr.json package-lock.json CHANGELOG.md + git commit -m "chore(release): bump version to ${RELEASE_VERSION}" + git push --set-upstream origin "release/${RELEASE_VERSION}" + + - name: Open pull request + env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: node scripts/create-release-pr.mjs + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: | + set -euo pipefail + node scripts/release.mjs notes > "${RUNNER_TEMP}/notes.md" + gh pr create \ + --base main \ + --head "release/${RELEASE_VERSION}" \ + --title "Release ${RELEASE_VERSION}" \ + --body-file "${RUNNER_TEMP}/notes.md" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b7298ab..9b622e9 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,11 +1,8 @@ name: Publish -# A push to main lets the release environment limit deployments to main. -# The merge commit is that push. Detect the release pull request from it. on: push: - branches: - - main + branches: [main] concurrency: group: publish-${{ github.ref }} @@ -16,47 +13,83 @@ permissions: {} jobs: gate: runs-on: ubuntu-24.04 + timeout-minutes: 15 outputs: - publish: ${{ steps.detect.outputs.publish }} + version: ${{ steps.pr.outputs.version }} permissions: contents: read pull-requests: read + steps: + - id: pr + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + ref="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls" --jq ' + [ + .[] + | select(.merged_at != null and .base.ref == "main" and .head.repo.full_name == env.GITHUB_REPOSITORY) + | .head.ref + | select(test("^release/(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$")) + | sub("^release/"; "") + ] + | if length > 1 then error("multiple release pull requests") else (.[0] // "") end + ')" + printf 'version=%s\n' "$ref" >> "$GITHUB_OUTPUT" + + publish: + needs: gate + if: success() && needs.gate.outputs.version != '' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + environment: release + permissions: + contents: read + id-token: write steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + # Omit registry-url. setup-node would set NODE_AUTH_TOKEN and npm would skip OIDC. - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 package-manager-cache: false - - id: detect - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: node scripts/create-release-pr.mjs --detect + - name: Publish to npm + run: | + unset NODE_AUTH_TOKEN NPM_TOKEN + npm publish --provenance --access public - publish: - needs: gate - if: success() && needs.gate.outputs.publish == 'true' + - name: Publish to JSR + run: npx --yes jsr@0.14.3 publish + + github-release: + needs: [gate, publish] + if: success() && needs.gate.outputs.version != '' runs-on: ubuntu-24.04 - environment: release + timeout-minutes: 15 permissions: contents: write - id-token: write - pull-requests: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - # Omit registry-url. setup-node would set NODE_AUTH_TOKEN and npm would skip OIDC. - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 package-manager-cache: false - - name: Publish to npm and JSR + - name: Create GitHub release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: node scripts/create-release-pr.mjs --publish + run: | + set -euo pipefail + V="$(node -p "require('./package.json').version")" + node scripts/release.mjs notes > "${RUNNER_TEMP}/notes.md" + gh release view "v${V}" || gh release create "v${V}" \ + --target "$GITHUB_SHA" \ + --title "$V" \ + --notes-file "${RUNNER_TEMP}/notes.md" diff --git a/.github/workflows/release-on-merge.yml b/.github/workflows/release-check.yml similarity index 75% rename from .github/workflows/release-on-merge.yml rename to .github/workflows/release-check.yml index 589c1cf..b896807 100644 --- a/.github/workflows/release-on-merge.yml +++ b/.github/workflows/release-check.yml @@ -1,8 +1,8 @@ -# Checks a release pull request before merge. publish.yml publishes after the merge reaches main. name: Release check on: pull_request: + branches: [main] permissions: {} @@ -10,6 +10,7 @@ jobs: check: name: Release check runs-on: ubuntu-24.04 + timeout-minutes: 15 permissions: contents: read steps: @@ -25,10 +26,10 @@ jobs: - name: Check version and changelog env: RELEASE_HEAD_REF: ${{ github.head_ref }} - run: node scripts/create-release-pr.mjs --check + run: node scripts/release.mjs check - name: Test the release helper run: node --test scripts/release.test.mjs - name: Build package - run: npm pack --ignore-scripts --pack-destination "${RUNNER_TEMP}" + run: npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP" diff --git a/RELEASING.md b/RELEASING.md index 2ae0705..2bab280 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -3,33 +3,28 @@ ## Cut a release 1. Add notes under `## Unreleased` in `CHANGELOG.md`. -2. Run Actions → **Prepare release**. Set `version` to `X.Y.Z`, or to `patch`, `minor`, or `major`. -3. The workflow pushes `release/X.Y.Z` and opens a pull request titled `Release X.Y.Z`. The body is the new changelog section. Merge it after **Release check** passes. -4. If the pull request shows **Approve workflows to run**, approve it. A pull request opened with the Actions token waits for that approval before checks start. +2. Run Actions → **Prepare release** on `main`. Set `version` to `X.Y.Z`, or to `patch`, `minor`, or `major`. -From a clone: + ```bash + gh workflow run "Prepare release" --ref main -f version=X.Y.Z + ``` -```bash -npm run release:pr -- X.Y.Z -``` - -`patch`, `minor`, and `major` work too. Omit the argument for a patch bump. Push the branch to this repository. +3. The workflow bumps the version, moves the changelog, runs the release checks, then pushes `release/X.Y.Z` and opens a pull request titled `Release X.Y.Z`. The body is the new changelog section. Merge the pull request yourself. +4. A pull request opened with the Actions token does not start `pull_request` workflows. Prepare release runs the checks before it pushes. If GitHub shows **Approve workflows to run**, approve it so the pull request checks can run. ## What runs -**Prepare release** creates `release/X.Y.Z` from `main`, sets the version in `package.json`, `jsr.json`, and the root `package-lock.json` fields, and moves `## Unreleased` to `## X.Y.Z - YYYY-MM-DD`. +### Prepare release -**Release check** runs on pull requests. On `release/X.Y.Z` the branch name, version manifests, and a dated changelog section must match, and `npm pack` must succeed. Other pull requests check that the manifests match and that `## Unreleased` exists. +Creates `release/X.Y.Z` from `main`. `npm version` sets `package.json` and `package-lock.json`. A small step sets `jsr.json`. `scripts/release.mjs` moves `## Unreleased` to `## X.Y.Z - YYYY-MM-DD`. The job then runs the release check and `npm pack` before the push. -**Publish** runs when a push to `main` is the merge of a `release/X.Y.Z` pull request from this repository. It publishes to npm (`npm publish --access public --provenance`, GitHub OIDC) and JSR (`npx jsr publish`, GitHub OIDC), then creates tag `vX.Y.Z` and a GitHub Release whose notes are that changelog section. The job uses the `release` environment. Other pushes to `main` stop at the gate. +### Release check -Re-run **Publish** on that commit if it fails after the registry has accepted the version. A re-run skips a registry that already has this commit and skips an existing tag. If the version is on npm or JSR from another commit, the job fails and leaves the tag uncreated. +On pull requests into `main`, the job **Release check** runs the same version and changelog check, `node --test scripts/release.test.mjs`, and `npm pack`. For a `release/X.Y.Z` head, the branch name, `package.json`, `jsr.json`, `package-lock.json`, and a dated changelog section must match. Other pull requests check that those manifests match and that `## Unreleased` exists. -### Tags +### Publish -New tags are `vX.Y.Z` (for example `v0.4.1`). - -Tags through `0.4.0` used a hyphen: `v-0.2.0` through `v-0.4.0`. Those tags stay as they are. +On a push to `main`, a short step reads the merged pull request. The `publish` job runs only for a `release/X.Y.Z` pull request from this repository. It uses the `release` environment and publishes with `npm publish --provenance --access public` and `npx --yes jsr@0.14.3 publish` (GitHub OIDC). A version already on npm or JSR fails that command. The `github-release` job then runs `gh release view` or `gh release create` for tag `vX.Y.Z`, with the changelog section as the notes. ## One-time owner setup @@ -44,5 +39,11 @@ Do this before the next release. This change does not create a tag or publish a - The new publisher must complete a publish within 2 days or it expires. Keep the current publisher until that publish succeeds, then delete the old one. 3. Confirm `@proxymesh/javascript-proxy-headers` on JSR is linked to `proxymesh/javascript-proxy-headers`. That link is JSR trusted publishing. JSR has no environment field and no token in this workflow. 4. Under Settings → Actions → General, allow GitHub Actions to create and approve pull requests. Prepare release needs that to open the pull request. -5. After the publisher with environment `release` has published once, delete repository secrets `NPM_TOKEN`, `NODE_AUTH_TOKEN`, and `JSR_TOKEN` if they are present. The publish job unsets them so a leftover token cannot take precedence over OIDC. -6. If branch protection still requires **Release on merge**, drop that check. Require **Release check** so a release pull request with a mismatched version or changelog cannot merge. +5. After the publisher with environment `release` has published once, delete repository secrets `NPM_TOKEN`, `NODE_AUTH_TOKEN`, and `JSR_TOKEN` if they are present. The npm publish step unsets `NODE_AUTH_TOKEN` and `NPM_TOKEN` so a leftover token cannot take precedence over OIDC. +6. If branch protection still requires **Release on merge**, drop that check. Require **Release check**. + +## Tags + +New tags are `vX.Y.Z` (for example `v0.4.1`). + +Tags through `0.4.0` used a hyphen: `v-0.2.0` through `v-0.4.0`. Those tags stay as they are. diff --git a/package.json b/package.json index 6c94ac8..cfccec3 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,6 @@ "LICENSE" ], "scripts": { - "release:pr": "node scripts/create-release-pr.mjs", "test:unit": "node --test test/test_connect_security.js test/test_ky_response.js", "test": "node test/test_proxy_headers.js core axios node-fetch got undici superagent ky wretch make-fetch-happen needle typed-rest-client", "test:run": "node run_tests.js", diff --git a/scripts/create-release-pr.mjs b/scripts/create-release-pr.mjs deleted file mode 100644 index 4d6f3e8..0000000 --- a/scripts/create-release-pr.mjs +++ /dev/null @@ -1,454 +0,0 @@ -#!/usr/bin/env node -/** - * Release helper. - * node scripts/create-release-pr.mjs [X.Y.Z|patch|minor|major] - * node scripts/create-release-pr.mjs --check - * node scripts/create-release-pr.mjs --detect - * node scripts/create-release-pr.mjs --publish - * - * Omit the version to bump the patch number. The pull request is left for a person to merge. - */ -import { execFileSync, spawnSync } from "node:child_process"; -import { appendFileSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; -import { fileURLToPath } from "node:url"; - -const root = join(dirname(fileURLToPath(import.meta.url)), ".."); -const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; - -function git(args) { - return execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim(); -} - -function gh(args) { - return execFileSync("gh", args, { cwd: root, encoding: "utf8" }).trim(); -} - -function parseSemver(value) { - const match = SEMVER.exec(String(value).trim()); - if (!match) throw new Error(`Version must be X.Y.Z (got ${JSON.stringify(value)}).`); - return [Number(match[1]), Number(match[2]), Number(match[3])]; -} - -export function resolveVersion(current, input) { - const raw = (input ?? "").trim(); - const spec = raw === "" ? "patch" : raw; - const [major, minor, patch] = parseSemver(current); - if (spec === "major") return `${major + 1}.0.0`; - if (spec === "minor") return `${major}.${minor + 1}.0`; - if (spec === "patch") return `${major}.${minor}.${patch + 1}`; - const [nextMajor, nextMinor, nextPatch] = parseSemver(spec); - const greater = nextMajor > major - || (nextMajor === major && nextMinor > minor) - || (nextMajor === major && nextMinor === minor && nextPatch > patch); - if (!greater) throw new Error(`New version must be greater than ${current} (got ${spec}).`); - return spec; -} - -function validDate(value) { - const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); - if (!match) return false; - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - const date = new Date(Date.UTC(year, month - 1, day)); - return date.getUTCFullYear() === year - && date.getUTCMonth() === month - 1 - && date.getUTCDate() === day; -} - -function headingPattern(version) { - parseSemver(version); - return new RegExp(`^## ${version.replaceAll(".", "\\.")} - (\\d{4}-\\d{2}-\\d{2})\\s*$`); -} - -function trimBlankLines(lines) { - let start = 0; - let end = lines.length; - while (start < end && lines[start].trim() === "") start += 1; - while (end > start && lines[end - 1].trim() === "") end -= 1; - return lines.slice(start, end); -} - -export function moveUnreleased(markdown, version, date) { - if (!validDate(date)) throw new Error(`Invalid release date ${date}.`); - const pattern = headingPattern(version); - const lines = markdown.replace(/\r\n/g, "\n").replace(/^\uFEFF/, "").split("\n"); - if (lines.some((line) => pattern.test(line))) { - throw new Error(`CHANGELOG.md already has a ${version} section.`); - } - const start = lines.findIndex((line) => /^## Unreleased\s*$/.test(line)); - if (start < 0) throw new Error("CHANGELOG.md is missing a ## Unreleased section."); - let end = lines.length; - for (let i = start + 1; i < lines.length; i += 1) { - if (lines[i].startsWith("## ")) { - end = i; - break; - } - } - const header = trimBlankLines(lines.slice(0, start)); - const body = trimBlankLines(lines.slice(start + 1, end)); - let restStart = end; - while (restStart < lines.length && lines[restStart].trim() === "") restStart += 1; - const rest = lines.slice(restStart); - const out = []; - if (header.length) out.push(...header, ""); - out.push("## Unreleased", "", `## ${version} - ${date}`); - if (body.length) out.push("", ...body); - if (rest.length) out.push("", ...rest); - return `${out.join("\n").replace(/\n+$/, "")}\n`; -} - -export function extractSection(markdown, version) { - const pattern = headingPattern(version); - const lines = markdown.replace(/\r\n/g, "\n").split("\n"); - const start = lines.findIndex((line) => pattern.test(line)); - if (start < 0) throw new Error(`CHANGELOG.md is missing a dated ${version} section.`); - const found = lines[start].match(pattern); - if (!validDate(found[1])) throw new Error(`CHANGELOG date for ${version} is invalid: ${found[1]}.`); - let end = lines.length; - for (let i = start + 1; i < lines.length; i += 1) { - if (lines[i].startsWith("## ")) { - end = i; - break; - } - } - return `${lines.slice(start, end).join("\n").trim()}\n`; -} - -export function readVersions(dir) { - const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); - const jsr = JSON.parse(readFileSync(join(dir, "jsr.json"), "utf8")); - const lock = JSON.parse(readFileSync(join(dir, "package-lock.json"), "utf8")); - return { - package: pkg.version, - jsr: jsr.version, - lock: lock.version, - lockPackage: lock.packages[""].version, - packageName: pkg.name, - jsrName: jsr.name, - }; -} - -export function requireVersion(versions, expected) { - const pkg = versions.package; - if (pkg !== versions.jsr || pkg !== versions.lock || pkg !== versions.lockPackage) { - throw new Error( - `Version mismatch: package.json=${pkg}, jsr.json=${versions.jsr}, package-lock.json=${versions.lock}, packages[""]=${versions.lockPackage}`, - ); - } - parseSemver(pkg); - if (expected !== undefined && pkg !== expected) { - throw new Error(`Version ${pkg} does not match ${expected}.`); - } -} - -function replaceVersionFields(path, from, to, count, exact) { - const needle = `"version": "${from}"`; - const next = `"version": "${to}"`; - let text = readFileSync(path, "utf8"); - const total = text.split(needle).length - 1; - if (exact && total !== count) { - throw new Error(`${path} has ${total} ${needle} fields, expected ${count}.`); - } - if (!exact && total < count) { - throw new Error(`${path} has ${total} ${needle} fields, expected at least ${count}.`); - } - let start = 0; - for (let i = 0; i < count; i += 1) { - const index = text.indexOf(needle, start); - text = `${text.slice(0, index)}${next}${text.slice(index + needle.length)}`; - start = index + next.length; - } - writeFileSync(path, text); -} - -// The first two package-lock version fields are this package. Later copies are dependencies. -export function writeVersions(dir, from, to) { - replaceVersionFields(join(dir, "package.json"), from, to, 1, true); - replaceVersionFields(join(dir, "jsr.json"), from, to, 1, true); - replaceVersionFields(join(dir, "package-lock.json"), from, to, 2, false); - requireVersion(readVersions(dir), to); -} - -function changelogText() { - return readFileSync(join(root, "CHANGELOG.md"), "utf8"); -} - -function check() { - const changelog = changelogText(); - if (!changelog.split("\n").some((line) => /^## Unreleased\s*$/.test(line))) { - throw new Error("CHANGELOG.md is missing a ## Unreleased section."); - } - const versions = readVersions(root); - const branch = (process.env.RELEASE_HEAD_REF || git(["branch", "--show-current"])).trim(); - if (branch.startsWith("release/")) { - const version = branch.slice("release/".length); - if (!SEMVER.test(version)) throw new Error(`Release branch must be release/X.Y.Z (got ${branch}).`); - requireVersion(versions, version); - extractSection(changelog, version); - console.log(`Release check passed for ${version}.`); - return; - } - requireVersion(versions); - console.log(`Version manifests match at ${versions.package}.`); -} - -function mergedReleasePull() { - const sha = process.env.GITHUB_SHA; - const repository = process.env.GITHUB_REPOSITORY; - if (!sha || !repository) throw new Error("GITHUB_SHA and GITHUB_REPOSITORY are required."); - const head = git(["rev-parse", "HEAD"]); - if (head !== sha) throw new Error(`Checkout is ${head}, expected ${sha}.`); - const pulls = JSON.parse(gh([ - "api", - `repos/${repository}/commits/${sha}/pulls`, - "-H", - "Accept: application/vnd.github+json", - ])); - const releases = pulls.filter((pr) => { - const ref = pr.head.ref; - return pr.merged_at - && pr.base.ref === "main" - && ref.startsWith("release/") - && SEMVER.test(ref.slice("release/".length)); - }); - const ours = releases.filter((pr) => pr.head.repo && pr.head.repo.full_name === repository); - if (releases.length > 0 && ours.length === 0) { - const other = releases[0].head.repo ? releases[0].head.repo.full_name : "another repository"; - throw new Error(`Release pull requests must come from ${repository} (got ${other}).`); - } - if (ours.length > 1) throw new Error(`Commit ${sha} matches multiple release pull requests.`); - return ours[0] || null; -} - -function npmGitHead(name, version) { - const spec = `${name}@${version}`; - const result = spawnSync("npm", ["view", spec, "gitHead", "--json"], { cwd: root, encoding: "utf8" }); - const output = `${result.stdout || ""}\n${result.stderr || ""}`; - if (result.status !== 0) { - if (output.includes("E404")) return { exists: false, gitHead: null }; - throw new Error(`npm view ${spec} failed: ${output.trim()}`); - } - const text = (result.stdout || "").trim(); - if (!text) return { exists: true, gitHead: null }; - const parsed = JSON.parse(text); - return { exists: true, gitHead: typeof parsed === "string" ? parsed : null }; -} - -async function jsrHasVersion(name, version) { - const response = await fetch(`https://jsr.io/${name}/meta.json`); - if (response.status === 404) return false; - if (!response.ok) throw new Error(`JSR meta for ${name} returned ${response.status}.`); - const body = await response.json(); - return Object.hasOwn(body.versions, version); -} - -function tagExists(repository, tag) { - const result = spawnSync("gh", ["api", `repos/${repository}/git/ref/tags/${tag}`], { - cwd: root, - encoding: "utf8", - }); - if (result.status === 0) return true; - const output = `${result.stdout || ""}\n${result.stderr || ""}`; - if (output.includes("404")) return false; - throw new Error(`Could not read tag ${tag}: ${output.trim()}`); -} - -function createGitHubRelease(repository, tag, version, sha, notes) { - const notesPath = join(tmpdir(), `release-notes-${version}.md`); - writeFileSync(notesPath, notes.endsWith("\n") ? notes : `${notes}\n`); - if (!tagExists(repository, tag)) { - execFileSync("gh", [ - "release", "create", tag, - "--repo", repository, - "--target", sha, - "--title", version, - "--notes-file", notesPath, - ], { cwd: root, stdio: "inherit" }); - return; - } - const existing = spawnSync("gh", ["release", "view", tag, "--repo", repository], { - cwd: root, - encoding: "utf8", - }); - if (existing.status === 0) { - console.log(`GitHub Release ${tag} already exists.`); - return; - } - const payload = join(tmpdir(), `release-${version}.json`); - writeFileSync(payload, JSON.stringify({ - tag_name: tag, - target_commitish: sha, - name: version, - body: notes, - })); - execFileSync("gh", [ - "api", "--method", "POST", `repos/${repository}/releases`, "--input", payload, - ], { cwd: root, stdio: "inherit" }); -} - -function detect() { - const pr = mergedReleasePull(); - const file = process.env.GITHUB_OUTPUT; - if (!pr) { - if (file) appendFileSync(file, "publish=false\n"); - console.log("Not a merged release pull request."); - return; - } - const version = pr.head.ref.slice("release/".length); - requireVersion(readVersions(root), version); - extractSection(changelogText(), version); - if (file) appendFileSync(file, `publish=true\nversion=${version}\n`); - console.log(`Will publish ${version} from pull request #${pr.number}.`); -} - -async function publish() { - const pr = mergedReleasePull(); - if (!pr) throw new Error("Publish expected a merged release pull request."); - const version = pr.head.ref.slice("release/".length); - const versions = readVersions(root); - requireVersion(versions, version); - const notes = extractSection(changelogText(), version); - const sha = process.env.GITHUB_SHA; - const repository = process.env.GITHUB_REPOSITORY; - const tag = `v${version}`; - const npmInfo = npmGitHead(versions.packageName, version); - const jsrHas = await jsrHasVersion(versions.jsrName, version); - if (npmInfo.exists && npmInfo.gitHead !== sha) { - throw new Error( - `${versions.packageName}@${version} is already on npm (gitHead ${npmInfo.gitHead || "missing"}, this commit ${sha}). Refusing to publish.`, - ); - } - if (jsrHas && !(npmInfo.exists && npmInfo.gitHead === sha)) { - throw new Error(`${versions.jsrName}@${version} is already on JSR. Refusing to publish.`); - } - const publishNpm = !npmInfo.exists; - const publishJsr = !jsrHas; - if (tagExists(repository, tag) && (publishNpm || publishJsr)) { - throw new Error(`Tag ${tag} already exists and ${version} is not fully published from ${sha}. Refusing to publish.`); - } - if (publishNpm || publishJsr) { - if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL || !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) { - throw new Error("GitHub OIDC is unavailable. The publish job needs id-token: write."); - } - } - // A NODE_AUTH_TOKEN or NPM_TOKEN, even an empty one, makes npm skip OIDC. - const env = { ...process.env }; - delete env.NODE_AUTH_TOKEN; - delete env.NPM_TOKEN; - delete env.JSR_TOKEN; - if (publishNpm) { - const npmVersion = execFileSync("npm", ["--version"], { cwd: root, encoding: "utf8" }).trim(); - const [major, minor, patch] = npmVersion.split(".").map(Number); - const npmOk = major > 11 || (major === 11 && (minor > 5 || (minor === 5 && patch >= 1))); - if (!npmOk) throw new Error(`npm ${npmVersion} is older than 11.5.1, which trusted publishing requires.`); - console.log(`Publishing ${versions.packageName}@${version} to npm.`); - execFileSync("npm", ["publish", "--access", "public", "--provenance"], { cwd: root, stdio: "inherit", env }); - } else { - console.log(`npm already has ${versions.packageName}@${version} from this commit.`); - } - if (publishJsr) { - console.log(`Publishing ${versions.jsrName}@${version} to JSR.`); - execFileSync("npx", ["--yes", "jsr", "publish"], { cwd: root, stdio: "inherit", env }); - } else { - console.log(`JSR already has ${versions.jsrName}@${version}.`); - } - createGitHubRelease(repository, tag, version, sha, notes); -} - -function prepare(input) { - if (process.env.PREPARE_FROM_CHECKOUT === "1") { - const currentBranch = git(["branch", "--show-current"]); - if (currentBranch !== "main") throw new Error(`Expected checkout on main, found ${currentBranch || "detached HEAD"}.`); - execFileSync("git", ["config", "user.name", "github-actions[bot]"], { cwd: root }); - execFileSync("git", ["config", "user.email", "41898282+github-actions[bot]@users.noreply.github.com"], { cwd: root }); - } else { - const status = git(["status", "--porcelain"]); - if (status) throw new Error("Working tree is not clean. Commit or stash changes before running this script."); - execFileSync("git", ["fetch", "origin", "main"], { cwd: root, stdio: "inherit" }); - execFileSync("git", ["checkout", "main"], { cwd: root, stdio: "inherit" }); - execFileSync("git", ["pull", "--ff-only", "origin", "main"], { cwd: root, stdio: "inherit" }); - } - - const current = readVersions(root); - requireVersion(current); - const version = resolveVersion(current.package, input); - const branch = `release/${version}`; - const local = spawnSync("git", ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], { cwd: root }); - if (local.status === 0) throw new Error(`Local branch ${branch} already exists.`); - if (git(["ls-remote", "--heads", "origin", branch])) { - throw new Error(`Remote branch origin/${branch} already exists.`); - } - - let created = false; - let pushed = false; - try { - execFileSync("git", ["checkout", "-b", branch], { cwd: root, stdio: "inherit" }); - created = true; - writeVersions(root, current.package, version); - const changelogPath = join(root, "CHANGELOG.md"); - const updated = moveUnreleased( - readFileSync(changelogPath, "utf8"), - version, - new Date().toISOString().slice(0, 10), - ); - writeFileSync(changelogPath, updated); - const section = extractSection(updated, version); - execFileSync("git", ["add", "package.json", "jsr.json", "package-lock.json", "CHANGELOG.md"], { cwd: root }); - execFileSync("git", ["commit", "-m", `chore(release): bump version to ${version}`], { - cwd: root, - stdio: "inherit", - }); - execFileSync("git", ["push", "--set-upstream", "origin", branch], { cwd: root, stdio: "inherit" }); - pushed = true; - const body = join(tmpdir(), `release-pr-${version}.md`); - writeFileSync(body, section); - const url = gh([ - "pr", "create", - "--base", "main", - "--head", branch, - "--title", `Release ${version}`, - "--body-file", body, - ]); - console.log(url); - console.log("Merge the pull request after Release check passes."); - } catch (error) { - if (created && !pushed) { - spawnSync("git", ["checkout", "-f", "main"], { cwd: root }); - spawnSync("git", ["branch", "-D", branch], { cwd: root }); - } - if (pushed) console.error(`Pushed ${branch}. The pull request was not created.`); - throw error; - } -} - -async function main() { - const command = process.argv[2]; - if (command === "--check") { - check(); - return; - } - if (command === "--detect") { - detect(); - return; - } - if (command === "--publish") { - await publish(); - return; - } - if (command && command.startsWith("--")) throw new Error(`Unknown command ${command}.`); - prepare(command ?? process.env.RELEASE_VERSION); -} - -const invoked = process.argv[1] - && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); -if (invoked) { - main().catch((error) => { - const message = error instanceof Error ? error.message : String(error); - if (process.env.GITHUB_ACTIONS) console.error(`::error::${message}`); - else console.error(message); - process.exit(1); - }); -} diff --git a/scripts/release.mjs b/scripts/release.mjs new file mode 100644 index 0000000..73945d6 --- /dev/null +++ b/scripts/release.mjs @@ -0,0 +1,147 @@ +#!/usr/bin/env node +/** + * Changelog and release check. + * node scripts/release.mjs plan|changelog|notes|check + */ +import { execFileSync } from "node:child_process"; +import { readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +function parseSemver(value) { + const match = SEMVER.exec(String(value).trim()); + if (!match) throw new Error(`Version must be X.Y.Z, patch, minor, or major (got ${JSON.stringify(value)}).`); + return [Number(match[1]), Number(match[2]), Number(match[3])]; +} + +export function resolveVersion(current, input) { + const spec = String(input ?? "").trim(); + const [major, minor, patch] = parseSemver(current); + if (spec === "major") return `${major + 1}.0.0`; + if (spec === "minor") return `${major}.${minor + 1}.0`; + if (spec === "patch") return `${major}.${minor}.${patch + 1}`; + const [nextMajor, nextMinor, nextPatch] = parseSemver(spec); + const greater = nextMajor > major + || (nextMajor === major && nextMinor > minor) + || (nextMajor === major && nextMinor === minor && nextPatch > patch); + if (!greater) throw new Error(`New version must be greater than ${current} (got ${spec}).`); + return spec; +} + +function validDate(value) { + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); + if (!match) return false; + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const date = new Date(Date.UTC(year, month - 1, day)); + return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day; +} + +function heading(version) { + parseSemver(version); + return new RegExp(`^## ${version.replaceAll(".", "\\.")} - (\\d{4}-\\d{2}-\\d{2})\\s*$`); +} + +function unreleasedAt(lines) { + return lines.findIndex((line) => /^## Unreleased\s*$/.test(line)); +} + +function nextHeading(lines, start) { + for (let i = start + 1; i < lines.length; i += 1) { + if (lines[i].startsWith("## ")) return i; + } + return lines.length; +} + +export function moveUnreleased(markdown, version, date) { + if (!validDate(date)) throw new Error(`Invalid release date ${date}.`); + const lines = markdown.replace(/\r\n/g, "\n").replace(/^\uFEFF/, "").split("\n"); + if (lines.some((line) => heading(version).test(line))) throw new Error(`CHANGELOG.md already has a ${version} section.`); + const start = unreleasedAt(lines); + if (start < 0) throw new Error("CHANGELOG.md is missing a ## Unreleased section."); + const end = nextHeading(lines, start); + const header = lines.slice(0, start).join("\n").trim(); + const body = lines.slice(start + 1, end).join("\n").trim(); + const rest = lines.slice(end).join("\n").trim(); + const out = []; + if (header) out.push(header, ""); + out.push("## Unreleased", "", `## ${version} - ${date}`); + if (body) out.push("", body); + if (rest) out.push("", rest); + return `${out.join("\n")}\n`; +} + +export function extractSection(markdown, version) { + const pattern = heading(version); + const lines = markdown.replace(/\r\n/g, "\n").split("\n"); + const start = lines.findIndex((line) => pattern.test(line)); + if (start < 0) throw new Error(`CHANGELOG.md is missing a dated ${version} section.`); + const found = lines[start].match(pattern); + if (!validDate(found[1])) throw new Error(`CHANGELOG date for ${version} is invalid: ${found[1]}.`); + return `${lines.slice(start, nextHeading(lines, start)).join("\n").trim()}\n`; +} + +function manifestVersion() { + const pkg = JSON.parse(readFileSync("package.json", "utf8")).version; + const jsr = JSON.parse(readFileSync("jsr.json", "utf8")).version; + const lock = JSON.parse(readFileSync("package-lock.json", "utf8")); + const lockPackage = lock.packages[""].version; + if (pkg !== jsr || pkg !== lock.version || pkg !== lockPackage) { + throw new Error(`Version mismatch: package.json=${pkg}, jsr.json=${jsr}, package-lock.json=${lock.version}, packages[""]=${lockPackage}`); + } + parseSemver(pkg); + return pkg; +} + +function check() { + const version = manifestVersion(); + const text = readFileSync("CHANGELOG.md", "utf8"); + if (unreleasedAt(text.replace(/\r\n/g, "\n").split("\n")) < 0) { + throw new Error("CHANGELOG.md is missing a ## Unreleased section."); + } + const branch = (process.env.RELEASE_HEAD_REF ?? execFileSync("git", ["branch", "--show-current"], { encoding: "utf8" })).trim(); + if (!branch.startsWith("release/")) { + console.log(`Version manifests match at ${version}.`); + return; + } + const name = branch.slice("release/".length); + if (!SEMVER.test(name)) throw new Error(`Release branch must be release/X.Y.Z (got ${branch}).`); + if (name !== version) throw new Error(`Version ${version} does not match ${name}.`); + extractSection(text, version); + console.log(`Release check passed for ${version}.`); +} + +function main() { + const command = process.argv[2]; + if (command === "plan") { + const input = process.argv[3] ?? process.env.RELEASE_VERSION; + process.stdout.write(`${resolveVersion(manifestVersion(), input)}\n`); + return; + } + if (command === "changelog") { + const path = "CHANGELOG.md"; + writeFileSync(path, moveUnreleased(readFileSync(path, "utf8"), manifestVersion(), new Date().toISOString().slice(0, 10))); + return; + } + if (command === "notes") { + process.stdout.write(extractSection(readFileSync("CHANGELOG.md", "utf8"), manifestVersion())); + return; + } + if (command === "check") { + check(); + return; + } + throw new Error(`Unknown command ${JSON.stringify(command)}.`); +} + +const entry = process.argv[1]; +if (entry !== undefined && realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url))) { + try { + main(); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); + } +} diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs index 47a0723..e22b73b 100644 --- a/scripts/release.test.mjs +++ b/scripts/release.test.mjs @@ -1,134 +1,45 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { cpSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { - extractSection, - moveUnreleased, - readVersions, - requireVersion, - resolveVersion, - writeVersions, -} from "./create-release-pr.mjs"; +import { extractSection, moveUnreleased, resolveVersion } from "./release.mjs"; const root = join(dirname(fileURLToPath(import.meta.url)), ".."); -test("resolveVersion bumps and rejects older versions", () => { - assert.equal(resolveVersion("1.2.3", ""), "1.2.4"); +test("resolveVersion bumps and rejects an older version", () => { assert.equal(resolveVersion("1.2.3", "patch"), "1.2.4"); assert.equal(resolveVersion("1.2.3", "minor"), "1.3.0"); assert.equal(resolveVersion("1.2.3", "major"), "2.0.0"); - assert.equal(resolveVersion("1.2.3", "1.2.4"), "1.2.4"); + assert.equal(resolveVersion("1.2.3", "1.4.0"), "1.4.0"); assert.throws(() => resolveVersion("1.2.3", "1.2.3"), /greater than/); assert.throws(() => resolveVersion("1.2.3", "v1.2.4"), /X\.Y\.Z/); }); -test("moveUnreleased keeps older sections and the empty heading", () => { - const source = [ - "# Changelog", - "", - "## Unreleased", - "", - "- Ship the release flow.", - "", - "## 0.4.0 - 2026-11-02", - "", - "- Older.", - "", - ].join("\n"); +test("moveUnreleased keeps the notes and the empty heading", () => { + const source = "# Changelog\n\n## Unreleased\n\n- Ship it.\n\n## 0.4.0 - 2026-11-02\n\n- Older.\n"; const moved = moveUnreleased(source, "0.4.1", "2026-11-12"); - assert.equal(moved, [ - "# Changelog", - "", - "## Unreleased", - "", - "## 0.4.1 - 2026-11-12", - "", - "- Ship the release flow.", - "", - "## 0.4.0 - 2026-11-02", - "", - "- Older.", - "", - ].join("\n")); - assert.equal(extractSection(moved, "0.4.1"), [ - "## 0.4.1 - 2026-11-12", - "", - "- Ship the release flow.", - "", - ].join("\n")); + assert.equal(moved, "# Changelog\n\n## Unreleased\n\n## 0.4.1 - 2026-11-12\n\n- Ship it.\n\n## 0.4.0 - 2026-11-02\n\n- Older.\n"); + assert.equal(extractSection(moved, "0.4.1"), "## 0.4.1 - 2026-11-12\n\n- Ship it.\n"); assert.throws(() => moveUnreleased(moved, "0.4.1", "2026-11-12"), /already has/); - assert.throws(() => moveUnreleased(source, "0.4.1", "2026-02-31"), /Invalid release date/); }); -test("moveUnreleased accepts an empty Unreleased section", () => { - const source = "# Changelog\r\n\r\n## Unreleased\r\n\r\n## 0.4.0 - 2026-11-02\r\n\r\n- Older.\r\n"; - const moved = moveUnreleased(source, "0.5.0", "2026-12-01"); - assert.equal(moved.includes("\r"), false); - assert.match(moved, /^# Changelog\n\n## Unreleased\n\n## 0\.5\.0 - 2026-12-01\n\n## 0\.4\.0 - 2026-11-02\n\n- Older\.\n$/); -}); - -test("writeVersions updates only this package in the lockfile", () => { - const dir = mkdtempSync(join(tmpdir(), "release-versions-")); - try { - for (const name of ["package.json", "jsr.json", "package-lock.json"]) { - cpSync(join(root, name), join(dir, name)); - } - const from = readVersions(dir).package; - const to = resolveVersion(from, "patch"); - const packageBefore = readFileSync(join(dir, "package.json"), "utf8"); - const jsrBefore = readFileSync(join(dir, "jsr.json"), "utf8"); - const lockBefore = readFileSync(join(dir, "package-lock.json"), "utf8"); - const needle = `"version": "${from}"`; - const beforeCount = lockBefore.split(needle).length - 1; - writeVersions(dir, from, to); - assert.equal( - readFileSync(join(dir, "package.json"), "utf8"), - packageBefore.replace(needle, `"version": "${to}"`), - ); - assert.equal( - readFileSync(join(dir, "jsr.json"), "utf8"), - jsrBefore.replace(needle, `"version": "${to}"`), - ); - let expectedLock = lockBefore; - for (let i = 0; i < 2; i += 1) expectedLock = expectedLock.replace(needle, `"version": "${to}"`); - const lockAfter = readFileSync(join(dir, "package-lock.json"), "utf8"); - assert.equal(lockAfter, expectedLock); - assert.equal(lockAfter.split(needle).length - 1, beforeCount - 2); - requireVersion(readVersions(dir), to); - } finally { - rmSync(dir, { recursive: true, force: true }); - } -}); - -test("check accepts the working tree and rejects a mismatched release branch", () => { - const version = readVersions(root).package; - const ok = spawnSync("node", ["scripts/create-release-pr.mjs", "--check"], { - cwd: root, - encoding: "utf8", - }); +test("check accepts this tree and rejects a mismatched release branch", () => { + const version = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version; + const ok = spawnSync(process.execPath, ["scripts/release.mjs", "check"], { cwd: root, encoding: "utf8" }); assert.equal(ok.status, 0, ok.stderr); - const release = spawnSync("node", ["scripts/create-release-pr.mjs", "--check"], { + const release = spawnSync(process.execPath, ["scripts/release.mjs", "check"], { cwd: root, encoding: "utf8", env: { ...process.env, RELEASE_HEAD_REF: `release/${version}` }, }); assert.equal(release.status, 0, release.stderr); - const mismatch = spawnSync("node", ["scripts/create-release-pr.mjs", "--check"], { + const mismatch = spawnSync(process.execPath, ["scripts/release.mjs", "check"], { cwd: root, encoding: "utf8", env: { ...process.env, RELEASE_HEAD_REF: "release/9.9.9" }, }); assert.equal(mismatch.status, 1); assert.match(mismatch.stderr, /does not match 9\.9\.9/); - const named = spawnSync("node", ["scripts/create-release-pr.mjs", "--check"], { - cwd: root, - encoding: "utf8", - env: { ...process.env, RELEASE_HEAD_REF: "release/not-a-version" }, - }); - assert.equal(named.status, 1); - assert.match(named.stderr, /release\/X\.Y\.Z/); }); From 9cb686e0e461736e2b195c1a736c6f894a1ba8ba Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:31:11 +0000 Subject: [PATCH 3/7] Apply the release review notes. Move the jsr.json bump into release.mjs, check the release version before publish, and stop telling the owner to require Release check. Co-authored-by: ProxyMesh AI --- .cursor/skills/release/SKILL.md | 2 +- .github/workflows/prepare-release.yml | 16 +----- .github/workflows/publish.yml | 11 ++-- RELEASING.md | 9 ++-- scripts/release.mjs | 73 ++++++++------------------- 5 files changed, 35 insertions(+), 76 deletions(-) diff --git a/.cursor/skills/release/SKILL.md b/.cursor/skills/release/SKILL.md index 542a2c8..dee34cc 100644 --- a/.cursor/skills/release/SKILL.md +++ b/.cursor/skills/release/SKILL.md @@ -26,7 +26,7 @@ In chat, users may type **`/release`** (patch bump), **`/release minor`**, **`/r gh workflow run "Prepare release" --ref main -f version=VERSION ``` -3. Tell the user to merge the pull request after they have looked at the diff. Prepare release runs the version, changelog, and `npm pack` checks before it pushes, because a pull request it opens does not start `pull_request` workflows. If GitHub shows **Approve workflows to run**, the user approves that so the other checks can run. +3. Tell the user to merge the pull request after they have looked at the diff. Prepare release runs the version, changelog, and `npm pack` checks before it pushes, because a pull request it opens does not start `pull_request` workflows. To run pull request checks on it, close and reopen the pull request. ## After merge diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index 5428cdc..bcd6c5e 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -46,21 +46,7 @@ jobs: run: npm version "$RELEASE_VERSION" --no-git-tag-version - name: Set jsr.json version - env: - RELEASE_VERSION: ${{ steps.version.outputs.version }} - run: | - node --input-type=module <<'EOF' - import { readFileSync, writeFileSync } from "node:fs"; - const path = "jsr.json"; - const version = process.env.RELEASE_VERSION; - const text = readFileSync(path, "utf8"); - const next = text.replace(/"version": "[^"]+"/, `"version": "${version}"`); - if (next === text) { - console.error("jsr.json has no version field"); - process.exit(1); - } - writeFileSync(path, next); - EOF + run: node scripts/release.mjs bump - name: Move changelog section run: node scripts/release.mjs changelog diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 9b622e9..0094814 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -57,6 +57,11 @@ jobs: node-version: 24 package-manager-cache: false + - name: Check release + env: + RELEASE_HEAD_REF: release/${{ needs.gate.outputs.version }} + run: node scripts/release.mjs check + - name: Publish to npm run: | unset NODE_AUTH_TOKEN NPM_TOKEN @@ -85,11 +90,11 @@ jobs: - name: Create GitHub release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VERSION: ${{ needs.gate.outputs.version }} run: | set -euo pipefail - V="$(node -p "require('./package.json').version")" node scripts/release.mjs notes > "${RUNNER_TEMP}/notes.md" - gh release view "v${V}" || gh release create "v${V}" \ + gh release view "v${VERSION}" || gh release create "v${VERSION}" \ --target "$GITHUB_SHA" \ - --title "$V" \ + --title "v${VERSION}" \ --notes-file "${RUNNER_TEMP}/notes.md" diff --git a/RELEASING.md b/RELEASING.md index 2bab280..b46a848 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -10,13 +10,13 @@ ``` 3. The workflow bumps the version, moves the changelog, runs the release checks, then pushes `release/X.Y.Z` and opens a pull request titled `Release X.Y.Z`. The body is the new changelog section. Merge the pull request yourself. -4. A pull request opened with the Actions token does not start `pull_request` workflows. Prepare release runs the checks before it pushes. If GitHub shows **Approve workflows to run**, approve it so the pull request checks can run. +4. A pull request opened with the Actions token does not start `pull_request` workflows. Prepare release runs the checks before it pushes. To run pull request checks on it, close and reopen the pull request. ## What runs ### Prepare release -Creates `release/X.Y.Z` from `main`. `npm version` sets `package.json` and `package-lock.json`. A small step sets `jsr.json`. `scripts/release.mjs` moves `## Unreleased` to `## X.Y.Z - YYYY-MM-DD`. The job then runs the release check and `npm pack` before the push. +Creates `release/X.Y.Z` from `main`. `npm version` sets `package.json` and `package-lock.json`. `scripts/release.mjs bump` sets `jsr.json`, then the script moves `## Unreleased` to `## X.Y.Z - YYYY-MM-DD`. The job then runs the release check and `npm pack` before the push. ### Release check @@ -35,12 +35,11 @@ Do this before the next release. This change does not create a tag or publish a - Package `javascript-proxy-headers` on npmjs.com → Settings → Trusted Publisher → Add - Organization `proxymesh`, repository `javascript-proxy-headers`, workflow filename `publish.yml` - Environment name `release` - - Allow direct `npm publish`. Publishers created after 3 Sep 2026 default to staged publish, and this workflow runs `npm publish`. - - The new publisher must complete a publish within 2 days or it expires. Keep the current publisher until that publish succeeds, then delete the old one. + - Allow direct `npm publish`. Keep the current publisher until a publish with environment `release` succeeds, then delete the old one. 3. Confirm `@proxymesh/javascript-proxy-headers` on JSR is linked to `proxymesh/javascript-proxy-headers`. That link is JSR trusted publishing. JSR has no environment field and no token in this workflow. 4. Under Settings → Actions → General, allow GitHub Actions to create and approve pull requests. Prepare release needs that to open the pull request. 5. After the publisher with environment `release` has published once, delete repository secrets `NPM_TOKEN`, `NODE_AUTH_TOKEN`, and `JSR_TOKEN` if they are present. The npm publish step unsets `NODE_AUTH_TOKEN` and `NPM_TOKEN` so a leftover token cannot take precedence over OIDC. -6. If branch protection still requires **Release on merge**, drop that check. Require **Release check**. +6. If branch protection still requires Release on merge, drop it. Don't make Release check a required check: release PRs are opened with GITHUB_TOKEN, so it doesn't run on them unless you close and reopen the PR. ## Tags diff --git a/scripts/release.mjs b/scripts/release.mjs index 73945d6..ee4cf75 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -1,20 +1,14 @@ #!/usr/bin/env node -/** - * Changelog and release check. - * node scripts/release.mjs plan|changelog|notes|check - */ +/** Changelog and release check: plan, bump, changelog, notes, check. */ import { execFileSync } from "node:child_process"; import { readFileSync, realpathSync, writeFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; - const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; - function parseSemver(value) { const match = SEMVER.exec(String(value).trim()); if (!match) throw new Error(`Version must be X.Y.Z, patch, minor, or major (got ${JSON.stringify(value)}).`); return [Number(match[1]), Number(match[2]), Number(match[3])]; } - export function resolveVersion(current, input) { const spec = String(input ?? "").trim(); const [major, minor, patch] = parseSemver(current); @@ -22,44 +16,21 @@ export function resolveVersion(current, input) { if (spec === "minor") return `${major}.${minor + 1}.0`; if (spec === "patch") return `${major}.${minor}.${patch + 1}`; const [nextMajor, nextMinor, nextPatch] = parseSemver(spec); - const greater = nextMajor > major - || (nextMajor === major && nextMinor > minor) - || (nextMajor === major && nextMinor === minor && nextPatch > patch); + const greater = nextMajor > major || (nextMajor === major && nextMinor > minor) || (nextMajor === major && nextMinor === minor && nextPatch > patch); if (!greater) throw new Error(`New version must be greater than ${current} (got ${spec}).`); return spec; } - -function validDate(value) { - const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); - if (!match) return false; - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - const date = new Date(Date.UTC(year, month - 1, day)); - return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day; -} - function heading(version) { - parseSemver(version); - return new RegExp(`^## ${version.replaceAll(".", "\\.")} - (\\d{4}-\\d{2}-\\d{2})\\s*$`); -} - -function unreleasedAt(lines) { - return lines.findIndex((line) => /^## Unreleased\s*$/.test(line)); + return new RegExp(`^## ${version.replaceAll(".", "\\.")} - \\d{4}-\\d{2}-\\d{2}\\s*$`); } - function nextHeading(lines, start) { - for (let i = start + 1; i < lines.length; i += 1) { - if (lines[i].startsWith("## ")) return i; - } - return lines.length; + const index = lines.findIndex((line, i) => i > start && line.startsWith("## ")); + return index < 0 ? lines.length : index; } - export function moveUnreleased(markdown, version, date) { - if (!validDate(date)) throw new Error(`Invalid release date ${date}.`); - const lines = markdown.replace(/\r\n/g, "\n").replace(/^\uFEFF/, "").split("\n"); + const lines = markdown.split("\n"); if (lines.some((line) => heading(version).test(line))) throw new Error(`CHANGELOG.md already has a ${version} section.`); - const start = unreleasedAt(lines); + const start = lines.findIndex((line) => /^## Unreleased\s*$/.test(line)); if (start < 0) throw new Error("CHANGELOG.md is missing a ## Unreleased section."); const end = nextHeading(lines, start); const header = lines.slice(0, start).join("\n").trim(); @@ -72,17 +43,12 @@ export function moveUnreleased(markdown, version, date) { if (rest) out.push("", rest); return `${out.join("\n")}\n`; } - export function extractSection(markdown, version) { - const pattern = heading(version); - const lines = markdown.replace(/\r\n/g, "\n").split("\n"); - const start = lines.findIndex((line) => pattern.test(line)); + const lines = markdown.split("\n"); + const start = lines.findIndex((line) => heading(version).test(line)); if (start < 0) throw new Error(`CHANGELOG.md is missing a dated ${version} section.`); - const found = lines[start].match(pattern); - if (!validDate(found[1])) throw new Error(`CHANGELOG date for ${version} is invalid: ${found[1]}.`); return `${lines.slice(start, nextHeading(lines, start)).join("\n").trim()}\n`; } - function manifestVersion() { const pkg = JSON.parse(readFileSync("package.json", "utf8")).version; const jsr = JSON.parse(readFileSync("jsr.json", "utf8")).version; @@ -94,11 +60,17 @@ function manifestVersion() { parseSemver(pkg); return pkg; } - +function bump() { + const version = JSON.parse(readFileSync("package.json", "utf8")).version; + const text = readFileSync("jsr.json", "utf8"); + const next = text.replace(/"version": "[^"]+"/, `"version": "${version}"`); + if (next === text) throw new Error("jsr.json has no version field."); + writeFileSync("jsr.json", next); +} function check() { const version = manifestVersion(); const text = readFileSync("CHANGELOG.md", "utf8"); - if (unreleasedAt(text.replace(/\r\n/g, "\n").split("\n")) < 0) { + if (!text.split("\n").some((line) => /^## Unreleased\s*$/.test(line))) { throw new Error("CHANGELOG.md is missing a ## Unreleased section."); } const branch = (process.env.RELEASE_HEAD_REF ?? execFileSync("git", ["branch", "--show-current"], { encoding: "utf8" })).trim(); @@ -112,7 +84,6 @@ function check() { extractSection(text, version); console.log(`Release check passed for ${version}.`); } - function main() { const command = process.argv[2]; if (command === "plan") { @@ -120,22 +91,20 @@ function main() { process.stdout.write(`${resolveVersion(manifestVersion(), input)}\n`); return; } + if (command === "bump") return bump(); if (command === "changelog") { const path = "CHANGELOG.md"; - writeFileSync(path, moveUnreleased(readFileSync(path, "utf8"), manifestVersion(), new Date().toISOString().slice(0, 10))); + const date = new Date().toISOString().slice(0, 10); + writeFileSync(path, moveUnreleased(readFileSync(path, "utf8"), manifestVersion(), date)); return; } if (command === "notes") { process.stdout.write(extractSection(readFileSync("CHANGELOG.md", "utf8"), manifestVersion())); return; } - if (command === "check") { - check(); - return; - } + if (command === "check") return check(); throw new Error(`Unknown command ${JSON.stringify(command)}.`); } - const entry = process.argv[1]; if (entry !== undefined && realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url))) { try { From 43fc6ee1eb1cf68db6bd8cc5351643b3cb575fda Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:45:16 +0000 Subject: [PATCH 4/7] Rename the publish lookup job to match the other repos. A push to main always runs lookup. publish and github-release run only after a release pull request from this repository. Co-authored-by: ProxyMesh AI --- .github/workflows/publish.yml | 14 +++++++------- RELEASING.md | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 0094814..b99a763 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -11,7 +11,7 @@ concurrency: permissions: {} jobs: - gate: + lookup: runs-on: ubuntu-24.04 timeout-minutes: 15 outputs: @@ -38,8 +38,8 @@ jobs: printf 'version=%s\n' "$ref" >> "$GITHUB_OUTPUT" publish: - needs: gate - if: success() && needs.gate.outputs.version != '' + needs: lookup + if: success() && needs.lookup.outputs.version != '' runs-on: ubuntu-24.04 timeout-minutes: 15 environment: release @@ -59,7 +59,7 @@ jobs: - name: Check release env: - RELEASE_HEAD_REF: release/${{ needs.gate.outputs.version }} + RELEASE_HEAD_REF: release/${{ needs.lookup.outputs.version }} run: node scripts/release.mjs check - name: Publish to npm @@ -71,8 +71,8 @@ jobs: run: npx --yes jsr@0.14.3 publish github-release: - needs: [gate, publish] - if: success() && needs.gate.outputs.version != '' + needs: [lookup, publish] + if: needs.lookup.outputs.version != '' && needs.publish.result == 'success' runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: @@ -90,7 +90,7 @@ jobs: - name: Create GitHub release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - VERSION: ${{ needs.gate.outputs.version }} + VERSION: ${{ needs.lookup.outputs.version }} run: | set -euo pipefail node scripts/release.mjs notes > "${RUNNER_TEMP}/notes.md" diff --git a/RELEASING.md b/RELEASING.md index b46a848..c909d49 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -24,7 +24,7 @@ On pull requests into `main`, the job **Release check** runs the same version an ### Publish -On a push to `main`, a short step reads the merged pull request. The `publish` job runs only for a `release/X.Y.Z` pull request from this repository. It uses the `release` environment and publishes with `npm publish --provenance --access public` and `npx --yes jsr@0.14.3 publish` (GitHub OIDC). A version already on npm or JSR fails that command. The `github-release` job then runs `gh release view` or `gh release create` for tag `vX.Y.Z`, with the changelog section as the notes. +A push to `main` runs **lookup**. When the merged pull request comes from this repo, targets `main`, and its branch is `release/X.Y.Z`, **publish** and **github-release** run; otherwise they are skipped and the `release` environment is not used. **publish** uses that environment and publishes with `npm publish --provenance --access public` and `npx --yes jsr@0.14.3 publish` (GitHub OIDC). A version already on npm or JSR fails that command. **github-release** then runs `gh release view` or `gh release create` for tag `vX.Y.Z`, with the changelog section as the notes. ## One-time owner setup From 63885b5ed711b89aa51e9f20aee6b3c150c1cdc9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 23:51:17 +0000 Subject: [PATCH 5/7] Stop using a GitHub release environment. Publish uses OIDC without a deployment environment. RELEASING.md tells the owner to leave the npm trusted publisher environment field blank. Co-authored-by: ProxyMesh AI --- .github/workflows/publish.yml | 1 - RELEASING.md | 17 ++++++++--------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b99a763..51b10f7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -42,7 +42,6 @@ jobs: if: success() && needs.lookup.outputs.version != '' runs-on: ubuntu-24.04 timeout-minutes: 15 - environment: release permissions: contents: read id-token: write diff --git a/RELEASING.md b/RELEASING.md index c909d49..548e614 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -24,22 +24,21 @@ On pull requests into `main`, the job **Release check** runs the same version an ### Publish -A push to `main` runs **lookup**. When the merged pull request comes from this repo, targets `main`, and its branch is `release/X.Y.Z`, **publish** and **github-release** run; otherwise they are skipped and the `release` environment is not used. **publish** uses that environment and publishes with `npm publish --provenance --access public` and `npx --yes jsr@0.14.3 publish` (GitHub OIDC). A version already on npm or JSR fails that command. **github-release** then runs `gh release view` or `gh release create` for tag `vX.Y.Z`, with the changelog section as the notes. +A push to `main` runs **lookup**. When the merged pull request comes from this repo, targets `main`, and its branch is `release/X.Y.Z`, **publish** and **github-release** run; otherwise they are skipped. **publish** publishes with `npm publish --provenance --access public` and `npx --yes jsr@0.14.3 publish` (GitHub OIDC). A version already on npm or JSR fails that command. **github-release** then runs `gh release view` or `gh release create` for tag `vX.Y.Z`, with the changelog section as the notes. ## One-time owner setup Do this before the next release. This change does not create a tag or publish a package. -1. Create a GitHub Environment named `release` (Settings → Environments). Publish runs on a push to `main`, so a deployment-branch rule can limit it to `main`. Required reviewers are optional. -2. npm already uses trusted publishing. Add a publisher for the environment. A saved publisher cannot be edited, so add a second one: +1. npm already uses trusted publishing. Add a publisher. A saved publisher cannot be edited, so add a second one: - Package `javascript-proxy-headers` on npmjs.com → Settings → Trusted Publisher → Add - Organization `proxymesh`, repository `javascript-proxy-headers`, workflow filename `publish.yml` - - Environment name `release` - - Allow direct `npm publish`. Keep the current publisher until a publish with environment `release` succeeds, then delete the old one. -3. Confirm `@proxymesh/javascript-proxy-headers` on JSR is linked to `proxymesh/javascript-proxy-headers`. That link is JSR trusted publishing. JSR has no environment field and no token in this workflow. -4. Under Settings → Actions → General, allow GitHub Actions to create and approve pull requests. Prepare release needs that to open the pull request. -5. After the publisher with environment `release` has published once, delete repository secrets `NPM_TOKEN`, `NODE_AUTH_TOKEN`, and `JSR_TOKEN` if they are present. The npm publish step unsets `NODE_AUTH_TOKEN` and `NPM_TOKEN` so a leftover token cannot take precedence over OIDC. -6. If branch protection still requires Release on merge, drop it. Don't make Release check a required check: release PRs are opened with GITHUB_TOKEN, so it doesn't run on them unless you close and reopen the PR. + - Environment name: leave blank + - Allow direct `npm publish`. Keep the current publisher until a publish with the new settings succeeds, then delete the old one. +2. Confirm `@proxymesh/javascript-proxy-headers` on JSR is linked to `proxymesh/javascript-proxy-headers`. That link is JSR trusted publishing. JSR has no environment field and no token in this workflow. +3. Under Settings → Actions → General, allow GitHub Actions to create and approve pull requests. Prepare release needs that to open the pull request. +4. After trusted publishing has published once, delete repository secrets `NPM_TOKEN`, `NODE_AUTH_TOKEN`, and `JSR_TOKEN` if they are present. The npm publish step unsets `NODE_AUTH_TOKEN` and `NPM_TOKEN` so a leftover token cannot take precedence over OIDC. +5. If branch protection still requires Release on merge, drop it. Don't make Release check a required check: release PRs are opened with GITHUB_TOKEN, so it doesn't run on them unless you close and reopen the PR. ## Tags From 6ce721ee53443fadc718846244c3562fe8b9a631 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 23:52:15 +0000 Subject: [PATCH 6/7] Clarify when to add a second npm trusted publisher. Owner setup step 1 says to verify the existing publisher first and only replace it when workflow or environment differs. Co-authored-by: ProxyMesh AI --- RELEASING.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/RELEASING.md b/RELEASING.md index 548e614..c31ce68 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -30,11 +30,12 @@ A push to `main` runs **lookup**. When the merged pull request comes from this r Do this before the next release. This change does not create a tag or publish a package. -1. npm already uses trusted publishing. Add a publisher. A saved publisher cannot be edited, so add a second one: - - Package `javascript-proxy-headers` on npmjs.com → Settings → Trusted Publisher → Add - - Organization `proxymesh`, repository `javascript-proxy-headers`, workflow filename `publish.yml` - - Environment name: leave blank - - Allow direct `npm publish`. Keep the current publisher until a publish with the new settings succeeds, then delete the old one. +1. On npmjs.com, open package `javascript-proxy-headers` → Settings → Trusted + Publisher and check the existing entry. A match is organization `proxymesh`, + repository `javascript-proxy-headers`, workflow `publish.yml`, environment + blank, and allow `npm publish`. If it matches, you are done. If the workflow + or environment differs, add a publisher with those values (saved publishers + cannot be edited), publish once successfully, then delete the old one. 2. Confirm `@proxymesh/javascript-proxy-headers` on JSR is linked to `proxymesh/javascript-proxy-headers`. That link is JSR trusted publishing. JSR has no environment field and no token in this workflow. 3. Under Settings → Actions → General, allow GitHub Actions to create and approve pull requests. Prepare release needs that to open the pull request. 4. After trusted publishing has published once, delete repository secrets `NPM_TOKEN`, `NODE_AUTH_TOKEN`, and `JSR_TOKEN` if they are present. The npm publish step unsets `NODE_AUTH_TOKEN` and `NPM_TOKEN` so a leftover token cannot take precedence over OIDC. From 13dc9eedd10f1d5d35bc932580214f8ffa23f251 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 13 Nov 2026 00:16:45 +0000 Subject: [PATCH 7/7] Trim owner setup to repository settings only. Remove npm, JSR, and secret steps from RELEASING.md; trusted publishing is already configured. Co-authored-by: ProxyMesh AI --- RELEASING.md | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/RELEASING.md b/RELEASING.md index c31ce68..fdcf99f 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -28,18 +28,11 @@ A push to `main` runs **lookup**. When the merged pull request comes from this r ## One-time owner setup -Do this before the next release. This change does not create a tag or publish a package. - -1. On npmjs.com, open package `javascript-proxy-headers` → Settings → Trusted - Publisher and check the existing entry. A match is organization `proxymesh`, - repository `javascript-proxy-headers`, workflow `publish.yml`, environment - blank, and allow `npm publish`. If it matches, you are done. If the workflow - or environment differs, add a publisher with those values (saved publishers - cannot be edited), publish once successfully, then delete the old one. -2. Confirm `@proxymesh/javascript-proxy-headers` on JSR is linked to `proxymesh/javascript-proxy-headers`. That link is JSR trusted publishing. JSR has no environment field and no token in this workflow. -3. Under Settings → Actions → General, allow GitHub Actions to create and approve pull requests. Prepare release needs that to open the pull request. -4. After trusted publishing has published once, delete repository secrets `NPM_TOKEN`, `NODE_AUTH_TOKEN`, and `JSR_TOKEN` if they are present. The npm publish step unsets `NODE_AUTH_TOKEN` and `NPM_TOKEN` so a leftover token cannot take precedence over OIDC. -5. If branch protection still requires Release on merge, drop it. Don't make Release check a required check: release PRs are opened with GITHUB_TOKEN, so it doesn't run on them unless you close and reopen the PR. +1. Under Settings → Actions → General, allow GitHub Actions to create and approve + pull requests. Prepare release needs that to open the pull request. +2. If branch protection still requires Release on merge, drop it. Don't make + Release check a required check: release PRs are opened with GITHUB_TOKEN, so + it doesn't run on them unless you close and reopen the PR. ## Tags