Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 73 additions & 6 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
name: Publish

# Publishes to npm when a version bump lands on main. Merging a "Prepare Node
# SDK x.y.z" PR is the release: this job publishes every package whose version
# npm does not have yet, then tags vX.Y.Z and creates the GitHub release.
#
# Authentication is npm trusted publishing (OIDC from this workflow), so there
# is no token to expire. NPM_TOKEN is the fallback until every package has a
# trusted publisher configured on npmjs.com.
#
# Safe to re-run: packages already on npm are skipped, and the tag and release
# are created only if they are missing.

on:
push:
tags:
- 'v*'
branches: [main]
paths:
- 'packages/*/package.json'
workflow_dispatch:

concurrency:
group: publish
cancel-in-progress: false

jobs:
publish:
name: Publish to npm
runs-on: ubuntu-latest
permissions:
contents: read
contents: write
id-token: write
steps:
- uses: actions/checkout@v5
Expand All @@ -19,8 +36,58 @@ jobs:
node-version: 22
cache: 'npm'
registry-url: 'https://registry.npmjs.org'
- run: npm ci
- run: npm run build
- run: npm publish --workspaces --access public
# Trusted publishing needs npm 11.5.1 or later.
- run: npm install -g npm@^11.5.1

- name: Find versions npm does not have
id: plan
run: |
node scripts/publish-plan.mjs > "$RUNNER_TEMP/plan.json"
cat "$RUNNER_TEMP/plan.json"
echo "version=$(node -p "require(process.env.RUNNER_TEMP + '/plan.json').version")" >> "$GITHUB_OUTPUT"
echo "dirs=$(node -p "require(process.env.RUNNER_TEMP + '/plan.json').packages.map(p => p.dir).join(' ')")" >> "$GITHUB_OUTPUT"

- name: Build and test
if: steps.plan.outputs.dirs != ''
run: |
npm ci
npm run build
npm test

- name: Publish
if: steps.plan.outputs.dirs != ''
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
DIRS: ${{ steps.plan.outputs.dirs }}
run: |
for dir in $DIRS; do
echo "::group::publish $dir"
npm publish --workspace "$dir" --access public --provenance
echo "::endgroup::"
done

- name: Confirm the registry has every package
run: |
for i in 1 2 3 4 5 6 7 8 9 10; do
left=$(node scripts/publish-plan.mjs | node -p "JSON.parse(require('fs').readFileSync(0, 'utf8')).packages.length")
[ "$left" = "0" ] && exit 0
echo "$left package(s) not visible yet; waiting"
sleep 30
done
node scripts/publish-plan.mjs
exit 1

