@red-hat-developer-hub/backstage-plugin-bulk-import-backend 5.2.1 → 5.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/config.d.ts +1 -1
  3. package/dist/catalog/catalogHttpClient.cjs.js.map +1 -1
  4. package/dist/catalog/catalogInfoGenerator.cjs.js.map +1 -1
  5. package/dist/catalog/catalogUtils.cjs.js.map +1 -1
  6. package/dist/generated/openapidocument.cjs.js +36 -0
  7. package/dist/generated/openapidocument.cjs.js.map +1 -1
  8. package/dist/github/GithubAppManager.cjs.js.map +1 -1
  9. package/dist/github/githubApiService.cjs.js.map +1 -1
  10. package/dist/github/types.cjs.js.map +1 -1
  11. package/dist/github/utils/ghUtils.cjs.js.map +1 -1
  12. package/dist/github/utils/orgUtils.cjs.js.map +1 -1
  13. package/dist/github/utils/prUtils.cjs.js.map +1 -1
  14. package/dist/github/utils/repoUtils.cjs.js.map +1 -1
  15. package/dist/github/utils/utils.cjs.js.map +1 -1
  16. package/dist/helpers/auditLogUtils.cjs.js.map +1 -1
  17. package/dist/helpers/auth.cjs.js.map +1 -1
  18. package/dist/helpers/loggingUtils.cjs.js.map +1 -1
  19. package/dist/helpers/pagination.cjs.js.map +1 -1
  20. package/dist/helpers/utils.cjs.js +11 -0
  21. package/dist/helpers/utils.cjs.js.map +1 -0
  22. package/dist/plugin.cjs.js.map +1 -1
  23. package/dist/service/handlers/handlers.cjs.js +4 -0
  24. package/dist/service/handlers/handlers.cjs.js.map +1 -1
  25. package/dist/service/handlers/import/bulkImports.cjs.js +18 -23
  26. package/dist/service/handlers/import/bulkImports.cjs.js.map +1 -1
  27. package/dist/service/handlers/import/importStatus.cjs.js.map +1 -1
  28. package/dist/service/handlers/organization/organizations.cjs.js.map +1 -1
  29. package/dist/service/handlers/ping/ping.cjs.js.map +1 -1
  30. package/dist/service/handlers/repository/repositories.cjs.js.map +1 -1
  31. package/dist/service/router.cjs.js +3 -1
  32. package/dist/service/router.cjs.js.map +1 -1
  33. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"repoUtils.cjs.js","sources":["../../../src/github/utils/repoUtils.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { LoggerService } from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport type {\n GithubCredentials,\n GithubIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName } from '../../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../../service/handlers/handlers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport type {\n ExtendedGithubCredentials,\n GithubAppCredentials,\n GithubFetchError,\n GithubRepository,\n} from '../types';\nimport { getAllAppOrgs } from './orgUtils';\nimport {\n computeTotalCountFromGitHubToken,\n createCredentialError,\n handleError,\n} from './utils';\n\nexport type ValidatedRepo = {\n ghConfig: GithubIntegrationConfig;\n credentials: ExtendedGithubCredentials[];\n owner: string;\n repo: string;\n branchName: string;\n};\n\nexport async function validateAndBuildRepoData(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n integrations: ScmIntegrations,\n config: Config,\n input: {\n repoUrl: string;\n },\n): Promise<ValidatedRepo> {\n const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(`Could not find GH integration from ${input.repoUrl}`);\n }\n\n const gitUrl = gitUrlParse(input.repoUrl);\n const owner = gitUrl.organization;\n const repo = gitUrl.name;\n\n const credentials = await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n const branchName = getBranchName(config);\n return { ghConfig, owner, repo, credentials, branchName };\n}\n\nexport async function searchRepos(\n octokit: Octokit,\n ghSearchQuery: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n): Promise<{ totalCount?: number; repositories: GithubRepository[] }> {\n const repoSearchResp = await octokit.rest.search.repos({\n q: ghSearchQuery,\n order: 'asc',\n page: pageNumber,\n per_page: pageSize,\n });\n return {\n totalCount: repoSearchResp?.data?.total_count,\n repositories:\n repoSearchResp?.data?.items?.map(repo => {\n return {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n };\n }) ?? [],\n };\n}\n\n/**\n * Adds the repositories accessible by the provided github app to the provided repositories Map<string, GithubRepository>\n * If any errors occurs, adds them to the provided errors Map<number, GithubFetchError>\n */\nexport async function addGithubAppRepositories(\n deps: {\n logger: LoggerService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n octokit: Octokit,\n credential: GithubAppCredentials,\n ghConfig: GithubIntegrationConfig,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n const allOrgsMap = await getAllAppOrgs(\n deps.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n const orgSearch: string[] = [];\n for (const [_orgUrl, ghOrg] of allOrgsMap) {\n orgSearch.push(`org:${ghOrg.name}`);\n }\n const query = `${search} in:name ${orgSearch.join(' ')}`;\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n const resp = await octokit.apps.listReposAccessibleToInstallation({\n page: pageNumber,\n per_page: pageSize,\n });\n const repos = resp?.data?.repositories ?? resp?.data;\n repos?.forEach(repo => {\n repositories.set(repo.full_name, {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n });\n });\n totalCount = resp?.data?.total_count;\n }\n } catch (err: any) {\n logErrorIfNeeded(\n deps.logger,\n `Fetching repositories with access token for github app ${credential.appId}`,\n err,\n );\n const credentialError = createCredentialError(credential, err as Error);\n if (credentialError) {\n errors.set(credential.appId, credentialError);\n }\n }\n return { totalCount };\n}\n\n/**\n * Adds the user or organization repositories accessible by the github token to the provided repositories Map<string, GithubRepository> if they're owned by the specified owner\n * If any errors occurs, adds them to the provided errors Map<number, GithubFetchError>\n */\nexport async function addGithubTokenRepositories(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n // Get currently authenticated user\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n let query = `${search} in:name user:${username}`;\n\n const allOrgsResp = await octokit.paginate(\n octokit.rest.orgs.listForAuthenticatedUser,\n {\n sort: 'full_name',\n direction: 'asc',\n },\n );\n const orgSearch: string[] = [];\n allOrgsResp?.forEach(org => orgSearch.push(`org:${org.login}`));\n if (orgSearch.length > 0) {\n query += ` ${orgSearch.join(' ')}`;\n }\n\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n /**\n * The listForAuthenticatedUser endpoint will grab all the repositories the github token has explicit access to.\n * These would include repositories they own, repositories where they are a collaborator,\n * and repositories that they can access through an organization membership.\n */\n const resp = await octokit.rest.repos.listForAuthenticatedUser({\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n resp?.data?.forEach(repo => {\n repositories.set(repo.full_name, {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n });\n });\n\n totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.repos\n .listForAuthenticatedUser({\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'repos.listForAuthenticatedUser',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n } catch (err) {\n handleError(\n deps,\n 'Fetching repositories with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n\nexport async function addGithubTokenOrgRepositories(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n org: string,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n const query = `${search} in:name org:${org}`;\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n /**\n * The listForAuthenticatedUser endpoint will grab all the repositories the github token has explicit access to.\n * These would include repositories they own, repositories where they are a collaborator,\n * and repositories that they can access through an organization membership.\n */\n const resp = await octokit.rest.repos.listForOrg({\n org,\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n resp?.data?.forEach(repo => {\n const githubRepo: GithubRepository = {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch ?? 'main',\n updated_at: repo.updated_at,\n };\n repositories.set(githubRepo.full_name, githubRepo);\n });\n\n totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.repos\n .listForOrg({\n org,\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'repos.listForOrg',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n } catch (err) {\n handleError(\n deps,\n 'Fetching org repositories with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n\nexport async function fileExistsInDefaultBranch(\n logger: LoggerService,\n octo: Octokit,\n owner: string,\n repo: string,\n fileName: string,\n defaultBranch: string = 'main',\n) {\n try {\n await octo.rest.repos.getContent({\n owner,\n repo,\n path: fileName,\n ref: defaultBranch,\n });\n return true;\n } catch (error: any) {\n if (error.status === 404) {\n return false;\n }\n logger.debug(\n `Unable to determine if a file named ${fileName} already exists in repo ${repo}: ${error}`,\n );\n return undefined;\n }\n}\n\nexport async function createOrUpdateFileInBranch(\n octo: Octokit,\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n): Promise<void> {\n try {\n const { data: existingFile } = await octo.rest.repos.getContent({\n owner: owner,\n repo: repo,\n path: fileName,\n ref: branchName,\n });\n // Response can either be a directory (array of files) or a single file element. In this case, we ensure it has the sha property to update it.\n if (Array.isArray(existingFile) || !('sha' in existingFile)) {\n throw new Error(\n `The content at path ${fileName} is not a file or the response from GitHub does not contain the 'sha' property.`,\n );\n }\n // If the file already exists, update it\n await octo.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n sha: existingFile.sha,\n branch: branchName,\n });\n } catch (error: any) {\n if (error.status === 404) {\n // If the file does not exist, create it\n await octo.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n branch: branchName,\n });\n } else {\n throw error;\n }\n }\n}\n"],"names":["gitUrlParse","getBranchName","DefaultPageNumber","DefaultPageSize","getAllAppOrgs","logErrorIfNeeded","createCredentialError","computeTotalCountFromGitHubToken","handleError"],"mappings":";;;;;;;;;;;;;;;;AAuDA,eAAsB,wBACpB,CAAA,yBAAA,EACA,YACA,EAAA,MAAA,EACA,KAGwB,EAAA;AACxB,EAAA,MAAM,WAAW,YAAa,CAAA,MAAA,CAAO,KAAM,CAAA,KAAA,CAAM,OAAO,CAAG,EAAA,MAAA;AAC3D,EAAA,IAAI,CAAC,QAAU,EAAA;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,CAAsC,mCAAA,EAAA,KAAA,CAAM,OAAO,CAAE,CAAA,CAAA;AAAA;AAGvE,EAAM,MAAA,MAAA,GAASA,4BAAY,CAAA,KAAA,CAAM,OAAO,CAAA;AACxC,EAAA,MAAM,QAAQ,MAAO,CAAA,YAAA;AACrB,EAAA,MAAM,OAAO,MAAO,CAAA,IAAA;AAEpB,EAAM,MAAA,WAAA,GAAc,MAAM,yBAAA,CAA0B,iBAAkB,CAAA;AAAA,IACpE,MAAM,QAAS,CAAA;AAAA,GAChB,CAAA;AACD,EAAI,IAAA,WAAA,CAAY,WAAW,CAAG,EAAA;AAC5B,IAAM,MAAA,IAAI,MAAM,CAAmC,iCAAA,CAAA,CAAA;AAAA;AAGrD,EAAM,MAAA,UAAA,GAAaC,2BAAc,MAAM,CAAA;AACvC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AA,QAC/C,KAAA;AAAA,QACA,IAAA;AAAA,QACA,IAAM,EAAA,QAAA;AAAA,QACN,OAAA,EAAS,OAAO,QAAQ,CAAA,YAAA,CAAA;AAAA,QACxB,OAAA,EAAS,KAAK,WAAW,CAAA;AAAA,QACzB,MAAQ,EAAA;AAAA,OACT,CAAA;AAAA,KACI,MAAA;AACL,MAAM,MAAA,KAAA;AAAA;AACR;AAEJ;;;;;;;;;;"}
