npm-publish.yml
This file
Path
.github/workflows/npm-publish.yml
78 lines · 2.8 KiB · YAML
Last changed by
ci: add npm staged publication with dist-tag support (#7464)Ulises Gascónbefore adoption3ce6d0e
History of this fileTake it
ci: add npm staged publication with dist-tag support (#7464)Ulises Gascónbefore adoption3ce6d0e
lines 1–78why, one step back1name: Publish package to npm23on:4 release:5 # "created" does not fire when a draft release is published, "published" does6 types: [published]78concurrency:9 group: "${{ github.workflow }} ✨ ${{ github.ref }}"10 cancel-in-progress: false1112permissions:13 contents: read1415jobs:16 publish:17 name: Publish to npm18 runs-on: ubuntu-latest19 permissions:20 contents: read21 id-token: write22 steps:23 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.124 with:25 persist-credentials: false2627 - name: Setup Node.js28 uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.029 with:30 node-version: "lts/*"31 registry-url: "https://registry.npmjs.org"3233 # npm stage publish requires npm >= 11.15.034 - name: Upgrade npm35 run: npm install -g npm@latest3637 # Derive the npm dist-tag from the package version rather than from the38 # release target branch, which is just whatever the "Target" dropdown held39 # when the release was created and has been wrong in the past. Publishing40 # a maintenance line must never overwrite "latest":41 # prerelease (e.g. 3.0.0-beta.1) -> next42 # major >= current npm "latest" major -> latest43 # major < current npm "latest" major -> latest-<major>44 # No data from the release event is used, so nothing untrusted reaches45 # the script.46 - name: Resolve npm dist-tag from package version47 id: dist-tag48 run: |49 node <<'EOF'50 const fs = require('fs')51 const { execFileSync } = require('child_process')5253 const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/54 const { name, version } = JSON.parse(fs.readFileSync('package.json', 'utf8'))55 const parsed = SEMVER.exec(version)56 if (!parsed) throw new Error(`Invalid version in package.json: ${version}`)5758 const latest = execFileSync('npm', ['view', name, 'version'], { encoding: 'utf8' }).trim()59 const latestParsed = SEMVER.exec(latest)60 if (!latestParsed) throw new Error(`Unexpected "latest" version on npm: ${latest}`)6162 const major = Number(parsed[1])63 const prerelease = parsed[4]64 const latestMajor = Number(latestParsed[1])6566 let tag67 if (prerelease) tag = 'next'68 else if (major >= latestMajor) tag = 'latest'69 else tag = `latest-${major}`7071 console.log(`${name}@${version} (npm latest: ${latest}) -> dist-tag "${tag}"`)72 fs.appendFileSync(process.env.GITHUB_OUTPUT, `tag=${tag}\n`)73 EOF7475 - name: Stage publish to npm76 env:77 NPM_DIST_TAG: ${{ steps.dist-tag.outputs.tag }}78 run: npm stage publish --tag "$NPM_DIST_TAG"