- name: Tag and release
env:
GH_TOKEN: ${{ github.token }}
VERSION: ${{ steps.plan.outputs.version }}
run: |
tag="v$VERSION"
if ! git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then
git tag "$tag" "$GITHUB_SHA"
git push origin "$tag"
fi
if ! gh release view "$tag" >/dev/null 2>&1; then
notes=$(awk -v v="$VERSION" '$0 ~ "^## \\[" v "\\]" {on=1; next} on && /^## \[/ {exit} on' CHANGELOG.md)
gh release create "$tag" --title "$tag" --notes "${notes:-All packages at $VERSION.}" --verify-tag
fi
9 changes: 4 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,11 +215,10 @@ export function analyzeRequest(metadata: RequestMetadata): LocalAnalysis {

(For maintainers only)

1. Update version in all package.json files
2. Update CHANGELOG.md
3. Create a git tag
4. Push to GitHub
5. Publish to npm
1. Open a "Prepare Node SDK x.y.z" pull request that sets the same version in every `packages/*/package.json` (and the `@webdecoy/node` dependency ranges) and adds the CHANGELOG entry.
2. Merge it. The Publish workflow runs on the push to `main`, builds and tests, publishes every package whose version npm does not have yet, checks the registry, then tags `vx.y.z` and creates the GitHub release from the CHANGELOG entry.

Publishing authenticates with npm trusted publishing from `.github/workflows/publish.yml`. If a run fails partway, re-run it: packages already on npm are skipped.

## Getting Help

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"build": "turbo run build",
"dev": "turbo run dev",
"lint": "turbo run lint",
"test": "turbo run test && npm run test:playground && npm run test:signed-agent",
"test": "turbo run test && npm run test:playground && npm run test:signed-agent && node --test scripts/publish-plan.test.mjs",
"clean": "turbo run clean && rm -rf node_modules",
"format": "prettier --write \"**/*.{ts,tsx,js,jsx,json,md}\"",
"check:edge": "npm run check:edge -w @webdecoy/node -w @webdecoy/nextjs -w @webdecoy/hono",
Expand Down
64 changes: 64 additions & 0 deletions scripts/publish-plan.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#!/usr/bin/env node
// Which public packages have a version that npm does not have yet.
//
// The publish workflow runs this on every push to main. A package whose
// package.json version is already on the registry is skipped, so a re-run
// after a partial failure publishes only what is missing, and a push that
// bumps nothing publishes nothing.
//
// Prints JSON: { version, packages: [{ name, dir }] }, in publish order
// (the core SDK first, then the packages that depend on it).
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';

const ORDER = ['@webdecoy/node', '@webdecoy/client'];

export function publishOrder(names) {
return [...names].sort((a, b) => {
const ia = ORDER.indexOf(a);
const ib = ORDER.indexOf(b);
return (ia === -1 ? ORDER.length : ia) - (ib === -1 ? ORDER.length : ib) || a.localeCompare(b);
});
}

export function readPackages(root) {
return readdirSync(join(root, 'packages'), { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => {
const dir = join('packages', d.name);
const pkg = JSON.parse(readFileSync(join(root, dir, 'package.json'), 'utf8'));
return { name: pkg.name, version: pkg.version, private: pkg.private === true, dir };
})
.filter((p) => !p.private);
}

async function published(name, version, fetchImpl) {
const res = await fetchImpl(`https://registry.npmjs.org/${name.replace('/', '%2f')}/${version}`, {
headers: { accept: 'application/json' },
});
if (res.status === 404) return false;
if (!res.ok) throw new Error(`registry answered ${res.status} for ${name}@${version}`);
return true;
}

export async function plan(root, fetchImpl = fetch) {
const pkgs = readPackages(root);
const versions = new Set(pkgs.map((p) => p.version));
if (versions.size !== 1) {
throw new Error(`packages disagree on the version: ${pkgs.map((p) => `${p.name}@${p.version}`).join(', ')}`);
}
const [version] = versions;
const missing = [];
for (const p of pkgs) {
if (!(await published(p.name, p.version, fetchImpl))) missing.push(p);
}
const byName = new Map(missing.map((p) => [p.name, p]));
return {
version,
packages: publishOrder(byName.keys()).map((n) => ({ name: n, dir: byName.get(n).dir })),
};
}

if (import.meta.url === `file://${process.argv[1]}`) {
console.log(JSON.stringify(await plan(process.cwd())));
}
67 changes: 67 additions & 0 deletions scripts/publish-plan.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { plan, publishOrder } from './publish-plan.mjs';

function repo(pkgs) {
const root = mkdtempSync(join(tmpdir(), 'publish-plan-'));
for (const [dir, pkg] of Object.entries(pkgs)) {
mkdirSync(join(root, 'packages', dir), { recursive: true });
writeFileSync(join(root, 'packages', dir, 'package.json'), JSON.stringify(pkg));
}
return root;
}

const registry = (have) => async (url) => {
const [, name, version] = url.match(/npmjs\.org\/(.+)\/([^/]+)$/);
return { status: have.has(`${decodeURIComponent(name)}@${version}`) ? 200 : 404, ok: true };
};

test('publishes only the versions npm does not have, core SDK first', async () => {
const root = repo({
express: { name: '@webdecoy/express', version: '1.2.0' },
webdecoy: { name: '@webdecoy/node', version: '1.2.0' },
client: { name: '@webdecoy/client', version: '1.2.0' },
});
const result = await plan(root, registry(new Set(['@webdecoy/client@1.2.0'])));
assert.equal(result.version, '1.2.0');
assert.deepEqual(result.packages.map((p) => p.name), ['@webdecoy/node', '@webdecoy/express']);
});

test('a push that bumps nothing publishes nothing', async () => {
const root = repo({ webdecoy: { name: '@webdecoy/node', version: '1.2.0' } });
const result = await plan(root, registry(new Set(['@webdecoy/node@1.2.0'])));
assert.deepEqual(result.packages, []);
});

test('private packages are never published', async () => {
const root = repo({
webdecoy: { name: '@webdecoy/node', version: '1.2.0' },
internal: { name: '@webdecoy/internal', version: '1.2.0', private: true },
});
const result = await plan(root, registry(new Set()));
assert.deepEqual(result.packages.map((p) => p.name), ['@webdecoy/node']);
});

test('refuses when packages disagree on the version', async () => {
const root = repo({
webdecoy: { name: '@webdecoy/node', version: '1.2.0' },
express: { name: '@webdecoy/express', version: '1.1.0' },
});
await assert.rejects(plan(root, registry(new Set())), /disagree/);
});

test('a registry error stops the plan rather than publishing blind', async () => {
const root = repo({ webdecoy: { name: '@webdecoy/node', version: '1.2.0' } });
await assert.rejects(plan(root, async () => ({ status: 503, ok: false })), /503/);
});

test('order puts the core SDK and client ahead of adapters', () => {
assert.deepEqual(publishOrder(['@webdecoy/hono', '@webdecoy/client', '@webdecoy/node']), [
'@webdecoy/node',
'@webdecoy/client',
'@webdecoy/hono',
]);
});
Loading