diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ed9342c..dac0ad7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,15 +72,8 @@ jobs: - name: Install dependencies run: npm install - - name: Build app - run: npm run build - - - name: Deploy to Netlify - run: | - deploy_message="$(git log -1 --pretty=%s)" - npx --yes netlify-cli deploy --prod --dir=dist --site \ - "$NETLIFY_SITE_ID" --auth "$NETLIFY_AUTH_TOKEN" \ - --message "$deploy_message" + - name: Publish Netlify production deploy + run: npx tsx src/scripts/publish-netlify-production-deploy.ts env: NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} diff --git a/README.md b/README.md index 5c96ce4..c61ebdd 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,13 @@ Install Playwright browsers only if you plan to run browser-based tests locally. npm start +## Deployment + +Netlify builds deploy previews, branch deploys, and production deploys. +Production auto publishing is locked in Netlify; GitHub Actions publishes the +matching production deploy after CI passes. See [Deployment](docs/DEPLOYMENT.md) +for the full production flow. + ### Tests npm test diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 0000000..796454d --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,43 @@ +# Deployment + +This site intentionally separates CI from production publishing. + +Netlify owns the builds. GitHub Actions owns the production publishing gate. +Auto publishing must stay locked in Netlify so production deploys can be built +without going live before CI passes. + +## Deploy Flow + +- Pull requests get Netlify Deploy Previews through Netlify's Git integration. +- Non-production branches get Netlify branch deploys, depending on the site's + branch deploy settings in Netlify. +- Pushes to `master` create Netlify production deploys, but Netlify does not + publish them automatically while auto publishing is locked. +- After GitHub Actions checks pass on `master`, the production deploy job finds + the Netlify production deploy for the same commit SHA and publishes that + deploy. + +## Production Invariants + +- Keep Netlify builds active. +- Keep Netlify auto publishing locked. +- Do not replace the GitHub Actions publish step with an artifact upload unless + production should stop exercising Netlify's build environment. +- Do not publish a Netlify deploy unless its commit SHA matches the GitHub + Actions run that passed CI. + +## Troubleshooting + +If production does not publish after CI passes: + +- Check the GitHub Actions production deploy job logs. +- Confirm `NETLIFY_AUTH_TOKEN` and `NETLIFY_SITE_ID` are available to GitHub + Actions. +- Confirm Netlify has a production deploy for the same commit SHA. +- Confirm the matching Netlify deploy reached the `ready` state. +- Confirm Netlify auto publishing is still locked; the workflow publishes one + matching deploy and does not unlock future automatic publishing. +- On pull requests, GitHub may still say "This branch has not been deployed" + even when Netlify's `deploy/netlify` check says the Deploy Preview is ready. + This is a GitHub UI quirk: Netlify reports the preview as a check/status, but + GitHub's deployments panel only reads GitHub Deployment records. diff --git a/netlify.toml b/netlify.toml index ee3d645..62fc3cf 100644 --- a/netlify.toml +++ b/netlify.toml @@ -1,4 +1,3 @@ [build] command = "npm run build" - ignore = "[ \"$CONTEXT\" = \"production\" ]" publish = "dist/" diff --git a/package-lock.json b/package-lock.json index c4d0efc..002c2ee 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,6 +29,7 @@ "stylelint": "^17.14.0", "stylelint-config-html": "^1.1.0", "stylelint-config-standard": "^40.0.0", + "tsx": "^4.22.4", "typescript": "^6.0.3", "vite": "^7.3.6" } @@ -8854,6 +8855,509 @@ "license": "0BSD", "optional": true }, + "node_modules/tsx": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz", + "integrity": "sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/tsx/node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, "node_modules/typesafe-path": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/typesafe-path/-/typesafe-path-0.2.2.tgz", diff --git a/package.json b/package.json index db9c1a6..05aec44 100644 --- a/package.json +++ b/package.json @@ -45,6 +45,7 @@ "stylelint": "^17.14.0", "stylelint-config-html": "^1.1.0", "stylelint-config-standard": "^40.0.0", + "tsx": "^4.22.4", "typescript": "^6.0.3", "vite": "^7.3.6" } diff --git a/src/scripts/publish-netlify-production-deploy.ts b/src/scripts/publish-netlify-production-deploy.ts new file mode 100644 index 0000000..bde21c2 --- /dev/null +++ b/src/scripts/publish-netlify-production-deploy.ts @@ -0,0 +1,263 @@ +#!/usr/bin/env -S npx tsx + +/** + * Publish the Netlify-built production deploy that matches the current GitHub + * Actions commit. Netlify owns the build because production should exercise the + * same platform path as deploy previews and branch deploys; GitHub Actions owns + * the publish gate so production only changes after CI passes. + */ + +import { pathToFileURL } from "node:url" + +type Fetch = typeof fetch + +export type NetlifyDeploy = { + branch?: string + commit_ref?: string + context?: string + deploy_ssl_url?: string + deploy_url?: string + error_message?: string + id: string + skipped?: boolean + ssl_url?: string + state?: string + title?: string + url?: string +} + +type PublishOptions = { + authToken: string + branch: string + commitRef: string + maxAttempts: number + perPage: number + pollIntervalMs: number + siteId: string +} + +type Dependencies = { + fetch: Fetch + log: (message: string) => void + sleep: (ms: number) => Promise +} + +const pendingStates = new Set([ + "accepted", + "building", + "enqueued", + "new", + "pending_review", + "preparing", + "prepared", + "processed", + "processing", + "retrying", + "uploaded", + "uploading", +]) + +const terminalFailureStates = new Set(["error", "rejected"]) + +/** + * Poll Netlify for the production deploy that matches CI's commit, then publish + * it once it is ready. This keeps the workflow from publishing an older or + * unrelated deploy while Netlify auto publishing is locked. + */ +export async function publishNetlifyProductionDeploy( + options: PublishOptions, + dependencies: Partial = {}, +): Promise { + const deps: Dependencies = { + fetch: dependencies.fetch ?? fetch, + log: dependencies.log ?? writeLine, + sleep: + dependencies.sleep ?? + ((ms) => new Promise((resolve) => setTimeout(resolve, ms))), + } + + for (let attempt = 1; attempt <= options.maxAttempts; attempt += 1) { + const deploys = await listProductionDeploys(options, deps.fetch) + const deploy = findMatchingDeploy(deploys, options) + + if (!deploy) { + deps.log( + `No Netlify production deploy found yet for ${options.commitRef} on ${options.branch}.`, + ) + await waitForNextAttempt(attempt, options, deps.sleep) + continue + } + + deps.log( + `Found Netlify deploy ${deploy.id} for ${options.commitRef} with state ${deploy.state ?? "unknown"}.`, + ) + + if (deploy.skipped || terminalFailureStates.has(deploy.state ?? "")) { + throw new Error(formatDeployFailure(deploy)) + } + + if (deploy.state === "ready") { + return restoreDeploy(deploy.id, options, deps.fetch) + } + + if (!pendingStates.has(deploy.state ?? "")) { + throw new Error( + `Netlify deploy ${deploy.id} has unsupported state ${deploy.state ?? "unknown"}.`, + ) + } + + await waitForNextAttempt(attempt, options, deps.sleep) + } + + throw new Error( + `Timed out waiting for Netlify production deploy for ${options.commitRef} on ${options.branch}.`, + ) +} + +/** + * Select the Netlify production deploy for the exact branch and commit. The + * explicit match is necessary because Netlify may list deploys from other + * branches, contexts, or nearby commits while CI is waiting. + */ +export function findMatchingDeploy( + deploys: NetlifyDeploy[], + options: Pick, +): NetlifyDeploy | undefined { + return deploys.find( + (deploy) => + deploy.commit_ref === options.commitRef && + deploy.branch === options.branch && + deploy.context === "production", + ) +} + +function formatDeployFailure(deploy: NetlifyDeploy): string { + if (deploy.skipped) { + return `Netlify deploy ${deploy.id} for ${deploy.commit_ref ?? "unknown commit"} was skipped.` + } + + const reason = deploy.error_message ? `: ${deploy.error_message}` : "" + return `Netlify deploy ${deploy.id} failed with state ${deploy.state ?? "unknown"}${reason}.` +} + +async function listProductionDeploys( + options: Pick, + fetchFn: Fetch, +): Promise { + const url = new URL( + `https://api.netlify.com/api/v1/sites/${encodeURIComponent(options.siteId)}/deploys`, + ) + url.searchParams.set("production", "true") + url.searchParams.set("branch", options.branch) + url.searchParams.set("per_page", String(options.perPage)) + + const response = await fetchFn(url, { + headers: { + Authorization: `Bearer ${options.authToken}`, + }, + }) + + if (!response.ok) { + throw new Error( + `Netlify deploy lookup failed with ${response.status} ${response.statusText}.`, + ) + } + + return response.json() as Promise +} + +async function restoreDeploy( + deployId: string, + options: Pick, + fetchFn: Fetch, +): Promise { + const url = `https://api.netlify.com/api/v1/sites/${encodeURIComponent( + options.siteId, + )}/deploys/${encodeURIComponent(deployId)}/restore` + const response = await fetchFn(url, { + headers: { + Authorization: `Bearer ${options.authToken}`, + }, + method: "POST", + }) + + if (!response.ok) { + throw new Error( + `Netlify deploy publish failed with ${response.status} ${response.statusText}.`, + ) + } + + return response.json() as Promise +} + +async function waitForNextAttempt( + attempt: number, + options: Pick, + sleep: Dependencies["sleep"], +): Promise { + if (attempt < options.maxAttempts) { + await sleep(options.pollIntervalMs) + } +} + +function readRequiredEnv(name: string): string { + const value = process.env[name] + if (!value) { + throw new Error(`Missing required environment variable: ${name}`) + } + return value +} + +function readPositiveIntegerEnv(name: string, fallback: number): number { + const value = process.env[name] + if (!value) { + return fallback + } + + const parsed = Number.parseInt(value, 10) + if (!Number.isInteger(parsed) || parsed <= 0) { + throw new Error(`${name} must be a positive integer.`) + } + + return parsed +} + +/** + * Read the GitHub Actions and Netlify settings needed by the publish job. + * Keeping this at the CLI boundary lets tests exercise the deploy logic without + * depending on process environment state. + */ +export function readOptionsFromEnv(): PublishOptions { + return { + authToken: readRequiredEnv("NETLIFY_AUTH_TOKEN"), + branch: process.env.NETLIFY_PRODUCTION_BRANCH ?? "master", + commitRef: readRequiredEnv("GITHUB_SHA"), + maxAttempts: readPositiveIntegerEnv("NETLIFY_DEPLOY_MAX_ATTEMPTS", 60), + perPage: readPositiveIntegerEnv("NETLIFY_DEPLOY_PER_PAGE", 50), + pollIntervalMs: readPositiveIntegerEnv( + "NETLIFY_DEPLOY_POLL_INTERVAL_MS", + 10_000, + ), + siteId: readRequiredEnv("NETLIFY_SITE_ID"), + } +} + +async function main(): Promise { + const deploy = await publishNetlifyProductionDeploy(readOptionsFromEnv()) + writeLine( + `Published Netlify deploy ${deploy.id}: ${ + deploy.ssl_url ?? deploy.url ?? deploy.deploy_ssl_url ?? deploy.deploy_url + }`, + ) +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + main().catch((error: unknown) => { + process.stderr.write(`${error instanceof Error ? error.message : error}\n`) + process.exitCode = 1 + }) +} + +function writeLine(message: string): void { + process.stdout.write(`${message}\n`) +} diff --git a/test/scripts/publish-netlify-production-deploy.test.ts b/test/scripts/publish-netlify-production-deploy.test.ts new file mode 100644 index 0000000..f8ed8ee --- /dev/null +++ b/test/scripts/publish-netlify-production-deploy.test.ts @@ -0,0 +1,165 @@ +import assert from "node:assert/strict" +import test from "node:test" + +import { + findMatchingDeploy, + type NetlifyDeploy, + publishNetlifyProductionDeploy, +} from "../../src/scripts/publish-netlify-production-deploy.ts" + +const options = { + authToken: "token", + branch: "master", + commitRef: "abc123", + maxAttempts: 3, + perPage: 50, + pollIntervalMs: 1, + siteId: "site-id", +} + +test("finds matching production deploy by commit and branch", () => { + const matchingDeploy = deploy({ id: "matching" }) + + assert.equal( + findMatchingDeploy( + [ + deploy({ commit_ref: "other" }), + deploy({ branch: "feature" }), + deploy({ context: "branch-deploy" }), + matchingDeploy, + ], + options, + ), + matchingDeploy, + ) +}) + +test("publishes a ready production deploy for the exact commit", async () => { + const fetch = createFetch([ + [deploy({ id: "ready-deploy" })], + deploy({ id: "published-deploy", ssl_url: "https://example.netlify.app" }), + ]) + + const published = await publishNetlifyProductionDeploy(options, { + fetch, + log: () => {}, + sleep: async () => {}, + }) + + assert.equal(published.id, "published-deploy") + assert.equal(fetch.calls.length, 2) + assert.equal(fetch.calls[1]?.method, "POST") + assert.match(fetch.calls[1]?.url ?? "", /\/ready-deploy\/restore$/) +}) + +test("waits for matching deploys that are still in progress", async () => { + const fetch = createFetch([ + [deploy({ id: "pending-deploy", state: "building" })], + [deploy({ id: "pending-deploy", state: "processing" })], + [deploy({ id: "pending-deploy", state: "ready" })], + deploy({ id: "published-deploy" }), + ]) + const slept: number[] = [] + + await publishNetlifyProductionDeploy(options, { + fetch, + log: () => {}, + sleep: async (ms) => { + slept.push(ms) + }, + }) + + assert.deepEqual(slept, [1, 1]) + assert.equal(fetch.calls.length, 4) + assert.equal(fetch.calls[fetch.calls.length - 1]?.method, "POST") +}) + +test("fails when the matching deploy errors", async () => { + const fetch = createFetch([ + [deploy({ error_message: "Build failed", id: "failed", state: "error" })], + ]) + + await assert.rejects( + publishNetlifyProductionDeploy(options, { + fetch, + log: () => {}, + sleep: async () => {}, + }), + /failed with state error: Build failed/, + ) + + assert.equal(fetch.calls.length, 1) +}) + +test("fails when the matching deploy was skipped", async () => { + const fetch = createFetch([[deploy({ id: "skipped", skipped: true })]]) + + await assert.rejects( + publishNetlifyProductionDeploy(options, { + fetch, + log: () => {}, + sleep: async () => {}, + }), + /was skipped/, + ) + + assert.equal(fetch.calls.length, 1) +}) + +test("times out without publishing when no matching deploy appears", async () => { + const fetch = createFetch([ + [deploy({ commit_ref: "other" })], + [deploy({ branch: "feature" })], + [deploy({ context: "deploy-preview" })], + ]) + + await assert.rejects( + publishNetlifyProductionDeploy(options, { + fetch, + log: () => {}, + sleep: async () => {}, + }), + /Timed out waiting/, + ) + + assert.equal(fetch.calls.length, 3) + assert.equal( + fetch.calls.some((call) => call.method === "POST"), + false, + ) +}) + +function deploy(overrides: Partial = {}): NetlifyDeploy { + return { + branch: options.branch, + commit_ref: options.commitRef, + context: "production", + id: "deploy-id", + state: "ready", + ...overrides, + } +} + +function createFetch(responses: unknown[]) { + const calls: Array<{ method: string; url: string }> = [] + + const fetch = async ( + input: string | URL | Request, + init?: RequestInit, + ): Promise => { + calls.push({ + method: init?.method ?? "GET", + url: String(input), + }) + + const body = responses.shift() + assert.notEqual(body, undefined, "Unexpected fetch call") + + return new Response(JSON.stringify(body), { + headers: { "content-type": "application/json" }, + status: 200, + }) + } + + return Object.assign(fetch, { calls }) +}