From dc26756c07d6251419395f879cb2949699fd3521 Mon Sep 17 00:00:00 2001 From: Peter Savchenko Date: Sat, 7 Feb 2026 19:00:27 +0300 Subject: [PATCH 1/5] github service, hasValue utils --- eslint.config.mjs | 12 +- package.json | 7 +- packages/core/README.md | 3 - packages/core/package.json | 36 - packages/core/src/index.ts | 8 - packages/core/tests/index.test.ts | 12 - packages/core/tsconfig.build.json | 7 - packages/github/README.md | 44 ++ packages/github/package.json | 44 ++ packages/github/src/index.ts | 9 + packages/github/src/normalizePrivateKey.ts | 58 ++ packages/github/src/service.ts | 690 +++++++++++++++++++ packages/github/src/types/index.ts | 78 +++ packages/github/tests/service.test.ts | 750 +++++++++++++++++++++ packages/github/tsconfig.build.json | 4 + packages/{core => github}/tsconfig.json | 15 +- packages/utils/package.json | 31 +- packages/utils/src/hasValue.ts | 8 + packages/utils/src/index.ts | 9 +- packages/utils/tests/hasValue.test.ts | 28 + packages/utils/tests/index.test.ts | 16 - packages/utils/tsconfig.build.json | 4 + packages/utils/tsconfig.json | 13 +- yarn.lock | 669 +++++++++++------- 24 files changed, 2205 insertions(+), 350 deletions(-) delete mode 100644 packages/core/README.md delete mode 100644 packages/core/package.json delete mode 100644 packages/core/src/index.ts delete mode 100644 packages/core/tests/index.test.ts delete mode 100644 packages/core/tsconfig.build.json create mode 100644 packages/github/README.md create mode 100644 packages/github/package.json create mode 100644 packages/github/src/index.ts create mode 100644 packages/github/src/normalizePrivateKey.ts create mode 100644 packages/github/src/service.ts create mode 100644 packages/github/src/types/index.ts create mode 100644 packages/github/tests/service.test.ts create mode 100644 packages/github/tsconfig.build.json rename packages/{core => github}/tsconfig.json (50%) create mode 100644 packages/utils/src/hasValue.ts create mode 100644 packages/utils/tests/hasValue.test.ts delete mode 100644 packages/utils/tests/index.test.ts create mode 100644 packages/utils/tsconfig.build.json diff --git a/eslint.config.mjs b/eslint.config.mjs index 669fa16..31a13a8 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -10,6 +10,14 @@ const __dirname = path.dirname(__filename); export default [ ...CodeX, ...EslintTestsConfig, + /* n/no-missing-import resolves from file dir and misses workspace deps; TypeScript validates imports via projectService */ + { + name: 'codex-lib-ts-workspace-resolve', + files: ['packages/**/*.ts'], + rules: { + 'n/no-missing-import': 'off', + }, + }, { name: 'codex-lib-ts', ignores: [ @@ -25,8 +33,8 @@ export default [ languageOptions: { parser: TsParser, parserOptions: { - project: path.resolve(__dirname, 'tsconfig.json'), - tsconfigRootDir: './', + projectService: true, + tsconfigRootDir: __dirname, sourceType: 'module', }, }, diff --git a/package.json b/package.json index 8c673a8..f663c26 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,6 @@ { - "name": "@codexteam/typescript-lib-template", + "name": "@hawk.so/kit", + "private": true, "version": "2.0.0", "description": "A quick start template for a new TypeScript library", "repository": "https://github.com/codex-team/typescript-lib-template.git", @@ -13,8 +14,8 @@ ], "scripts": { "clean": "rimraf -g \"packages/**/dist\" \"packages/**/*.tsbuildinfo\"", - "lint": "yarn workspaces foreach -A run lint", - "lint:fix": "yarn workspaces foreach -A run lint --fix", + "lint": "yarn workspaces foreach -At run build && yarn workspaces foreach -A run lint", + "lint:fix": "yarn workspaces foreach -At run build && yarn workspaces foreach -A run lint --fix", "test": "vitest --watch=false", "coverage": "vitest --watch=false --coverage", "preinstall": "npx only-allow yarn" diff --git a/packages/core/README.md b/packages/core/README.md deleted file mode 100644 index 1b78703..0000000 --- a/packages/core/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# @codexteam/typescript-lib-template Core - -This package contains the core of the library diff --git a/packages/core/package.json b/packages/core/package.json deleted file mode 100644 index f26bc90..0000000 --- a/packages/core/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "mylib", - "version": "0.0.0", - "type": "module", - "author": "CodeX ", - "exports": { - ".": { - "types": "./dist/types.d.ts", - "import": "./dist/index.js" - } - }, - "main": "./dist/index.js", - "types": "./dist/types.d.ts", - "files": [ - "dist" - ], - "scripts": { - "clean": "rimraf dist *.tsbuildinfo", - "lint": "eslint ./src", - "lint:fix": "yarn lint --fix", - "build": "tsc -p tsconfig.build.json", - "test:dev": "vitest", - "test": "vitest run", - "coverage": "vitest run --coverage" - }, - "dependencies": { - "mylib-utils": "workspace:^" - }, - "devDependencies": { - "@vitest/coverage-v8": "^2.1.4", - "eslint": "^9.14.0", - "rimraf": "^6.0.1", - "typescript": "^5.6.3", - "vitest": "^2.1.4" - } -} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts deleted file mode 100644 index d308854..0000000 --- a/packages/core/src/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { myUtil } from 'mylib-utils'; - -/** - * Simple function that returns string - */ -export default function main(): string { - return 'It works! ' + myUtil(1, 2); -} diff --git a/packages/core/tests/index.test.ts b/packages/core/tests/index.test.ts deleted file mode 100644 index ca58bf8..0000000 --- a/packages/core/tests/index.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import main from '../src/index'; -import { describe, test, expect } from 'vitest'; - -describe('My Package test', () => { - describe('main()', () => { - test('shoul return a contatinated string', () => { - const result = main(); - - expect(result).toBe('It works! 3'); - }); - }); -}); diff --git a/packages/core/tsconfig.build.json b/packages/core/tsconfig.build.json deleted file mode 100644 index 78e108d..0000000 --- a/packages/core/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "exclude": [ - "./tests/**/*", - "jest.config.ts" - ] -} diff --git a/packages/github/README.md b/packages/github/README.md new file mode 100644 index 0000000..b6eccda --- /dev/null +++ b/packages/github/README.md @@ -0,0 +1,44 @@ +# @hawk.so/github-sdk + +GitHub API client for Hawk. Unified service for GitHub App, Issues, OAuth. +Shared by API and Workers. + +## Build + +```bash +cd utils/packages/github && yarn build +``` + +Build before using in API or Workers (when using `file:` dependency). + +## Usage + +Pass configuration via constructor: + +```typescript +import { GitHubService, type GitHubServiceConfig } from '@hawk.so/github-sdk'; + +const config: GitHubServiceConfig = { + appId: process.env.GITHUB_APP_ID!, + privateKey: process.env.GITHUB_PRIVATE_KEY!, + appSlug: process.env.GITHUB_APP_SLUG, + clientId: process.env.GITHUB_APP_CLIENT_ID, + clientSecret: process.env.GITHUB_APP_CLIENT_SECRET, + apiUrl: process.env.API_URL, // required for getInstallationUrl, OAuth +}; + +const githubService = new GitHubService(config); +``` + +API and Workers read env vars and pass them to the constructor. + +## Config fields + +| Field | Required for | +|---------------|-----------------------------------------------| +| `appId` | all | +| `privateKey` | all (PEM format, `\n` escape sequences) | +| `appSlug` | optional (default: `hawk-tracker`) | +| `clientId` | OAuth (token exchange, refresh) | +| `clientSecret`| OAuth | +| `apiUrl` | `getInstallationUrl`, OAuth redirect URI. Hawk Api host. | diff --git a/packages/github/package.json b/packages/github/package.json new file mode 100644 index 0000000..f6dc991 --- /dev/null +++ b/packages/github/package.json @@ -0,0 +1,44 @@ +{ + "name": "@hawk.so/github-sdk", + "version": "1.0.0", + "description": "GitHub API client for Hawk (GitHub App, Issues, OAuth)", + "author": "CodeX ", + "license": "AGPL-3.0-only", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.js", + "import": "./dist/index.js" + } + }, + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "clean": "rimraf dist *.tsbuildinfo", + "lint": "eslint ./src", + "lint:fix": "eslint ./src --fix", + "build": "tsc -p tsconfig.build.json", + "test": "vitest run", + "test:dev": "vitest" + }, + "dependencies": { + "@hawk.so/utils": "workspace:*", + "@octokit/oauth-methods": "^4.0.0", + "@octokit/rest": "^22.0.1", + "@octokit/types": "^16.0.0", + "jsonwebtoken": "^9.0.3" + }, + "devDependencies": { + "@types/jsonwebtoken": "^8.3.5", + "eslint": "^9.14.0", + "rimraf": "^6.0.1", + "typescript": "^5.6.3", + "vitest": "^2.1.4" + }, + "engines": { + "node": ">=18.0.0" + } +} diff --git a/packages/github/src/index.ts b/packages/github/src/index.ts new file mode 100644 index 0000000..339b8c0 --- /dev/null +++ b/packages/github/src/index.ts @@ -0,0 +1,9 @@ +export { GitHubService } from './service'; +export type { + GitHubServiceConfig, + IssueData, + GitHubIssue, + Installation, + Repository +} from './types'; +export { normalizeGitHubPrivateKey } from './normalizePrivateKey'; diff --git a/packages/github/src/normalizePrivateKey.ts b/packages/github/src/normalizePrivateKey.ts new file mode 100644 index 0000000..7dfd687 --- /dev/null +++ b/packages/github/src/normalizePrivateKey.ts @@ -0,0 +1,58 @@ +/** + * Normalize and validate GitHub App private key. + * + * @param rawPrivateKey - raw value from env (GITHUB_PRIVATE_KEY) + * @returns PEM-encoded private key string + */ +export function normalizeGitHubPrivateKey(rawPrivateKey: string): string { + /** + * Trim and remove surrounding quotes (dotenv can keep them) + */ + let privateKey = rawPrivateKey.trim(); + + if ( + (privateKey.startsWith('"') && privateKey.endsWith('"')) || + (privateKey.startsWith('\'') && privateKey.endsWith('\'')) + ) { + privateKey = privateKey.slice(1, -1); + } + + /** + * Support passing base64-encoded private key (common in CI). + * If it doesn't look like a PEM block but looks like base64, decode it. + */ + const MIN_BASE64_KEY_LENGTH = 200; + + if (!privateKey.includes('BEGIN') && /^[A-Za-z0-9+/=\s]+$/.test(privateKey) && privateKey.length > MIN_BASE64_KEY_LENGTH) { + try { + privateKey = Buffer.from(privateKey, 'base64').toString('utf8'); + } catch { + /** + * Keep original value, we'll validate below. + */ + } + } + + /** + * Replace literal "\n" sequences with actual newlines. + */ + if (privateKey.includes('\\n') && !privateKey.includes('\n')) { + privateKey = privateKey.replace(/\\n/g, '\n'); + } + + /** + * Normalize Windows line endings if any. + */ + privateKey = privateKey.replace(/\r\n/g, '\n'); + + /** + * Basic validation: must be a PEM private key. + */ + if (!privateKey.includes('-----BEGIN') || !privateKey.includes('PRIVATE KEY-----')) { + throw new Error( + 'GITHUB_PRIVATE_KEY must be a valid PEM-encoded private key (-----BEGIN ... PRIVATE KEY----- ... -----END ... PRIVATE KEY-----)' + ); + } + + return privateKey; +} diff --git a/packages/github/src/service.ts b/packages/github/src/service.ts new file mode 100644 index 0000000..1a69457 --- /dev/null +++ b/packages/github/src/service.ts @@ -0,0 +1,690 @@ +import jwt from 'jsonwebtoken'; +import { Octokit } from '@octokit/rest'; +import { exchangeWebFlowCode, refreshToken as refreshOAuthToken } from '@octokit/oauth-methods'; +import { hasValue } from '@hawk.so/utils'; +import { normalizeGitHubPrivateKey } from './normalizePrivateKey'; +import type { + GitHubServiceConfig, + Installation, + Repository, + IssueData, + GitHubIssue +} from './types'; + +/** + * Milliseconds in one minute + */ +const MINUTE_MS = 60_000; + +/** + * Buffer time before token expiration to trigger refresh (5 minutes) + */ +// eslint-disable-next-line @typescript-eslint/no-magic-numbers +const TOKEN_REFRESH_BUFFER_MS = 5 * MINUTE_MS; + +/** + * Service for interacting with GitHub API + */ +export class GitHubService { + // eslint-disable-next-line @typescript-eslint/naming-convention + private static readonly DEFAULT_TIMEOUT = 10000; + // eslint-disable-next-line @typescript-eslint/naming-convention + private static readonly JWT_EXPIRATION_MINUTES = 10; + + private readonly appId: string; + private readonly privateKey: string; + private readonly appSlug: string; + private readonly clientId?: string; + private readonly clientSecret?: string; + private readonly apiUrl?: string; + + /** + * Creates a GitHubService instance. + * @param config - App credentials and optional OAuth/API settings (e.g. from env). + */ + constructor(config: GitHubServiceConfig) { + if (!hasValue(config.appId)) { + throw new Error('appId is required'); + } + + if (!hasValue(config.privateKey)) { + throw new Error('privateKey is required'); + } + + this.appId = config.appId; + this.privateKey = normalizeGitHubPrivateKey(config.privateKey); + this.appSlug = hasValue(config.appSlug) ? config.appSlug : 'hawk-tracker'; + this.clientId = config.clientId; + this.clientSecret = config.clientSecret; + this.apiUrl = config.apiUrl; + } + + /** + * Returns the GitHub App installation URL for the given state. + * @param state - Opaque state string to pass through the OAuth flow. + * @returns Full URL to start the app installation flow. + */ + public getInstallationUrl(state: string): string { + if (!hasValue(this.apiUrl)) { + throw new Error('apiUrl is required for getInstallationUrl (pass it in constructor config)'); + } + + const redirectUrl = `${this.apiUrl}/integration/github/oauth`; + + return `https://github.com/apps/${this.appSlug}/installations/new?state=${encodeURIComponent(state)}&redirect_url=${encodeURIComponent(redirectUrl)}`; + } + + /** + * Uninstalls the GitHub App from the given installation. + * @param installationId - GitHub App installation ID. + */ + public async deleteInstallation(installationId: string): Promise { + const token = this.createJWT(); + const octokit = this.createOctokit(token); + + await octokit.rest.apps.deleteInstallation({ + // eslint-disable-next-line @typescript-eslint/naming-convention + installation_id: parseInt(installationId, 10), + }); + } + + /** + * Fetches installation metadata for the given installation ID. + * @param installationId - GitHub App installation ID. + * @returns Installation details (id, account, target_type, permissions). + */ + public async getInstallationForRepository(installationId: string): Promise { + const token = this.createJWT(); + const octokit = this.createOctokit(token); + + try { + const { data } = await octokit.rest.apps.getInstallation({ + // eslint-disable-next-line @typescript-eslint/naming-convention + installation_id: parseInt(installationId, 10), + }); + + let accountLogin = ''; + let accountType = ''; + + if (data.account) { + if ('login' in data.account) { + accountLogin = data.account.login; + accountType = 'login' in data.account && 'type' in data.account ? data.account.type : 'User'; + } else if ('slug' in data.account) { + accountLogin = data.account.slug; + accountType = 'Organization'; + } + } + + return { + id: data.id, + account: { + login: accountLogin, + type: accountType, + }, + // eslint-disable-next-line @typescript-eslint/naming-convention + target_type: data.target_type, + permissions: data.permissions ?? {}, + }; + } catch (error) { + throw new Error(`Failed to get installation: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Lists repositories accessible to the given installation, sorted by last updated. + * @param installationId - GitHub App installation ID. + * @returns Array of repository summaries. + */ + public async getRepositoriesForInstallation(installationId: string): Promise { + if (!hasValue(installationId)) { + throw new Error('installationId is required for getting repositories'); + } + + const accessToken = await this.createInstallationToken(installationId); + const octokit = this.createOctokit(accessToken); + + try { + const jwtToken = this.createJWT(); + const jwtOctokit = this.createOctokit(jwtToken); + + const installationInfo = await jwtOctokit.rest.apps.getInstallation({ + // eslint-disable-next-line @typescript-eslint/naming-convention + installation_id: parseInt(installationId, 10), + }); + + console.log('Installation info:', { + id: installationInfo.data.id, + account: installationInfo.data.account, + // eslint-disable-next-line @typescript-eslint/naming-convention + target_type: installationInfo.data.target_type, + // eslint-disable-next-line @typescript-eslint/naming-convention + repository_selection: installationInfo.data.repository_selection, + }); + + const repositoriesData = await octokit.paginate( + octokit.rest.apps.listReposAccessibleToInstallation, + { + // eslint-disable-next-line @typescript-eslint/naming-convention + installation_id: parseInt(installationId, 10), + // eslint-disable-next-line @typescript-eslint/naming-convention + per_page: 100, + } + ); + + console.log(`Total repositories fetched: ${repositoriesData.length}`); + + const repositories = repositoriesData.map(repo => ({ + id: repo.id.toString(), + name: repo.name, + fullName: repo.full_name, + private: repo.private || false, + htmlUrl: repo.html_url, + updatedAt: hasValue(repo.updated_at) ? new Date(repo.updated_at) : new Date(0), + language: hasValue(repo.language) ? repo.language : null, + })); + + return repositories.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime()); + } catch (error) { + throw new Error(`Failed to get repositories: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Creates a GitHub issue in the given repository using installation access. + * @param repoFullName - Repository in "owner/repo" format. + * @param installationId - GitHub App installation ID (required). + * @param issueData - Issue title, body, and optional labels. + * @returns Created issue (number, html_url, title, state). + */ + public async createIssue( + repoFullName: string, + installationId: string | null, + issueData: IssueData + ): Promise { + const [owner, repo] = repoFullName.split('/'); + + if (!hasValue(owner) || !hasValue(repo)) { + throw new Error(`Invalid repository name format: ${repoFullName}. Expected format: owner/repo`); + } + + if (!hasValue(installationId)) { + throw new Error('installationId is required for creating GitHub issues'); + } + + const accessToken = await this.createInstallationToken(installationId); + const octokit = this.createOctokit(accessToken); + + try { + const { data } = await octokit.rest.issues.create({ + owner, + repo, + title: issueData.title, + body: issueData.body, + labels: issueData.labels, + }); + + return { + number: data.number, + // eslint-disable-next-line @typescript-eslint/naming-convention + html_url: data.html_url, + title: data.title, + state: data.state, + }; + } catch (error) { + throw new Error(`Failed to create issue: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Assigns the Copilot coding agent (copilot-swe-agent) to the given issue via GraphQL. + * @param repoFullName - Repository in "owner/repo" format. + * @param issueNumber - Number of the issue in the repository. + * @param delegatedUserToken - User access token with repo scope (e.g. from OAuth). + */ + public async assignCopilot( + repoFullName: string, + issueNumber: number, + delegatedUserToken: string + ): Promise { + const [owner, repo] = repoFullName.split('/'); + + if (!owner || !repo) { + throw new Error(`Invalid repository name format: ${repoFullName}. Expected format: owner/repo`); + } + + const octokit = this.createOctokit(delegatedUserToken); + + try { + const suggestedActorsLimit = 100; + const repoInfoQuery = ` + query($owner: String!, $name: String!, $issueNumber: Int!) { + repository(owner: $owner, name: $name) { + id + issue(number: $issueNumber) { + id + } + suggestedActors(capabilities: [CAN_BE_ASSIGNED], first: ${suggestedActorsLimit}) { + nodes { + login + __typename + ... on Bot { + id + } + ... on User { + id + } + } + } + } + } + `; + + /** GraphQL response shape for repository + issue + suggestedActors query. */ + /* eslint-disable jsdoc/require-jsdoc */ + type RepoInfoGraphQLResponse = { + repository?: { + id: string; + issue?: { id: string }; + suggestedActors: { + nodes: Array<{ login: string; __typename?: string; id?: string }>; + }; + }; + }; + /* eslint-enable jsdoc/require-jsdoc */ + + const repoInfo = await octokit.graphql(repoInfoQuery, { + owner, + name: repo, + issueNumber, + }); + + console.log('[GitHub API] Repository info query response:', JSON.stringify(repoInfo, null, 2)); + + const repositoryId = repoInfo?.repository?.id; + const issueId = repoInfo?.repository?.issue?.id; + + if (!hasValue(repositoryId)) { + throw new Error(`Failed to get repository ID for ${repoFullName}`); + } + + if (!hasValue(issueId)) { + throw new Error(`Failed to get issue ID for issue #${issueNumber}`); + } + + /** Node in suggestedActors (login, optional __typename and id). */ + /* eslint-disable-next-line jsdoc/require-jsdoc */ + type SuggestedActorNode = { login: string; __typename?: string; id?: string }; + let copilotBot = (repoInfo?.repository?.suggestedActors?.nodes ?? []).find( + (node: SuggestedActorNode) => node.login === 'copilot-swe-agent' + ); + + console.log('[GitHub API] Copilot bot found in suggestedActors:', copilotBot ? { login: copilotBot.login, id: copilotBot.id } : 'not found'); + + if (!hasValue(copilotBot) || !hasValue(copilotBot?.id)) { + console.log('[GitHub API] Trying to get Copilot bot directly by login...'); + + try { + const copilotBotQuery = ` + query($login: String!) { + user(login: $login) { + id + login + __typename + } + } + `; + + /** GraphQL response shape for user(login) query. */ + /* eslint-disable jsdoc/require-jsdoc */ + type CopilotUserInfoGraphQLResponse = { + user?: { id: string; login: string; __typename?: string }; + }; + /* eslint-enable jsdoc/require-jsdoc */ + + const copilotUserInfo = await octokit.graphql(copilotBotQuery, { + login: 'copilot-swe-agent', + }); + + console.log('[GitHub API] Direct Copilot bot query response:', JSON.stringify(copilotUserInfo, null, 2)); + + if (hasValue(copilotUserInfo?.user?.id)) { + copilotBot = { + login: copilotUserInfo.user.login, + id: copilotUserInfo.user.id, + }; + } + } catch (directQueryError) { + console.log('[GitHub API] Failed to get Copilot bot directly:', directQueryError); + } + } + + if (!hasValue(copilotBot) || !hasValue(copilotBot?.id)) { + throw new Error('Copilot coding agent (copilot-swe-agent) is not available for this repository'); + } + + console.log('[GitHub API] Using Copilot bot:', { login: copilotBot.login, id: copilotBot.id }); + + const assignCopilotMutation = ` + mutation($issueId: ID!, $assigneeIds: [ID!]!) { + addAssigneesToAssignable(input: { + assignableId: $issueId + assigneeIds: $assigneeIds + }) { + assignable { + ... on Issue { + id + number + assignees(first: 10) { + nodes { + login + } + } + } + ... on PullRequest { + id + number + assignees(first: 10) { + nodes { + login + } + } + } + } + } + } + `; + + /** GraphQL response shape for addAssigneesToAssignable mutation. */ + /* eslint-disable jsdoc/require-jsdoc */ + type AssignCopilotGraphQLResponse = { + addAssigneesToAssignable?: { + assignable?: { + id: string; + number: number; + assignees?: { nodes?: Array<{ login: string }> }; + }; + }; + }; + /* eslint-enable jsdoc/require-jsdoc */ + + const response = await octokit.graphql(assignCopilotMutation, { + issueId, + assigneeIds: [copilotBot.id], + }); + + console.log('[GitHub API] Assign Copilot mutation response:', JSON.stringify(response, null, 2)); + + const assignable = response?.addAssigneesToAssignable?.assignable; + + if (!assignable) { + throw new Error('Failed to assign Copilot to issue'); + } + + /* eslint-disable-next-line jsdoc/require-jsdoc */ + const assignedLogins = assignable.assignees?.nodes?.map((n: { login: string }) => n.login) || []; + console.log(`[GitHub API] Issue assignees after mutation:`, assignedLogins); + + const assignedNumber = assignable.number; + + if (assignedLogins.includes('copilot-swe-agent')) { + console.log(`[GitHub API] Successfully assigned Copilot to issue #${assignedNumber}`); + } else { + console.log(`[GitHub API] Copilot assignment mutation completed for issue #${assignedNumber}, but assignees list not yet updated in response`); + } + } catch (error) { + throw new Error(`Failed to assign Copilot: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Returns a valid access token, refreshing it if expired or near expiry. + * Used by workers when assigning Copilot with delegated user token. + * @param tokenInfo - Current access/refresh tokens and their expiry dates. + * @param onRefresh - Optional callback invoked when tokens are refreshed (e.g. to persist). + * @returns Valid access token string. + */ + public async getValidAccessToken( + /* eslint-disable jsdoc/require-jsdoc */ + tokenInfo: { + accessToken: string; + refreshToken: string; + accessTokenExpiresAt: Date | null; + refreshTokenExpiresAt: Date | null; + }, + onRefresh?: (newTokens: { + accessToken: string; + refreshToken: string; + expiresAt: Date | null; + refreshTokenExpiresAt: Date | null; + }) => Promise + /* eslint-enable jsdoc/require-jsdoc */ + ): Promise { + const now = new Date(); + + if (tokenInfo.accessTokenExpiresAt) { + const timeUntilExpiration = tokenInfo.accessTokenExpiresAt.getTime() - now.getTime(); + + if (timeUntilExpiration <= TOKEN_REFRESH_BUFFER_MS) { + if (!hasValue(tokenInfo.refreshToken)) { + throw new Error('Access token expired and no refresh token available'); + } + + if (tokenInfo.refreshTokenExpiresAt && tokenInfo.refreshTokenExpiresAt <= now) { + throw new Error('Refresh token is expired'); + } + + if (!hasValue(this.clientId) || !hasValue(this.clientSecret)) { + throw new Error('GITHUB_APP_CLIENT_ID and GITHUB_APP_CLIENT_SECRET are required for token refresh'); + } + + const newTokens = await this.refreshUserToken(tokenInfo.refreshToken); + + if (onRefresh) { + await onRefresh(newTokens); + } + + return newTokens.accessToken; + } + } + + return tokenInfo.accessToken; + } + + /** + * Exchanges an OAuth authorization code for access and refresh tokens. + * @param code - Authorization code from GitHub OAuth callback. + * @param redirectUri - Redirect URI used in the OAuth request (defaults to apiUrl + /integration/github/oauth). + * @returns Access token, refresh token, expiry dates, and authenticated user. + */ + /* eslint-disable jsdoc/require-jsdoc */ + public async exchangeOAuthCodeForToken( + code: string, + redirectUri?: string + ): Promise<{ + accessToken: string; + refreshToken: string; + expiresAt: Date | null; + refreshTokenExpiresAt: Date | null; + user: { id: number; login: string }; + }> { + /* eslint-enable jsdoc/require-jsdoc */ + if (!hasValue(this.clientId) || !hasValue(this.clientSecret)) { + throw new Error('GITHUB_APP_CLIENT_ID and GITHUB_APP_CLIENT_SECRET are required for OAuth token exchange'); + } + + try { + if (!hasValue(redirectUri)) { + if (!hasValue(this.apiUrl)) { + throw new Error('apiUrl is required for exchangeOAuthCodeForToken when redirectUri is not provided (pass it in constructor config)'); + } + redirectUri = `${this.apiUrl}/integration/github/oauth`; + } + + const { authentication } = await exchangeWebFlowCode({ + clientType: 'github-app', + clientId: this.clientId, + clientSecret: this.clientSecret, + code, + redirectUrl: redirectUri, + }); + + if (!authentication.token) { + throw new Error('No access token in OAuth response'); + } + + const accessToken = authentication.token; + const refreshToken = 'refreshToken' in authentication && authentication.refreshToken + ? authentication.refreshToken + : ''; + const expiresAt = 'expiresAt' in authentication && authentication.expiresAt + ? new Date(authentication.expiresAt) + : null; + const refreshTokenExpiresAt = 'refreshTokenExpiresAt' in authentication && authentication.refreshTokenExpiresAt + ? new Date(authentication.refreshTokenExpiresAt) + : null; + + const octokit = this.createOctokit(accessToken); + const { data: userData } = await octokit.rest.users.getAuthenticated(); + + return { + accessToken, + refreshToken, + expiresAt, + refreshTokenExpiresAt, + user: { id: userData.id, login: userData.login }, + }; + } catch (error) { + throw new Error(`Failed to exchange OAuth code for token: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Checks whether a user access token is valid and returns user info if so. + * @param accessToken - GitHub user access token (e.g. from OAuth). + * @returns valid, optional user (id, login), and status ('active' or 'revoked'). + */ + /* eslint-disable jsdoc/require-jsdoc */ + public async validateUserToken(accessToken: string): Promise<{ valid: boolean; user?: { id: number; login: string }; status: 'active' | 'revoked' }> { + try { + const octokit = this.createOctokit(accessToken); + const { data: userData } = await octokit.rest.users.getAuthenticated(); + + return { + valid: true, + user: { id: userData.id, login: userData.login }, + status: 'active', + }; + } catch (error: unknown) { + const err = error as { status?: number }; + /* eslint-enable jsdoc/require-jsdoc */ + if (err?.status === 401 || err?.status === 403) { + return { valid: false, status: 'revoked' }; + } + throw new Error(`Failed to validate user token: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Refreshes a user OAuth token using the refresh token. + * @param refreshToken - Current refresh token. + * @returns New access token, refresh token, and expiry dates. + */ + /* eslint-disable jsdoc/require-jsdoc */ + public async refreshUserToken(refreshToken: string): Promise<{ + accessToken: string; + refreshToken: string; + expiresAt: Date | null; + refreshTokenExpiresAt: Date | null; + }> { + /* eslint-enable jsdoc/require-jsdoc */ + if (!hasValue(this.clientId) || !hasValue(this.clientSecret)) { + throw new Error('GITHUB_APP_CLIENT_ID and GITHUB_APP_CLIENT_SECRET are required for token refresh'); + } + + try { + const { authentication } = await refreshOAuthToken({ + clientType: 'github-app', + clientId: this.clientId, + clientSecret: this.clientSecret, + refreshToken, + }); + + if (!authentication.token) { + throw new Error('No access token in refresh response'); + } + + const newRefreshToken = 'refreshToken' in authentication + ? authentication.refreshToken || refreshToken + : refreshToken; + + return { + accessToken: authentication.token, + refreshToken: newRefreshToken, + expiresAt: 'expiresAt' in authentication && authentication.expiresAt + ? new Date(authentication.expiresAt) + : null, + refreshTokenExpiresAt: 'refreshTokenExpiresAt' in authentication && authentication.refreshTokenExpiresAt + ? new Date(authentication.refreshTokenExpiresAt) + : null, + }; + } catch (error) { + throw new Error(`Failed to refresh user token: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Creates an Octokit client with the given auth token and default timeout/headers. + * @param auth - GitHub token (JWT or user access token). + * @returns Octokit instance. + */ + private createOctokit(auth: string): Octokit { + return new Octokit({ + auth, + request: { + timeout: GitHubService.DEFAULT_TIMEOUT, + headers: { + // eslint-disable-next-line @typescript-eslint/naming-convention + 'GraphQL-Features': 'issues_copilot_assignment_api_support', + }, + }, + }); + } + + /** + * Creates a JWT for GitHub App authentication (installation/auth as app). + * @returns Signed JWT string. + */ + private createJWT(): string { + const privateKey = this.privateKey; + const now = Math.floor(Date.now() / 1000); + + const payload = { + iat: now - 60, + exp: now + GitHubService.JWT_EXPIRATION_MINUTES * 60, + iss: this.appId, + }; + + return jwt.sign(payload, privateKey, { algorithm: 'RS256' }); + } + + /** + * Creates an installation access token for the given installation ID. + * @param installationId - GitHub App installation ID. + * @returns Installation access token string. + */ + private async createInstallationToken(installationId: string): Promise { + const token = this.createJWT(); + const octokit = this.createOctokit(token); + + try { + const { data } = await octokit.rest.apps.createInstallationAccessToken({ + // eslint-disable-next-line @typescript-eslint/naming-convention + installation_id: parseInt(installationId, 10), + }); + return data.token; + } catch (error) { + throw new Error(`Failed to create installation token: ${error instanceof Error ? error.message : String(error)}`); + } + } +} diff --git a/packages/github/src/types/index.ts b/packages/github/src/types/index.ts new file mode 100644 index 0000000..f74c34f --- /dev/null +++ b/packages/github/src/types/index.ts @@ -0,0 +1,78 @@ +import type { Endpoints } from '@octokit/types'; + +/** + * Parameters for creating a GitHub Issue. + * Extracted from Octokit types for POST /repos/{owner}/{repo}/issues. + */ +export type IssueData = Pick< + Endpoints['POST /repos/{owner}/{repo}/issues']['parameters'], + 'title' | 'body' | 'labels' +>; + +/** + * GitHub Issue as returned by the API. + * Extracted from Octokit types for POST /repos/{owner}/{repo}/issues response. + */ +export type GitHubIssue = Pick< + Endpoints['POST /repos/{owner}/{repo}/issues']['response']['data'], + 'number' | 'html_url' | 'title' | 'state' +>; + +/** + * GitHub Repository data. + * Ephemeral data, not stored in database. + */ +export type Repository = { + /** Repository ID (node_id). */ + id: string; + /** Repository name without owner. */ + name: string; + /** Full name "owner/name". */ + fullName: string; + /** Whether the repository is private. */ + private: boolean; + /** URL of the repository on GitHub. */ + htmlUrl: string; + /** Last update time. */ + updatedAt: Date; + /** Primary language or null if unknown. */ + language: string | null; +}; + +/** + * GitHub App Installation as returned by the API. + */ +export type Installation = { + /** Installation ID. */ + id: number; + /** Account where the app is installed. */ + account: { + /** GitHub username or org login. */ + login: string; + /** Account type (e.g. "User", "Organization"). */ + type: string; + }; + /** Target type of the installation (e.g. "User", "Organization"). */ + target_type: string; + /** Permissions granted to the app (scope -> access level). */ + permissions: Record; +}; + +/** + * Configuration for GitHubService. + * Values should be read from env by the caller (API, Workers) and passed in. + */ +export interface GitHubServiceConfig { + /** GitHub App ID. */ + appId: string; + /** PEM private key for the GitHub App. */ + privateKey: string; + /** App slug (URL name). Defaults to "hawk-tracker" if omitted. */ + appSlug?: string; + /** OAuth App client ID for user login flow. */ + clientId?: string; + /** OAuth App client secret for user login flow. */ + clientSecret?: string; + /** Base URL of the API (e.g. for GitHub Enterprise). */ + apiUrl?: string; +} diff --git a/packages/github/tests/service.test.ts b/packages/github/tests/service.test.ts new file mode 100644 index 0000000..7390080 --- /dev/null +++ b/packages/github/tests/service.test.ts @@ -0,0 +1,750 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import jwt from 'jsonwebtoken'; +import { GitHubService } from '../src/service'; + +const mockOctokitRef = vi.hoisted(() => ({ current: null as Record | null })); +const mockExchangeWebFlowCode = vi.fn(); +const mockRefreshOAuthToken = vi.fn(); + +vi.mock('@octokit/rest', () => ({ + Octokit: vi.fn().mockImplementation(() => mockOctokitRef.current), +})); + +vi.mock('@octokit/oauth-methods', () => ({ + exchangeWebFlowCode: (...args: unknown[]) => mockExchangeWebFlowCode(...args), + refreshToken: (...args: unknown[]) => mockRefreshOAuthToken(...args), +})); + +vi.mock('jsonwebtoken'); + +describe('GitHubService', () => { + let githubService: GitHubService; + const testAppId = '123456'; + const testAppSlug = 'hawk-tracker'; + const testPrivateKey = '-----BEGIN RSA PRIVATE KEY-----\nTEST_KEY\n-----END RSA PRIVATE KEY-----'; + const testClientId = 'Iv1.client-id'; + const testClientSecret = 'client-secret'; + const testInstallationId = '789012'; + const testApiUrl = 'https://api.example.com'; + + let mockOctokit: { + rest: { + apps: { + createInstallationAccessToken: ReturnType; + getInstallation: ReturnType; + deleteInstallation: ReturnType; + listReposAccessibleToInstallation: ReturnType; + }; + issues: { + create: ReturnType; + addAssignees: ReturnType; + }; + users: { + getAuthenticated: ReturnType; + }; + }; + graphql: ReturnType; + paginate: ReturnType; + }; + + const createMockOctokit = () => ({ + rest: { + apps: { + createInstallationAccessToken: vi.fn(), + getInstallation: vi.fn(), + deleteInstallation: vi.fn(), + listReposAccessibleToInstallation: vi.fn(), + }, + issues: { + create: vi.fn(), + addAssignees: vi.fn(), + }, + users: { + getAuthenticated: vi.fn(), + }, + }, + graphql: vi.fn(), + paginate: vi.fn(), + }); + + const getConfig = () => ({ + appId: testAppId, + privateKey: testPrivateKey, + appSlug: testAppSlug, + clientId: testClientId, + clientSecret: testClientSecret, + apiUrl: testApiUrl, + }); + + beforeEach(() => { + vi.clearAllMocks(); + + mockOctokit = createMockOctokit(); + mockOctokitRef.current = mockOctokit; + + githubService = new GitHubService(getConfig()); + }); + + describe('constructor', () => { + it('should throw if appId is missing', () => { + expect(() => { + new GitHubService({ + ...getConfig(), + appId: '', + }); + }).toThrow('appId is required'); + }); + + it('should throw if privateKey is missing', () => { + expect(() => { + new GitHubService({ + ...getConfig(), + privateKey: '', + }); + }).toThrow('privateKey is required'); + }); + }); + + describe('getInstallationUrl', () => { + it('should generate installation URL with state and redirect_url parameters url encoded', () => { + const state = 'test-state-123'; + + const url = githubService.getInstallationUrl(state); + + expect(url).toBe( + `https://github.com/apps/${testAppSlug}/installations/new?state=${encodeURIComponent(state)}&redirect_url=${encodeURIComponent(`${testApiUrl}/integration/github/oauth`)}` + ); + }); + + it('should throw error if apiUrl is not provided in config', () => { + const serviceWithoutApiUrl = new GitHubService({ + appId: testAppId, + privateKey: testPrivateKey, + appSlug: testAppSlug, + }); + + expect(() => { + serviceWithoutApiUrl.getInstallationUrl('test-state'); + }).toThrow('apiUrl is required for getInstallationUrl (pass it in constructor config)'); + }); + }); + + describe('getInstallationForRepository', () => { + const mockJwtToken = 'mock-jwt-token'; + + it('should get installation information for User account', async () => { + vi.mocked(jwt.sign).mockImplementation(() => mockJwtToken); + + /* eslint-disable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + mockOctokit.rest.apps.getInstallation.mockResolvedValue({ + data: { + id: 12345, + account: { + login: 'octocat', + type: 'User', + id: 1, + node_id: 'MDQ6VXNlcjE=', + avatar_url: 'https://github.com/images/error/octocat_happy.gif', + }, + target_type: 'User', + permissions: { + issues: 'write', + metadata: 'read', + }, + }, + } as any); + /* eslint-enable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + + const result = await githubService.getInstallationForRepository(testInstallationId); + + expect(result).toEqual({ + id: 12345, + account: { + login: 'octocat', + type: 'User', + }, + target_type: 'User', + permissions: { + issues: 'write', + metadata: 'read', + }, + }); + + expect(mockOctokit.rest.apps.getInstallation).toHaveBeenCalledWith({ + installation_id: parseInt(testInstallationId, 10), + }); + }); + + it('should get installation information for Organization account', async () => { + vi.mocked(jwt.sign).mockImplementation(() => mockJwtToken); + + /* eslint-disable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + mockOctokit.rest.apps.getInstallation.mockResolvedValue({ + data: { + id: 12345, + account: { + slug: 'my-org', + type: 'Organization', + id: 1, + node_id: 'MDEyOk9yZ2FuaXphdGlvbjE=', + avatar_url: 'https://github.com/images/error/octocat_happy.gif', + }, + target_type: 'Organization', + permissions: { + issues: 'write', + metadata: 'read', + }, + }, + } as any); + /* eslint-enable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + + const result = await githubService.getInstallationForRepository(testInstallationId); + + expect(result).toEqual({ + id: 12345, + account: { + login: 'my-org', + type: 'Organization', + }, + target_type: 'Organization', + permissions: { + issues: 'write', + metadata: 'read', + }, + }); + }); + + it('should throw error if request fails', async () => { + vi.mocked(jwt.sign).mockImplementation(() => mockJwtToken); + + mockOctokit.rest.apps.getInstallation.mockRejectedValue(new Error('Network error')); + + await expect( + githubService.getInstallationForRepository(testInstallationId) + ).rejects.toThrow('Failed to get installation'); + }); + }); + + describe('createIssue', () => { + const mockJwtToken = 'mock-jwt-token'; + const mockInstallationToken = 'mock-installation-token'; + + beforeEach(() => { + vi.mocked(jwt.sign).mockImplementation(() => mockJwtToken); + + /* eslint-disable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + mockOctokit.rest.apps.createInstallationAccessToken.mockResolvedValue({ + data: { + token: mockInstallationToken, + expires_at: '2025-01-01T00:00:00Z', + }, + } as any); + /* eslint-enable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + }); + + it('should create issue successfully', async () => { + const issueData = { + title: 'Test Issue', + body: 'Test body', + labels: ['bug'], + }; + + /* eslint-disable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + mockOctokit.rest.issues.create.mockResolvedValue({ + data: { + number: 123, + html_url: 'https://github.com/owner/repo/issues/123', + title: 'Test Issue', + state: 'open', + }, + } as any); + /* eslint-enable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + + const result = await githubService.createIssue('owner/repo', testInstallationId, issueData); + + expect(result).toEqual({ + number: 123, + html_url: 'https://github.com/owner/repo/issues/123', + title: 'Test Issue', + state: 'open', + }); + + expect(mockOctokit.rest.issues.create).toHaveBeenCalledWith({ + owner: 'owner', + repo: 'repo', + title: 'Test Issue', + body: 'Test body', + labels: ['bug'], + }); + }); + + it('should create issue without labels', async () => { + const issueData = { + title: 'Test Issue', + body: 'Test body', + }; + + /* eslint-disable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + mockOctokit.rest.issues.create.mockResolvedValue({ + data: { + number: 124, + html_url: 'https://github.com/owner/repo/issues/124', + title: 'Test Issue', + state: 'open', + }, + } as any); + /* eslint-enable @typescript-eslint/camelcase, camelcase, @typescript-eslint/no-explicit-any */ + + const result = await githubService.createIssue('owner/repo', testInstallationId, issueData); + + expect(result.number).toBe(124); + expect(mockOctokit.rest.issues.create).toHaveBeenCalledWith({ + owner: 'owner', + repo: 'repo', + title: 'Test Issue', + body: 'Test body', + labels: undefined, + }); + }); + + it('should throw error for invalid repository name format', async () => { + const issueData = { + title: 'Test Issue', + body: 'Test body', + }; + + await expect( + githubService.createIssue('invalid-repo-name', testInstallationId, issueData) + ).rejects.toThrow('Invalid repository name format: invalid-repo-name. Expected format: owner/repo'); + }); + + it('should throw error if issue creation fails', async () => { + const issueData = { + title: 'Test Issue', + body: 'Test body', + }; + + mockOctokit.rest.issues.create.mockRejectedValue(new Error('Repository not found')); + + await expect( + githubService.createIssue('owner/repo', testInstallationId, issueData) + ).rejects.toThrow('Failed to create issue'); + }); + }); + + describe('assignCopilot', () => { + const mockDelegatedUserToken = 'mock-delegated-user-token'; + + it('should assign Copilot to issue successfully', async () => { + const issueNumber = 123; + + mockOctokit.graphql + .mockResolvedValueOnce({ + repository: { + id: 'repo-123', + issue: { id: 'issue-456' }, + suggestedActors: { + nodes: [ + { + login: 'copilot-swe-agent', + __typename: 'Bot', + id: 'bot-789', + }, + ], + }, + }, + }) + .mockResolvedValueOnce({ + addAssigneesToAssignable: { + assignable: { + id: 'issue-456', + number: issueNumber, + assignees: { nodes: [] }, + }, + }, + }); + + await githubService.assignCopilot('owner/repo', issueNumber, mockDelegatedUserToken); + + expect(mockOctokit.graphql).toHaveBeenCalledTimes(2); + }); + + it('should throw error if assignment fails', async () => { + const issueNumber = 123; + + mockOctokit.graphql + .mockResolvedValueOnce({ + repository: { + id: 'repo-123', + issue: { id: 'issue-456' }, + suggestedActors: { + nodes: [ + { + login: 'copilot-swe-agent', + id: 'bot-789', + }, + ], + }, + }, + }) + .mockRejectedValue(new Error('Issue not found')); + + await expect( + githubService.assignCopilot('owner/repo', issueNumber, mockDelegatedUserToken) + ).rejects.toThrow('Failed to assign Copilot'); + }); + }); + + describe('deleteInstallation', () => { + const mockJwtToken = 'mock-jwt-token'; + + it('should delete installation successfully', async () => { + vi.mocked(jwt.sign).mockImplementation(() => mockJwtToken); + mockOctokit.rest.apps.deleteInstallation.mockResolvedValue(undefined); + + await githubService.deleteInstallation(testInstallationId); + + expect(mockOctokit.rest.apps.deleteInstallation).toHaveBeenCalledWith({ + installation_id: parseInt(testInstallationId, 10), + }); + }); + + it('should throw error if delete fails', async () => { + vi.mocked(jwt.sign).mockImplementation(() => mockJwtToken); + mockOctokit.rest.apps.deleteInstallation.mockRejectedValue(new Error('Not found')); + + await expect(githubService.deleteInstallation(testInstallationId)).rejects.toThrow('Not found'); + }); + }); + + describe('getRepositoriesForInstallation', () => { + const mockJwtToken = 'mock-jwt-token'; + const mockInstallationToken = 'mock-installation-token'; + + beforeEach(() => { + vi.mocked(jwt.sign).mockImplementation(() => mockJwtToken); + + mockOctokit.rest.apps.createInstallationAccessToken.mockResolvedValue({ + data: { token: mockInstallationToken, expires_at: '2025-01-01T00:00:00Z' }, + } as any); + + mockOctokit.rest.apps.getInstallation.mockResolvedValue({ + data: { id: 12345, account: { login: 'test' }, target_type: 'User', repository_selection: 'all' }, + } as any); + }); + + it('should return repositories sorted by updatedAt desc', async () => { + const reposData = [ + { + id: 1, + name: 'repo1', + full_name: 'owner/repo1', + private: false, + html_url: 'https://github.com/owner/repo1', + updated_at: '2024-01-02T00:00:00Z', + language: 'TypeScript', + }, + { + id: 2, + name: 'repo2', + full_name: 'owner/repo2', + private: true, + html_url: 'https://github.com/owner/repo2', + updated_at: '2024-01-03T00:00:00Z', + language: null, + }, + ]; + + mockOctokit.paginate.mockResolvedValue(reposData); + + const result = await githubService.getRepositoriesForInstallation(testInstallationId); + + expect(result).toHaveLength(2); + expect(result[0].name).toBe('repo2'); + expect(result[0].fullName).toBe('owner/repo2'); + expect(result[0].language).toBeNull(); + expect(result[1].name).toBe('repo1'); + expect(result[1].language).toBe('TypeScript'); + }); + + it('should throw error if installationId is empty', async () => { + await expect(githubService.getRepositoriesForInstallation('')).rejects.toThrow( + 'installationId is required for getting repositories' + ); + }); + + it('should throw error if paginate fails', async () => { + mockOctokit.paginate.mockRejectedValue(new Error('API error')); + + await expect( + githubService.getRepositoriesForInstallation(testInstallationId) + ).rejects.toThrow('Failed to get repositories'); + }); + }); + + describe('getValidAccessToken', () => { + it('should return access token when not expired', async () => { + const tokenInfo = { + accessToken: 'valid-token', + refreshToken: 'refresh-123', + accessTokenExpiresAt: new Date(Date.now() + 10 * 60 * 1000), + refreshTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), + }; + + const result = await githubService.getValidAccessToken(tokenInfo); + + expect(result).toBe('valid-token'); + expect(mockRefreshOAuthToken).not.toHaveBeenCalled(); + }); + + it('should return access token when accessTokenExpiresAt is null', async () => { + const tokenInfo = { + accessToken: 'valid-token', + refreshToken: 'refresh-123', + accessTokenExpiresAt: null, + refreshTokenExpiresAt: null, + }; + + const result = await githubService.getValidAccessToken(tokenInfo); + + expect(result).toBe('valid-token'); + expect(mockRefreshOAuthToken).not.toHaveBeenCalled(); + }); + + it('should refresh token when expired and call onRefresh', async () => { + const tokenInfo = { + accessToken: 'expired-token', + refreshToken: 'refresh-123', + accessTokenExpiresAt: new Date(Date.now() - 1000), + refreshTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), + }; + + const expiresAt = new Date(Date.now() + 60 * 60 * 1000); + const refreshTokenExpiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); + + mockRefreshOAuthToken.mockResolvedValue({ + authentication: { + token: 'new-access-token', + refreshToken: 'new-refresh-token', + expiresAt, + refreshTokenExpiresAt, + }, + }); + + const onRefresh = vi.fn().mockResolvedValue(undefined); + + const result = await githubService.getValidAccessToken(tokenInfo, onRefresh); + + expect(result).toBe('new-access-token'); + expect(mockRefreshOAuthToken).toHaveBeenCalledWith( + expect.objectContaining({ refreshToken: 'refresh-123' }) + ); + expect(onRefresh).toHaveBeenCalledWith({ + accessToken: 'new-access-token', + refreshToken: 'new-refresh-token', + expiresAt, + refreshTokenExpiresAt, + }); + }); + + it('should throw when expired and no refresh token', async () => { + const tokenInfo = { + accessToken: 'expired-token', + refreshToken: '', + accessTokenExpiresAt: new Date(Date.now() - 1000), + refreshTokenExpiresAt: null, + }; + + await expect(githubService.getValidAccessToken(tokenInfo)).rejects.toThrow( + 'Access token expired and no refresh token available' + ); + }); + + it('should throw when refresh token is expired', async () => { + const tokenInfo = { + accessToken: 'expired-token', + refreshToken: 'refresh-123', + accessTokenExpiresAt: new Date(Date.now() - 1000), + refreshTokenExpiresAt: new Date(Date.now() - 1000), + }; + + await expect(githubService.getValidAccessToken(tokenInfo)).rejects.toThrow('Refresh token is expired'); + }); + + it('should throw when clientId/clientSecret not set and refresh needed', async () => { + const serviceWithoutOAuth = new GitHubService({ + appId: testAppId, + privateKey: testPrivateKey, + apiUrl: testApiUrl, + }); + + const tokenInfo = { + accessToken: 'expired-token', + refreshToken: 'refresh-123', + accessTokenExpiresAt: new Date(Date.now() - 1000), + refreshTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), + }; + + await expect(serviceWithoutOAuth.getValidAccessToken(tokenInfo)).rejects.toThrow( + 'GITHUB_APP_CLIENT_ID and GITHUB_APP_CLIENT_SECRET are required for token refresh' + ); + }); + }); + + describe('exchangeOAuthCodeForToken', () => { + it('should exchange code for token successfully', async () => { + mockExchangeWebFlowCode.mockResolvedValue({ + authentication: { + token: 'access-token-123', + refreshToken: 'refresh-token-456', + expiresAt: '2025-12-31T23:59:59Z', + refreshTokenExpiresAt: '2026-12-31T23:59:59Z', + }, + }); + + mockOctokit.rest.users.getAuthenticated.mockResolvedValue({ + data: { id: 42, login: 'testuser' }, + }); + + const result = await githubService.exchangeOAuthCodeForToken('auth-code-xyz'); + + expect(result).toEqual({ + accessToken: 'access-token-123', + refreshToken: 'refresh-token-456', + expiresAt: expect.any(Date), + refreshTokenExpiresAt: expect.any(Date), + user: { id: 42, login: 'testuser' }, + }); + expect(mockExchangeWebFlowCode).toHaveBeenCalledWith( + expect.objectContaining({ + code: 'auth-code-xyz', + clientId: testClientId, + clientSecret: testClientSecret, + redirectUrl: `${testApiUrl}/integration/github/oauth`, + }) + ); + }); + + it('should use provided redirectUri', async () => { + mockExchangeWebFlowCode.mockResolvedValue({ + authentication: { token: 'token' }, + }); + mockOctokit.rest.users.getAuthenticated.mockResolvedValue({ + data: { id: 1, login: 'user' }, + }); + + await githubService.exchangeOAuthCodeForToken('code', 'https://custom.com/oauth'); + + expect(mockExchangeWebFlowCode).toHaveBeenCalledWith( + expect.objectContaining({ redirectUrl: 'https://custom.com/oauth' }) + ); + }); + + it('should throw when clientId/clientSecret not set', async () => { + const serviceWithoutOAuth = new GitHubService({ + appId: testAppId, + privateKey: testPrivateKey, + apiUrl: testApiUrl, + }); + + await expect( + serviceWithoutOAuth.exchangeOAuthCodeForToken('code') + ).rejects.toThrow('GITHUB_APP_CLIENT_ID and GITHUB_APP_CLIENT_SECRET are required for OAuth token exchange'); + }); + + it('should throw when apiUrl not set and redirectUri not provided', async () => { + const serviceWithoutApiUrl = new GitHubService({ + appId: testAppId, + privateKey: testPrivateKey, + clientId: testClientId, + clientSecret: testClientSecret, + }); + + await expect( + serviceWithoutApiUrl.exchangeOAuthCodeForToken('code') + ).rejects.toThrow('apiUrl is required for exchangeOAuthCodeForToken when redirectUri is not provided'); + }); + }); + + describe('validateUserToken', () => { + it('should return valid for valid token', async () => { + mockOctokit.rest.users.getAuthenticated.mockResolvedValue({ + data: { id: 100, login: 'validuser' }, + }); + + const result = await githubService.validateUserToken('valid-token'); + + expect(result).toEqual({ + valid: true, + user: { id: 100, login: 'validuser' }, + status: 'active', + }); + }); + + it('should return revoked for 401', async () => { + const err = new Error('Unauthorized') as Error & { status?: number }; + err.status = 401; + mockOctokit.rest.users.getAuthenticated.mockRejectedValue(err); + + const result = await githubService.validateUserToken('invalid-token'); + + expect(result).toEqual({ valid: false, status: 'revoked' }); + }); + + it('should return revoked for 403', async () => { + const err = new Error('Forbidden') as Error & { status?: number }; + err.status = 403; + mockOctokit.rest.users.getAuthenticated.mockRejectedValue(err); + + const result = await githubService.validateUserToken('forbidden-token'); + + expect(result).toEqual({ valid: false, status: 'revoked' }); + }); + + it('should throw for other errors', async () => { + mockOctokit.rest.users.getAuthenticated.mockRejectedValue(new Error('Network error')); + + await expect(githubService.validateUserToken('token')).rejects.toThrow('Failed to validate user token'); + }); + }); + + describe('refreshUserToken', () => { + it('should refresh token successfully', async () => { + mockRefreshOAuthToken.mockResolvedValue({ + authentication: { + token: 'new-access-token', + refreshToken: 'new-refresh-token', + expiresAt: '2025-12-31T23:59:59Z', + refreshTokenExpiresAt: '2026-12-31T23:59:59Z', + }, + }); + + const result = await githubService.refreshUserToken('old-refresh-token'); + + expect(result).toEqual({ + accessToken: 'new-access-token', + refreshToken: 'new-refresh-token', + expiresAt: expect.any(Date), + refreshTokenExpiresAt: expect.any(Date), + }); + expect(mockRefreshOAuthToken).toHaveBeenCalledWith( + expect.objectContaining({ + refreshToken: 'old-refresh-token', + clientId: testClientId, + clientSecret: testClientSecret, + }) + ); + }); + + it('should throw when clientId/clientSecret not set', async () => { + const serviceWithoutOAuth = new GitHubService({ + appId: testAppId, + privateKey: testPrivateKey, + }); + + await expect(serviceWithoutOAuth.refreshUserToken('refresh')).rejects.toThrow( + 'GITHUB_APP_CLIENT_ID and GITHUB_APP_CLIENT_SECRET are required for token refresh' + ); + }); + }); +}); diff --git a/packages/github/tsconfig.build.json b/packages/github/tsconfig.build.json new file mode 100644 index 0000000..da4af7c --- /dev/null +++ b/packages/github/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["**/*.test.ts", "**/*.spec.ts"] +} diff --git a/packages/core/tsconfig.json b/packages/github/tsconfig.json similarity index 50% rename from packages/core/tsconfig.json rename to packages/github/tsconfig.json index 4013f94..e6945b3 100644 --- a/packages/core/tsconfig.json +++ b/packages/github/tsconfig.json @@ -1,18 +1,15 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "target": "esnext", - "module": "esnext", + "target": "ES2020", + "module": "commonjs", + "moduleResolution": "node", "outDir": "./dist", "rootDir": "./src", "declaration": true, "declarationMap": true, - "composite": true + "strict": true, + "skipLibCheck": true }, - "include": [ - "./src/**/*" - ], - "references": [ - { "path": "../utils" } - ] + "include": ["src/**/*", "tests/**/*"] } diff --git a/packages/utils/package.json b/packages/utils/package.json index ca9235a..c0e21ba 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -1,23 +1,36 @@ { - "name": "mylib-utils", - "version": "0.0.0", - "main": "src/index.ts", - "type": "module", + "name": "@hawk.so/utils", + "version": "1.0.0", + "description": "Shared utilities for Hawk packages", "author": "CodeX ", + "license": "MIT", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.js", + "import": "./dist/index.js" + } + }, + "main": "./dist/index.js", + "types": "./dist/index.d.ts", "files": [ - "src" + "dist" ], "scripts": { + "clean": "rimraf dist *.tsbuildinfo", "lint": "eslint ./src", - "lint:fix": "yarn lint --fix", - "test:dev": "vitest", + "lint:fix": "eslint ./src --fix", + "build": "tsc -p tsconfig.build.json", "test": "vitest run", - "coverage": "vitest run --coverage" + "test:dev": "vitest" }, "devDependencies": { - "@vitest/coverage-v8": "^2.1.4", "eslint": "^9.14.0", + "rimraf": "^6.0.1", "typescript": "^5.6.3", "vitest": "^2.1.4" + }, + "engines": { + "node": ">=18.0.0" } } diff --git a/packages/utils/src/hasValue.ts b/packages/utils/src/hasValue.ts new file mode 100644 index 0000000..d3e3871 --- /dev/null +++ b/packages/utils/src/hasValue.ts @@ -0,0 +1,8 @@ +/** + * Returns true if specified value is not undefined, null and empty string. + * @param v - Value to check. + * @returns True when `v` is defined, not null, and not empty string. + */ +export function hasValue(v: unknown): boolean { + return v !== undefined && v !== null && v !== ''; +} diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 6cf06bb..84bea9a 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -1,8 +1 @@ -/** - * This is an example of a utility function - * @param a - first number - * @param b - second number - */ -export function myUtil(a: number, b: number): number { - return a + b; -} +export { hasValue } from './hasValue'; diff --git a/packages/utils/tests/hasValue.test.ts b/packages/utils/tests/hasValue.test.ts new file mode 100644 index 0000000..4e37e2c --- /dev/null +++ b/packages/utils/tests/hasValue.test.ts @@ -0,0 +1,28 @@ +import { describe, it, expect } from 'vitest'; +import { hasValue } from '../src/hasValue'; + +describe('hasValue', () => { + it('returns false for undefined', () => { + expect(hasValue(undefined)).toBe(false); + }); + + it('returns false for null', () => { + expect(hasValue(null)).toBe(false); + }); + + it('returns false for empty string', () => { + expect(hasValue('')).toBe(false); + }); + + it('returns true for non-empty string', () => { + expect(hasValue('x')).toBe(true); + }); + + it('returns true for number 0', () => { + expect(hasValue(0)).toBe(true); + }); + + it('returns true for object', () => { + expect(hasValue({})).toBe(true); + }); +}); diff --git a/packages/utils/tests/index.test.ts b/packages/utils/tests/index.test.ts deleted file mode 100644 index fd66267..0000000 --- a/packages/utils/tests/index.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { myUtil } from 'mylib-utils'; -import { describe, test, expect } from 'vitest'; - -describe('My Utils package test', () => { - describe('myUtil()', () => { - test('shoul return a summ of two passed numbers', () => { - const number1 = 5; - const number2 = 10; - - const summ = myUtil(number1, number2); - - // eslint-disable-next-line @typescript-eslint/no-magic-numbers - expect(summ).toBe(15); - }); - }); -}); diff --git a/packages/utils/tsconfig.build.json b/packages/utils/tsconfig.build.json new file mode 100644 index 0000000..da4af7c --- /dev/null +++ b/packages/utils/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["**/*.test.ts", "**/*.spec.ts"] +} diff --git a/packages/utils/tsconfig.json b/packages/utils/tsconfig.json index d34d17c..e6945b3 100644 --- a/packages/utils/tsconfig.json +++ b/packages/utils/tsconfig.json @@ -1,8 +1,15 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "target": "esnext", - "module": "esnext", - "composite": true + "target": "ES2020", + "module": "commonjs", + "moduleResolution": "node", + "outDir": "./dist", + "rootDir": "./src", + "declaration": true, + "declarationMap": true, + "strict": true, + "skipLibCheck": true }, + "include": ["src/**/*", "tests/**/*"] } diff --git a/yarn.lock b/yarn.lock index 82475f9..4c3e133 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5,72 +5,6 @@ __metadata: version: 8 cacheKey: 10c0 -"@ampproject/remapping@npm:^2.3.0": - version: 2.3.0 - resolution: "@ampproject/remapping@npm:2.3.0" - dependencies: - "@jridgewell/gen-mapping": "npm:^0.3.5" - "@jridgewell/trace-mapping": "npm:^0.3.24" - checksum: 10c0/81d63cca5443e0f0c72ae18b544cc28c7c0ec2cea46e7cb888bb0e0f411a1191d0d6b7af798d54e30777d8d1488b2ec0732aac2be342d3d7d3ffd271c6f489ed - languageName: node - linkType: hard - -"@babel/helper-string-parser@npm:^7.25.9": - version: 7.25.9 - resolution: "@babel/helper-string-parser@npm:7.25.9" - checksum: 10c0/7244b45d8e65f6b4338a6a68a8556f2cb161b782343e97281a5f2b9b93e420cad0d9f5773a59d79f61d0c448913d06f6a2358a87f2e203cf112e3c5b53522ee6 - languageName: node - linkType: hard - -"@babel/helper-validator-identifier@npm:^7.25.9": - version: 7.25.9 - resolution: "@babel/helper-validator-identifier@npm:7.25.9" - checksum: 10c0/4fc6f830177b7b7e887ad3277ddb3b91d81e6c4a24151540d9d1023e8dc6b1c0505f0f0628ae653601eb4388a8db45c1c14b2c07a9173837aef7e4116456259d - languageName: node - linkType: hard - -"@babel/parser@npm:^7.25.4": - version: 7.26.2 - resolution: "@babel/parser@npm:7.26.2" - dependencies: - "@babel/types": "npm:^7.26.0" - bin: - parser: ./bin/babel-parser.js - checksum: 10c0/751a743087b3a9172a7599f1421830d44c38f065ef781588d2bfb1c98f9b461719a226feb13c868d7a284783eee120c88ea522593118f2668f46ebfb1105c4d7 - languageName: node - linkType: hard - -"@babel/types@npm:^7.25.4, @babel/types@npm:^7.26.0": - version: 7.26.0 - resolution: "@babel/types@npm:7.26.0" - dependencies: - "@babel/helper-string-parser": "npm:^7.25.9" - "@babel/helper-validator-identifier": "npm:^7.25.9" - checksum: 10c0/b694f41ad1597127e16024d766c33a641508aad037abd08d0d1f73af753e1119fa03b4a107d04b5f92cc19c095a594660547ae9bead1db2299212d644b0a5cb8 - languageName: node - linkType: hard - -"@bcoe/v8-coverage@npm:^0.2.3": - version: 0.2.3 - resolution: "@bcoe/v8-coverage@npm:0.2.3" - checksum: 10c0/6b80ae4cb3db53f486da2dc63b6e190a74c8c3cca16bb2733f234a0b6a9382b09b146488ae08e2b22cf00f6c83e20f3e040a2f7894f05c045c946d6a090b1d52 - languageName: node - linkType: hard - -"@codexteam/typescript-lib-template@workspace:.": - version: 0.0.0-use.local - resolution: "@codexteam/typescript-lib-template@workspace:." - dependencies: - eslint: "npm:^9.14.0" - eslint-config-codex: "npm:^2.0.3" - rimraf: "npm:^6.0.1" - ts-node: "npm:^10.9.2" - typescript: "npm:^5.6.3" - typescript-eslint: "npm:^8.13.0" - vitest: "npm:^2.1.4" - languageName: unknown - linkType: soft - "@cspotcode/source-map-support@npm:^0.8.0": version: 0.8.1 resolution: "@cspotcode/source-map-support@npm:0.8.1" @@ -340,6 +274,48 @@ __metadata: languageName: node linkType: hard +"@hawk.so/github-sdk@workspace:packages/github": + version: 0.0.0-use.local + resolution: "@hawk.so/github-sdk@workspace:packages/github" + dependencies: + "@hawk.so/utils": "workspace:*" + "@octokit/oauth-methods": "npm:^4.0.0" + "@octokit/rest": "npm:^22.0.1" + "@octokit/types": "npm:^16.0.0" + "@types/jsonwebtoken": "npm:^8.3.5" + eslint: "npm:^9.14.0" + jsonwebtoken: "npm:^9.0.3" + rimraf: "npm:^6.0.1" + typescript: "npm:^5.6.3" + vitest: "npm:^2.1.4" + languageName: unknown + linkType: soft + +"@hawk.so/kit@workspace:.": + version: 0.0.0-use.local + resolution: "@hawk.so/kit@workspace:." + dependencies: + eslint: "npm:^9.14.0" + eslint-config-codex: "npm:^2.0.3" + rimraf: "npm:^6.0.1" + ts-node: "npm:^10.9.2" + typescript: "npm:^5.6.3" + typescript-eslint: "npm:^8.13.0" + vitest: "npm:^2.1.4" + languageName: unknown + linkType: soft + +"@hawk.so/utils@workspace:*, @hawk.so/utils@workspace:packages/utils": + version: 0.0.0-use.local + resolution: "@hawk.so/utils@workspace:packages/utils" + dependencies: + eslint: "npm:^9.14.0" + rimraf: "npm:^6.0.1" + typescript: "npm:^5.6.3" + vitest: "npm:^2.1.4" + languageName: unknown + linkType: soft + "@humanfs/core@npm:^0.19.1": version: 0.19.1 resolution: "@humanfs/core@npm:0.19.1" @@ -392,39 +368,14 @@ __metadata: languageName: node linkType: hard -"@istanbuljs/schema@npm:^0.1.2": - version: 0.1.3 - resolution: "@istanbuljs/schema@npm:0.1.3" - checksum: 10c0/61c5286771676c9ca3eb2bd8a7310a9c063fb6e0e9712225c8471c582d157392c88f5353581c8c9adbe0dff98892317d2fdfc56c3499aa42e0194405206a963a - languageName: node - linkType: hard - -"@jridgewell/gen-mapping@npm:^0.3.5": - version: 0.3.5 - resolution: "@jridgewell/gen-mapping@npm:0.3.5" - dependencies: - "@jridgewell/set-array": "npm:^1.2.1" - "@jridgewell/sourcemap-codec": "npm:^1.4.10" - "@jridgewell/trace-mapping": "npm:^0.3.24" - checksum: 10c0/1be4fd4a6b0f41337c4f5fdf4afc3bd19e39c3691924817108b82ffcb9c9e609c273f936932b9fba4b3a298ce2eb06d9bff4eb1cc3bd81c4f4ee1b4917e25feb - languageName: node - linkType: hard - -"@jridgewell/resolve-uri@npm:^3.0.3, @jridgewell/resolve-uri@npm:^3.1.0": +"@jridgewell/resolve-uri@npm:^3.0.3": version: 3.1.2 resolution: "@jridgewell/resolve-uri@npm:3.1.2" checksum: 10c0/d502e6fb516b35032331406d4e962c21fe77cdf1cbdb49c6142bcbd9e30507094b18972778a6e27cbad756209cfe34b1a27729e6fa08a2eb92b33943f680cf1e languageName: node linkType: hard -"@jridgewell/set-array@npm:^1.2.1": - version: 1.2.1 - resolution: "@jridgewell/set-array@npm:1.2.1" - checksum: 10c0/2a5aa7b4b5c3464c895c802d8ae3f3d2b92fcbe84ad12f8d0bfbb1f5ad006717e7577ee1fd2eac00c088abe486c7adb27976f45d2941ff6b0b92b2c3302c60f4 - languageName: node - linkType: hard - -"@jridgewell/sourcemap-codec@npm:^1.4.10, @jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.5.0": +"@jridgewell/sourcemap-codec@npm:^1.4.10, @jridgewell/sourcemap-codec@npm:^1.5.0": version: 1.5.0 resolution: "@jridgewell/sourcemap-codec@npm:1.5.0" checksum: 10c0/2eb864f276eb1096c3c11da3e9bb518f6d9fc0023c78344cdc037abadc725172c70314bdb360f2d4b7bffec7f5d657ce006816bc5d4ecb35e61b66132db00c18 @@ -441,16 +392,6 @@ __metadata: languageName: node linkType: hard -"@jridgewell/trace-mapping@npm:^0.3.23, @jridgewell/trace-mapping@npm:^0.3.24": - version: 0.3.25 - resolution: "@jridgewell/trace-mapping@npm:0.3.25" - dependencies: - "@jridgewell/resolve-uri": "npm:^3.1.0" - "@jridgewell/sourcemap-codec": "npm:^1.4.14" - checksum: 10c0/3d1ce6ebc69df9682a5a8896b414c6537e428a1d68b02fcc8363b04284a8ca0df04d0ee3013132252ab14f2527bc13bea6526a912ecb5658f0e39fd2860b4df4 - languageName: node - linkType: hard - "@nodelib/fs.scandir@npm:2.1.5": version: 2.1.5 resolution: "@nodelib/fs.scandir@npm:2.1.5" @@ -500,6 +441,199 @@ __metadata: languageName: node linkType: hard +"@octokit/auth-token@npm:^6.0.0": + version: 6.0.0 + resolution: "@octokit/auth-token@npm:6.0.0" + checksum: 10c0/32ecc904c5f6f4e5d090bfcc679d70318690c0a0b5040cd9a25811ad9dcd44c33f2cf96b6dbee1cd56cf58fde28fb1819c01b58718aa5c971f79c822357cb5c0 + languageName: node + linkType: hard + +"@octokit/core@npm:^7.0.6": + version: 7.0.6 + resolution: "@octokit/core@npm:7.0.6" + dependencies: + "@octokit/auth-token": "npm:^6.0.0" + "@octokit/graphql": "npm:^9.0.3" + "@octokit/request": "npm:^10.0.6" + "@octokit/request-error": "npm:^7.0.2" + "@octokit/types": "npm:^16.0.0" + before-after-hook: "npm:^4.0.0" + universal-user-agent: "npm:^7.0.0" + checksum: 10c0/95a328ff7c7223d9eb4aa778c63171828514ae0e0f588d33beb81a4dc03bbeae055382f6060ce23c979ab46272409942ff2cf3172109999e48429c47055b1fbe + languageName: node + linkType: hard + +"@octokit/endpoint@npm:^11.0.2": + version: 11.0.2 + resolution: "@octokit/endpoint@npm:11.0.2" + dependencies: + "@octokit/types": "npm:^16.0.0" + universal-user-agent: "npm:^7.0.2" + checksum: 10c0/878ac12fbccff772968689b4744590677c5a3f12bebe31544832c84761bf1c6be521e8a3af07abffc9455a74dd4d1f350d714fc46fd7ce14a0a2b5f2d4e3a84c + languageName: node + linkType: hard + +"@octokit/endpoint@npm:^9.0.6": + version: 9.0.6 + resolution: "@octokit/endpoint@npm:9.0.6" + dependencies: + "@octokit/types": "npm:^13.1.0" + universal-user-agent: "npm:^6.0.0" + checksum: 10c0/8e06197b21869aeb498e0315093ca6fbee12bd1bdcfc1667fcd7d79d827d84f2c5a30702ffd28bba7879780e367d14c30df5b20d47fcaed5de5fdc05f5d4e013 + languageName: node + linkType: hard + +"@octokit/graphql@npm:^9.0.3": + version: 9.0.3 + resolution: "@octokit/graphql@npm:9.0.3" + dependencies: + "@octokit/request": "npm:^10.0.6" + "@octokit/types": "npm:^16.0.0" + universal-user-agent: "npm:^7.0.0" + checksum: 10c0/58588d3fb2834f64244fa5376ca7922a30117b001b621e141fab0d52806370803ab0c046ac99b120fa5f45b770f52a815157fb6ffc147fc6c1da4047c1f1af49 + languageName: node + linkType: hard + +"@octokit/oauth-authorization-url@npm:^6.0.2": + version: 6.0.2 + resolution: "@octokit/oauth-authorization-url@npm:6.0.2" + checksum: 10c0/8c06e538b3e392f0fa68f3347078c32f92c03474eb214e4e82774513a54c164bac14c228f7dbd79d22a920df1a8b2e0765dd6ee45929bda0b77e5cf7f0d92c71 + languageName: node + linkType: hard + +"@octokit/oauth-methods@npm:^4.0.0": + version: 4.1.0 + resolution: "@octokit/oauth-methods@npm:4.1.0" + dependencies: + "@octokit/oauth-authorization-url": "npm:^6.0.2" + "@octokit/request": "npm:^8.3.1" + "@octokit/request-error": "npm:^5.1.0" + "@octokit/types": "npm:^13.0.0" + btoa-lite: "npm:^1.0.0" + checksum: 10c0/3ab7ab41e82faebb662bfc4cc20756f008adb37b447386c29ddb09cbac5d1867b1b23f2f8dd268e06dca5ff1c874162e01d475f15634b42e6ab0a95471dcc365 + languageName: node + linkType: hard + +"@octokit/openapi-types@npm:^24.2.0": + version: 24.2.0 + resolution: "@octokit/openapi-types@npm:24.2.0" + checksum: 10c0/8f47918b35e9b7f6109be6f7c8fc3a64ad13a48233112b29e92559e64a564b810eb3ebf81b4cd0af1bb2989d27b9b95cca96e841ec4e23a3f68703cefe62fd9e + languageName: node + linkType: hard + +"@octokit/openapi-types@npm:^27.0.0": + version: 27.0.0 + resolution: "@octokit/openapi-types@npm:27.0.0" + checksum: 10c0/602d1de033da180a2e982cdbd3646bd5b2e16ecf36b9955a0f23e37ae9e6cb086abb48ff2ae6f2de000fce03e8ae9051794611ae4a95a8f5f6fb63276e7b8e31 + languageName: node + linkType: hard + +"@octokit/plugin-paginate-rest@npm:^14.0.0": + version: 14.0.0 + resolution: "@octokit/plugin-paginate-rest@npm:14.0.0" + dependencies: + "@octokit/types": "npm:^16.0.0" + peerDependencies: + "@octokit/core": ">=6" + checksum: 10c0/841d79d4ccfe18fc809a4a67529b75c1dcdda13399bf4bf5b48ce7559c8b4b2cd422e3204bad4cbdea31c0cf0943521067415268e5bcfc615a3b813e058cad6b + languageName: node + linkType: hard + +"@octokit/plugin-request-log@npm:^6.0.0": + version: 6.0.0 + resolution: "@octokit/plugin-request-log@npm:6.0.0" + peerDependencies: + "@octokit/core": ">=6" + checksum: 10c0/40e46ad0c77235742d0bf698ab4e17df1ae06e0d7824ffc5867ed71e27de860875adb73d89629b823fe8647459a8f262c26ed1aa6ee374873fa94095f37df0bb + languageName: node + linkType: hard + +"@octokit/plugin-rest-endpoint-methods@npm:^17.0.0": + version: 17.0.0 + resolution: "@octokit/plugin-rest-endpoint-methods@npm:17.0.0" + dependencies: + "@octokit/types": "npm:^16.0.0" + peerDependencies: + "@octokit/core": ">=6" + checksum: 10c0/cf9984d7cf6a36ff7ff1b86078ae45fe246e3df10fcef0bccf20c8cfd27bf5e7d98dcb9cf5a7b56332b9c6fa30be28d159c2987d272a4758f77056903d94402f + languageName: node + linkType: hard + +"@octokit/request-error@npm:^5.1.0, @octokit/request-error@npm:^5.1.1": + version: 5.1.1 + resolution: "@octokit/request-error@npm:5.1.1" + dependencies: + "@octokit/types": "npm:^13.1.0" + deprecation: "npm:^2.0.0" + once: "npm:^1.4.0" + checksum: 10c0/dc9fc76ea5e4199273e4665ce9ddf345fe8f25578d9999c9a16f276298e61ee6fe0e6f5a6147b91ba3b34fdf5b9e6b7af6ae13d6333175e95b30c574088f7a2d + languageName: node + linkType: hard + +"@octokit/request-error@npm:^7.0.2": + version: 7.1.0 + resolution: "@octokit/request-error@npm:7.1.0" + dependencies: + "@octokit/types": "npm:^16.0.0" + checksum: 10c0/62b90a54545c36a30b5ffdda42e302c751be184d85b68ffc7f1242c51d7ca54dbd185b7d0027b491991776923a910c85c9c51269fe0d86111bac187507a5abc4 + languageName: node + linkType: hard + +"@octokit/request@npm:^10.0.6": + version: 10.0.7 + resolution: "@octokit/request@npm:10.0.7" + dependencies: + "@octokit/endpoint": "npm:^11.0.2" + "@octokit/request-error": "npm:^7.0.2" + "@octokit/types": "npm:^16.0.0" + fast-content-type-parse: "npm:^3.0.0" + universal-user-agent: "npm:^7.0.2" + checksum: 10c0/f789a75bf681b204ccd3d538921db662e148ed980005158d80ec4f16811e9ab73f375d4f30ef697852abd748a62f025060ea1b0c5198ec9c2e8d04e355064390 + languageName: node + linkType: hard + +"@octokit/request@npm:^8.3.1": + version: 8.4.1 + resolution: "@octokit/request@npm:8.4.1" + dependencies: + "@octokit/endpoint": "npm:^9.0.6" + "@octokit/request-error": "npm:^5.1.1" + "@octokit/types": "npm:^13.1.0" + universal-user-agent: "npm:^6.0.0" + checksum: 10c0/1a69dcb7336de708a296db9e9a58040e5b284a87495a63112f80eb0007da3fc96a9fadecb9e875fc63cf179c23a0f81031fbef2a6f610a219e45805ead03fcf3 + languageName: node + linkType: hard + +"@octokit/rest@npm:^22.0.1": + version: 22.0.1 + resolution: "@octokit/rest@npm:22.0.1" + dependencies: + "@octokit/core": "npm:^7.0.6" + "@octokit/plugin-paginate-rest": "npm:^14.0.0" + "@octokit/plugin-request-log": "npm:^6.0.0" + "@octokit/plugin-rest-endpoint-methods": "npm:^17.0.0" + checksum: 10c0/f3abd84e887cc837973214ce70720a9bba53f5575f40601c6122aa25206e9055d859c0388437f0a137f6cd0e4ff405e1b46b903475b0db32a17bada0c6513d5b + languageName: node + linkType: hard + +"@octokit/types@npm:^13.0.0, @octokit/types@npm:^13.1.0": + version: 13.10.0 + resolution: "@octokit/types@npm:13.10.0" + dependencies: + "@octokit/openapi-types": "npm:^24.2.0" + checksum: 10c0/f66a401b89d653ec28e5c1529abdb7965752db4d9d40fa54c80e900af4c6bf944af6bd0a83f5b4f1eecb72e3d646899dfb27ffcf272ac243552de7e3b97a038d + languageName: node + linkType: hard + +"@octokit/types@npm:^16.0.0": + version: 16.0.0 + resolution: "@octokit/types@npm:16.0.0" + dependencies: + "@octokit/openapi-types": "npm:^27.0.0" + checksum: 10c0/b8d41098ba6fc194d13d641f9441347e3a3b96c0efabac0e14f57319340a2d4d1c8676e4cb37ab3062c5c323c617e790b0126916e9bf7b201b0cced0826f8ae2 + languageName: node + linkType: hard + "@pkgjs/parseargs@npm:^0.11.0": version: 0.11.0 resolution: "@pkgjs/parseargs@npm:0.11.0" @@ -711,6 +845,24 @@ __metadata: languageName: node linkType: hard +"@types/jsonwebtoken@npm:^8.3.5": + version: 8.5.9 + resolution: "@types/jsonwebtoken@npm:8.5.9" + dependencies: + "@types/node": "npm:*" + checksum: 10c0/4374b0f1b5641d1dd8847fa6f50bd34ec215f3244ea045556d2caa74ed559b2571502db73526bb8fbff038a60ff7e6bf56ffa79679c0b03539b55fda32617a23 + languageName: node + linkType: hard + +"@types/node@npm:*": + version: 25.1.0 + resolution: "@types/node@npm:25.1.0" + dependencies: + undici-types: "npm:~7.16.0" + checksum: 10c0/5f393a127dc9565e2e152514a271455d580c7095afc51302e73ffe8aac3526b64ebacc3c10dd40c93cef81a95436ef2c6a8b522930df567a3f6b189c0eef649a + languageName: node + linkType: hard + "@typescript-eslint/eslint-plugin@npm:8.13.0": version: 8.13.0 resolution: "@typescript-eslint/eslint-plugin@npm:8.13.0" @@ -827,32 +979,6 @@ __metadata: languageName: node linkType: hard -"@vitest/coverage-v8@npm:^2.1.4": - version: 2.1.4 - resolution: "@vitest/coverage-v8@npm:2.1.4" - dependencies: - "@ampproject/remapping": "npm:^2.3.0" - "@bcoe/v8-coverage": "npm:^0.2.3" - debug: "npm:^4.3.7" - istanbul-lib-coverage: "npm:^3.2.2" - istanbul-lib-report: "npm:^3.0.1" - istanbul-lib-source-maps: "npm:^5.0.6" - istanbul-reports: "npm:^3.1.7" - magic-string: "npm:^0.30.12" - magicast: "npm:^0.3.5" - std-env: "npm:^3.7.0" - test-exclude: "npm:^7.0.1" - tinyrainbow: "npm:^1.2.0" - peerDependencies: - "@vitest/browser": 2.1.4 - vitest: 2.1.4 - peerDependenciesMeta: - "@vitest/browser": - optional: true - checksum: 10c0/f795fdd645ccc46de45baa431a1b3b216d74195b9751cb0498009b8ef929dcd48c2f858570d421908549f5a631ac2931f7c7f3fe4ff0bc80707805beda5c18d7 - languageName: node - linkType: hard - "@vitest/expect@npm:2.1.4": version: 2.1.4 resolution: "@vitest/expect@npm:2.1.4" @@ -1151,6 +1277,13 @@ __metadata: languageName: node linkType: hard +"before-after-hook@npm:^4.0.0": + version: 4.0.0 + resolution: "before-after-hook@npm:4.0.0" + checksum: 10c0/9f8ae8d1b06142bcfb9ef6625226b5e50348bb11210f266660eddcf9734e0db6f9afc4cb48397ee3f5ac0a3728f3ae401cdeea88413f7bed748a71db84657be2 + languageName: node + linkType: hard + "boolbase@npm:^1.0.0": version: 1.0.0 resolution: "boolbase@npm:1.0.0" @@ -1186,6 +1319,20 @@ __metadata: languageName: node linkType: hard +"btoa-lite@npm:^1.0.0": + version: 1.0.0 + resolution: "btoa-lite@npm:1.0.0" + checksum: 10c0/7a4f0568ae3c915464650f98fde7901ae07b13a333a614515a0c86876b3528670fafece28dfef9745d971a613bb83341823afb0c20c6f318b384c1e364b9eb95 + languageName: node + linkType: hard + +"buffer-equal-constant-time@npm:^1.0.1": + version: 1.0.1 + resolution: "buffer-equal-constant-time@npm:1.0.1" + checksum: 10c0/fb2294e64d23c573d0dd1f1e7a466c3e978fe94a4e0f8183937912ca374619773bef8e2aceb854129d2efecbbc515bbd0cc78d2734a3e3031edb0888531bbc8e + languageName: node + linkType: hard + "cac@npm:^6.7.14": version: 6.7.14 resolution: "cac@npm:6.7.14" @@ -1367,7 +1514,7 @@ __metadata: languageName: node linkType: hard -"debug@npm:4, debug@npm:^4.1.1, debug@npm:^4.3.1, debug@npm:^4.3.2, debug@npm:^4.3.4, debug@npm:^4.3.6, debug@npm:^4.3.7": +"debug@npm:4, debug@npm:^4.3.1, debug@npm:^4.3.2, debug@npm:^4.3.4, debug@npm:^4.3.6, debug@npm:^4.3.7": version: 4.3.7 resolution: "debug@npm:4.3.7" dependencies: @@ -1424,6 +1571,13 @@ __metadata: languageName: node linkType: hard +"deprecation@npm:^2.0.0": + version: 2.3.1 + resolution: "deprecation@npm:2.3.1" + checksum: 10c0/23d688ba66b74d09b908c40a76179418acbeeb0bfdf218c8075c58ad8d0c315130cb91aa3dffb623aa3a411a3569ce56c6460de6c8d69071c17fe6dd2442f032 + languageName: node + linkType: hard + "diff@npm:^4.0.1": version: 4.0.2 resolution: "diff@npm:4.0.2" @@ -1447,6 +1601,15 @@ __metadata: languageName: node linkType: hard +"ecdsa-sig-formatter@npm:1.0.11": + version: 1.0.11 + resolution: "ecdsa-sig-formatter@npm:1.0.11" + dependencies: + safe-buffer: "npm:^5.0.1" + checksum: 10c0/ebfbf19d4b8be938f4dd4a83b8788385da353d63307ede301a9252f9f7f88672e76f2191618fd8edfc2f24679236064176fab0b78131b161ee73daa37125408c + languageName: node + linkType: hard + "emoji-regex@npm:^8.0.0": version: 8.0.0 resolution: "emoji-regex@npm:8.0.0" @@ -2067,6 +2230,13 @@ __metadata: languageName: node linkType: hard +"fast-content-type-parse@npm:^3.0.0": + version: 3.0.0 + resolution: "fast-content-type-parse@npm:3.0.0" + checksum: 10c0/06251880c83b7118af3a5e66e8bcee60d44f48b39396fc60acc2b4630bd5f3e77552b999b5c8e943d45a818854360e5e97164c374ec4b562b4df96a2cdf2e188 + languageName: node + linkType: hard + "fast-deep-equal@npm:^3.1.1, fast-deep-equal@npm:^3.1.3": version: 3.1.3 resolution: "fast-deep-equal@npm:3.1.3" @@ -2295,7 +2465,7 @@ __metadata: languageName: node linkType: hard -"glob@npm:^10.2.2, glob@npm:^10.3.10, glob@npm:^10.4.1": +"glob@npm:^10.2.2, glob@npm:^10.3.10": version: 10.4.5 resolution: "glob@npm:10.4.5" dependencies: @@ -2438,13 +2608,6 @@ __metadata: languageName: node linkType: hard -"html-escaper@npm:^2.0.0": - version: 2.0.2 - resolution: "html-escaper@npm:2.0.2" - checksum: 10c0/208e8a12de1a6569edbb14544f4567e6ce8ecc30b9394fcaa4e7bb1e60c12a7c9a1ed27e31290817157e8626f3a4f29e76c8747030822eb84a6abb15c255f0a0 - languageName: node - linkType: hard - "http-cache-semantics@npm:^4.1.1": version: 4.1.1 resolution: "http-cache-semantics@npm:4.1.1" @@ -2725,45 +2888,6 @@ __metadata: languageName: node linkType: hard -"istanbul-lib-coverage@npm:^3.0.0, istanbul-lib-coverage@npm:^3.2.2": - version: 3.2.2 - resolution: "istanbul-lib-coverage@npm:3.2.2" - checksum: 10c0/6c7ff2106769e5f592ded1fb418f9f73b4411fd5a084387a5410538332b6567cd1763ff6b6cadca9b9eb2c443cce2f7ea7d7f1b8d315f9ce58539793b1e0922b - languageName: node - linkType: hard - -"istanbul-lib-report@npm:^3.0.0, istanbul-lib-report@npm:^3.0.1": - version: 3.0.1 - resolution: "istanbul-lib-report@npm:3.0.1" - dependencies: - istanbul-lib-coverage: "npm:^3.0.0" - make-dir: "npm:^4.0.0" - supports-color: "npm:^7.1.0" - checksum: 10c0/84323afb14392de8b6a5714bd7e9af845cfbd56cfe71ed276cda2f5f1201aea673c7111901227ee33e68e4364e288d73861eb2ed48f6679d1e69a43b6d9b3ba7 - languageName: node - linkType: hard - -"istanbul-lib-source-maps@npm:^5.0.6": - version: 5.0.6 - resolution: "istanbul-lib-source-maps@npm:5.0.6" - dependencies: - "@jridgewell/trace-mapping": "npm:^0.3.23" - debug: "npm:^4.1.1" - istanbul-lib-coverage: "npm:^3.0.0" - checksum: 10c0/ffe75d70b303a3621ee4671554f306e0831b16f39ab7f4ab52e54d356a5d33e534d97563e318f1333a6aae1d42f91ec49c76b6cd3f3fb378addcb5c81da0255f - languageName: node - linkType: hard - -"istanbul-reports@npm:^3.1.7": - version: 3.1.7 - resolution: "istanbul-reports@npm:3.1.7" - dependencies: - html-escaper: "npm:^2.0.0" - istanbul-lib-report: "npm:^3.0.0" - checksum: 10c0/a379fadf9cf8dc5dfe25568115721d4a7eb82fbd50b005a6672aff9c6989b20cc9312d7865814e0859cd8df58cbf664482e1d3604be0afde1f7fc3ccc1394a51 - languageName: node - linkType: hard - "jackspeak@npm:^3.1.2": version: 3.4.3 resolution: "jackspeak@npm:3.4.3" @@ -2843,6 +2967,45 @@ __metadata: languageName: node linkType: hard +"jsonwebtoken@npm:^9.0.3": + version: 9.0.3 + resolution: "jsonwebtoken@npm:9.0.3" + dependencies: + jws: "npm:^4.0.1" + lodash.includes: "npm:^4.3.0" + lodash.isboolean: "npm:^3.0.3" + lodash.isinteger: "npm:^4.0.4" + lodash.isnumber: "npm:^3.0.3" + lodash.isplainobject: "npm:^4.0.6" + lodash.isstring: "npm:^4.0.1" + lodash.once: "npm:^4.0.0" + ms: "npm:^2.1.1" + semver: "npm:^7.5.4" + checksum: 10c0/6ca7f1e54886ea3bde7146a5a22b53847c46e25453c7f7307a69818b9a6ad48c390b2e59d5690fcfd03c529b01960060cc4bb0c686991d6edae2285dfd30f4ba + languageName: node + linkType: hard + +"jwa@npm:^2.0.1": + version: 2.0.1 + resolution: "jwa@npm:2.0.1" + dependencies: + buffer-equal-constant-time: "npm:^1.0.1" + ecdsa-sig-formatter: "npm:1.0.11" + safe-buffer: "npm:^5.0.1" + checksum: 10c0/ab3ebc6598e10dc11419d4ed675c9ca714a387481466b10e8a6f3f65d8d9c9237e2826f2505280a739cf4cbcf511cb288eeec22b5c9c63286fc5a2e4f97e78cf + languageName: node + linkType: hard + +"jws@npm:^4.0.1": + version: 4.0.1 + resolution: "jws@npm:4.0.1" + dependencies: + jwa: "npm:^2.0.1" + safe-buffer: "npm:^5.0.1" + checksum: 10c0/6be1ed93023aef570ccc5ea8d162b065840f3ef12f0d1bb3114cade844de7a357d5dc558201d9a65101e70885a6fa56b17462f520e6b0d426195510618a154d0 + languageName: node + linkType: hard + "keyv@npm:^4.5.4": version: 4.5.4 resolution: "keyv@npm:4.5.4" @@ -2871,6 +3034,48 @@ __metadata: languageName: node linkType: hard +"lodash.includes@npm:^4.3.0": + version: 4.3.0 + resolution: "lodash.includes@npm:4.3.0" + checksum: 10c0/7ca498b9b75bf602d04e48c0adb842dfc7d90f77bcb2a91a2b2be34a723ad24bc1c8b3683ec6b2552a90f216c723cdea530ddb11a3320e08fa38265703978f4b + languageName: node + linkType: hard + +"lodash.isboolean@npm:^3.0.3": + version: 3.0.3 + resolution: "lodash.isboolean@npm:3.0.3" + checksum: 10c0/0aac604c1ef7e72f9a6b798e5b676606042401dd58e49f051df3cc1e3adb497b3d7695635a5cbec4ae5f66456b951fdabe7d6b387055f13267cde521f10ec7f7 + languageName: node + linkType: hard + +"lodash.isinteger@npm:^4.0.4": + version: 4.0.4 + resolution: "lodash.isinteger@npm:4.0.4" + checksum: 10c0/4c3e023a2373bf65bf366d3b8605b97ec830bca702a926939bcaa53f8e02789b6a176e7f166b082f9365bfec4121bfeb52e86e9040cb8d450e64c858583f61b7 + languageName: node + linkType: hard + +"lodash.isnumber@npm:^3.0.3": + version: 3.0.3 + resolution: "lodash.isnumber@npm:3.0.3" + checksum: 10c0/2d01530513a1ee4f72dd79528444db4e6360588adcb0e2ff663db2b3f642d4bb3d687051ae1115751ca9082db4fdef675160071226ca6bbf5f0c123dbf0aa12d + languageName: node + linkType: hard + +"lodash.isplainobject@npm:^4.0.6": + version: 4.0.6 + resolution: "lodash.isplainobject@npm:4.0.6" + checksum: 10c0/afd70b5c450d1e09f32a737bed06ff85b873ecd3d3d3400458725283e3f2e0bb6bf48e67dbe7a309eb371a822b16a26cca4a63c8c52db3fc7dc9d5f9dd324cbb + languageName: node + linkType: hard + +"lodash.isstring@npm:^4.0.1": + version: 4.0.1 + resolution: "lodash.isstring@npm:4.0.1" + checksum: 10c0/09eaf980a283f9eef58ef95b30ec7fee61df4d6bf4aba3b5f096869cc58f24c9da17900febc8ffd67819b4e29de29793190e88dc96983db92d84c95fa85d1c92 + languageName: node + linkType: hard + "lodash.merge@npm:^4.6.2": version: 4.6.2 resolution: "lodash.merge@npm:4.6.2" @@ -2878,6 +3083,13 @@ __metadata: languageName: node linkType: hard +"lodash.once@npm:^4.0.0": + version: 4.1.1 + resolution: "lodash.once@npm:4.1.1" + checksum: 10c0/46a9a0a66c45dd812fcc016e46605d85ad599fe87d71a02f6736220554b52ffbe82e79a483ad40f52a8a95755b0d1077fba259da8bfb6694a7abbf4a48f1fc04 + languageName: node + linkType: hard + "lodash@npm:^4.17.21": version: 4.17.21 resolution: "lodash@npm:4.17.21" @@ -2915,26 +3127,6 @@ __metadata: languageName: node linkType: hard -"magicast@npm:^0.3.5": - version: 0.3.5 - resolution: "magicast@npm:0.3.5" - dependencies: - "@babel/parser": "npm:^7.25.4" - "@babel/types": "npm:^7.25.4" - source-map-js: "npm:^1.2.0" - checksum: 10c0/a6cacc0a848af84f03e3f5bda7b0de75e4d0aa9ddce5517fd23ed0f31b5ddd51b2d0ff0b7e09b51f7de0f4053c7a1107117edda6b0732dca3e9e39e6c5a68c64 - languageName: node - linkType: hard - -"make-dir@npm:^4.0.0": - version: 4.0.0 - resolution: "make-dir@npm:4.0.0" - dependencies: - semver: "npm:^7.5.3" - checksum: 10c0/69b98a6c0b8e5c4fe9acb61608a9fbcfca1756d910f51e5dbe7a9e5cfb74fca9b8a0c8a0ffdf1294a740826c1ab4871d5bf3f62f72a3049e5eac6541ddffed68 - languageName: node - linkType: hard - "make-error@npm:^1.1.1": version: 1.3.6 resolution: "make-error@npm:1.3.6" @@ -3113,30 +3305,6 @@ __metadata: languageName: node linkType: hard -"mylib-utils@workspace:^, mylib-utils@workspace:packages/utils": - version: 0.0.0-use.local - resolution: "mylib-utils@workspace:packages/utils" - dependencies: - "@vitest/coverage-v8": "npm:^2.1.4" - eslint: "npm:^9.14.0" - typescript: "npm:^5.6.3" - vitest: "npm:^2.1.4" - languageName: unknown - linkType: soft - -"mylib@workspace:packages/core": - version: 0.0.0-use.local - resolution: "mylib@workspace:packages/core" - dependencies: - "@vitest/coverage-v8": "npm:^2.1.4" - eslint: "npm:^9.14.0" - mylib-utils: "workspace:^" - rimraf: "npm:^6.0.1" - typescript: "npm:^5.6.3" - vitest: "npm:^2.1.4" - languageName: unknown - linkType: soft - "nanoid@npm:^3.3.7": version: 3.3.7 resolution: "nanoid@npm:3.3.7" @@ -3260,6 +3428,15 @@ __metadata: languageName: node linkType: hard +"once@npm:^1.4.0": + version: 1.4.0 + resolution: "once@npm:1.4.0" + dependencies: + wrappy: "npm:1" + checksum: 10c0/5d48aca287dfefabd756621c5dfce5c91a549a93e9fdb7b8246bc4c4790aa2ec17b34a260530474635147aeb631a2dcc8b32c613df0675f96041cbb8244517d0 + languageName: node + linkType: hard + "optionator@npm:^0.9.3": version: 0.9.4 resolution: "optionator@npm:0.9.4" @@ -3637,6 +3814,13 @@ __metadata: languageName: node linkType: hard +"safe-buffer@npm:^5.0.1": + version: 5.2.1 + resolution: "safe-buffer@npm:5.2.1" + checksum: 10c0/6501914237c0a86e9675d4e51d89ca3c21ffd6a31642efeba25ad65720bce6921c9e7e974e5be91a786b25aa058b5303285d3c15dbabf983a919f5f630d349f3 + languageName: node + linkType: hard + "safe-regex-test@npm:^1.0.3": version: 1.0.3 resolution: "safe-regex-test@npm:1.0.3" @@ -3664,7 +3848,7 @@ __metadata: languageName: node linkType: hard -"semver@npm:^7.3.5, semver@npm:^7.3.6, semver@npm:^7.5.3, semver@npm:^7.5.4, semver@npm:^7.6.0, semver@npm:^7.6.3": +"semver@npm:^7.3.5, semver@npm:^7.3.6, semver@npm:^7.5.4, semver@npm:^7.6.0, semver@npm:^7.6.3": version: 7.6.3 resolution: "semver@npm:7.6.3" bin: @@ -3776,7 +3960,7 @@ __metadata: languageName: node linkType: hard -"source-map-js@npm:^1.2.0, source-map-js@npm:^1.2.1": +"source-map-js@npm:^1.2.1": version: 1.2.1 resolution: "source-map-js@npm:1.2.1" checksum: 10c0/7bda1fc4c197e3c6ff17de1b8b2c20e60af81b63a52cb32ec5a5d67a20a7d42651e2cb34ebe93833c5a2a084377e17455854fee3e21e7925c64a51b6a52b0faf @@ -3972,17 +4156,6 @@ __metadata: languageName: node linkType: hard -"test-exclude@npm:^7.0.1": - version: 7.0.1 - resolution: "test-exclude@npm:7.0.1" - dependencies: - "@istanbuljs/schema": "npm:^0.1.2" - glob: "npm:^10.4.1" - minimatch: "npm:^9.0.4" - checksum: 10c0/6d67b9af4336a2e12b26a68c83308c7863534c65f27ed4ff7068a56f5a58f7ac703e8fc80f698a19bb154fd8f705cdf7ec347d9512b2c522c737269507e7b263 - languageName: node - linkType: hard - "text-table@npm:^0.2.0": version: 0.2.0 resolution: "text-table@npm:0.2.0" @@ -4214,6 +4387,13 @@ __metadata: languageName: node linkType: hard +"undici-types@npm:~7.16.0": + version: 7.16.0 + resolution: "undici-types@npm:7.16.0" + checksum: 10c0/3033e2f2b5c9f1504bdc5934646cb54e37ecaca0f9249c983f7b1fc2e87c6d18399ebb05dc7fd5419e02b2e915f734d872a65da2e3eeed1813951c427d33cc9a + languageName: node + linkType: hard + "unique-filename@npm:^3.0.0": version: 3.0.0 resolution: "unique-filename@npm:3.0.0" @@ -4232,6 +4412,20 @@ __metadata: languageName: node linkType: hard +"universal-user-agent@npm:^6.0.0": + version: 6.0.1 + resolution: "universal-user-agent@npm:6.0.1" + checksum: 10c0/5c9c46ffe19a975e11e6443640ed4c9e0ce48fcc7203325757a8414ac49940ebb0f4667f2b1fa561489d1eb22cb2d05a0f7c82ec20c5cba42e58e188fb19b187 + languageName: node + linkType: hard + +"universal-user-agent@npm:^7.0.0, universal-user-agent@npm:^7.0.2": + version: 7.0.3 + resolution: "universal-user-agent@npm:7.0.3" + checksum: 10c0/6043be466a9bb96c0ce82392842d9fddf4c37e296f7bacc2cb25f47123990eb436c82df824644f9c5070a94dbdb117be17f66d54599ab143648ec57ef93dbcc8 + languageName: node + linkType: hard + "uri-js@npm:^4.2.2": version: 4.4.1 resolution: "uri-js@npm:4.4.1" @@ -4468,6 +4662,13 @@ __metadata: languageName: node linkType: hard +"wrappy@npm:1": + version: 1.0.2 + resolution: "wrappy@npm:1.0.2" + checksum: 10c0/56fece1a4018c6a6c8e28fbc88c87e0fbf4ea8fd64fc6c63b18f4acc4bd13e0ad2515189786dd2c30d3eec9663d70f4ecf699330002f8ccb547e4a18231fc9f0 + languageName: node + linkType: hard + "xml-name-validator@npm:^4.0.0": version: 4.0.0 resolution: "xml-name-validator@npm:4.0.0" From 43558cd84e2ffdd2cec083cc092296bc314d8777 Mon Sep 17 00:00:00 2001 From: Peter Savchenko Date: Sat, 7 Feb 2026 19:16:11 +0300 Subject: [PATCH 2/5] Use tsconfig.eslint for ESLint + add build script --- eslint.config.mjs | 2 +- package.json | 1 + tsconfig.eslint.json | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 tsconfig.eslint.json diff --git a/eslint.config.mjs b/eslint.config.mjs index 31a13a8..536e4c5 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -33,7 +33,7 @@ export default [ languageOptions: { parser: TsParser, parserOptions: { - projectService: true, + project: path.join(__dirname, 'tsconfig.eslint.json'), tsconfigRootDir: __dirname, sourceType: 'module', }, diff --git a/package.json b/package.json index f663c26..3b9d620 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "packages/*" ], "scripts": { + "build": "yarn workspaces foreach -At run build", "clean": "rimraf -g \"packages/**/dist\" \"packages/**/*.tsbuildinfo\"", "lint": "yarn workspaces foreach -At run build && yarn workspaces foreach -A run lint", "lint:fix": "yarn workspaces foreach -At run build && yarn workspaces foreach -A run lint --fix", diff --git a/tsconfig.eslint.json b/tsconfig.eslint.json new file mode 100644 index 0000000..650abaa --- /dev/null +++ b/tsconfig.eslint.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "baseUrl": ".", + "paths": { + "@hawk.so/utils": ["packages/utils/src/index.ts"] + } + }, + "include": [ + "packages/*/src/**/*", + "packages/*/tests/**/*", + "eslint.config.mjs" + ] +} From 10344a53b5046756ca3527848e0dd12b9383712d Mon Sep 17 00:00:00 2001 From: Peter Savchenko Date: Sat, 7 Feb 2026 21:58:29 +0300 Subject: [PATCH 3/5] lint code --- .github/workflows/main.yml | 50 +++--- packages/github/src/index.ts | 6 +- packages/github/src/normalizePrivateKey.ts | 7 +- packages/github/src/service.ts | 180 +++++++++++++++------ packages/github/src/types/index.ts | 40 +++++ packages/utils/src/hasValue.ts | 2 +- packages/utils/src/index.ts | 1 + packages/utils/src/time.ts | 30 ++++ 8 files changed, 232 insertions(+), 84 deletions(-) create mode 100644 packages/utils/src/time.ts diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 77e05e9..b906926 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -3,7 +3,7 @@ name: CI on: push jobs: - lint-test: + lint-test-build-publish: runs-on: ubuntu-20.04 steps: - name: Checkout repository @@ -40,31 +40,31 @@ jobs: - name: Run unit tests run: yarn test - # - name: Build library - # run: yarn build + - name: Build library + run: yarn build - # - name: Publish library - # if: ${{ github.ref == 'refs/heads/main' }} - # run: yarn publish --access=public - # env: - # NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + - name: Publish library + if: ${{ github.ref == 'refs/heads/main' }} + run: yarn publish --access=public + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - # notify: - # needs: lint-test-build-publish - # if: github.ref == 'refs/heads/main' - # runs-on: ubuntu-20.04 - # steps: - # - name: Checkout repository - # uses: actions/checkout@v2 + notify: + needs: lint-test-build-publish + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-20.04 + steps: + - name: Checkout repository + uses: actions/checkout@v2 - # - name: Get package info - # id: package - # uses: codex-team/action-nodejs-package-info@v1 + - name: Get package info + id: package + uses: codex-team/action-nodejs-package-info@v1 - # - name: Send a message - # uses: codex-team/action-codexbot-notify@v1 - # with: - # webhook: ${{ secrets.CODEX_BOT_WEBHOOK }} - # message: '📦 [${{ steps.package.outputs.name }}](${{ steps.package.outputs.npmjs-link }}) ${{ steps.package.outputs.version }} was published' - # parse_mode: 'markdown' - # disable_web_page_preview: true + - name: Send a message + uses: codex-team/action-codexbot-notify@v1 + with: + webhook: ${{ secrets.CODEX_BOT_WEBHOOK_HAWK }} + message: '📦 [${{ steps.package.outputs.name }}](${{ steps.package.outputs.npmjs-link }}) ${{ steps.package.outputs.version }} was published' + parse_mode: 'markdown' + disable_web_page_preview: true diff --git a/packages/github/src/index.ts b/packages/github/src/index.ts index 339b8c0..86e3227 100644 --- a/packages/github/src/index.ts +++ b/packages/github/src/index.ts @@ -1,9 +1,11 @@ export { GitHubService } from './service'; export type { GitHubServiceConfig, - IssueData, GitHubIssue, + GitHubUser, Installation, - Repository + OAuthTokens, + Repository, + ValidateUserTokenResult } from './types'; export { normalizeGitHubPrivateKey } from './normalizePrivateKey'; diff --git a/packages/github/src/normalizePrivateKey.ts b/packages/github/src/normalizePrivateKey.ts index 7dfd687..fea9e36 100644 --- a/packages/github/src/normalizePrivateKey.ts +++ b/packages/github/src/normalizePrivateKey.ts @@ -1,6 +1,7 @@ +import { Buffer } from 'buffer'; + /** * Normalize and validate GitHub App private key. - * * @param rawPrivateKey - raw value from env (GITHUB_PRIVATE_KEY) * @returns PEM-encoded private key string */ @@ -11,8 +12,8 @@ export function normalizeGitHubPrivateKey(rawPrivateKey: string): string { let privateKey = rawPrivateKey.trim(); if ( - (privateKey.startsWith('"') && privateKey.endsWith('"')) || - (privateKey.startsWith('\'') && privateKey.endsWith('\'')) + (privateKey.startsWith('"') && privateKey.endsWith('"')) + || (privateKey.startsWith('\'') && privateKey.endsWith('\'')) ) { privateKey = privateKey.slice(1, -1); } diff --git a/packages/github/src/service.ts b/packages/github/src/service.ts index 1a69457..a9ea590 100644 --- a/packages/github/src/service.ts +++ b/packages/github/src/service.ts @@ -1,43 +1,75 @@ import jwt from 'jsonwebtoken'; import { Octokit } from '@octokit/rest'; import { exchangeWebFlowCode, refreshToken as refreshOAuthToken } from '@octokit/oauth-methods'; -import { hasValue } from '@hawk.so/utils'; +import { hasValue, TimeMs } from '@hawk.so/utils'; import { normalizeGitHubPrivateKey } from './normalizePrivateKey'; import type { GitHubServiceConfig, + GitHubUser, Installation, Repository, IssueData, - GitHubIssue + GitHubIssue, + OAuthTokens, + ValidateUserTokenResult } from './types'; /** - * Milliseconds in one minute + * Buffer time before token expiration to trigger refresh (5 minutes) */ -const MINUTE_MS = 60_000; +// eslint-disable-next-line @typescript-eslint/no-magic-numbers +const TOKEN_REFRESH_BUFFER_MS = 5 * TimeMs.Minute; /** - * Buffer time before token expiration to trigger refresh (5 minutes) + * Error object with optional HTTP status (e.g. from Octokit request failure). */ -// eslint-disable-next-line @typescript-eslint/no-magic-numbers -const TOKEN_REFRESH_BUFFER_MS = 5 * MINUTE_MS; +/* eslint-disable-next-line jsdoc/require-jsdoc */ +type ErrorWithStatus = { status?: number }; /** * Service for interacting with GitHub API */ export class GitHubService { - // eslint-disable-next-line @typescript-eslint/naming-convention - private static readonly DEFAULT_TIMEOUT = 10000; + // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-magic-numbers + private static readonly DEFAULT_TIMEOUT = 10 * TimeMs.Second; // eslint-disable-next-line @typescript-eslint/naming-convention private static readonly JWT_EXPIRATION_MINUTES = 10; + /** + * GitHub App ID; used to sign JWTs and identify the app in API requests. + */ private readonly appId: string; + + /** + * PEM private key for the GitHub App; used to sign JWTs for app and installation auth. + */ private readonly privateKey: string; + + /** + * App slug (URL name); used in installation and OAuth URLs (e.g. github.com/apps/{appSlug}/installations/new). + */ private readonly appSlug: string; + + /** + * OAuth App client ID; required for exchanging codes and refreshing user tokens. + */ private readonly clientId?: string; + + /** + * OAuth App client secret; required for exchanging codes and refreshing user tokens. + */ private readonly clientSecret?: string; + + /** + * Base URL of the API; used for OAuth redirect URLs and when not using public GitHub. + */ private readonly apiUrl?: string; + /** + * Whether to emit debug logs. + */ + private readonly logs: boolean; + /** * Creates a GitHubService instance. * @param config - App credentials and optional OAuth/API settings (e.g. from env). @@ -57,6 +89,7 @@ export class GitHubService { this.clientId = config.clientId; this.clientSecret = config.clientSecret; this.apiUrl = config.apiUrl; + this.logs = config.logs !== false; } /** @@ -153,7 +186,7 @@ export class GitHubService { installation_id: parseInt(installationId, 10), }); - console.log('Installation info:', { + this.log('Installation info:', { id: installationInfo.data.id, account: installationInfo.data.account, // eslint-disable-next-line @typescript-eslint/naming-convention @@ -172,7 +205,7 @@ export class GitHubService { } ); - console.log(`Total repositories fetched: ${repositoriesData.length}`); + this.log(`Total repositories fetched: ${repositoriesData.length}`); const repositories = repositoriesData.map(repo => ({ id: repo.id.toString(), @@ -281,17 +314,22 @@ export class GitHubService { `; /** GraphQL response shape for repository + issue + suggestedActors query. */ - /* eslint-disable jsdoc/require-jsdoc */ type RepoInfoGraphQLResponse = { + /* eslint-disable jsdoc/require-jsdoc */ repository?: { id: string; issue?: { id: string }; suggestedActors: { - nodes: Array<{ login: string; __typename?: string; id?: string }>; + nodes: Array<{ + login: string; + // eslint-disable-next-line @typescript-eslint/naming-convention + __typename?: string; + id?: string; + }>; }; }; + /* eslint-enable jsdoc/require-jsdoc */ }; - /* eslint-enable jsdoc/require-jsdoc */ const repoInfo = await octokit.graphql(repoInfoQuery, { owner, @@ -299,7 +337,7 @@ export class GitHubService { issueNumber, }); - console.log('[GitHub API] Repository info query response:', JSON.stringify(repoInfo, null, 2)); + this.log('[GitHub API] Repository info query response:', JSON.stringify(repoInfo, null, 2)); const repositoryId = repoInfo?.repository?.id; const issueId = repoInfo?.repository?.issue?.id; @@ -313,16 +351,31 @@ export class GitHubService { } /** Node in suggestedActors (login, optional __typename and id). */ - /* eslint-disable-next-line jsdoc/require-jsdoc */ - type SuggestedActorNode = { login: string; __typename?: string; id?: string }; + /* eslint-disable jsdoc/require-jsdoc */ + type SuggestedActorNode = { + login: string; + // eslint-disable-next-line @typescript-eslint/naming-convention + __typename?: string; + id?: string ; + }; + /* eslint-enable jsdoc/require-jsdoc */ + let copilotBot = (repoInfo?.repository?.suggestedActors?.nodes ?? []).find( (node: SuggestedActorNode) => node.login === 'copilot-swe-agent' ); - console.log('[GitHub API] Copilot bot found in suggestedActors:', copilotBot ? { login: copilotBot.login, id: copilotBot.id } : 'not found'); + this.log( + '[GitHub API] Copilot bot found in suggestedActors:', + copilotBot + ? { + login: copilotBot.login, + id: copilotBot.id, + } + : 'not found' + ); if (!hasValue(copilotBot) || !hasValue(copilotBot?.id)) { - console.log('[GitHub API] Trying to get Copilot bot directly by login...'); + this.log('[GitHub API] Trying to get Copilot bot directly by login...'); try { const copilotBotQuery = ` @@ -338,7 +391,12 @@ export class GitHubService { /** GraphQL response shape for user(login) query. */ /* eslint-disable jsdoc/require-jsdoc */ type CopilotUserInfoGraphQLResponse = { - user?: { id: string; login: string; __typename?: string }; + user?: { + id: string; + login: string; + // eslint-disable-next-line @typescript-eslint/naming-convention + __typename?: string; + }; }; /* eslint-enable jsdoc/require-jsdoc */ @@ -346,7 +404,7 @@ export class GitHubService { login: 'copilot-swe-agent', }); - console.log('[GitHub API] Direct Copilot bot query response:', JSON.stringify(copilotUserInfo, null, 2)); + this.log('[GitHub API] Direct Copilot bot query response:', JSON.stringify(copilotUserInfo, null, 2)); if (hasValue(copilotUserInfo?.user?.id)) { copilotBot = { @@ -355,7 +413,7 @@ export class GitHubService { }; } } catch (directQueryError) { - console.log('[GitHub API] Failed to get Copilot bot directly:', directQueryError); + this.log('[GitHub API] Failed to get Copilot bot directly:', directQueryError); } } @@ -363,7 +421,10 @@ export class GitHubService { throw new Error('Copilot coding agent (copilot-swe-agent) is not available for this repository'); } - console.log('[GitHub API] Using Copilot bot:', { login: copilotBot.login, id: copilotBot.id }); + this.log('[GitHub API] Using Copilot bot:', { + login: copilotBot.login, + id: copilotBot.id, + }); const assignCopilotMutation = ` mutation($issueId: ID!, $assigneeIds: [ID!]!) { @@ -413,7 +474,7 @@ export class GitHubService { assigneeIds: [copilotBot.id], }); - console.log('[GitHub API] Assign Copilot mutation response:', JSON.stringify(response, null, 2)); + this.log('[GitHub API] Assign Copilot mutation response:', JSON.stringify(response, null, 2)); const assignable = response?.addAssigneesToAssignable?.assignable; @@ -423,14 +484,15 @@ export class GitHubService { /* eslint-disable-next-line jsdoc/require-jsdoc */ const assignedLogins = assignable.assignees?.nodes?.map((n: { login: string }) => n.login) || []; - console.log(`[GitHub API] Issue assignees after mutation:`, assignedLogins); + + this.log(`[GitHub API] Issue assignees after mutation:`, assignedLogins); const assignedNumber = assignable.number; if (assignedLogins.includes('copilot-swe-agent')) { - console.log(`[GitHub API] Successfully assigned Copilot to issue #${assignedNumber}`); + this.log(`[GitHub API] Successfully assigned Copilot to issue #${assignedNumber}`); } else { - console.log(`[GitHub API] Copilot assignment mutation completed for issue #${assignedNumber}, but assignees list not yet updated in response`); + this.log(`[GitHub API] Copilot assignment mutation completed for issue #${assignedNumber}, but assignees list not yet updated in response`); } } catch (error) { throw new Error(`Failed to assign Copilot: ${error instanceof Error ? error.message : String(error)}`); @@ -452,12 +514,7 @@ export class GitHubService { accessTokenExpiresAt: Date | null; refreshTokenExpiresAt: Date | null; }, - onRefresh?: (newTokens: { - accessToken: string; - refreshToken: string; - expiresAt: Date | null; - refreshTokenExpiresAt: Date | null; - }) => Promise + onRefresh?: (newTokens: OAuthTokens) => Promise /* eslint-enable jsdoc/require-jsdoc */ ): Promise { const now = new Date(); @@ -506,7 +563,7 @@ export class GitHubService { refreshToken: string; expiresAt: Date | null; refreshTokenExpiresAt: Date | null; - user: { id: number; login: string }; + user: GitHubUser; }> { /* eslint-enable jsdoc/require-jsdoc */ if (!hasValue(this.clientId) || !hasValue(this.clientSecret)) { @@ -552,7 +609,10 @@ export class GitHubService { refreshToken, expiresAt, refreshTokenExpiresAt, - user: { id: userData.id, login: userData.login }, + user: { + id: userData.id, + login: userData.login, + }, }; } catch (error) { throw new Error(`Failed to exchange OAuth code for token: ${error instanceof Error ? error.message : String(error)}`); @@ -564,22 +624,32 @@ export class GitHubService { * @param accessToken - GitHub user access token (e.g. from OAuth). * @returns valid, optional user (id, login), and status ('active' or 'revoked'). */ - /* eslint-disable jsdoc/require-jsdoc */ - public async validateUserToken(accessToken: string): Promise<{ valid: boolean; user?: { id: number; login: string }; status: 'active' | 'revoked' }> { + public async validateUserToken(accessToken: string): Promise { try { const octokit = this.createOctokit(accessToken); const { data: userData } = await octokit.rest.users.getAuthenticated(); return { valid: true, - user: { id: userData.id, login: userData.login }, + user: { + id: userData.id, + login: userData.login, + }, status: 'active', }; } catch (error: unknown) { - const err = error as { status?: number }; - /* eslint-enable jsdoc/require-jsdoc */ - if (err?.status === 401 || err?.status === 403) { - return { valid: false, status: 'revoked' }; + const err = error as ErrorWithStatus; + + /** HTTP 401 Unauthorized */ + const HTTP_UNAUTHORIZED = 401; + /** HTTP 403 Forbidden */ + const HTTP_FORBIDDEN = 403; + + if (err?.status === HTTP_UNAUTHORIZED || err?.status === HTTP_FORBIDDEN) { + return { + valid: false, + status: 'revoked', + }; } throw new Error(`Failed to validate user token: ${error instanceof Error ? error.message : String(error)}`); } @@ -590,14 +660,7 @@ export class GitHubService { * @param refreshToken - Current refresh token. * @returns New access token, refresh token, and expiry dates. */ - /* eslint-disable jsdoc/require-jsdoc */ - public async refreshUserToken(refreshToken: string): Promise<{ - accessToken: string; - refreshToken: string; - expiresAt: Date | null; - refreshTokenExpiresAt: Date | null; - }> { - /* eslint-enable jsdoc/require-jsdoc */ + public async refreshUserToken(refreshToken: string): Promise { if (!hasValue(this.clientId) || !hasValue(this.clientSecret)) { throw new Error('GITHUB_APP_CLIENT_ID and GITHUB_APP_CLIENT_SECRET are required for token refresh'); } @@ -633,6 +696,16 @@ export class GitHubService { } } + /** + * Logs a message when logs are enabled. + * @param args - Arguments passed to console.log. + */ + private log(...args: unknown[]): void { + if (this.logs) { + console.log('[GitHubService]', ...args); + } + } + /** * Creates an Octokit client with the given auth token and default timeout/headers. * @param auth - GitHub token (JWT or user access token). @@ -657,11 +730,11 @@ export class GitHubService { */ private createJWT(): string { const privateKey = this.privateKey; - const now = Math.floor(Date.now() / 1000); + const now = Math.floor(Date.now() / TimeMs.Second); const payload = { - iat: now - 60, - exp: now + GitHubService.JWT_EXPIRATION_MINUTES * 60, + iat: now - TimeMs.Minute / TimeMs.Second, + exp: now + GitHubService.JWT_EXPIRATION_MINUTES * (TimeMs.Minute / TimeMs.Second), iss: this.appId, }; @@ -682,6 +755,7 @@ export class GitHubService { // eslint-disable-next-line @typescript-eslint/naming-convention installation_id: parseInt(installationId, 10), }); + return data.token; } catch (error) { throw new Error(`Failed to create installation token: ${error instanceof Error ? error.message : String(error)}`); diff --git a/packages/github/src/types/index.ts b/packages/github/src/types/index.ts index f74c34f..33f3187 100644 --- a/packages/github/src/types/index.ts +++ b/packages/github/src/types/index.ts @@ -53,11 +53,27 @@ export type Installation = { type: string; }; /** Target type of the installation (e.g. "User", "Organization"). */ + // eslint-disable-next-line @typescript-eslint/naming-convention target_type: string; /** Permissions granted to the app (scope -> access level). */ permissions: Record; }; +/** + * OAuth access and refresh tokens with expiry dates. + * Returned by refreshUserToken and passed to onRefresh when getValidAccessToken refreshes tokens. + */ +export type OAuthTokens = { + /** GitHub user access token for API calls. */ + accessToken: string; + /** Refresh token used to obtain a new access token when it expires. */ + refreshToken: string; + /** When the access token expires, or null if unknown. */ + expiresAt: Date | null; + /** When the refresh token expires, or null if unknown. */ + refreshTokenExpiresAt: Date | null; +}; + /** * Configuration for GitHubService. * Values should be read from env by the caller (API, Workers) and passed in. @@ -75,4 +91,28 @@ export interface GitHubServiceConfig { clientSecret?: string; /** Base URL of the API (e.g. for GitHub Enterprise). */ apiUrl?: string; + /** Whether to emit debug logs. Defaults to true. */ + logs?: boolean; } + +/** + * Fields that we use from the GitHub user identity. + */ +export type GitHubUser = { + /** GitHub user ID. */ + id: number; + /** GitHub username (login). */ + login: string; +}; + +/** + * Whether a user access token is still valid and the authenticated user (or revocation status). + */ +export type ValidateUserTokenResult = { + /** True if the token is valid and accepted by GitHub. */ + valid: boolean; + /** Authenticated user (id, login) when valid. */ + user?: GitHubUser; + /** 'active' when valid, 'revoked' when token was rejected (e.g. 401/403). */ + status: 'active' | 'revoked'; +}; diff --git a/packages/utils/src/hasValue.ts b/packages/utils/src/hasValue.ts index d3e3871..c4f9881 100644 --- a/packages/utils/src/hasValue.ts +++ b/packages/utils/src/hasValue.ts @@ -3,6 +3,6 @@ * @param v - Value to check. * @returns True when `v` is defined, not null, and not empty string. */ -export function hasValue(v: unknown): boolean { +export function hasValue(v: T | undefined | null): v is T { return v !== undefined && v !== null && v !== ''; } diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 84bea9a..c708a54 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -1 +1,2 @@ export { hasValue } from './hasValue'; +export { TimeMs } from './time'; diff --git a/packages/utils/src/time.ts b/packages/utils/src/time.ts new file mode 100644 index 0000000..2f0a9e2 --- /dev/null +++ b/packages/utils/src/time.ts @@ -0,0 +1,30 @@ +/* eslint-disable @typescript-eslint/no-magic-numbers */ +/** + * Time intervals in ms + */ +export enum TimeMs { + /** + * One millisecond (1 ms). + */ + Millisecond = 1, + /** + * One second in milliseconds. + */ + Second = TimeMs.Millisecond * 1000, + /** + * One minute in milliseconds. + */ + Minute = TimeMs.Second * 60, + /** + * One hour in milliseconds. + */ + Hour = TimeMs.Minute * 60, + /** + * One day in milliseconds. + */ + Day = TimeMs.Hour * 24, + /** + * One week in milliseconds. + */ + Week = TimeMs.Day * 7 +} From 923cec9becb14139b72a6548e888511be19610db Mon Sep 17 00:00:00 2001 From: Peter Savchenko Date: Sat, 7 Feb 2026 22:03:30 +0300 Subject: [PATCH 4/5] package info upd --- LICENSE | 220 ++++++++++++++++++++++++++++++++++++++++++++++----- package.json | 7 +- 2 files changed, 202 insertions(+), 25 deletions(-) diff --git a/LICENSE b/LICENSE index 0ad8b72..36a7d2a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,199 @@ -MIT License - -Copyright (c) 2021 CodeX - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright © 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS +0. Definitions. +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +hawk.javascript – Error tracking for JavaScript/TypeScript applications. + +Copyright (C) 2025 CodeX + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . diff --git a/package.json b/package.json index 3b9d620..3cc4386 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,10 @@ { "name": "@hawk.so/kit", "private": true, - "version": "2.0.0", - "description": "A quick start template for a new TypeScript library", - "repository": "https://github.com/codex-team/typescript-lib-template.git", + "description": "Set of utils for Hawk services development", + "repository": "https://github.com/codex-team/hawk.kit", "author": "CodeX ", - "license": "MIT", + "license": "AGPL-3.0", "engines": { "node": ">=22.0.0" }, From d21439b3c2d5005ef2396c3e1c7f5a0d7d514148 Mon Sep 17 00:00:00 2001 From: Peter Savchenko Date: Sat, 7 Feb 2026 22:06:19 +0300 Subject: [PATCH 5/5] update readme --- README.md | 66 ++++++------ packages/github/LICENSE | 199 ++++++++++++++++++++++++++++++++++++ packages/github/README.md | 15 ++- packages/utils/LICENSE | 199 ++++++++++++++++++++++++++++++++++++ packages/utils/README.md | 42 ++++++++ packages/utils/package.json | 2 +- 6 files changed, 491 insertions(+), 32 deletions(-) create mode 100644 packages/github/LICENSE create mode 100644 packages/utils/LICENSE create mode 100644 packages/utils/README.md diff --git a/README.md b/README.md index 8380bf8..43e3023 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,40 @@ -# @codexteam/typescript-lib-template -A quick start template for a new TypeScript library - -[![NPM version](https://img.shields.io/npm/v/@codexteam/typescript-lib-template?style=flat-square)](https://www.npmjs.com/package/@codexteam/typescript-lib-template) -[![License](https://img.shields.io/npm/l/@codexteam/typescript-lib-template?style=flat-square)](https://www.npmjs.com/package/@codexteam/typescript-lib-template) - -## Features - -- 💄 Yarn 4 -- 🛍️ Yarn Workspaces -- 💎 ESLint 9 with [eslint-config-codex](http://github.com/codex-team/eslint-config/) -- 🥃 Typescript 5 -- 🥊 npx only-allow yarn -- 🌶️ Tests with [Vitest](https://vitest.dev) -- 🍀 GitHub Actions for test/lint/build/publish purposes - -## How to use -1. Click [here](https://github.com/codex-team/typescript-lib-template/generate) and fill setting for new repository -2. Update root package `package.json`, change main package name -3. Update "core" package `package.json`: - 1. Change `name` - 2. Adjust `main`, `types`, `exports` -5. Change name of `packages/core` to your main package name -5. Go to `packages/utils` and adjust its name or remove the package if you don't need it -3. Change NPM package scope from [workflow file](./.github/workflows/main.yml) or remove it -4. Fill `NPM_TOKEN` and `CODEX_BOT_WEBHOOK` secrets in your repository or organization settings -5. Start writing your new library! - -# About CodeX +# @hawk.so/kit + +Set of packages for Hawk services development (monorepo). + +## Packages + +- **[@hawk.so/utils](./packages/utils)** — shared utilities for Hawk packages. + - `hasValue` — check that a value is not `undefined`, `null`, or empty string. + - `TimeMs` — enum of time intervals in milliseconds (Second, Minute, Hour, Day, Week). + +- **[@hawk.so/github-sdk](./packages/github)** — GitHub API client for Hawk. + - `GitHubService` — GitHub App (installation, installations, repositories). + - Create and manage issues, assign Copilot to an issue. + - OAuth: exchange code for token, refresh token, validate user token. + - `normalizeGitHubPrivateKey` — normalize PEM key from env (base64, quotes, `\n`). + - Types: `GitHubServiceConfig`, `OAuthTokens`, `GitHubUser`, `ValidateUserTokenResult`, `Repository`, `Installation`, `GitHubIssue`, `IssueData`. + +## Requirements + +- Node.js >= 22.0.0 +- Yarn 4 (Corepack enabled in repo) + +## Commands + +```bash +yarn install # install dependencies +yarn build # build all packages +yarn lint # lint (build + eslint across packages) +yarn test # run tests +yarn clean # remove dist and tsbuildinfo +``` + +## License + +AGPL-3.0 + +## About CodeX diff --git a/packages/github/LICENSE b/packages/github/LICENSE new file mode 100644 index 0000000..36a7d2a --- /dev/null +++ b/packages/github/LICENSE @@ -0,0 +1,199 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright © 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS +0. Definitions. +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +hawk.javascript – Error tracking for JavaScript/TypeScript applications. + +Copyright (C) 2025 CodeX + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . diff --git a/packages/github/README.md b/packages/github/README.md index b6eccda..cf4f4f8 100644 --- a/packages/github/README.md +++ b/packages/github/README.md @@ -6,7 +6,7 @@ Shared by API and Workers. ## Build ```bash -cd utils/packages/github && yarn build +cd packages/github && yarn build ``` Build before using in API or Workers (when using `file:` dependency). @@ -41,4 +41,15 @@ API and Workers read env vars and pass them to the constructor. | `appSlug` | optional (default: `hawk-tracker`) | | `clientId` | OAuth (token exchange, refresh) | | `clientSecret`| OAuth | -| `apiUrl` | `getInstallationUrl`, OAuth redirect URI. Hawk Api host. | +| `apiUrl` | `getInstallationUrl`, OAuth redirect URI. Hawk API host. | + +## About CodeX + + + +CodeX is a team of digital specialists around the world interested in building high-quality open source products on a global market. We are [open](https://codex.so/join) for young people who want to constantly improve their skills and grow professionally with experiments in cutting-edge technologies. + +| 🌐 | Join 👋 | Twitter | Instagram | +| -- | -- | -- | -- | +| [codex.so](https://codex.so) | [codex.so/join](https://codex.so/join) |[@codex_team](http://twitter.com/codex_team) | [@codex_team](http://instagram.com/codex_team/) | + diff --git a/packages/utils/LICENSE b/packages/utils/LICENSE new file mode 100644 index 0000000..36a7d2a --- /dev/null +++ b/packages/utils/LICENSE @@ -0,0 +1,199 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright © 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS +0. Definitions. +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +hawk.javascript – Error tracking for JavaScript/TypeScript applications. + +Copyright (C) 2025 CodeX + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . diff --git a/packages/utils/README.md b/packages/utils/README.md new file mode 100644 index 0000000..e02954b --- /dev/null +++ b/packages/utils/README.md @@ -0,0 +1,42 @@ +# @hawk.so/utils + +Shared utilities for Hawk packages. + +## Contents + +- **hasValue(v)** — returns `true` if the value is not `undefined`, not `null`, and not an empty string; otherwise `false`. +- **TimeMs** — enum of time intervals in milliseconds: + - `Millisecond`, `Second`, `Minute`, `Hour`, `Day`, `Week` + +## Installation + +```bash +yarn add @hawk.so/utils +``` + +## Example + +```typescript +import { hasValue, TimeMs } from '@hawk.so/utils'; + +if (hasValue(process.env.API_KEY)) { + // ... +} + +const fiveMinutes = 5 * TimeMs.Minute; +``` + +## License + +AGPL-3.0 + +## About CodeX + + + +CodeX is a team of digital specialists around the world interested in building high-quality open source products on a global market. We are [open](https://codex.so/join) for young people who want to constantly improve their skills and grow professionally with experiments in cutting-edge technologies. + +| 🌐 | Join 👋 | Twitter | Instagram | +| -- | -- | -- | -- | +| [codex.so](https://codex.so) | [codex.so/join](https://codex.so/join) |[@codex_team](http://twitter.com/codex_team) | [@codex_team](http://instagram.com/codex_team/) | + diff --git a/packages/utils/package.json b/packages/utils/package.json index c0e21ba..20bbf01 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -3,7 +3,7 @@ "version": "1.0.0", "description": "Shared utilities for Hawk packages", "author": "CodeX ", - "license": "MIT", + "license": "AGPL-3.0", "exports": { ".": { "types": "./dist/index.d.ts",