├── .eslintignore ├── .prettierignore ├── .prettierrc.json ├── .gitignore ├── src ├── utils │ ├── env.ts │ ├── int.ts │ ├── github.test.ts │ ├── github.ts │ ├── int.test.ts │ ├── package.ts │ ├── semver.ts │ └── semver.test.ts ├── index.ts └── scripts │ ├── generate.ts │ └── publish.ts ├── tsconfig.json ├── package.json ├── .github └── workflows │ └── publish.yaml ├── LICENSE.md └── README.md /.eslintignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /build -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | /dist 3 | .auri/*.md -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "useTabs": true, 3 | "trailingComma": "none", 4 | "printWidth": 100 5 | } 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /dist 3 | .DS_Store 4 | .env 5 | 6 | .COMMITS 7 | 8 | package-lock.json 9 | pnpm-lock.yaml -------------------------------------------------------------------------------- /src/utils/env.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | 3 | dotenv.config(); 4 | 5 | export function env(key: string): string { 6 | if (key in process.env && typeof process.env[key] === "string") { 7 | return process.env[key] as string; 8 | } 9 | throw new Error(`Environment variable "${key}" is undefined`); 10 | } 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": true, 4 | "checkJs": true, 5 | "noImplicitAny": true, 6 | "module": "es2022", 7 | "moduleResolution": "node", 8 | "target": "es2022", 9 | "allowSyntheticDefaultImports": true, 10 | "outDir": "./dist", 11 | "strict": true 12 | }, 13 | "include": ["src"], 14 | "exclude": ["src/**/*.test.ts"] 15 | } 16 | -------------------------------------------------------------------------------- /src/utils/int.ts: -------------------------------------------------------------------------------- 1 | export function convertPositiveIntegerString(s: string): number { 2 | if (s.length === 0) { 3 | throw new Error("Failed to parse string"); 4 | } 5 | for (let i = 0; i < s.length; i++) { 6 | const code = s.charCodeAt(i); 7 | // is leading zero 8 | if (s.length > 1 && i === 0 && code === 0x30) { 9 | throw new Error("Failed to parse string"); 10 | } 11 | if (code < 0x30 || code > 0x39) { 12 | throw new Error("Failed to parse string"); 13 | } 14 | } 15 | return Number(s); 16 | } 17 | -------------------------------------------------------------------------------- /src/utils/github.test.ts: -------------------------------------------------------------------------------- 1 | import * as vitest from "vitest"; 2 | 3 | import { parseGitHubGitRepositoryURL, GitHubRepository } from "./github.js"; 4 | 5 | vitest.test("parseGitHubGitRepositoryURL()", () => { 6 | const expected: GitHubRepository = { 7 | gitURL: "https://github.com/foo/bar.git", 8 | owner: "foo", 9 | name: "bar" 10 | }; 11 | vitest 12 | .expect(parseGitHubGitRepositoryURL("https://github.com/foo/bar.git")) 13 | .toStrictEqual(expected); 14 | 15 | vitest.expect(() => parseGitHubGitRepositoryURL("https://github.com/foo/bar")).toThrowError(); 16 | }); 17 | -------------------------------------------------------------------------------- /src/utils/github.ts: -------------------------------------------------------------------------------- 1 | export function parseGitHubGitRepositoryURL(url: string): GitHubRepository { 2 | if (!url.endsWith(".git")) { 3 | throw new Error("Invalid repository URL"); 4 | } 5 | const parsed = new URL(url); 6 | if (parsed.origin !== "https://github.com") { 7 | throw new Error("Invalid GitHub repository URL"); 8 | } 9 | const pathnameParts = parsed.pathname.split("/").slice(1); 10 | if (pathnameParts.length < 2) { 11 | throw new Error("Invalid GitHub repository URL"); 12 | } 13 | const repositoryName = pathnameParts[1].slice(0, -4); 14 | const repository: GitHubRepository = { 15 | gitURL: url, 16 | owner: pathnameParts[0], 17 | name: repositoryName 18 | }; 19 | return repository; 20 | } 21 | 22 | export interface GitHubRepository { 23 | gitURL: string; 24 | owner: string; 25 | name: string; 26 | } 27 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "auri", 3 | "version": "3.1.2", 4 | "description": "Organize package changes and releases", 5 | "type": "module", 6 | "files": [ 7 | "dist", 8 | "CHANGELOG.md" 9 | ], 10 | "bin": "./dist/index.js", 11 | "scripts": { 12 | "build": "shx rm -rf ./dist/* && tsc", 13 | "auri": "node ./dist/index.js", 14 | "format": "prettier -w .", 15 | "test": "vitest run --sequence.concurrent" 16 | }, 17 | "keywords": [ 18 | "npm", 19 | "changesets" 20 | ], 21 | "repository": { 22 | "type": "git", 23 | "url": "https://github.com/pilcrowonpaper/auri.git", 24 | "directory": "/" 25 | }, 26 | "author": "pilcrowOnPaper", 27 | "license": "MIT", 28 | "devDependencies": { 29 | "@types/node": "^18.14.4", 30 | "prettier": "^2.8.3", 31 | "shx": "^0.3.4", 32 | "typescript": "^4.9.4", 33 | "vitest": "^2.1.8" 34 | }, 35 | "dependencies": { 36 | "dotenv": "^16.0.3" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/utils/int.test.ts: -------------------------------------------------------------------------------- 1 | import { test, expect } from "vitest"; 2 | import { convertPositiveIntegerString } from "./int.js"; 3 | 4 | test("parsePositiveIntegerString()", () => { 5 | expect(convertPositiveIntegerString("0")).toBe(0); 6 | expect(convertPositiveIntegerString("7")).toBe(7); 7 | expect(convertPositiveIntegerString("1320832952")).toBe(1320832952); 8 | expect(() => convertPositiveIntegerString("")).toThrowError(); 9 | expect(() => convertPositiveIntegerString("01")).toThrowError(); 10 | expect(() => convertPositiveIntegerString("1.42")).toThrowError(); 11 | expect(() => convertPositiveIntegerString("-1")).toThrowError(); 12 | expect(() => convertPositiveIntegerString("a")).toThrowError(); 13 | expect(() => convertPositiveIntegerString("0xff")).toThrowError(); 14 | expect(() => convertPositiveIntegerString("ff")).toThrowError(); 15 | expect(() => convertPositiveIntegerString("5e2")).toThrowError(); 16 | }); 17 | -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: "Publish package" 2 | on: [push] 3 | 4 | env: 5 | AURI_GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 6 | AURI_NPM_TOKEN: ${{secrets.AURI_NPM_TOKEN}} 7 | 8 | jobs: 9 | publish-package: 10 | name: Publish package and release with Auri 11 | runs-on: ubuntu-latest 12 | if: github.repository == 'pilcrowonpaper/auri' && github.ref == 'refs/heads/main' 13 | permissions: 14 | contents: write 15 | id-token: write 16 | steps: 17 | - name: Setup actions 18 | uses: actions/checkout@v3 19 | with: 20 | ref: ${{ github.ref }} 21 | - name: Setup Node 22 | uses: actions/setup-node@v3 23 | with: 24 | node-version: 20 25 | registry-url: "https://registry.npmjs.org/" 26 | - name: Install dependencies 27 | run: npm install 28 | - name: Build Auri 29 | run: npm run build 30 | - name: Publish package and release 31 | run: npm run auri publish 32 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 pilcrowOnPaper 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import { publishScript } from "./scripts/publish.js"; 3 | import { generateScript } from "./scripts/generate.js"; 4 | 5 | // TODO: Add --github-actions flag to format errors 6 | // TODO: Add --build-command parameter to pass custom build command 7 | async function main(): Promise { 8 | const nodeArgs = process.execArgv; 9 | const args = process.argv.slice(nodeArgs.length + 2); 10 | 11 | if (args[0] === "generate") { 12 | try { 13 | await generateScript(); 14 | } catch (e) { 15 | let message = "An unknown error occurred"; 16 | if (e instanceof Error) { 17 | message = e.message; 18 | } 19 | process.stderr.write(`::error ::${message}`); 20 | return process.exit(1); 21 | } 22 | return process.exit(); 23 | } 24 | 25 | if (args[0] === "publish") { 26 | try { 27 | await publishScript(); 28 | } catch (e) { 29 | let message = "An unknown error occurred"; 30 | if (e instanceof Error) { 31 | message = e.message; 32 | } 33 | process.stderr.write(`::error ::${message}`); 34 | return process.exit(1); 35 | } 36 | return process.exit(); 37 | } 38 | } 39 | 40 | main(); 41 | -------------------------------------------------------------------------------- /src/utils/package.ts: -------------------------------------------------------------------------------- 1 | export function parsePackageJSON(data: unknown): PackageMetaData { 2 | if (typeof data !== "object" || data === null) { 3 | throw new Error("Invalid package.json"); 4 | } 5 | 6 | let name: string; 7 | if ("name" in data && typeof data.name === "string") { 8 | name = data.name; 9 | } else { 10 | throw new Error("Missing or invalid 'name' field"); 11 | } 12 | 13 | let version: string; 14 | if ("version" in data && typeof data.version === "string") { 15 | version = data.version; 16 | } else { 17 | throw new Error("Missing or invalid 'version' field"); 18 | } 19 | if (!/^[a-zA-Z0-9-._]*$/.test(version)) { 20 | throw new Error("Missing or invalid 'version' field"); 21 | } 22 | if (version.includes("..")) { 23 | throw new Error("Missing or invalid 'version' field"); 24 | } 25 | 26 | let repository: string; 27 | if ( 28 | "repository" in data && 29 | typeof data.repository === "object" && 30 | data.repository !== null && 31 | "url" in data.repository && 32 | typeof data.repository.url === "string" 33 | ) { 34 | if (data.repository.url.endsWith(".git")) { 35 | repository = data.repository.url; 36 | } else { 37 | repository = data.repository.url + ".git"; 38 | } 39 | } else { 40 | throw new Error("Missing or invalid 'repository.url' field"); 41 | } 42 | const metadata: PackageMetaData = { 43 | name, 44 | version, 45 | repository 46 | }; 47 | return metadata; 48 | } 49 | 50 | export interface PackageMetaData { 51 | name: string; 52 | version: string; 53 | repository: string; 54 | } 55 | -------------------------------------------------------------------------------- /src/utils/semver.ts: -------------------------------------------------------------------------------- 1 | import { convertPositiveIntegerString } from "./int.js"; 2 | 3 | export function parseSemver(version: string): Semver { 4 | let parts = version.split("-"); 5 | if (parts.length > 2) { 6 | throw new Error("Invalid version format"); 7 | } 8 | const mainParts = parts[0].split("."); 9 | if (mainParts.length !== 3) { 10 | throw new Error("Invalid version format"); 11 | } 12 | 13 | let major: number; 14 | try { 15 | major = convertPositiveIntegerString(mainParts[0]); 16 | } catch { 17 | throw new Error("Invalid version format"); 18 | } 19 | let minor: number; 20 | try { 21 | minor = convertPositiveIntegerString(mainParts[1]); 22 | } catch { 23 | throw new Error("Invalid version format"); 24 | } 25 | let patch: number; 26 | try { 27 | patch = convertPositiveIntegerString(mainParts[2]); 28 | } catch { 29 | throw new Error("Invalid version format"); 30 | } 31 | 32 | if (parts.length === 1) { 33 | const semver: Semver = { 34 | major, 35 | minor, 36 | patch, 37 | next: null 38 | }; 39 | return semver; 40 | } 41 | const nextParts = parts[1].split("."); 42 | if (nextParts.length !== 2) { 43 | throw new Error("Invalid version format"); 44 | } 45 | if (nextParts[0] !== "next") { 46 | throw new Error("Invalid version format"); 47 | } 48 | let next: number; 49 | try { 50 | next = convertPositiveIntegerString(nextParts[1]); 51 | } catch { 52 | throw new Error("Invalid version format"); 53 | } 54 | const semver: Semver = { 55 | major, 56 | minor, 57 | patch, 58 | next 59 | }; 60 | return semver; 61 | } 62 | 63 | export interface Semver { 64 | major: number; 65 | minor: number; 66 | patch: number; 67 | next: number | null; 68 | } 69 | -------------------------------------------------------------------------------- /src/scripts/generate.ts: -------------------------------------------------------------------------------- 1 | import * as fs from "fs/promises"; 2 | import * as childprocess from "child_process"; 3 | 4 | import { parsePackageJSON } from "../utils/package.js"; 5 | import { GitHubRepository, parseGitHubGitRepositoryURL } from "../utils/github.js"; 6 | 7 | export async function generateScript(): Promise { 8 | const packageJSONFile = await fs.readFile("package.json"); 9 | const packageJSON: unknown = JSON.parse(packageJSONFile.toString()); 10 | const metadata = parsePackageJSON(packageJSON); 11 | // NOTE: parsePackageJSON() checks that PackageMetaData.version only includes '.', '-', or "_" as special characters. 12 | const packageVersionSafe = metadata.version; 13 | 14 | let repository: GitHubRepository; 15 | try { 16 | repository = parseGitHubGitRepositoryURL(metadata.repository); 17 | } catch { 18 | throw new Error("Invalid GitHub repository URL"); 19 | } 20 | 21 | // TODO: Support line breaks in commit messages? 22 | const output = childprocess 23 | .execSync(`git --no-pager log --pretty=tformat:"%H%n%s" "v${packageVersionSafe}..HEAD"`) 24 | .toString(); 25 | const lines = output.split("\n").slice(0, -1); 26 | const commitHashes: string[] = []; 27 | for (let i = 0; i < lines.length; i += 2) { 28 | if ( 29 | lines[i + 1].startsWith("docs:") || 30 | lines[i + 1].startsWith("style:") || 31 | lines[i + 1].startsWith("test:") 32 | ) { 33 | continue; 34 | } 35 | commitHashes.push(lines[i]); 36 | } 37 | 38 | let changeFile = ""; 39 | for (let i = 0; i < commitHashes.length; i++) { 40 | changeFile += `https://github.com/${repository.owner}/${repository.name}/commit/${commitHashes[i]}`; 41 | if (i !== commitHashes.length - 1) { 42 | changeFile += "\n"; 43 | } 44 | } 45 | 46 | await fs.writeFile(".COMMITS", changeFile); 47 | 48 | // Create file if not exists 49 | await fs.writeFile(".RELEASE.md", "", { 50 | flag: "a+" 51 | }); 52 | } 53 | -------------------------------------------------------------------------------- /src/utils/semver.test.ts: -------------------------------------------------------------------------------- 1 | import * as vitest from "vitest"; 2 | 3 | import { parseSemver, Semver } from "./semver.js"; 4 | 5 | vitest.test("parseSemver()", () => { 6 | let expected: Semver = { 7 | major: 2, 8 | minor: 0, 9 | patch: 0, 10 | next: null 11 | }; 12 | vitest.expect(parseSemver("2.0.0")).toStrictEqual(expected); 13 | 14 | expected = { 15 | major: 0, 16 | minor: 1, 17 | patch: 2, 18 | next: null 19 | }; 20 | vitest.expect(parseSemver("0.1.2")).toStrictEqual(expected); 21 | 22 | expected = { 23 | major: 10403, 24 | minor: 2043, 25 | patch: 850323, 26 | next: null 27 | }; 28 | vitest.expect(parseSemver("10403.2043.850323")).toStrictEqual(expected); 29 | 30 | expected = { 31 | major: 2, 32 | minor: 0, 33 | patch: 0, 34 | next: 3 35 | }; 36 | vitest.expect(parseSemver("2.0.0-next.3")).toStrictEqual(expected); 37 | 38 | vitest.expect(() => parseSemver("2.0")).toThrowError(); 39 | vitest.expect(() => parseSemver("2")).toThrowError(); 40 | vitest.expect(() => parseSemver("a.b.c")).toThrowError(); 41 | vitest.expect(() => parseSemver("2.0.0-beta.1")).toThrowError(); 42 | vitest.expect(() => parseSemver("2.0.0-next")).toThrowError(); 43 | vitest.expect(() => parseSemver("2.0.0-next.")).toThrowError(); 44 | vitest.expect(() => parseSemver("ff.ff.ff-next.1")).toThrowError(); 45 | vitest.expect(() => parseSemver("1.1.1-next.ff")).toThrowError(); 46 | vitest.expect(() => parseSemver("0xff.0xff.0xff-next.1")).toThrowError(); 47 | vitest.expect(() => parseSemver("1.1.1-next.0xff")).toThrowError(); 48 | vitest.expect(() => parseSemver("-1.-1.-1-next.1")).toThrowError(); 49 | vitest.expect(() => parseSemver("1.1.1-next.-1")).toThrowError(); 50 | vitest.expect(() => parseSemver("01.01.01-next.1")).toThrowError(); 51 | vitest.expect(() => parseSemver("1.1.1-next.01")).toThrowError(); 52 | vitest.expect(() => parseSemver("1a.1a.1a-next.1")).toThrowError(); 53 | vitest.expect(() => parseSemver("1.1.1-next.1a")).toThrowError(); 54 | }); 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Auri 2 | 3 | Organize package changes and releases in monolith repositories. 4 | 5 | ``` 6 | npm i -D auri 7 | yarn add -D auri 8 | pnpm add -D auri 9 | ``` 10 | 11 | Run commands: 12 | 13 | ``` 14 | npx auri 15 | pnpm auri 16 | yarn auri 17 | ``` 18 | 19 | ## Prerequisites 20 | 21 | Auri does not work on certain repository setups: 22 | 23 | - Your repository is hosted on GitHub. 24 | - Single monolith repository (no monorepos). 25 | - The package can be built and published with: `npm run build && npm publish`. 26 | - The package's `package.json` is in the repository root. 27 | - Pull requests are squashed and merge. 28 | 29 | In addition, it's built with a few opinions in mind: 30 | 31 | - Only supports version formats like 2.0.0 for normal releases and formats like 2.0.0-next.1 for prereleases (it must be next). 32 | - Prereleases are tagged as 'next' on NPM. 33 | - Non-latest, non-next releases (e.g. 1.8.0 when latest is 2.3.0) will be tagged as 'legacy' on NPM. 34 | 35 | ## Setup 36 | 37 | Install Auri via NPM and update your repository. 38 | 39 | ### 1. Generate access tokens 40 | 41 | Create an NPM automation access token (classic). 42 | 43 | ### 2. Create GitHub workflow 44 | 45 | Create a GitHub workflow that runs on every push. The NPM token should be named `NODE_AUTH_TOKEN` and the GitHub token as `AURI_NPM_TOKEN`. 46 | 47 | It is crucial that you setup `actions/checkout@v3` with `github.ref`. Auri expects the current branch to be the target branch. 48 | 49 | ```yaml 50 | # .github/workflows/publish.yaml 51 | name: "Publish package" 52 | on: [push] 53 | 54 | env: 55 | AURI_GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 56 | AURI_NPM_TOKEN: ${{secrets.AURI_NPM_TOKEN}} 57 | 58 | jobs: 59 | publish-package: 60 | name: Publish package and release with Auri 61 | runs-on: ubuntu-latest 62 | # TODO: Update repository name. 63 | if: github.repository == 'pilcrowonpaper/auri' && github.ref == 'refs/heads/main' 64 | permissions: 65 | contents: write 66 | id-token: write 67 | steps: 68 | - name: Setup actions 69 | uses: actions/checkout@v3 70 | with: 71 | ref: ${{ github.ref }} 72 | - name: Setup Node 73 | uses: actions/setup-node@v3 74 | with: 75 | node-version: 20 76 | registry-url: "https://registry.npmjs.org/" 77 | - name: Install dependencies 78 | run: npm install 79 | - name: Build package 80 | run: npm run build 81 | - name: Publish package and release 82 | run: npm run auri publish 83 | ``` 84 | 85 | ### 3. Configure permissions 86 | 87 | Go to your repository's settings, and go to "Code and automation" > "Actions" > "General." Go to "Workflow permissions" and enable: 88 | 89 | - "Read and write permissions" 90 | - "Allow GitHub Actions to create and approve pull requests" 91 | 92 | If your GitHub workflow have `permissions` defined, make sure `content` is set to `write`: 93 | 94 | ```yaml 95 | permissions: 96 | contents: write 97 | ``` 98 | 99 | ## Instructions 100 | 101 | When you're ready to publish your package, run `auri generate` on your local machine. This will create a `.COMMITS` file with a list of commits since the last release (the version in package.json). Commits starting with `docs:`, `style:`, or `test:` will be ignored. This will also create a `.RELEASE.md`. Using `.COMMITS` as a reference, write your changelog in `.RELEASE.md`. Update the version field in your package.json and commit the change. 102 | 103 | With the GitHub action, Auri will build and publish your package to NPM and use the `.RELEASE.md` to publish a new GitHub release. 104 | -------------------------------------------------------------------------------- /src/scripts/publish.ts: -------------------------------------------------------------------------------- 1 | import * as fs from "fs/promises"; 2 | import * as childprocess from "child_process"; 3 | 4 | import { parsePackageJSON } from "../utils/package.js"; 5 | import { env } from "../utils/env.js"; 6 | import { parseSemver, Semver } from "../utils/semver.js"; 7 | import { parseGitHubGitRepositoryURL, GitHubRepository } from "../utils/github.js"; 8 | 9 | export async function publishScript(): Promise { 10 | const npmToken = env("AURI_NPM_TOKEN"); 11 | if (!isSafeString(npmToken)) { 12 | throw new Error("Invalid NPM token"); 13 | } 14 | const npmTokenSafe = npmToken; 15 | 16 | const githubToken = env("AURI_GITHUB_TOKEN"); 17 | 18 | let releaseFileBytes: Uint8Array; 19 | try { 20 | releaseFileBytes = await fs.readFile(".RELEASE.md"); 21 | } catch { 22 | // File does no exist. 23 | return; 24 | } 25 | const releaseFile = new TextDecoder().decode(releaseFileBytes); 26 | 27 | const packageJSONFile = await fs.readFile("package.json"); 28 | const packageJSON: unknown = JSON.parse(packageJSONFile.toString()); 29 | const metadata = parsePackageJSON(packageJSON); 30 | 31 | let repository: GitHubRepository; 32 | try { 33 | repository = parseGitHubGitRepositoryURL(metadata.repository); 34 | } catch { 35 | throw new Error("Invalid GitHub repository URL"); 36 | } 37 | 38 | const publishedVersions = await getPublishedVersions(metadata.name); 39 | if (publishedVersions.includes(metadata.version)) { 40 | return; 41 | } 42 | 43 | const releaseTag = calculateReleaseTag(metadata.version, publishedVersions); 44 | 45 | try { 46 | childprocess.execSync("npm install"); 47 | } catch { 48 | throw new Error("Failed to install dependencies"); 49 | } 50 | 51 | try { 52 | childprocess.execSync("npm run build"); 53 | } catch { 54 | throw new Error("Failed to build package"); 55 | } 56 | 57 | if (releaseTag === ReleaseTag.Latest) { 58 | try { 59 | childprocess.execSync( 60 | `NODE_AUTH_TOKEN=${npmTokenSafe} npm publish --provenance --access=public` 61 | ); 62 | } catch { 63 | throw new Error("Failed to publish package as latest"); 64 | } 65 | } else if (releaseTag === ReleaseTag.Next) { 66 | try { 67 | childprocess.execSync( 68 | `NODE_AUTH_TOKEN=${npmTokenSafe} npm publish --provenance --access=public --tag=next` 69 | ); 70 | } catch { 71 | throw new Error("Failed to publish package as next"); 72 | } 73 | } else if (releaseTag === ReleaseTag.Legacy) { 74 | try { 75 | childprocess.execSync( 76 | `NODE_AUTH_TOKEN=${npmTokenSafe} npm publish --provenance --access=public --tag=legacy` 77 | ); 78 | } catch { 79 | throw new Error("Failed to publish package as legacy"); 80 | } 81 | } else { 82 | throw new Error("Invalid state"); 83 | } 84 | 85 | const currentBranch = getCurrentBranch(); 86 | try { 87 | await createGitHubRelease( 88 | githubToken, 89 | repository, 90 | currentBranch, 91 | metadata.version, 92 | releaseTag, 93 | releaseFile 94 | ); 95 | } catch { 96 | throw new Error("Failed to create GitHub release"); 97 | } 98 | 99 | childprocess.execSync(`git config user.name "github-actions[bot]"`); 100 | childprocess.execSync( 101 | `git config user.email "41898282+github-actions[bot]@users.noreply.github.com"` 102 | ); 103 | try { 104 | childprocess.execSync( 105 | `git remote set-url origin https://x-access-token:${githubToken}@github.com/${repository.owner}/${repository.name}.git` 106 | ); 107 | } catch { 108 | throw new Error("Failed to access repository."); 109 | } 110 | await fs.rm(".RELEASE.md"); 111 | 112 | try { 113 | childprocess.execSync("git add ."); 114 | childprocess.execSync(`git commit -m "delete .RELEASE.md"`); 115 | childprocess.execSync(`git push origin ${currentBranch}`); 116 | } catch { 117 | throw new Error("Failed to delete .RELEASE.md"); 118 | } 119 | } 120 | 121 | async function getPublishedVersions(name: string): Promise { 122 | const npmRegistryUrl = new URL(name, "https://registry.npmjs.org"); 123 | const npmRegistryResponse = await fetch(npmRegistryUrl); 124 | if (!npmRegistryResponse.ok) { 125 | throw new Error("Failed to fetch NPM data"); 126 | } 127 | const npmRegistry: unknown = await npmRegistryResponse.json(); 128 | if (typeof npmRegistry !== "object" || npmRegistry === null) { 129 | throw new Error("Failed to parse NPM data"); 130 | } 131 | let publishedVersions: string[]; 132 | if ("time" in npmRegistry && typeof npmRegistry.time === "object" && npmRegistry.time !== null) { 133 | publishedVersions = Object.keys(npmRegistry.time); 134 | } else { 135 | throw new Error("Failed to parse NPM data"); 136 | } 137 | return publishedVersions; 138 | } 139 | 140 | function calculateReleaseTag(currentVersion: string, publishedVersions: string[]): ReleaseTag { 141 | const currentSemver = parseSemver(currentVersion); 142 | if (currentSemver.next !== null) { 143 | return ReleaseTag.Next; 144 | } 145 | for (const publishedVersion of publishedVersions) { 146 | let publishedSemver: Semver; 147 | try { 148 | publishedSemver = parseSemver(publishedVersion); 149 | } catch { 150 | // Ignore unknown version formats. 151 | continue; 152 | } 153 | if (publishedSemver.next === null && publishedSemver.major > currentSemver.major) { 154 | return ReleaseTag.Legacy; 155 | } 156 | } 157 | return ReleaseTag.Latest; 158 | } 159 | 160 | enum ReleaseTag { 161 | Latest = 0, 162 | Next, 163 | Legacy 164 | } 165 | 166 | async function createGitHubRelease( 167 | token: string, 168 | repository: GitHubRepository, 169 | branch: string, 170 | version: string, 171 | releaseTag: ReleaseTag, 172 | body: string 173 | ): Promise { 174 | const requestBody = JSON.stringify({ 175 | tag_name: `v${version}`, 176 | target_commitish: branch, 177 | name: `v${version}`, 178 | body: body, 179 | make_latest: releaseTag === ReleaseTag.Latest ? "true" : "false", 180 | prerelease: releaseTag === ReleaseTag.Next 181 | }); 182 | const response = await fetch( 183 | `https://api.github.com/repos/${repository.owner}/${repository.name}/releases`, 184 | { 185 | method: "POST", 186 | body: requestBody, 187 | headers: { 188 | Authorization: `Bearer ${token}`, 189 | Accept: "application/json" 190 | } 191 | } 192 | ); 193 | if (response.body !== null) { 194 | await response.body.cancel(); 195 | } 196 | if (!response.ok) { 197 | throw new Error("Failed to create GitHub release"); 198 | } 199 | } 200 | 201 | function isSafeString(s: string): boolean { 202 | return /[a-zA-Z0-9.-_]*/.test(s); 203 | } 204 | 205 | function getCurrentBranch(): string { 206 | const bytes: Uint8Array = childprocess.execSync("git rev-parse --abbrev-ref HEAD"); 207 | const branch = new TextDecoder().decode(bytes).trim(); 208 | return branch; 209 | } 210 | --------------------------------------------------------------------------------