diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4b2e6698..db16e897 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,6 +7,11 @@ on: permissions: contents: write + # npm Trusted Publishing (OIDC); no npm token is stored in the repo. + id-token: write + +concurrency: + group: release-${{ github.ref }} jobs: release: @@ -14,8 +19,22 @@ jobs: steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 + - uses: actions/setup-node@v4 + with: + node-version: 24 + # Trusted Publishing needs npm >= 11.5.1. + - run: npm install -g npm@11 + - name: Check tag matches CLI version + run: | + VERSION="$(node -p "require('./cli/package.json').version")" + if [[ "v$VERSION" != "$GITHUB_REF_NAME" ]]; then + echo "::error::Tag $GITHUB_REF_NAME does not match cli/package.json version $VERSION" + exit 1 + fi - run: bun install --frozen-lockfile - run: bun run build:single-exe:all + - name: Publish to npm + run: bun run --cwd cli publish-npm - name: Package release artifacts run: | cd cli/dist-exe diff --git a/bun.lock b/bun.lock index 09c15627..68d542ef 100644 --- a/bun.lock +++ b/bun.lock @@ -47,13 +47,6 @@ "typescript": "^5", "vitest": "^4.0.16", }, - "optionalDependencies": { - "@twsxtd/hapi-darwin-arm64": "0.31.2", - "@twsxtd/hapi-darwin-x64": "0.31.2", - "@twsxtd/hapi-linux-arm64": "0.31.2", - "@twsxtd/hapi-linux-x64": "0.31.2", - "@twsxtd/hapi-win32-x64": "0.31.2", - }, }, "docs": { "name": "hapi-docs", @@ -1111,16 +1104,6 @@ "@twsxtd/hapi": ["@twsxtd/hapi@workspace:cli"], - "@twsxtd/hapi-darwin-arm64": ["@twsxtd/hapi-darwin-arm64@0.31.2", "", { "os": "darwin", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-vb0dhAIuoEm13sRE/PX7uW5ZThucJWw0eta5Y5gFNXtySqJGBGkZTMAzzrsRRzPKvxDO8etdO7LVO+mat9R90w=="], - - "@twsxtd/hapi-darwin-x64": ["@twsxtd/hapi-darwin-x64@0.31.2", "", { "os": "darwin", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-3LCrR+vdUkOie5JilNqh4g+K0lCsNRcLemof+sBeW0djqA+604taRu+CvYQO36Edj0KMnlxcrdtWGYQ1PQtHfg=="], - - "@twsxtd/hapi-linux-arm64": ["@twsxtd/hapi-linux-arm64@0.31.2", "", { "os": "linux", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-xI1NNKXjDXcIb2b1BdEBSa0ligiurstAs+QIRSUZo5m8eQ0uTXXCltkol/S2BLqQA9X9mSABZVieqaFob2PW2Q=="], - - "@twsxtd/hapi-linux-x64": ["@twsxtd/hapi-linux-x64@0.31.2", "", { "os": "linux", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-yWoUQhPXC5Wyt7P984ewgimqrFsq2e2YNYrk4B/HzTpE5WctvbN0VgczHMtLPmnbg1hFQrS3xhDCz2LwiohJkA=="], - - "@twsxtd/hapi-win32-x64": ["@twsxtd/hapi-win32-x64@0.31.2", "", { "os": "win32", "cpu": "x64", "bin": { "hapi": "bin/hapi.exe" } }, "sha512-U4XZN0r/3v42FkXaJlcdQwzapxf+4DK13g5Xgu+S0fEpz26grgmBd8EInDhNKCZROB33DAQU0fU0g4pUXxNaRw=="], - "@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="], "@types/babel__core": ["@types/babel__core@7.20.5", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="], diff --git a/cli/README.md b/cli/README.md index 8c9b0eea..fdacc873 100644 --- a/cli/README.md +++ b/cli/README.md @@ -314,10 +314,17 @@ bun run build:single-exe From the repository root, `bun run release-all ` updates the CLI package, shared app version, iOS `MARKETING_VERSION` (app and notification extension, all -configurations), and Android's default `versionName` before building and publishing. -Use `--dry-run` to preview without changing files or publishing. Native build -numbers (`CURRENT_PROJECT_VERSION` / `versionCode`) remain managed separately; -Android's `-PhapiVersionName` override is preserved. +configurations), and Android's default `versionName`, then commits, tags `v`, +and pushes. It requires a clean working tree on `main`. Use `--dry-run` to preview +without changing files. Native build numbers (`CURRENT_PROJECT_VERSION` / `versionCode`) +remain managed separately; Android's `-PhapiVersionName` override is preserved. + +The pushed tag triggers `.github/workflows/release.yml`, which builds all binaries, +runs `bun run --cwd cli publish-npm`, and creates the GitHub Release. npm publishing +uses [Trusted Publishing](https://docs.npmjs.com/trusted-publishers) (OIDC), so no npm +token is involved; each `@twsxtd/hapi*` package must list `tiann/hapi` / +`release.yml` as its trusted publisher on npmjs.com. Packages already on npm are +skipped, so a failed release can be retried by re-running the workflow. ## Related docs diff --git a/cli/package.json b/cli/package.json index 51743db8..f3bfcbf1 100644 --- a/cli/package.json +++ b/cli/package.json @@ -25,13 +25,6 @@ "default": "./src/runtime/embeddedAssets.stub.ts" } }, - "optionalDependencies": { - "@twsxtd/hapi-darwin-arm64": "0.31.2", - "@twsxtd/hapi-darwin-x64": "0.31.2", - "@twsxtd/hapi-linux-arm64": "0.31.2", - "@twsxtd/hapi-linux-x64": "0.31.2", - "@twsxtd/hapi-win32-x64": "0.31.2" - }, "scripts": { "postinstall": "node -e \"try{require('fs').chmodSync(require('path').join(__dirname,'bin','hapi.cjs'),0o755)}catch(e){}\"", "typecheck": "tsc --noEmit", @@ -50,7 +43,8 @@ "dev": "bun src/index.ts", "dev:local-server": "bun --env-file .env.dev-local-server src/index.ts", "dev:integration-test-env": "bun --env-file .env.integration-test src/index.ts", - "release-all": "bun run scripts/release-all.ts" + "release-all": "bun run scripts/release-all.ts", + "publish-npm": "bun run scripts/publish-npm.ts" }, "dependencies": { "@hapi/protocol": "workspace:*", diff --git a/cli/scripts/prepare-npm-packages.ts b/cli/scripts/prepare-npm-packages.ts index cd7c54f9..d138fbfd 100644 --- a/cli/scripts/prepare-npm-packages.ts +++ b/cli/scripts/prepare-npm-packages.ts @@ -6,12 +6,11 @@ * 2. Generates the main npm package (wrapper) * 3. Generates package.json for each platform package * 4. Copies binaries from dist-exe to npm package directories - * 5. Updates optionalDependencies versions in main package.json * * Run after `bun run build:exe:all` */ -import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { chmodSync, copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -188,31 +187,12 @@ async function preparePlatform( console.log(`Copied: ${srcBin} -> ${destBin}`); } -function updateMainPackageOptionalDeps(version: string): void { - const pkgPath = join(projectRoot, 'package.json'); - const content = readFileSync(pkgPath, 'utf-8'); - const pkg = JSON.parse(content); - - // Update optionalDependencies versions - if (!pkg.optionalDependencies) { - pkg.optionalDependencies = {}; - } - - pkg.optionalDependencies = buildOptionalDependencies(version); - - writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n'); - console.log(`Updated optionalDependencies in package.json to version ${version}`); -} - async function main(): Promise { console.log('Preparing npm platform packages...\n'); const mainPkg = await readMainPackageJson(); console.log(`Version: ${mainPkg.version}\n`); - // Update optionalDependencies in main package.json - updateMainPackageOptionalDeps(mainPkg.version); - const distExeDir = join(projectRoot, 'dist-exe'); const npmDir = join(projectRoot, 'npm'); diff --git a/cli/scripts/publish-npm.ts b/cli/scripts/publish-npm.ts new file mode 100644 index 00000000..59b83499 --- /dev/null +++ b/cli/scripts/publish-npm.ts @@ -0,0 +1,100 @@ +#!/usr/bin/env bun +/** + * Publish the CLI to npm. Runs in the Release workflow via npm Trusted Publishing (OIDC), + * so no npm token is needed. Expects binaries in dist-exe (`bun run build:single-exe:all`). + * + * 1. Prepare npm packages from dist-exe + * 2. Publish platform packages + * 3. Wait until every platform package is live on npm + * 4. Publish the main package + * + * Packages already on npm are skipped, so a failed run can simply be re-run. + */ + +import { execSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const projectRoot = join(import.meta.dir, '..'); +const dryRun = process.argv.includes('--dry-run'); + +const platforms = ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64', 'win32-x64']; +const mainPackage = '@twsxtd/hapi'; + +function run(cmd: string, cwd = projectRoot): void { + console.log(`\n$ ${cmd}`); + execSync(cmd, { cwd, stdio: 'inherit' }); +} + +function isPublished(name: string, version: string): boolean { + try { + const published = execSync(`npm view ${name}@${version} version`, { + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'ignore'], + }).trim(); + return published === version; + } catch { + return false; + } +} + +function publish(name: string, version: string, dir: string): void { + if (isPublished(name, version)) { + console.log(` βœ“ ${name}@${version} already published, skipping`); + return; + } + run(`npm publish --access public${dryRun ? ' --dry-run' : ''}`, dir); +} + +async function waitForPackages(names: string[], version: string): Promise { + const timeoutMs = 10 * 60 * 1000; + const intervalMs = 15_000; + const deadline = Date.now() + timeoutMs; + const pending = new Set(names); + + while (pending.size > 0) { + for (const name of [...pending]) { + if (isPublished(name, version)) { + console.log(` βœ“ ${name}@${version} is live on npm`); + pending.delete(name); + } + } + if (pending.size === 0) { + return; + } + if (Date.now() >= deadline) { + console.error(`❌ Timed out waiting for platform packages on npm: ${[...pending].join(', ')}`); + console.error(' The main package was NOT published. Re-run the workflow to retry.'); + process.exit(1); + } + console.log(` ⏳ Waiting for: ${[...pending].join(', ')} (retry in ${intervalMs / 1000}s)...`); + await new Promise(resolve => setTimeout(resolve, intervalMs)); + } +} + +async function main(): Promise { + const version: string = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf-8')).version; + console.log(`\nπŸ“€ Publishing ${mainPackage}@${version} to npm${dryRun ? ' (dry-run)' : ''}`); + + run('bun run prepare-npm-packages'); + + const platformPackages = platforms.map(platform => `${mainPackage}-${platform}`); + for (const [index, platform] of platforms.entries()) { + publish(platformPackages[index], version, join(projectRoot, 'npm', platform)); + } + + // The main package pins platform packages via optionalDependencies, so publishing it first + // would let users install a version whose platform binary does not exist yet. + if (!dryRun) { + console.log('\nπŸ” Verifying platform packages are live on npm...'); + await waitForPackages(platformPackages, version); + } + + publish(mainPackage, version, join(projectRoot, 'npm', 'main')); + console.log(`\nβœ… Published ${mainPackage}@${version} to npm`); +} + +main().catch(err => { + console.error('Publish failed:', err); + process.exit(1); +}); diff --git a/cli/scripts/release-all.ts b/cli/scripts/release-all.ts index ae3651a5..1e4939df 100644 --- a/cli/scripts/release-all.ts +++ b/cli/scripts/release-all.ts @@ -1,231 +1,90 @@ #!/usr/bin/env bun /** - * Unified release script that handles the complete release flow: + * Start a release: * 1. Bump CLI, shared, iOS, and Android versions - * 2. Build binaries (with embedded web assets) - * 3. Publish platform packages first (so lockfile can resolve them) - * 4. Verify all platform packages are live on npm - * 5. Publish main package + * 2. Refresh bun.lock for the new workspace version + * 3. Git commit + tag + push * - * Re-running with the same version is safe: packages already on npm are skipped, - * so a release that failed midway can be resumed. - * 6. bun install --lockfile-only --os=* --cpu=* (to lock all platform packages) - * 7. Git commit + tag + push + * Pushing the tag triggers .github/workflows/release.yml, which builds the binaries, + * publishes to npm via Trusted Publishing, and creates the GitHub Release. */ import { execSync } from 'node:child_process'; import { join } from 'node:path'; import { updateReleaseVersions } from './release-version'; -const scriptDir = import.meta.dir; -const projectRoot = join(scriptDir, '..'); -const repoRoot = join(projectRoot, '..'); +const repoRoot = join(import.meta.dir, '..', '..'); -// θ§£ζžε‚ζ•° const args = process.argv.slice(2); const version = args.find(arg => !arg.startsWith('--')); const dryRun = args.includes('--dry-run'); -const publishNpm = args.includes('--publish-npm'); // εͺ发布 npmοΌŒθ·³θΏ‡ git ζ“δ½œ -const skipBuild = args.includes('--skip-build'); // θ·³θΏ‡ζž„ε»ΊοΌˆδΊŒθΏ›εˆΆε·²ε­˜εœ¨οΌ‰ if (!version) { - console.error('Usage: bun run scripts/release-all.ts [options]'); - console.error('Options:'); - console.error(' --dry-run Preview the release process'); - console.error(' --publish-npm Only publish to npm, skip git operations'); - console.error(' --skip-build Skip building binaries (use existing)'); + console.error('Usage: bun run scripts/release-all.ts [--dry-run]'); console.error('Example: bun run scripts/release-all.ts 0.2.0'); process.exit(1); } -function run(cmd: string, cwd = projectRoot): void { +const releaseFiles = [ + 'cli/package.json', + 'shared/src/buildInfo.ts', + 'ios/Hapi.xcodeproj/project.pbxproj', + 'android/app/build.gradle.kts', + 'bun.lock', +]; + +function git(cmd: string): string { + return execSync(`git ${cmd}`, { encoding: 'utf-8', cwd: repoRoot }).trim(); +} + +function run(cmd: string): void { console.log(`\n$ ${cmd}`); if (!dryRun) { - execSync(cmd, { cwd, stdio: 'inherit' }); + execSync(cmd, { cwd: repoRoot, stdio: 'inherit' }); } } -const platforms = ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64', 'win32-x64']; -const mainPackage = '@twsxtd/hapi'; - -function isPublished(name: string, expectedVersion: string): boolean { - try { - const published = execSync(`npm view ${name}@${expectedVersion} version`, { - encoding: 'utf-8', - stdio: ['ignore', 'pipe', 'ignore'], - }).trim(); - return published === expectedVersion; - } catch { - return false; - } +function fail(message: string): never { + console.error(`❌ ${message}`); + process.exit(1); } -function assertNpmLogin(): string { - try { - return execSync('npm whoami', { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); - } catch { - console.error('❌ npm token is missing or invalid. Run `npm login` (or set a new token) first.'); - process.exit(1); - } -} +function main(version: string): void { + const tag = `v${version}`; + console.log(`\nπŸš€ Starting release ${tag}${dryRun ? ' (dry-run)' : ''}\n`); -// npm answers an unauthorized publish to a scoped package with a misleading 404, -// so verify write access to every package before publishing anything. -function assertWriteAccess(packages: string[]): void { - let access: Record; - try { - access = JSON.parse(execSync('npm access list packages --json', { - encoding: 'utf-8', - stdio: ['ignore', 'pipe', 'ignore'], - })); - } catch { - console.error('❌ Could not list npm package access. Check that your npm token is valid.'); - process.exit(1); - } - const missing = packages.filter(name => access[name] !== 'read-write'); - if (missing.length > 0) { - console.error(`❌ npm token lacks write access to: ${missing.join(', ')}`); - console.error(' Use a token with read-write permission on all @twsxtd/hapi* packages.'); - process.exit(1); - } -} - -async function waitForPlatformPackages(platforms: string[], expectedVersion: string): Promise { - const timeoutMs = 10 * 60 * 1000; - const intervalMs = 15_000; - const deadline = Date.now() + timeoutMs; - const pending = new Set(platforms.map(platform => `@twsxtd/hapi-${platform}`)); - - while (pending.size > 0) { - for (const name of [...pending]) { - if (isPublished(name, expectedVersion)) { - console.log(` βœ“ ${name}@${expectedVersion} is live on npm`); - pending.delete(name); - } - } - if (pending.size === 0) { - return; - } - if (Date.now() >= deadline) { - console.error(`❌ Timed out waiting for platform packages on npm: ${[...pending].join(', ')}`); - console.error(' The main package was NOT published. Publish the missing platform packages and re-run with --publish-npm.'); - process.exit(1); - } - console.log(` ⏳ Waiting for: ${[...pending].join(', ')} (retry in ${intervalMs / 1000}s)...`); - await new Promise(resolve => setTimeout(resolve, intervalMs)); - } -} - -async function runWithTimeoutRetry(cmd: string, cwd = projectRoot): Promise { - const timeoutCmd = `timeout 60s ${cmd}`; - while (true) { - console.log(`\n$ ${timeoutCmd}`); - if (dryRun) { - return; - } - try { - execSync(timeoutCmd, { cwd, stdio: 'inherit' }); - return; - } catch { - console.warn(`⚠️ ${cmd} failed or timed out. Retrying in 60s...`); - await new Promise(resolve => setTimeout(resolve, 60_000)); - } - } -} - -async function main(version: string): Promise { - const flags = [dryRun && 'dry-run', publishNpm && 'publish-npm', skipBuild && 'skip-build'].filter(Boolean); - console.log(`\nπŸš€ Starting release v${version}${flags.length ? ` (${flags.join(', ')})` : ''}\n`); - - // Pre-check: Ensure we're on main branch console.log('πŸ” Pre-checks...'); - const currentBranch = execSync('git branch --show-current', { encoding: 'utf-8', cwd: repoRoot }).trim(); + const currentBranch = git('branch --show-current'); if (currentBranch !== 'main') { - console.error(`❌ Release must be run from main branch (current: ${currentBranch})`); - process.exit(1); + fail(`Release must be run from main branch (current: ${currentBranch})`); } console.log(' βœ“ On main branch'); - // Pre-check: Ensure npm is logged in (skip in dry-run mode) - if (!dryRun) { - const npmUser = assertNpmLogin(); - console.log(` βœ“ Logged in to npm as: ${npmUser}`); - assertWriteAccess([mainPackage, ...platforms.map(platform => `${mainPackage}-${platform}`)]); - console.log(' βœ“ npm token can publish all packages'); - } else { - console.log(' βœ“ Skipping npm login and access checks (dry-run)'); + if (git('status --porcelain') !== '') { + fail('Working tree is not clean. Commit or stash your changes first.'); } + console.log(' βœ“ Working tree is clean'); - // Step 1: Update all release versions before building or publishing. - console.log('πŸ“¦ Step 1: Updating CLI, shared, iOS, and Android versions...'); + if (git(`tag --list ${tag}`) !== '') { + fail(`Tag ${tag} already exists`); + } + console.log(` βœ“ Tag ${tag} is available`); + + console.log('\nπŸ“¦ Step 1: Updating CLI, shared, iOS, and Android versions...'); const oldVersion = updateReleaseVersions(repoRoot, version, dryRun); console.log(` ${oldVersion} β†’ ${version}`); - // Step 2: Build all platform binaries (with embedded web assets) - if (!skipBuild) { - console.log('\nπŸ”¨ Step 2: Building all platform binaries with web assets...'); - run('bun run build:single-exe:all', repoRoot); - } else { - console.log('\nπŸ”¨ Step 2: Skipping build (--skip-build)'); - } + console.log('\nπŸ“₯ Step 2: Updating lockfile...'); + run('bun install --lockfile-only'); - // Step 3: Prepare and publish platform packages - console.log('\nπŸ“€ Step 3: Publishing platform packages...'); - run('bun run prepare-npm-packages'); - for (const platform of platforms) { - const name = `${mainPackage}-${platform}`; - if (!dryRun && isPublished(name, version)) { - console.log(` βœ“ ${name}@${version} already published, skipping`); - continue; - } - const npmDir = join(projectRoot, 'npm', platform); - run(`npm publish --access public${dryRun ? ' --dry-run' : ''}`, npmDir); - } + console.log('\nπŸ“ Step 3: Creating git commit and tag...'); + run(`git add ${releaseFiles.join(' ')}`); + run(`git commit -m "Release version ${version}"`); + run(`git tag ${tag}`); + run(`git push --atomic origin main ${tag}`); - // Step 4: Verify all platform packages are live on npm before publishing the main package. - // The main package pins platform packages via optionalDependencies, so publishing it first - // would let users install a version whose platform binary does not exist yet. - if (dryRun) { - console.log('\nπŸ” Step 4: Skipping platform package verification (dry-run)'); - } else { - console.log('\nπŸ” Step 4: Verifying platform packages are live on npm...'); - await waitForPlatformPackages(platforms, version); - } - - // Step 5: Publish main package - console.log('\nπŸ“€ Step 5: Publishing main package...'); - if (!dryRun && isPublished(mainPackage, version)) { - console.log(` βœ“ ${mainPackage}@${version} already published, skipping`); - } else { - if (!dryRun) { - // The token may have expired while building or waiting for platform packages. - assertNpmLogin(); - } - const mainNpmDir = join(projectRoot, 'npm', 'main'); - run(`npm publish --access public${dryRun ? ' --dry-run' : ''}`, mainNpmDir); - } - - // --publish-npm ζ¨‘εΌεˆ°ζ­€η»“ζŸ - if (publishNpm) { - console.log(`\nβœ… Published v${version} to npm!`); - return; - } - - // Step 6: bun install to get complete lockfile - console.log('\nπŸ“₯ Step 6: Updating lockfile for all platform packages...'); - - await runWithTimeoutRetry('bun install --lockfile-only --os=* --cpu=*', repoRoot); - // Step 7: Git commit + tag + push - console.log('\nπŸ“ Step 7: Creating git commit and tag...'); - run(`git add .`, repoRoot); - run(`git commit -m "Release version ${version}"`, repoRoot); - run(`git tag v${version}`, repoRoot); - run(`git push && git push --tags`, repoRoot); - - console.log(`\nβœ… Release v${version} completed!`); + console.log(`\nβœ… Pushed ${tag}. The Release workflow will build and publish it:`); + console.log(' https://github.com/tiann/hapi/actions/workflows/release.yml'); } -main(version).catch(err => { - console.error('Release failed:', err); - process.exit(1); -}); +main(version);