1
+ {"version":3,"file":"repoUtils.cjs.js","sources":["../../../src/github/utils/repoUtils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { LoggerService } from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport type {\n GithubCredentials,\n GithubIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName } from '../../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../../service/handlers/handlers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport type {\n ExtendedGithubCredentials,\n GithubAppCredentials,\n GithubFetchError,\n GithubRepository,\n} from '../types';\nimport { getAllAppOrgs } from './orgUtils';\nimport {\n computeTotalCountFromGitHubToken,\n createCredentialError,\n handleError,\n} from './utils';\n\nexport type ValidatedRepo = {\n ghConfig: GithubIntegrationConfig;\n credentials: ExtendedGithubCredentials[];\n owner: string;\n repo: string;\n branchName: string;\n};\n\nexport async function validateAndBuildRepoData(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n integrations: ScmIntegrations,\n config: Config,\n input: {\n repoUrl: string;\n },\n): Promise<ValidatedRepo> {\n const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(`Could not find GH integration from ${input.repoUrl}`);\n }\n\n const gitUrl = gitUrlParse(input.repoUrl);\n const owner = gitUrl.organization;\n const repo = gitUrl.name;\n\n const credentials = await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n const branchName = getBranchName(config);\n return { ghConfig, owner, repo, credentials, branchName };\n}\n\nexport async function searchRepos(\n octokit: Octokit,\n ghSearchQuery: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n): Promise<{ totalCount?: number; repositories: GithubRepository[] }> {\n const repoSearchResp = await octokit.rest.search.repos({\n q: ghSearchQuery,\n order: 'asc',\n page: pageNumber,\n per_page: pageSize,\n });\n return {\n totalCount: repoSearchResp?.data?.total_count,\n repositories:\n repoSearchResp?.data?.items?.map(repo => {\n return {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n };\n }) ?? [],\n };\n}\n\n/**\n * Adds the repositories accessible by the provided github app to the provided repositories Map<string, GithubRepository>\n * If any errors occurs, adds them to the provided errors Map<number, GithubFetchError>\n */\nexport async function addGithubAppRepositories(\n deps: {\n logger: LoggerService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n octokit: Octokit,\n credential: GithubAppCredentials,\n ghConfig: GithubIntegrationConfig,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n const allOrgsMap = await getAllAppOrgs(\n deps.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n const orgSearch: string[] = [];\n for (const [_orgUrl, ghOrg] of allOrgsMap) {\n orgSearch.push(`org:${ghOrg.name}`);\n }\n const query = `${search} in:name ${orgSearch.join(' ')}`;\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n const resp = await octokit.apps.listReposAccessibleToInstallation({\n page: pageNumber,\n per_page: pageSize,\n });\n const repos = resp?.data?.repositories ?? resp?.data;\n repos?.forEach(repo => {\n repositories.set(repo.full_name, {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n });\n });\n totalCount = resp?.data?.total_count;\n }\n } catch (err: any) {\n logErrorIfNeeded(\n deps.logger,\n `Fetching repositories with access token for github app ${credential.appId}`,\n err,\n );\n const credentialError = createCredentialError(credential, err as Error);\n if (credentialError) {\n errors.set(credential.appId, credentialError);\n }\n }\n return { totalCount };\n}\n\n/**\n * Adds the user or organization repositories accessible by the github token to the provided repositories Map<string, GithubRepository> if they're owned by the specified owner\n * If any errors occurs, adds them to the provided errors Map<number, GithubFetchError>\n */\nexport async function addGithubTokenRepositories(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n // Get currently authenticated user\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n let query = `${search} in:name user:${username}`;\n\n const allOrgsResp = await octokit.paginate(\n octokit.rest.orgs.listForAuthenticatedUser,\n {\n sort: 'full_name',\n direction: 'asc',\n },\n );\n const orgSearch: string[] = [];\n allOrgsResp?.forEach(org => orgSearch.push(`org:${org.login}`));\n if (orgSearch.length > 0) {\n query += ` ${orgSearch.join(' ')}`;\n }\n\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n /**\n * The listForAuthenticatedUser endpoint will grab all the repositories the github token has explicit access to.\n * These would include repositories they own, repositories where they are a collaborator,\n * and repositories that they can access through an organization membership.\n */\n const resp = await octokit.rest.repos.listForAuthenticatedUser({\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n resp?.data?.forEach(repo => {\n repositories.set(repo.full_name, {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n });\n });\n\n totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.repos\n .listForAuthenticatedUser({\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'repos.listForAuthenticatedUser',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n } catch (err) {\n handleError(\n deps,\n 'Fetching repositories with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n\nexport async function addGithubTokenOrgRepositories(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n org: string,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n const query = `${search} in:name org:${org}`;\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n /**\n * The listForAuthenticatedUser endpoint will grab all the repositories the github token has explicit access to.\n * These would include repositories they own, repositories where they are a collaborator,\n * and repositories that they can access through an organization membership.\n */\n const resp = await octokit.rest.repos.listForOrg({\n org,\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n resp?.data?.forEach(repo => {\n const githubRepo: GithubRepository = {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch ?? 'main',\n updated_at: repo.updated_at,\n };\n repositories.set(githubRepo.full_name, githubRepo);\n });\n\n totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.repos\n .listForOrg({\n org,\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'repos.listForOrg',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n } catch (err) {\n handleError(\n deps,\n 'Fetching org repositories with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n\nexport async function fileExistsInDefaultBranch(\n logger: LoggerService,\n octo: Octokit,\n owner: string,\n repo: string,\n fileName: string,\n defaultBranch: string = 'main',\n) {\n try {\n await octo.rest.repos.getContent({\n owner,\n repo,\n path: fileName,\n ref: defaultBranch,\n });\n return true;\n } catch (error: any) {\n if (error.status === 404) {\n return false;\n }\n logger.debug(\n `Unable to determine if a file named ${fileName} already exists in repo ${repo}: ${error}`,\n );\n return undefined;\n }\n}\n\nexport async function createOrUpdateFileInBranch(\n octo: Octokit,\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n): Promise<void> {\n try {\n const { data: existingFile } = await octo.rest.repos.getContent({\n owner: owner,\n repo: repo,\n path: fileName,\n ref: branchName,\n });\n // Response can either be a directory (array of files) or a single file element. In this case, we ensure it has the sha property to update it.\n if (Array.isArray(existingFile) || !('sha' in existingFile)) {\n throw new Error(\n `The content at path ${fileName} is not a file or the response from GitHub does not contain the 'sha' property.`,\n );\n }\n // If the file already exists, update it\n await octo.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n sha: existingFile.sha,\n branch: branchName,\n });\n } catch (error: any) {\n if (error.status === 404) {\n // If the file does not exist, create it\n await octo.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n branch: branchName,\n });\n } else {\n throw error;\n }\n }\n}\n"],"names":["gitUrlParse","getBranchName","DefaultPageNumber","DefaultPageSize","getAllAppOrgs","logErrorIfNeeded","createCredentialError","computeTotalCountFromGitHubToken","handleError"],"mappings":";;;;;;;;;;;;;;;;AAuDA,eAAsB,wBACpB,CAAA,yBAAA,EACA,YACA,EAAA,MAAA,EACA,KAGwB,EAAA;AACxB,EAAA,MAAM,WAAW,YAAa,CAAA,MAAA,CAAO,KAAM,CAAA,KAAA,CAAM,OAAO,CAAG,EAAA,MAAA;AAC3D,EAAA,IAAI,CAAC,QAAU,EAAA;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,CAAsC,mCAAA,EAAA,KAAA,CAAM,OAAO,CAAE,CAAA,CAAA;AAAA;AAGvE,EAAM,MAAA,MAAA,GAASA,4BAAY,CAAA,KAAA,CAAM,OAAO,CAAA;AACxC,EAAA,MAAM,QAAQ,MAAO,CAAA,YAAA;AACrB,EAAA,MAAM,OAAO,MAAO,CAAA,IAAA;AAEpB,EAAM,MAAA,WAAA,GAAc,MAAM,yBAAA,CAA0B,iBAAkB,CAAA;AAAA,IACpE,MAAM,QAAS,CAAA;AAA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AA,MAClB,MAAQ,EAAA;AAAA,KACT,CAAA;AAAA,WACM,KAAY,EAAA;AACnB,IAAI,IAAA,KAAA,CAAM,WAAW,GAAK,EAAA;AAExB,MAAM,MAAA,IAAA,CAAK,IAAK,CAAA,KAAA,CAAM,0BAA2B,CAAA;AAAA,QAC/C,KAAA;AAAA,QACA,IAAA;AAAA,QACA,IAAM,EAAA,QAAA;AAAA,QACN,OAAA,EAAS,OAAO,QAAQ,CAAA,YAAA,CAAA;AAAA,QACxB,OAAA,EAAS,KAAK,WAAW,CAAA;AAAA,QACzB,MAAQ,EAAA;AAAA,OACT,CAAA;AAAA,KACI,MAAA;AACL,MAAM,MAAA,KAAA;AAAA;AACR;AAEJ;;;;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs.js","sources":["../../../src/github/utils/utils.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport {\n ScmIntegrations,\n type GithubIntegrationConfig,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { logErrorIfNeeded } from '../../helpers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n} from '../types';\nimport { buildOcto } from './ghUtils';\nimport { validateAndBuildRepoData, ValidatedRepo } from './repoUtils';\n\n/**\n * Creates the GithubFetchError to be stored in the returned errors array of the returned GithubRepositoryResponse object\n */\nexport function createCredentialError(\n credential: ExtendedGithubCredentials,\n err?: Error,\n): GithubFetchError | undefined {\n if (err) {\n if (isGithubAppCredential(credential)) {\n return {\n appId: credential.appId,\n type: 'app',\n error: {\n name: err.name,\n message: err.message,\n },\n };\n }\n return {\n type: 'token',\n error: {\n name: err.name,\n message: err.message,\n },\n };\n }\n if ('error' in credential) {\n return {\n appId: credential.appId,\n type: 'app',\n error: {\n name: credential.error.name,\n message: credential.error.message,\n },\n };\n }\n return undefined;\n}\n\nexport function verifyAndGetIntegrations(\n deps: {\n logger: LoggerService;\n },\n\n integrations: ScmIntegrations,\n) {\n const ghConfigs = integrations.github.list().map(ghInt => ghInt.config);\n if (ghConfigs.length === 0) {\n deps.logger.debug(\n 'No GitHub Integration in config => returning an empty list of repositories.',\n );\n throw new Error(\n \"Looks like there is no GitHub Integration in config. Please add a configuration entry under 'integrations.github\",\n );\n }\n return ghConfigs;\n}\n\nexport async function getCredentialsFromIntegrations(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfigs: GithubIntegrationConfig[],\n) {\n const credentialsByConfig = new Map<\n GithubIntegrationConfig,\n ExtendedGithubCredentials[]\n >();\n for (const ghConfig of ghConfigs) {\n const creds = await getCredentialsForConfig(\n githubCredentialsProvider,\n ghConfig,\n );\n credentialsByConfig.set(ghConfig, creds);\n }\n return credentialsByConfig;\n}\n\nexport async function getCredentialsForConfig(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfig: GithubIntegrationConfig,\n) {\n return await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n}\n\nexport async function extractConfigAndCreds(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n integrations: ScmIntegrations,\n input: {\n repoUrl: string;\n defaultBranch?: string;\n },\n) {\n const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(`Could not find GH integration from ${input.repoUrl}`);\n }\n\n const credentials = await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n const gitUrl = gitUrlParse(input.repoUrl);\n return { ghConfig, credentials, gitUrl };\n}\n\nexport function handleError(\n deps: {\n logger: LoggerService;\n },\n desc: string,\n credential: ExtendedGithubCredentials,\n errors: Map<number, GithubFetchError>,\n err: any,\n) {\n logErrorIfNeeded(deps.logger, `${desc} failed`, err);\n const credentialError = createCredentialError(credential, err as Error);\n if (credentialError) {\n errors.set(-1, credentialError);\n }\n}\n\nexport async function computeTotalCountFromGitHubToken(\n deps: {\n logger: LoggerService;\n },\n lastPageDataLengthProviderFn: (lastPageNumber: number) => Promise<number>,\n ghApiName: string,\n pageSize?: number,\n linkHeader?: string,\n): Promise<number | undefined> {\n // There is no direct way to get the total count of repositories other than using octokit.paginate,\n // but will make us retrieve all pages, thus increasing our response time.\n // Workaround here is to analyze the headers, and get the link to the last page.\n if (!linkHeader) {\n deps.logger.debug(\n `No link header found in response from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n const lastPageLink = linkHeader\n .split(',')\n .find(s => s.includes('rel=\"last\"'));\n if (!lastPageLink) {\n deps.logger.debug(\n `No rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n const match = lastPageLink.match(/page=(\\d+)/);\n if (!match || match.length < 2) {\n deps.logger.debug(\n `Unable to extract page number from rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n\n const lastPageNumber = parseInt(match[1], 10);\n // Fetch the last page to count its items, as it might contain fewer than the requested size\n const lastPageDataLength = await lastPageDataLengthProviderFn(lastPageNumber);\n return pageSize\n ? (lastPageNumber - 1) * pageSize + lastPageDataLength\n : undefined;\n}\n\nexport async function executeFunctionOnFirstSuccessfulIntegration<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n config: Config;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n repoUrl: string;\n fn: (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ) => Promise<{ successful: boolean; result?: T }>;\n },\n) {\n const validatedRepo = await validateAndBuildRepoData(\n deps.githubCredentialsProvider,\n integrations,\n deps.config,\n params,\n );\n for (const credential of validatedRepo.credentials) {\n const octo = buildOcto(\n {\n logger: deps.logger,\n cache: deps.cache,\n },\n { credential, owner: validatedRepo.owner },\n validatedRepo.ghConfig.apiBaseUrl,\n );\n if (!octo) {\n continue;\n }\n const res = await params.fn(validatedRepo, octo);\n if (!res.successful) {\n continue;\n }\n return res.result;\n }\n return undefined;\n}\n\nexport async function fetchFromAllIntegrations<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n dataFetcher: (\n octo: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => Promise<{\n stopFetchingData?: boolean;\n result?: T;\n errors?: GithubFetchError[];\n }>;\n },\n) {\n const ghConfigs = verifyAndGetIntegrations(deps, integrations);\n\n const credentialsByConfig = await getCredentialsFromIntegrations(\n deps.githubCredentialsProvider,\n ghConfigs,\n );\n const errors = new Map<number, GithubFetchError>();\n const data: T[] = [];\n const dataErrs: GithubFetchError[] = [];\n let stopFetchingData: boolean | undefined = false;\n for (const [ghConfig, credentials] of credentialsByConfig) {\n if (stopFetchingData) {\n break;\n }\n deps.logger.debug(\n `Got ${credentials.length} credential(s) for ${ghConfig.host}`,\n );\n for (const credential of credentials) {\n const octokit = buildOcto(\n deps,\n { credential, errors },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n const res = await params.dataFetcher(octokit, credential, ghConfig);\n res.errors?.forEach(err => dataErrs.push(err));\n\n if (res.result) {\n data.push(res.result);\n }\n\n stopFetchingData = res.stopFetchingData;\n }\n }\n\n const aggregatedErrors = new Map<number, GithubFetchError>();\n errors.forEach((err, num) => aggregatedErrors.set(num, err));\n dataErrs.forEach((err, idx) => aggregatedErrors.set(idx, err));\n\n return { data, errors: aggregatedErrors };\n}\n\nexport function computeTotalCount<T>(\n data: T[],\n countList: number[],\n pageSize: number,\n) {\n let totalCount = countList.reduce(\n (accumulator, currentValue) => accumulator + currentValue,\n 0,\n );\n if (totalCount < pageSize) {\n totalCount = data.length;\n }\n return totalCount;\n}\n\nexport function extractLocationOwnerMap(locationUrls: string[]) {\n const locationGitOwnerMap = new Map<string, string>();\n for (const locationUrl of locationUrls) {\n const split = locationUrl.split('/blob/');\n if (split.length < 2) {\n continue;\n }\n locationGitOwnerMap.set(locationUrl, gitUrlParse(split[0]).owner);\n }\n return locationGitOwnerMap;\n}\n"],"names":["isGithubAppCredential","logErrorIfNeeded","validateAndBuildRepoData","buildOcto","gitUrlParse"],"mappings":";;;;;;;;;;;;;;;AA0CgB,SAAA,qBAAA,CACd,YACA,GAC8B,EAAA;AAC9B,EAAA,IAAI,GAAK,EAAA;AACP,IAAI,IAAAA,2BAAA,CAAsB,UAAU,CAAG,EAAA;AACrC,MAAO,OAAA;AAAA,QACL,OAAO,UAAW,CAAA,KAAA;AAAA,QAClB,IAAM,EAAA,KAAA;AAAA,QACN,KAAO,EAAA;AAAA,UACL,MAAM,GAAI,CAAA,IAAA;AAAA,UACV,SAAS,GAAI,CAAA;AAAA;AACf,OACF;AAAA;AAEF,IAAO,OAAA;AAAA,MACL,IAAM,EAAA,OAAA;AAAA,MACN,KAAO,EAAA;AAAA,QACL,MAAM,GAAI,CAAA,IAAA;AAAA,QACV,SAAS,GAAI,CAAA;AAAA;AACf,KACF;AAAA;AAEF,EAAA,IAAI,WAAW,UAAY,EAAA;AACzB,IAAO,OAAA;AAAA,MACL,OAAO,UAAW,CAAA,KAAA;AAAA,MAClB,IAAM,EAAA,KAAA;AAAA,MACN,KAAO,EAAA;AAAA,QACL,IAAA,EAAM,WAAW,KAAM,CAAA,IAAA;AAAA,QACvB,OAAA,EAAS,WAAW,KA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EAAA,KAAA,MAAW,eAAe,YAAc,EAAA;AACtC,IAAM,MAAA,KAAA,GAAQ,WAAY,CAAA,KAAA,CAAM,QAAQ,CAAA;AACxC,IAAI,IAAA,KAAA,CAAM,SAAS,CAAG,EAAA;AACpB,MAAA;AAAA;AAEF,IAAA,mBAAA,CAAoB,IAAI,WAAa,EAAAC,4BAAA,CAAY,MAAM,CAAC,CAAC,EAAE,KAAK,CAAA;AAAA;AAElE,EAAO,OAAA,mBAAA;AACT;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"utils.cjs.js","sources":["../../../src/github/utils/utils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport {\n ScmIntegrations,\n type GithubIntegrationConfig,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { logErrorIfNeeded } from '../../helpers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n} from '../types';\nimport { buildOcto } from './ghUtils';\nimport { validateAndBuildRepoData, ValidatedRepo } from './repoUtils';\n\n/**\n * Creates the GithubFetchError to be stored in the returned errors array of the returned GithubRepositoryResponse object\n */\nexport function createCredentialError(\n credential: ExtendedGithubCredentials,\n err?: Error,\n): GithubFetchError | undefined {\n if (err) {\n if (isGithubAppCredential(credential)) {\n return {\n appId: credential.appId,\n type: 'app',\n error: {\n name: err.name,\n message: err.message,\n },\n };\n }\n return {\n type: 'token',\n error: {\n name: err.name,\n message: err.message,\n },\n };\n }\n if ('error' in credential) {\n return {\n appId: credential.appId,\n type: 'app',\n error: {\n name: credential.error.name,\n message: credential.error.message,\n },\n };\n }\n return undefined;\n}\n\nexport function verifyAndGetIntegrations(\n deps: {\n logger: LoggerService;\n },\n\n integrations: ScmIntegrations,\n) {\n const ghConfigs = integrations.github.list().map(ghInt => ghInt.config);\n if (ghConfigs.length === 0) {\n deps.logger.debug(\n 'No GitHub Integration in config => returning an empty list of repositories.',\n );\n throw new Error(\n \"Looks like there is no GitHub Integration in config. Please add a configuration entry under 'integrations.github\",\n );\n }\n return ghConfigs;\n}\n\nexport async function getCredentialsFromIntegrations(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfigs: GithubIntegrationConfig[],\n) {\n const credentialsByConfig = new Map<\n GithubIntegrationConfig,\n ExtendedGithubCredentials[]\n >();\n for (const ghConfig of ghConfigs) {\n const creds = await getCredentialsForConfig(\n githubCredentialsProvider,\n ghConfig,\n );\n credentialsByConfig.set(ghConfig, creds);\n }\n return credentialsByConfig;\n}\n\nexport async function getCredentialsForConfig(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfig: GithubIntegrationConfig,\n) {\n return await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n}\n\nexport async function extractConfigAndCreds(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n integrations: ScmIntegrations,\n input: {\n repoUrl: string;\n defaultBranch?: string;\n },\n) {\n const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(`Could not find GH integration from ${input.repoUrl}`);\n }\n\n const credentials = await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n const gitUrl = gitUrlParse(input.repoUrl);\n return { ghConfig, credentials, gitUrl };\n}\n\nexport function handleError(\n deps: {\n logger: LoggerService;\n },\n desc: string,\n credential: ExtendedGithubCredentials,\n errors: Map<number, GithubFetchError>,\n err: any,\n) {\n logErrorIfNeeded(deps.logger, `${desc} failed`, err);\n const credentialError = createCredentialError(credential, err as Error);\n if (credentialError) {\n errors.set(-1, credentialError);\n }\n}\n\nexport async function computeTotalCountFromGitHubToken(\n deps: {\n logger: LoggerService;\n },\n lastPageDataLengthProviderFn: (lastPageNumber: number) => Promise<number>,\n ghApiName: string,\n pageSize?: number,\n linkHeader?: string,\n): Promise<number | undefined> {\n // There is no direct way to get the total count of repositories other than using octokit.paginate,\n // but will make us retrieve all pages, thus increasing our response time.\n // Workaround here is to analyze the headers, and get the link to the last page.\n if (!linkHeader) {\n deps.logger.debug(\n `No link header found in response from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n const lastPageLink = linkHeader\n .split(',')\n .find(s => s.includes('rel=\"last\"'));\n if (!lastPageLink) {\n deps.logger.debug(\n `No rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n const match = lastPageLink.match(/page=(\\d+)/);\n if (!match || match.length < 2) {\n deps.logger.debug(\n `Unable to extract page number from rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n\n const lastPageNumber = parseInt(match[1], 10);\n // Fetch the last page to count its items, as it might contain fewer than the requested size\n const lastPageDataLength = await lastPageDataLengthProviderFn(lastPageNumber);\n return pageSize\n ? (lastPageNumber - 1) * pageSize + lastPageDataLength\n : undefined;\n}\n\nexport async function executeFunctionOnFirstSuccessfulIntegration<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n config: Config;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n repoUrl: string;\n fn: (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ) => Promise<{ successful: boolean; result?: T }>;\n },\n) {\n const validatedRepo = await validateAndBuildRepoData(\n deps.githubCredentialsProvider,\n integrations,\n deps.config,\n params,\n );\n for (const credential of validatedRepo.credentials) {\n const octo = buildOcto(\n {\n logger: deps.logger,\n cache: deps.cache,\n },\n { credential, owner: validatedRepo.owner },\n validatedRepo.ghConfig.apiBaseUrl,\n );\n if (!octo) {\n continue;\n }\n const res = await params.fn(validatedRepo, octo);\n if (!res.successful) {\n continue;\n }\n return res.result;\n }\n return undefined;\n}\n\nexport async function fetchFromAllIntegrations<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n dataFetcher: (\n octo: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => Promise<{\n stopFetchingData?: boolean;\n result?: T;\n errors?: GithubFetchError[];\n }>;\n },\n) {\n const ghConfigs = verifyAndGetIntegrations(deps, integrations);\n\n const credentialsByConfig = await getCredentialsFromIntegrations(\n deps.githubCredentialsProvider,\n ghConfigs,\n );\n const errors = new Map<number, GithubFetchError>();\n const data: T[] = [];\n const dataErrs: GithubFetchError[] = [];\n let stopFetchingData: boolean | undefined = false;\n for (const [ghConfig, credentials] of credentialsByConfig) {\n if (stopFetchingData) {\n break;\n }\n deps.logger.debug(\n `Got ${credentials.length} credential(s) for ${ghConfig.host}`,\n );\n for (const credential of credentials) {\n const octokit = buildOcto(\n deps,\n { credential, errors },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n const res = await params.dataFetcher(octokit, credential, ghConfig);\n res.errors?.forEach(err => dataErrs.push(err));\n\n if (res.result) {\n data.push(res.result);\n }\n\n stopFetchingData = res.stopFetchingData;\n }\n }\n\n const aggregatedErrors = new Map<number, GithubFetchError>();\n errors.forEach((err, num) => aggregatedErrors.set(num, err));\n dataErrs.forEach((err, idx) => aggregatedErrors.set(idx, err));\n\n return { data, errors: aggregatedErrors };\n}\n\nexport function computeTotalCount<T>(\n data: T[],\n countList: number[],\n pageSize: number,\n) {\n let totalCount = countList.reduce(\n (accumulator, currentValue) => accumulator + currentValue,\n 0,\n );\n if (totalCount < pageSize) {\n totalCount = data.length;\n }\n return totalCount;\n}\n\nexport function extractLocationOwnerMap(locationUrls: string[]) {\n const locationGitOwnerMap = new Map<string, string>();\n for (const locationUrl of locationUrls) {\n const split = locationUrl.split('/blob/');\n if (split.length < 2) {\n continue;\n }\n locationGitOwnerMap.set(locationUrl, gitUrlParse(split[0]).owner);\n }\n return locationGitOwnerMap;\n}\n"],"names":["isGithubAppCredential","logErrorIfNeeded","validateAndBuildRepoData","buildOcto","gitUrlParse"],"mappings":";;;;;;;;;;;;;;;AA0CgB,SAAA,qBAAA,CACd,YACA,GAC8B,EAAA;AAC9B,EAAA,IAAI,GAAK,EAAA;AACP,IAAI,IAAAA,2BAAA,CAAsB,UAAU,CAAG,EAAA;AACrC,MAAO,OAAA;AAAA,QACL,OAAO,UAAW,CAAA,KAAA;AAAA,QAClB,IAAM,EAAA,KAAA;AAAA,QACN,KAAO,EAAA;AAAA,UACL,MAAM,GAAI,CAAA,IAAA;AAAA,UACV,SAAS,GAAI,CAAA;AAAA;AACf,OACF;AAAA;AAEF,IAAO,OAAA;AAAA,MACL,IAAM,EAAA,OAAA;AAAA,MACN,KAAO,EAAA;AAAA,QACL,MAAM,GAAI,CAAA,IAAA;AAAA,QACV,SAAS,GAAI,CAAA;AAAA;AACf,KACF;AAAA;AAEF,EAAA,IAAI,WAAW,UAAY,EAAA;AACzB,IAAO,OAAA;AAAA,MACL,OAAO,UAAW,CAAA,KAAA;AAAA,MAClB,IAAM,EAAA,KAAA;AAAA,MACN,KAAO,EAAA;AAAA,QACL,IAAA,EAAM,WAAW,KAAM,CAAA,IAAA;AAAA,QACvB,OAAA,EAAS,WAAW,KAAM,CAAA;AAAA;AAC5B,KACF;AAAA;AAEF,EAAO,OAAA,KAAA,CAAA;AACT;AAEgB,SAAA,wBAAA,CACd,MAIA,YACA,EAAA;AACA,EAAM,MAAA,SAAA,GAAY,aAAa,MAAO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A;AACpB,MAAA;AAAA;AAEF,IAAA,mBAAA,CAAoB,IAAI,WAAa,EAAAC,4BAAA,CAAY,MAAM,CAAC,CAAC,EAAE,KAAK,CAAA;AAAA;AAElE,EAAO,OAAA,mBAAA;AACT;;;;;;;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"auditLogUtils.cjs.js","sources":["../../src/helpers/auditLogUtils.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NotFoundError, type NotAllowedError } from '@backstage/errors';\n\nimport type { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\nimport express from 'express';\n\nconst EVENT_PREFIX = 'BulkImport';\nconst UNKNOWN_ENDPOINT_EVENT = `${EVENT_PREFIX}UnknownEndpoint`;\n\nexport async function auditLogRequestSuccess(\n auditLogger: AuditLogger,\n openApiOperationId: string | undefined,\n req: express.Request,\n responseStatus: number,\n) {\n if (!openApiOperationId) {\n auditLogUnknownEndpoint(auditLogger, req);\n return;\n }\n auditLogger.auditLog({\n eventName: operationIdToEventName(openApiOperationId),\n stage: 'completion',\n status: 'succeeded',\n level: 'info',\n request: req,\n response: {\n status: responseStatus,\n },\n message: `'${req.method} ${\n req.path\n }' endpoint hit by ${await auditLogger.getActorId(req)}`,\n });\n}\n\nexport async function auditLogRequestError(\n auditLogger: AuditLogger,\n openApiOperationId: string | undefined,\n req: express.Request,\n error: any,\n) {\n if (!openApiOperationId) {\n auditLogUnknownEndpoint(auditLogger, req);\n return;\n }\n auditLogger.auditLog({\n eventName: operationIdToEventName(openApiOperationId),\n stage: 'completion',\n status: 'failed',\n level: 'error',\n request: req,\n response: {\n status: 500,\n body: {\n errors: [\n {\n name: error.name,\n message: error.message || 'internal server error',\n },\n ],\n },\n },\n errors: [error],\n message: `Error while requesting the '${req.method} ${\n req.path\n }' endpoint (request from ${await auditLogger.getActorId(req)})`,\n });\n}\n\nexport async function auditLogUnknownEndpoint(\n auditLogger: AuditLogger,\n req: express.Request,\n) {\n const error = new NotFoundError(`'${req.method} ${req.path}' not found`);\n auditLogger.auditLog({\n eventName: UNKNOWN_ENDPOINT_EVENT,\n stage: 'initiation',\n status: 'failed',\n level: 'info',\n request: req,\n response: {\n status: 404,\n body: {\n errors: [\n {\n name: error.name,\n message: error.message,\n },\n ],\n },\n },\n errors: [error],\n message: `${await auditLogger.getActorId(req)} requested the unknown '${\n req.method\n } ${req.path}' endpoint`,\n });\n}\n\nexport async function auditLogAuthError(\n auditLogger: AuditLogger,\n openApiOperationId: string | undefined,\n req: express.Request,\n error: NotAllowedError,\n) {\n if (!openApiOperationId) {\n auditLogUnknownEndpoint(auditLogger, req);\n return;\n }\n auditLogger.auditLog({\n eventName: operationIdToEventName(openApiOperationId),\n stage: 'authorization',\n status: 'failed',\n level: 'warn',\n request: req,\n response: {\n status: 403,\n body: {\n errors: [\n {\n name: error.name,\n message: error.message,\n },\n ],\n },\n },\n errors: [error],\n message: `${await auditLogger.getActorId(\n req,\n )} not authorized to request the '${req.method} ${req.path}' endpoint`,\n });\n}\n\nfunction operationIdToEventName(openApiOperationId: string): string {\n if (openApiOperationId.length === 0) {\n return EVENT_PREFIX;\n }\n return `${EVENT_PREFIX}${openApiOperationId\n .charAt(0)\n .toUpperCase()}${openApiOperationId.slice(1)}`;\n}\n"],"names":["NotFoundError"],"mappings":";;;;AAqBA,MAAM,YAAe,GAAA,YAAA;AACrB,MAAM,sBAAA,GAAyB,GAAG,YAAY,CAAA,eAAA,CAAA;AAE9C,eAAsB,sBACpB,CAAA,WAAA,EACA,kBACA,EAAA,GAAA,EACA,cACA,EAAA;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Q,EAAA,QAAA;AAAA,IACR,KAAO,EAAA,MAAA;AAAA,IACP,OAAS,EAAA,GAAA;AAAA,IACT,QAAU,EAAA;AAAA,MACR,MAAQ,EAAA,GAAA;AAAA,MACR,IAAM,EAAA;AAAA,QACJ,MAAQ,EAAA;AAAA,UACN;AAAA,YACE,MAAM,KAAM,CAAA,IAAA;AAAA,YACZ,SAAS,KAAM,CAAA;AAAA;AACjB;AACF;AACF,KACF;AAAA,IACA,MAAA,EAAQ,CAAC,KAAK,CAAA;AAAA,IACd,OAAA,EAAS,CAAG,EAAA,MAAM,WAAY,CAAA,UAAA;AAAA,MAC5B;AAAA,KACD,CAAmC,gCAAA,EAAA,GAAA,CAAI,MAAM,CAAA,CAAA,EAAI,IAAI,IAAI,CAAA,UAAA;AAAA,GAC3D,CAAA;AACH;AAEA,SAAS,uBAAuB,kBAAoC,EAAA;AAClE,EAAI,IAAA,kBAAA,CAAmB,WAAW,CAAG,EAAA;AACnC,IAAO,OAAA,YAAA;AAAA;AAET,EAAA,OAAO,CAAG,EAAA,YAAY,CAAG,EAAA,kBAAA,CACtB,MAAO,CAAA,CAAC,CACR,CAAA,WAAA,EAAa,CAAA,EAAG,kBAAmB,CAAA,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAChD;;;;;;;"}
1
+ {"version":3,"file":"auditLogUtils.cjs.js","sources":["../../src/helpers/auditLogUtils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NotFoundError, type NotAllowedError } from '@backstage/errors';\n\nimport type { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\nimport express from 'express';\n\nconst EVENT_PREFIX = 'BulkImport';\nconst UNKNOWN_ENDPOINT_EVENT = `${EVENT_PREFIX}UnknownEndpoint`;\n\nexport async function auditLogRequestSuccess(\n auditLogger: AuditLogger,\n openApiOperationId: string | undefined,\n req: express.Request,\n responseStatus: number,\n) {\n if (!openApiOperationId) {\n auditLogUnknownEndpoint(auditLogger, req);\n return;\n }\n auditLogger.auditLog({\n eventName: operationIdToEventName(openApiOperationId),\n stage: 'completion',\n status: 'succeeded',\n level: 'info',\n request: req,\n response: {\n status: responseStatus,\n },\n message: `'${req.method} ${\n req.path\n }' endpoint hit by ${await auditLogger.getActorId(req)}`,\n });\n}\n\nexport async function auditLogRequestError(\n auditLogger: AuditLogger,\n openApiOperationId: string | undefined,\n req: express.Request,\n error: any,\n) {\n if (!openApiOperationId) {\n auditLogUnknownEndpoint(auditLogger, req);\n return;\n }\n auditLogger.auditLog({\n eventName: operationIdToEventName(openApiOperationId),\n stage: 'completion',\n status: 'failed',\n level: 'error',\n request: req,\n response: {\n status: 500,\n body: {\n errors: [\n {\n name: error.name,\n message: error.message || 'internal server error',\n },\n ],\n },\n },\n errors: [error],\n message: `Error while requesting the '${req.method} ${\n req.path\n }' endpoint (request from ${await auditLogger.getActorId(req)})`,\n });\n}\n\nexport async function auditLogUnknownEndpoint(\n auditLogger: AuditLogger,\n req: express.Request,\n) {\n const error = new NotFoundError(`'${req.method} ${req.path}' not found`);\n auditLogger.auditLog({\n eventName: UNKNOWN_ENDPOINT_EVENT,\n stage: 'initiation',\n status: 'failed',\n level: 'info',\n request: req,\n response: {\n status: 404,\n body: {\n errors: [\n {\n name: error.name,\n message: error.message,\n },\n ],\n },\n },\n errors: [error],\n message: `${await auditLogger.getActorId(req)} requested the unknown '${\n req.method\n } ${req.path}' endpoint`,\n });\n}\n\nexport async function auditLogAuthError(\n auditLogger: AuditLogger,\n openApiOperationId: string | undefined,\n req: express.Request,\n error: NotAllowedError,\n) {\n if (!openApiOperationId) {\n auditLogUnknownEndpoint(auditLogger, req);\n return;\n }\n auditLogger.auditLog({\n eventName: operationIdToEventName(openApiOperationId),\n stage: 'authorization',\n status: 'failed',\n level: 'warn',\n request: req,\n response: {\n status: 403,\n body: {\n errors: [\n {\n name: error.name,\n message: error.message,\n },\n ],\n },\n },\n errors: [error],\n message: `${await auditLogger.getActorId(\n req,\n )} not authorized to request the '${req.method} ${req.path}' endpoint`,\n });\n}\n\nfunction operationIdToEventName(openApiOperationId: string): string {\n if (openApiOperationId.length === 0) {\n return EVENT_PREFIX;\n }\n return `${EVENT_PREFIX}${openApiOperationId\n .charAt(0)\n .toUpperCase()}${openApiOperationId.slice(1)}`;\n}\n"],"names":["NotFoundError"],"mappings":";;;;AAqBA,MAAM,YAAe,GAAA,YAAA;AACrB,MAAM,sBAAA,GAAyB,GAAG,YAAY,CAAA,eAAA,CAAA;AAE9C,eAAsB,sBACpB,CAAA,WAAA,EACA,kBACA,EAAA,GAAA,EACA,cACA,EAAA;AACA,EAAA,IAAI,CAAC,kBAAoB,EAAA;AACvB,IAAA,uBAAA,CAAwB,aAAa,GAAG,CAAA;AACxC,IAAA;AAAA;AAEF,EAAA,WAAA,CAAY,QAAS,CAAA;AAAA,IACnB,SAAA,EAAW,uBAAuB,kBAAkB,CAAA;AAAA,IACpD,KAAO,EAAA,YAAA;AAAA,IACP,MAAQ,EAAA,WAAA;AAAA,IACR,KAAO,EAAA,MAAA;AAAA,IACP,OAAS,EAAA,GAAA;AAAA,IACT,QAAU,EAAA;AAAA,MACR,MAAQ,EAAA;AAAA,KACV;AAAA,IACA,OAAS,EAAA,CAAA,CAAA,EAAI,GAAI,CAAA,MAAM,CACrB,CAAA,EAAA,GAAA,CAAI,IACN,CAAA,kBAAA,EAAqB,MAAM,WAAA,CAAY,UAAW,CAAA,GAAG,CAAC,CAAA;AAAA,GACvD,CAAA;AACH;AAEA,eAAsB,oBACpB,CAAA,WAAA,EACA,kBACA,EAAA,GAAA,EACA,KACA,EAAA;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;AAAA;AAET,EAAA,OAAO,CAAG,EAAA,YAAY,CAAG,EAAA,kBAAA,CACtB,MAAO,CAAA,CAAC,CACR,CAAA,WAAA,EAAa,CAAA,EAAG,kBAAmB,CAAA,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAChD;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"auth.cjs.js","sources":["../../src/helpers/auth.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n AuthService,\n HttpAuthService,\n PermissionsService,\n} from '@backstage/backend-plugin-api';\nimport { NotAllowedError } from '@backstage/errors';\nimport { AuthorizeResult } from '@backstage/plugin-permission-common';\n\nimport type { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\nimport express from 'express';\n\nimport { bulkImportPermission } from '@red-hat-developer-hub/backstage-plugin-bulk-import-common';\n\nimport { auditLogAuthError } from './auditLogUtils';\n\n/**\n * This will resolve to { result: AuthorizeResult.ALLOW } if the permission framework is disabled\n */\nexport async function permissionCheck(\n auditLogger: AuditLogger,\n openApiOperationId: string | undefined,\n permissions: PermissionsService,\n httpAuth: HttpAuthService,\n req: express.Request,\n) {\n const decision = (\n await permissions.authorize(\n [\n {\n permission: bulkImportPermission,\n resourceRef: bulkImportPermission.resourceType,\n },\n ],\n {\n credentials: await httpAuth.credentials(req),\n },\n )\n )[0];\n\n if (decision.result === AuthorizeResult.DENY) {\n const err = new NotAllowedError('Unauthorized');\n auditLogAuthError(auditLogger, openApiOperationId, req, err);\n throw err;\n }\n}\n\nexport async function getTokenForPlugin(\n auth: AuthService,\n targetPluginId: string,\n): Promise<string> {\n const resp = await auth.getPluginRequestToken({\n onBehalfOf: await auth.getOwnServiceCredentials(),\n targetPluginId,\n });\n return resp.token;\n}\n"],"names":["bulkImportPermission","AuthorizeResult","NotAllowedError","auditLogAuthError"],"mappings":";;;;;;;AAkCA,eAAsB,eACpB,CAAA,WAAA,EACA,kBACA,EAAA,WAAA,EACA,UACA,GACA,EAAA;AACA,EAAM,MAAA,QAAA,GAAA,CACJ,MAAM,WAAY,CAAA,SAAA;AAAA,IAChB;AAAA,MACE;AAAA,QACE,UAAY,EAAAA,oDAAA;AAAA,QACZ,aAAaA,oDAAqB,CAAA;AAAA;AACpC,KACF;AAAA,IACA;AAAA,MACE,WAAa,EAAA,MAAM,QAAS,CAAA,WAAA,CAAY,GAAG;AAAA;AAC7C,KAEF,CAAC,CAAA;AAEH,EAAI,IAAA,QAAA,CAAS,MAAW,KAAAC,sCAAA,CAAgB,IAAM,EAAA;AAC5C,IAAM,MAAA,GAAA,GAAM,IAAIC,sBAAA,CAAgB,cAAc,CAAA;AAC9C,IAAkBC,+BAAA,CAAA,WAAA,EAAa,kBAAoB,EAAA,GAAA,EAAK,GAAG,CAAA;AAC3D,IAAM,MAAA,GAAA;AAAA;AAEV;AAEsB,eAAA,iBAAA,CACpB,MACA,cACiB,EAAA;AACjB,EAAM,MAAA,IAAA,GAAO,MAAM,IAAA,CAAK,qBAAsB,CAAA;AAAA,IAC5C,UAAA,EAAY,MAAM,IAAA,CAAK,wBAAyB,EAAA;AAAA,IAChD;AAAA,GACD,CAAA;AACD,EAAA,OAAO,IAAK,CAAA,KAAA;AACd;;;;;"}
1
+ {"version":3,"file":"auth.cjs.js","sources":["../../src/helpers/auth.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n AuthService,\n HttpAuthService,\n PermissionsService,\n} from '@backstage/backend-plugin-api';\nimport { NotAllowedError } from '@backstage/errors';\nimport { AuthorizeResult } from '@backstage/plugin-permission-common';\n\nimport type { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\nimport express from 'express';\n\nimport { bulkImportPermission } from '@red-hat-developer-hub/backstage-plugin-bulk-import-common';\n\nimport { auditLogAuthError } from './auditLogUtils';\n\n/**\n * This will resolve to { result: AuthorizeResult.ALLOW } if the permission framework is disabled\n */\nexport async function permissionCheck(\n auditLogger: AuditLogger,\n openApiOperationId: string | undefined,\n permissions: PermissionsService,\n httpAuth: HttpAuthService,\n req: express.Request,\n) {\n const decision = (\n await permissions.authorize(\n [\n {\n permission: bulkImportPermission,\n resourceRef: bulkImportPermission.resourceType,\n },\n ],\n {\n credentials: await httpAuth.credentials(req),\n },\n )\n )[0];\n\n if (decision.result === AuthorizeResult.DENY) {\n const err = new NotAllowedError('Unauthorized');\n auditLogAuthError(auditLogger, openApiOperationId, req, err);\n throw err;\n }\n}\n\nexport async function getTokenForPlugin(\n auth: AuthService,\n targetPluginId: string,\n): Promise<string> {\n const resp = await auth.getPluginRequestToken({\n onBehalfOf: await auth.getOwnServiceCredentials(),\n targetPluginId,\n });\n return resp.token;\n}\n"],"names":["bulkImportPermission","AuthorizeResult","NotAllowedError","auditLogAuthError"],"mappings":";;;;;;;AAkCA,eAAsB,eACpB,CAAA,WAAA,EACA,kBACA,EAAA,WAAA,EACA,UACA,GACA,EAAA;AACA,EAAM,MAAA,QAAA,GAAA,CACJ,MAAM,WAAY,CAAA,SAAA;AAAA,IAChB;AAAA,MACE;AAAA,QACE,UAAY,EAAAA,oDAAA;AAAA,QACZ,aAAaA,oDAAqB,CAAA;AAAA;AACpC,KACF;AAAA,IACA;AAAA,MACE,WAAa,EAAA,MAAM,QAAS,CAAA,WAAA,CAAY,GAAG;AAAA;AAC7C,KAEF,CAAC,CAAA;AAEH,EAAI,IAAA,QAAA,CAAS,MAAW,KAAAC,sCAAA,CAAgB,IAAM,EAAA;AAC5C,IAAM,MAAA,GAAA,GAAM,IAAIC,sBAAA,CAAgB,cAAc,CAAA;AAC9C,IAAkBC,+BAAA,CAAA,WAAA,EAAa,kBAAoB,EAAA,GAAA,EAAK,GAAG,CAAA;AAC3D,IAAM,MAAA,GAAA;AAAA;AAEV;AAEsB,eAAA,iBAAA,CACpB,MACA,cACiB,EAAA;AACjB,EAAM,MAAA,IAAA,GAAO,MAAM,IAAA,CAAK,qBAAsB,CAAA;AAAA,IAC5C,UAAA,EAAY,MAAM,IAAA,CAAK,wBAAyB,EAAA;AAAA,IAChD;AAAA,GACD,CAAA;AACD,EAAA,OAAO,IAAK,CAAA,KAAA;AACd;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"loggingUtils.cjs.js","sources":["../../src/helpers/loggingUtils.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { LoggerService } from '@backstage/backend-plugin-api';\nimport { isError } from '@backstage/errors';\n\n/**\n * Logs the error specified by ensuring no sensitive internal data is disclosed.\n * @param logger the logger\n * @param logMsg the log message\n * @param error the error\n */\nexport function logErrorIfNeeded(\n logger: LoggerService,\n logMsg: string,\n error: any,\n) {\n if (isError(error)) {\n // Ensure that we don't log any sensitive internal data:\n logger.error(logMsg, {\n // Default Error properties:\n name: error.name,\n message: error.message,\n stack: error.stack,\n // Additional status code if available:\n status: (error.response as { status?: string })?.status,\n });\n }\n}\n"],"names":["isError"],"mappings":";;;;AAyBgB,SAAA,gBAAA,CACd,MACA,EAAA,MAAA,EACA,KACA,EAAA;AACA,EAAI,IAAAA,cAAA,CAAQ,KAAK,CAAG,EAAA;AAElB,IAAA,MAAA,CAAO,MAAM,MAAQ,EAAA;AAAA;AAAA,MAEnB,MAAM,KAAM,CAAA,IAAA;AAAA,MACZ,SAAS,KAAM,CAAA,OAAA;AAAA,MACf,OAAO,KAAM,CAAA,KAAA;AAAA;AAAA,MAEb,MAAA,EAAS,MAAM,QAAkC,EAAA;AAAA,KAClD,CAAA;AAAA;AAEL;;;;"}
1
+ {"version":3,"file":"loggingUtils.cjs.js","sources":["../../src/helpers/loggingUtils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { LoggerService } from '@backstage/backend-plugin-api';\nimport { isError } from '@backstage/errors';\n\n/**\n * Logs the error specified by ensuring no sensitive internal data is disclosed.\n * @param logger the logger\n * @param logMsg the log message\n * @param error the error\n */\nexport function logErrorIfNeeded(\n logger: LoggerService,\n logMsg: string,\n error: any,\n) {\n if (isError(error)) {\n // Ensure that we don't log any sensitive internal data:\n logger.error(logMsg, {\n // Default Error properties:\n name: error.name,\n message: error.message,\n stack: error.stack,\n // Additional status code if available:\n status: (error.response as { status?: string })?.status,\n });\n }\n}\n"],"names":["isError"],"mappings":";;;;AAyBgB,SAAA,gBAAA,CACd,MACA,EAAA,MAAA,EACA,KACA,EAAA;AACA,EAAI,IAAAA,cAAA,CAAQ,KAAK,CAAG,EAAA;AAElB,IAAA,MAAA,CAAO,MAAM,MAAQ,EAAA;AAAA;AAAA,MAEnB,MAAM,KAAM,CAAA,IAAA;AAAA,MACZ,SAAS,KAAM,CAAA,OAAA;AAAA,MACf,OAAO,KAAM,CAAA,KAAA;AAAA;AAAA,MAEb,MAAA,EAAS,MAAM,QAAkC,EAAA;AAAA,KAClD,CAAA;AAAA;AAEL;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"pagination.cjs.js","sources":["../../src/helpers/pagination.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a paginated chunk of the specified array\n * @param array the array to paginate\n * @param page the page number\n * @param size the maximum number of elements in each page\n */\nexport function paginateArray<T>(\n array: T[] | undefined,\n page: number,\n size: number,\n): { result: T[]; totalCount: number } {\n if (page <= 0) {\n throw new Error(`page must be >0. Got page=${page}`);\n }\n if (size < 0) {\n throw new Error(`size must be >=0. Got size=${size}`);\n }\n\n const startIndex = (page - 1) * size;\n const endIndex = startIndex + size;\n\n return {\n result: array?.slice(startIndex, endIndex) ?? [],\n totalCount: array?.length ?? 0,\n };\n}\n"],"names":[],"mappings":";;AAsBgB,SAAA,aAAA,CACd,KACA,EAAA,IAAA,EACA,IACqC,EAAA;AACrC,EAAA,IAAI,QAAQ,CAAG,EAAA;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,CAA6B,0BAAA,EAAA,IAAI,CAAE,CAAA,CAAA;AAAA;AAErD,EAAA,IAAI,OAAO,CAAG,EAAA;AACZ,IAAA,MAAM,IAAI,KAAA,CAAM,CAA8B,2BAAA,EAAA,IAAI,CAAE,CAAA,CAAA;AAAA;AAGtD,EAAM,MAAA,UAAA,GAAA,CAAc,OAAO,CAAK,IAAA,IAAA;AAChC,EAAA,MAAM,WAAW,UAAa,GAAA,IAAA;AAE9B,EAAO,OAAA;AAAA,IACL,QAAQ,KAAO,EAAA,KAAA,CAAM,UAAY,EAAA,QAAQ,KAAK,EAAC;AAAA,IAC/C,UAAA,EAAY,OAAO,MAAU,IAAA;AAAA,GAC/B;AACF;;;;"}
1
+ {"version":3,"file":"pagination.cjs.js","sources":["../../src/helpers/pagination.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a paginated chunk of the specified array\n * @param array the array to paginate\n * @param page the page number\n * @param size the maximum number of elements in each page\n */\nexport function paginateArray<T>(\n array: T[] | undefined,\n page: number,\n size: number,\n): { result: T[]; totalCount: number } {\n if (page <= 0) {\n throw new Error(`page must be >0. Got page=${page}`);\n }\n if (size < 0) {\n throw new Error(`size must be >=0. Got size=${size}`);\n }\n\n const startIndex = (page - 1) * size;\n const endIndex = startIndex + size;\n\n return {\n result: array?.slice(startIndex, endIndex) ?? [],\n totalCount: array?.length ?? 0,\n };\n}\n"],"names":[],"mappings":";;AAsBgB,SAAA,aAAA,CACd,KACA,EAAA,IAAA,EACA,IACqC,EAAA;AACrC,EAAA,IAAI,QAAQ,CAAG,EAAA;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,CAA6B,0BAAA,EAAA,IAAI,CAAE,CAAA,CAAA;AAAA;AAErD,EAAA,IAAI,OAAO,CAAG,EAAA;AACZ,IAAA,MAAM,IAAI,KAAA,CAAM,CAA8B,2BAAA,EAAA,IAAI,CAAE,CAAA,CAAA;AAAA;AAGtD,EAAM,MAAA,UAAA,GAAA,CAAc,OAAO,CAAK,IAAA,IAAA;AAChC,EAAA,MAAM,WAAW,UAAa,GAAA,IAAA;AAE9B,EAAO,OAAA;AAAA,IACL,QAAQ,KAAO,EAAA,KAAA,CAAM,UAAY,EAAA,QAAQ,KAAK,EAAC;AAAA,IAC/C,UAAA,EAAY,OAAO,MAAU,IAAA;AAAA,GAC/B;AACF;;;;"}
@@ -0,0 +1,11 @@
1
+ 'use strict';
2
+
3
+ function getNestedValue(obj, path) {
4
+ return path.split(".").reduce(
5
+ (acc, key) => acc && acc[key] ? acc[key] : void 0,
6
+ obj
7
+ );
8
+ }
9
+
10
+ exports.getNestedValue = getNestedValue;
11
+ //# sourceMappingURL=utils.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.cjs.js","sources":["../../src/helpers/utils.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function getNestedValue<T>(obj: T, path: string): any {\n return path\n .split('.')\n .reduce(\n (acc, key) =>\n acc && (acc as Record<string, any>)[key]\n ? (acc as Record<string, any>)[key]\n : undefined,\n obj,\n );\n}\n"],"names":[],"mappings":";;AAegB,SAAA,cAAA,CAAkB,KAAQ,IAAmB,EAAA;AAC3D,EAAO,OAAA,IAAA,CACJ,KAAM,CAAA,GAAG,CACT,CAAA,MAAA;AAAA,IACC,CAAC,KAAK,GACJ,KAAA,GAAA,IAAQ,IAA4B,GAAG,CAAA,GAClC,GAA4B,CAAA,GAAG,CAChC,GAAA,KAAA,CAAA;AAAA,IACN;AAAA,GACF;AACJ;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.cjs.js","sources":["../src/plugin.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha';\n\nimport { createRouter } from './service/router';\n\n/**\n * The bulk-import backend plugin.\n * @public\n */\nexport const bulkImportPlugin = createBackendPlugin({\n pluginId: 'bulk-import',\n register(env) {\n env.registerInit({\n deps: {\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n http: coreServices.httpRouter,\n cache: coreServices.cache,\n discovery: coreServices.discovery,\n permissions: coreServices.permissions,\n httpAuth: coreServices.httpAuth,\n auth: coreServices.auth,\n catalogApi: catalogServiceRef,\n },\n async init({\n config,\n logger,\n http,\n cache,\n discovery,\n permissions,\n httpAuth,\n auth,\n catalogApi,\n }) {\n const router = await createRouter({\n config,\n cache,\n discovery,\n permissions,\n logger,\n httpAuth,\n auth,\n catalogApi,\n });\n http.use(router);\n http.addAuthPolicy({\n path: '/ping',\n allow: 'unauthenticated',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","coreServices","catalogServiceRef","router","createRouter"],"mappings":";;;;;;AA4BO,MAAM,mBAAmBA,oCAAoB,CAAA;AAAA,EAClD,QAAU,EAAA,aAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,QAAQC,6BAAa,CAAA,MAAA;AAAA,QACrB,QAAQA,6BAAa,CAAA,UAAA;AAAA,QACrB,MAAMA,6BAAa,CAAA,UAAA;AAAA,QACnB,OAAOA,6BAAa,CAAA,KAAA;AAAA,QACpB,WAAWA,6BAAa,CAAA,SAAA;AAAA,QACxB,aAAaA,6BAAa,CAAA,WAAA;AAAA,QAC1B,UAAUA,6BAAa,CAAA,QAAA;AAAA,QACvB,MAAMA,6BAAa,CAAA,IAAA;AAAA,QACnB,UAAY,EAAAC;AAAA,OACd;AAAA,MACA,MAAM,IAAK,CAAA;AAAA,QACT,MAAA;AAAA,QACA,MAAA;AAAA,QACA,IAAA;AAAA,QACA,KAAA;AAAA,QACA,SAAA;AAAA,QACA,WAAA;AAAA,QACA,QAAA;AAAA,QACA,IAAA;AAAA,QACA;AAAA,OACC,EAAA;AACD,QAAM,MAAAC,QAAA,GAAS,MAAMC,mBAAa,CAAA;AAAA,UAChC,MAAA;AAAA,UACA,KAAA;AAAA,UACA,SAAA;AAAA,UACA,WAAA;AAAA,UACA,MAAA;AAAA,UACA,QAAA;AAAA,UACA,IAAA;AAAA,UACA;AAAA,SACD,CAAA;AACD,QAAA,IAAA,CAAK,IAAID,QAAM,CAAA;AACf,QAAA,IAAA,CAAK,aAAc,CAAA;AAAA,UACjB,IAAM,EAAA,OAAA;AAAA,UACN,KAAO,EAAA;AAAA,SACR,CAAA;AAAA;AACH,KACD,CAAA;AAAA;AAEL,CAAC;;;;"}
1
+ {"version":3,"file":"plugin.cjs.js","sources":["../src/plugin.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha';\n\nimport { createRouter } from './service/router';\n\n/**\n * The bulk-import backend plugin.\n * @public\n */\nexport const bulkImportPlugin = createBackendPlugin({\n pluginId: 'bulk-import',\n register(env) {\n env.registerInit({\n deps: {\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n http: coreServices.httpRouter,\n cache: coreServices.cache,\n discovery: coreServices.discovery,\n permissions: coreServices.permissions,\n httpAuth: coreServices.httpAuth,\n auth: coreServices.auth,\n catalogApi: catalogServiceRef,\n },\n async init({\n config,\n logger,\n http,\n cache,\n discovery,\n permissions,\n httpAuth,\n auth,\n catalogApi,\n }) {\n const router = await createRouter({\n config,\n cache,\n discovery,\n permissions,\n logger,\n httpAuth,\n auth,\n catalogApi,\n });\n http.use(router);\n http.addAuthPolicy({\n path: '/ping',\n allow: 'unauthenticated',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","coreServices","catalogServiceRef","router","createRouter"],"mappings":";;;;;;AA4BO,MAAM,mBAAmBA,oCAAoB,CAAA;AAAA,EAClD,QAAU,EAAA,aAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,QAAQC,6BAAa,CAAA,MAAA;AAAA,QACrB,QAAQA,6BAAa,CAAA,UAAA;AAAA,QACrB,MAAMA,6BAAa,CAAA,UAAA;AAAA,QACnB,OAAOA,6BAAa,CAAA,KAAA;AAAA,QACpB,WAAWA,6BAAa,CAAA,SAAA;AAAA,QACxB,aAAaA,6BAAa,CAAA,WAAA;AAAA,QAC1B,UAAUA,6BAAa,CAAA,QAAA;AAAA,QACvB,MAAMA,6BAAa,CAAA,IAAA;AAAA,QACnB,UAAY,EAAAC;AAAA,OACd;AAAA,MACA,MAAM,IAAK,CAAA;AAAA,QACT,MAAA;AAAA,QACA,MAAA;AAAA,QACA,IAAA;AAAA,QACA,KAAA;AAAA,QACA,SAAA;AAAA,QACA,WAAA;AAAA,QACA,QAAA;AAAA,QACA,IAAA;AAAA,QACA;AAAA,OACC,EAAA;AACD,QAAM,MAAAC,QAAA,GAAS,MAAMC,mBAAa,CAAA;AAAA,UAChC,MAAA;AAAA,UACA,KAAA;AAAA,UACA,SAAA;AAAA,UACA,WAAA;AAAA,UACA,MAAA;AAAA,UACA,QAAA;AAAA,UACA,IAAA;AAAA,UACA;AAAA,SACD,CAAA;AACD,QAAA,IAAA,CAAK,IAAID,QAAM,CAAA;AACf,QAAA,IAAA,CAAK,aAAc,CAAA;AAAA,UACjB,IAAM,EAAA,OAAA;AAAA,UACN,KAAO,EAAA;AAAA,SACR,CAAA;AAAA;AACH,KACD,CAAA;AAAA;AAEL,CAAC;;;;"}
@@ -2,7 +2,11 @@
2
2
 
3
3
  const DefaultPageNumber = 1;
4
4
  const DefaultPageSize = 20;
5
+ const DefaultSortColumn = "repository.name";
6
+ const DefaultSortOrder = "asc";
5
7
 
6
8
  exports.DefaultPageNumber = DefaultPageNumber;
7
9
  exports.DefaultPageSize = DefaultPageSize;
10
+ exports.DefaultSortColumn = DefaultSortColumn;
11
+ exports.DefaultSortOrder = DefaultSortOrder;
8
12
  //# sourceMappingURL=handlers.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.cjs.js","sources":["../../../src/service/handlers/handlers.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const DefaultPageNumber = 1;\nexport const DefaultPageSize = 20;\n\nexport interface HandlerResponse<ResponseBody = any> {\n statusCode: number;\n responseBody?: ResponseBody;\n}\n"],"names":[],"mappings":";;AAgBO,MAAM,iBAAoB,GAAA;AAC1B,MAAM,eAAkB,GAAA;;;;;"}
1
+ {"version":3,"file":"handlers.cjs.js","sources":["../../../src/service/handlers/handlers.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type { Components } from '../../generated/openapi';\n\nexport const DefaultPageNumber = 1;\nexport const DefaultPageSize = 20;\n\nexport const DefaultSortColumn: Components.Parameters.SortColumnQueryParam =\n 'repository.name';\nexport const DefaultSortOrder: Components.Parameters.SortOrderQueryParam =\n 'asc';\n\nexport interface HandlerResponse<ResponseBody = any> {\n statusCode: number;\n responseBody?: ResponseBody;\n}\n"],"names":[],"mappings":";;AAiBO,MAAM,iBAAoB,GAAA;AAC1B,MAAM,eAAkB,GAAA;AAExB,MAAM,iBACX,GAAA;AACK,MAAM,gBACX,GAAA;;;;;;;"}
@@ -7,24 +7,26 @@ require('@backstage/plugin-permission-common');
7
7
  require('@red-hat-developer-hub/backstage-plugin-bulk-import-common');
8
8
  var loggingUtils = require('../../../helpers/loggingUtils.cjs.js');
9
9
  var pagination = require('../../../helpers/pagination.cjs.js');
10
+ var utils = require('../../../helpers/utils.cjs.js');
10
11
  var handlers = require('../handlers.cjs.js');
11
12
 
12
13
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
13
14
 
14
15
  var gitUrlParse__default = /*#__PURE__*/_interopDefaultCompat(gitUrlParse);
15
16
 
16
- function sortImports(imports) {
17
+ function sortImports(imports, sortColumn = handlers.DefaultSortColumn, sortOrder = handlers.DefaultSortOrder) {
17
18
  imports.sort((a, b) => {
18
- if (a.repository?.name === void 0 && b.repository?.name === void 0) {
19
- return 0;
19
+ const value1 = utils.getNestedValue(a, sortColumn);
20
+ const value2 = utils.getNestedValue(b, sortColumn);
21
+ if (value1 === void 0 && value2 === void 0) return 0;
22
+ if (value1 === void 0) return sortOrder === "asc" ? -1 : 1;
23
+ if (value2 === void 0) return sortOrder === "asc" ? 1 : -1;
24
+ if (sortColumn === "lastUpdate") {
25
+ const date1 = new Date(value1);
26
+ const date2 = new Date(value2);
27
+ return sortOrder === "asc" ? date2.getTime() - date1.getTime() : date1.getTime() - date2.getTime();
20
28
  }
21
- if (a.repository?.name === void 0) {
22
- return -1;
23
- }
24
- if (b.repository?.name === void 0) {
25
- return 1;
26
- }
27
- return a.repository.name.localeCompare(b.repository.name);
29
+ return sortOrder === "asc" ? value1.localeCompare(value2) : value2.localeCompare(value1);
28
30
  });
29
31
  }
30
32
  async function findAllImports(deps, requestHeaders, queryParams) {
@@ -32,9 +34,8 @@ async function findAllImports(deps, requestHeaders, queryParams) {
32
34
  const search = queryParams?.search;
33
35
  const pageNumber = queryParams?.pageNumber ?? handlers.DefaultPageNumber;
34
36
  const pageSize = queryParams?.pageSize ?? handlers.DefaultPageSize;
35
- deps.logger.debug(
36
- `Getting all bulk import jobs (apiVersion=${apiVersion}, search=${search}, page=${pageNumber}, size=${pageSize})..`
37
- );
37
+ const sortColumn = queryParams?.sortColumn ?? handlers.DefaultSortColumn;
38
+ const sortOrder = queryParams?.sortOrder ?? handlers.DefaultSortOrder;
38
39
  const catalogFilename = catalogUtils.getCatalogFilename(deps.config);
39
40
  const allLocations = (await deps.catalogHttpClient.listCatalogUrlLocations(
40
41
  search,
@@ -81,7 +82,7 @@ async function findAllImports(deps, requestHeaders, queryParams) {
81
82
  source: location ? allLocations.get(location)?.source : void 0
82
83
  };
83
84
  });
84
- sortImports(imports);
85
+ sortImports(imports, sortColumn, sortOrder);
85
86
  const paginated = pagination.paginateArray(imports, pageNumber, pageSize);
86
87
  if (apiVersion === "v1") {
87
88
  return {
@@ -189,9 +190,7 @@ async function handleAddedReposFromCreateImportJobs(deps, importRequests) {
189
190
  req.repository.url,
190
191
  req.repository.defaultBranch
191
192
  );
192
- const hasLocation = await deps.catalogHttpClient.verifyLocationExistence(
193
- repoCatalogUrl
194
- );
193
+ const hasLocation = await deps.catalogHttpClient.verifyLocationExistence(repoCatalogUrl);
195
194
  if (!hasLocation) {
196
195
  continue;
197
196
  }
@@ -360,9 +359,7 @@ async function dryRunCreateImportJobs(deps, importRequests) {
360
359
  }
361
360
  async function performDryRunChecks(deps, req) {
362
361
  const checkCatalog = async (catalogEntityName) => {
363
- const hasEntity = await deps.catalogHttpClient.hasEntityInCatalog(
364
- catalogEntityName
365
- );
362
+ const hasEntity = await deps.catalogHttpClient.hasEntityInCatalog(catalogEntityName);
366
363
  if (hasEntity) {
367
364
  return { dryRunStatuses: ["CATALOG_ENTITY_CONFLICT"] };
368
365
  }
@@ -474,9 +471,7 @@ async function findImportStatusByRepo(deps, repoUrl, defaultBranch, includeCatal
474
471
  defaultBranch
475
472
  );
476
473
  }
477
- const ghRepo = await deps.githubApiService.getRepositoryFromIntegrations(
478
- repoUrl
479
- );
474
+ const ghRepo = await deps.githubApiService.getRepositoryFromIntegrations(repoUrl);
480
475
  result.lastUpdate = ghRepo.repository?.updated_at ?? void 0;
481
476
  return {
482
477
  statusCode: 200,