diff --git a/.imgbotconfig b/.imgbotconfig index f337e087dc..2f4af2ed5e 100644 --- a/.imgbotconfig +++ b/.imgbotconfig @@ -1,5 +1,3 @@ { - "ignoredFiles": [ - "docs/assets/**/*.svg" - ] + "ignoredFiles": ["docs/assets/**/*.svg"] } diff --git a/docs/auth/add-auth-provider.md b/docs/auth/add-auth-provider.md index 56586cbfc6..472a6a0abc 100644 --- a/docs/auth/add-auth-provider.md +++ b/docs/auth/add-auth-provider.md @@ -244,9 +244,7 @@ export interface OAuthProviderHandlers { req: express.Request, options: Record, ): Promise; - handler( - req: express.Request, - ): Promise<{ + handler(req: express.Request): Promise<{ response: AuthResponse; refreshToken?: string; }>; diff --git a/docs/integrations/bitbucket/discovery.md b/docs/integrations/bitbucket/discovery.md index 1538806e39..708acd8db2 100644 --- a/docs/integrations/bitbucket/discovery.md +++ b/docs/integrations/bitbucket/discovery.md @@ -56,13 +56,11 @@ matching repository is processed. repository. ```typescript -const customRepositoryParser: BitbucketRepositoryParser = async function* customRepositoryParser({ - client, - repository, -}) { - // Custom logic for interpret the matching repository. - // See defaultRepositoryParser for an example -}; +const customRepositoryParser: BitbucketRepositoryParser = + async function* customRepositoryParser({ client, repository }) { + // Custom logic for interpret the matching repository. + // See defaultRepositoryParser for an example + }; const processor = BitbucketDiscoveryProcessor.fromConfig(env.config, { parser: customRepositoryParser, diff --git a/packages/backend-common/src/cache/CacheManager.test.ts b/packages/backend-common/src/cache/CacheManager.test.ts index b55b63f469..fb73687f54 100644 --- a/packages/backend-common/src/cache/CacheManager.test.ts +++ b/packages/backend-common/src/cache/CacheManager.test.ts @@ -104,7 +104,7 @@ describe('CacheManager', () => { manager.forPlugin(plugin2Id).getClient({ defaultTtl: expectedTtl }); const client = DefaultCacheClient as jest.Mock; - const cache = (Keyv as unknown) as jest.Mock; + const cache = Keyv as unknown as jest.Mock; expect(cache).toHaveBeenCalledTimes(2); expect(client).toHaveBeenCalledTimes(2); @@ -124,7 +124,7 @@ describe('CacheManager', () => { const expectedNamespace = 'test-plugin'; manager.forPlugin(expectedNamespace).getClient(); - const cache = (Keyv as unknown) as jest.Mock; + const cache = Keyv as unknown as jest.Mock; const mockCalls = cache.mock.calls.splice(-1); const callArgs = mockCalls[0]; expect(callArgs[0].store).toBeInstanceOf(NoStore); @@ -138,7 +138,7 @@ describe('CacheManager', () => { .forPlugin(expectedNamespace) .getClient({ defaultTtl: expectedTtl }); - const cache = (Keyv as unknown) as jest.Mock; + const cache = Keyv as unknown as jest.Mock; const mockCalls = cache.mock.calls.splice(-1); const callArgs = mockCalls[0]; expect(callArgs[0]).toMatchObject({ @@ -162,7 +162,7 @@ describe('CacheManager', () => { const expectedTtl = 3600; manager.forPlugin('test').getClient({ defaultTtl: expectedTtl }); - const cache = (Keyv as unknown) as jest.Mock; + const cache = Keyv as unknown as jest.Mock; const mockCacheCalls = cache.mock.calls.splice(-1); expect(mockCacheCalls[0][0]).toMatchObject({ ttl: expectedTtl, diff --git a/packages/backend-common/src/database/DatabaseManager.ts b/packages/backend-common/src/database/DatabaseManager.ts index f3a3f218b0..2d60104bcb 100644 --- a/packages/backend-common/src/database/DatabaseManager.ts +++ b/packages/backend-common/src/database/DatabaseManager.ts @@ -110,9 +110,7 @@ export class DatabaseManager { * @returns Object with client type returned as `client` and boolean representing whether * or not the client was overridden as `overridden` */ - private getClientType( - pluginId: string, - ): { + private getClientType(pluginId: string): { client: string; overridden: boolean; } { diff --git a/packages/backend-common/src/database/connectors/mysql.ts b/packages/backend-common/src/database/connectors/mysql.ts index f2f2298559..94dce508c7 100644 --- a/packages/backend-common/src/database/connectors/mysql.ts +++ b/packages/backend-common/src/database/connectors/mysql.ts @@ -149,7 +149,7 @@ export async function ensureMysqlDatabaseExists( ) { const admin = createMysqlDatabaseClient(dbConfig, { connection: { - database: (null as unknown) as string, + database: null as unknown as string, }, }); diff --git a/packages/backend-common/src/reading/AzureUrlReader.test.ts b/packages/backend-common/src/reading/AzureUrlReader.test.ts index 2b7c21d4ab..c7c8853929 100644 --- a/packages/backend-common/src/reading/AzureUrlReader.test.ts +++ b/packages/backend-common/src/reading/AzureUrlReader.test.ts @@ -78,21 +78,17 @@ describe('AzureUrlReader', () => { it.each([ { - url: - 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml&version=GBmaster', + url: 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml&version=GBmaster', config: createConfig(), response: expect.objectContaining({ - url: - 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml&version=master', + url: 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml&version=master', }), }, { - url: - 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml', + url: 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml', config: createConfig(), response: expect.objectContaining({ - url: - 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml', + url: 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml', }), }, { diff --git a/packages/backend-common/src/reading/AzureUrlReader.ts b/packages/backend-common/src/reading/AzureUrlReader.ts index bc22854d4e..d2c056508d 100644 --- a/packages/backend-common/src/reading/AzureUrlReader.ts +++ b/packages/backend-common/src/reading/AzureUrlReader.ts @@ -129,7 +129,7 @@ export class AzureUrlReader implements UrlReader { } return await this.deps.treeResponseFactory.fromZipArchive({ - stream: (archiveAzureResponse.body as unknown) as Readable, + stream: archiveAzureResponse.body as unknown as Readable, etag: commitSha, filter: options?.filter, }); diff --git a/packages/backend-common/src/reading/BitbucketUrlReader.ts b/packages/backend-common/src/reading/BitbucketUrlReader.ts index 2849bc3cd9..2a979a464f 100644 --- a/packages/backend-common/src/reading/BitbucketUrlReader.ts +++ b/packages/backend-common/src/reading/BitbucketUrlReader.ts @@ -60,13 +60,8 @@ export class BitbucketUrlReader implements UrlReader { private readonly integration: BitbucketIntegration, private readonly deps: { treeResponseFactory: ReadTreeResponseFactory }, ) { - const { - host, - apiBaseUrl, - token, - username, - appPassword, - } = integration.config; + const { host, apiBaseUrl, token, username, appPassword } = + integration.config; if (!apiBaseUrl) { throw new Error( @@ -138,7 +133,7 @@ export class BitbucketUrlReader implements UrlReader { } return await this.deps.treeResponseFactory.fromTarArchive({ - stream: (archiveBitbucketResponse.body as unknown) as Readable, + stream: archiveBitbucketResponse.body as unknown as Readable, subpath: filepath, etag: lastCommitShortHash, filter: options?.filter, diff --git a/packages/backend-common/src/reading/GithubUrlReader.test.ts b/packages/backend-common/src/reading/GithubUrlReader.test.ts index c8002cd3ce..f9717a862a 100644 --- a/packages/backend-common/src/reading/GithubUrlReader.test.ts +++ b/packages/backend-common/src/reading/GithubUrlReader.test.ts @@ -41,9 +41,9 @@ const treeResponseFactory = DefaultReadTreeResponseFactory.create({ config: new ConfigReader({}), }); -const mockCredentialsProvider = ({ +const mockCredentialsProvider = { getCredentials: jest.fn().mockResolvedValue({ headers: {} }), -} as unknown) as GithubCredentialsProvider; +} as unknown as GithubCredentialsProvider; const githubProcessor = new GithubUrlReader( new GitHubIntegration( diff --git a/packages/backend-common/src/reading/GithubUrlReader.ts b/packages/backend-common/src/reading/GithubUrlReader.ts index bccddc6838..930c544287 100644 --- a/packages/backend-common/src/reading/GithubUrlReader.ts +++ b/packages/backend-common/src/reading/GithubUrlReader.ts @@ -39,10 +39,14 @@ import { ReadUrlResponse, } from './types'; -export type GhRepoResponse = RestEndpointMethodTypes['repos']['get']['response']['data']; -export type GhBranchResponse = RestEndpointMethodTypes['repos']['getBranch']['response']['data']; -export type GhTreeResponse = RestEndpointMethodTypes['git']['getTree']['response']['data']; -export type GhBlobResponse = RestEndpointMethodTypes['git']['getBlob']['response']['data']; +export type GhRepoResponse = + RestEndpointMethodTypes['repos']['get']['response']['data']; +export type GhBranchResponse = + RestEndpointMethodTypes['repos']['getBranch']['response']['data']; +export type GhTreeResponse = + RestEndpointMethodTypes['git']['getTree']['response']['data']; +export type GhBlobResponse = + RestEndpointMethodTypes['git']['getBlob']['response']['data']; /** * A processor that adds the ability to read files from GitHub v3 APIs, such as @@ -195,7 +199,7 @@ export class GithubUrlReader implements UrlReader { return await this.deps.treeResponseFactory.fromTarArchive({ // TODO(Rugvip): Underlying implementation of fetch will be node-fetch, we probably want // to stick to using that in exclusively backend code. - stream: (archive.body as unknown) as Readable, + stream: archive.body as unknown as Readable, subpath, etag: sha, filter: options?.filter, @@ -258,9 +262,7 @@ export class GithubUrlReader implements UrlReader { })); } - private async getRepoDetails( - url: string, - ): Promise<{ + private async getRepoDetails(url: string): Promise<{ repo: GhRepoResponse; branch: GhBranchResponse; }> { diff --git a/packages/backend-common/src/reading/GitlabUrlReader.test.ts b/packages/backend-common/src/reading/GitlabUrlReader.test.ts index 945444d8ed..51b211e698 100644 --- a/packages/backend-common/src/reading/GitlabUrlReader.test.ts +++ b/packages/backend-common/src/reading/GitlabUrlReader.test.ts @@ -108,36 +108,30 @@ describe('GitlabUrlReader', () => { it.each([ // Project URLs { - url: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', + url: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', config: createConfig(), response: expect.objectContaining({ - url: - 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', + url: 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', headers: expect.objectContaining({ 'private-token': '', }), }), }, { - url: - 'https://gitlab.example.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', + url: 'https://gitlab.example.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', config: createConfig('0123456789'), response: expect.objectContaining({ - url: - 'https://gitlab.example.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', + url: 'https://gitlab.example.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', headers: expect.objectContaining({ 'private-token': '0123456789', }), }), }, { - url: - 'https://gitlab.com/groupA/teams/teamA/repoA/-/blob/branch/my/path/to/file.yaml', // Repo not in subgroup + url: 'https://gitlab.com/groupA/teams/teamA/repoA/-/blob/branch/my/path/to/file.yaml', // Repo not in subgroup config: createConfig(), response: expect.objectContaining({ - url: - 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', + url: 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', }), }, diff --git a/packages/backend-common/src/reading/GitlabUrlReader.ts b/packages/backend-common/src/reading/GitlabUrlReader.ts index 6c272471e2..27c31c7673 100644 --- a/packages/backend-common/src/reading/GitlabUrlReader.ts +++ b/packages/backend-common/src/reading/GitlabUrlReader.ts @@ -170,7 +170,7 @@ export class GitlabUrlReader implements UrlReader { } return await this.deps.treeResponseFactory.fromTarArchive({ - stream: (archiveGitLabResponse.body as unknown) as Readable, + stream: archiveGitLabResponse.body as unknown as Readable, subpath: filepath, etag: commitSha, filter: options?.filter, diff --git a/packages/backend-common/src/reading/tree/TarArchiveResponse.ts b/packages/backend-common/src/reading/tree/TarArchiveResponse.ts index a81add58f7..173f6a886a 100644 --- a/packages/backend-common/src/reading/tree/TarArchiveResponse.ts +++ b/packages/backend-common/src/reading/tree/TarArchiveResponse.ts @@ -28,7 +28,7 @@ import { import { stripFirstDirectoryFromPath } from './util'; // Tar types for `Parse` is not a proper constructor, but it should be -const TarParseStream = (Parse as unknown) as { new (): ParseStream }; +const TarParseStream = Parse as unknown as { new (): ParseStream }; const pipeline = promisify(pipelineCb); diff --git a/packages/backend-common/src/scm/git.test.ts b/packages/backend-common/src/scm/git.test.ts index 0b70edc45d..abbafc375d 100644 --- a/packages/backend-common/src/scm/git.test.ts +++ b/packages/backend-common/src/scm/git.test.ts @@ -123,9 +123,9 @@ describe('Git', () => { await git.clone({ url, dir }); - const { onAuth } = ((isomorphic.clone as unknown) as jest.Mock< - typeof isomorphic['clone'] - >).mock.calls[0][0]!; + const { onAuth } = ( + isomorphic.clone as unknown as jest.Mock + ).mock.calls[0][0]!; expect(onAuth()).toEqual(auth); }); @@ -190,9 +190,9 @@ describe('Git', () => { await git.fetch({ remote, dir }); - const { onAuth } = ((isomorphic.fetch as unknown) as jest.Mock< - typeof isomorphic['fetch'] - >).mock.calls[0][0]!; + const { onAuth } = ( + isomorphic.fetch as unknown as jest.Mock + ).mock.calls[0][0]!; expect(onAuth()).toEqual(auth); }); @@ -279,9 +279,9 @@ describe('Git', () => { await git.push({ remote, dir }); - const { onAuth } = ((isomorphic.push as unknown) as jest.Mock< - typeof isomorphic['push'] - >).mock.calls[0][0]!; + const { onAuth } = ( + isomorphic.push as unknown as jest.Mock + ).mock.calls[0][0]!; expect(onAuth()).toEqual(auth); }); diff --git a/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts b/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts index 7a3ebfed70..ed16c9c9a7 100644 --- a/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts +++ b/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts @@ -154,14 +154,8 @@ export class ServiceBuilderImpl implements ServiceBuilder { async start(): Promise { const app = express(); - const { - port, - host, - logger, - corsOptions, - httpsSettings, - helmetOptions, - } = this.getOptions(); + const { port, host, logger, corsOptions, httpsSettings, helmetOptions } = + this.getOptions(); app.use(helmet(helmetOptions)); if (corsOptions) { diff --git a/packages/backend-common/src/util/DockerContainerRunner.ts b/packages/backend-common/src/util/DockerContainerRunner.ts index 8dbc5335c9..33a4874151 100644 --- a/packages/backend-common/src/util/DockerContainerRunner.ts +++ b/packages/backend-common/src/util/DockerContainerRunner.ts @@ -92,18 +92,17 @@ export class DockerContainerRunner implements ContainerRunner { Env.push(`${key}=${value}`); } - const [ - { Error: error, StatusCode: statusCode }, - ] = await this.dockerClient.run(imageName, args, logStream, { - Volumes, - HostConfig: { - Binds, - }, - ...(workingDir ? { WorkingDir: workingDir } : {}), - Entrypoint: command, - Env, - ...userOptions, - } as Docker.ContainerCreateOptions); + const [{ Error: error, StatusCode: statusCode }] = + await this.dockerClient.run(imageName, args, logStream, { + Volumes, + HostConfig: { + Binds, + }, + ...(workingDir ? { WorkingDir: workingDir } : {}), + Entrypoint: command, + Env, + ...userOptions, + } as Docker.ContainerCreateOptions); if (error) { throw new Error( diff --git a/packages/backend-test-utils/src/database/types.ts b/packages/backend-test-utils/src/database/types.ts index b5516a19c0..514a3a85e8 100644 --- a/packages/backend-test-utils/src/database/types.ts +++ b/packages/backend-test-utils/src/database/types.ts @@ -38,33 +38,31 @@ export type Instance = { databaseManager: DatabaseManager; connections: Array; }; -export const allDatabases: Record< - TestDatabaseId, - TestDatabaseProperties -> = Object.freeze({ - POSTGRES_13: { - name: 'Postgres 13.x', - driver: 'pg', - dockerImageName: 'postgres:13', - connectionStringEnvironmentVariableName: - 'BACKSTAGE_TEST_DATABASE_POSTGRES13_CONNECTION_STRING', - }, - POSTGRES_9: { - name: 'Postgres 9.x', - driver: 'pg', - dockerImageName: 'postgres:9', - connectionStringEnvironmentVariableName: - 'BACKSTAGE_TEST_DATABASE_POSTGRES9_CONNECTION_STRING', - }, - MYSQL_8: { - name: 'MySQL 8.x', - driver: 'mysql2', - dockerImageName: 'mysql:8', - connectionStringEnvironmentVariableName: - 'BACKSTAGE_TEST_DATABASE_MYSQL8_CONNECTION_STRING', - }, - SQLITE_3: { - name: 'SQLite 3.x', - driver: 'sqlite3', - }, -}); +export const allDatabases: Record = + Object.freeze({ + POSTGRES_13: { + name: 'Postgres 13.x', + driver: 'pg', + dockerImageName: 'postgres:13', + connectionStringEnvironmentVariableName: + 'BACKSTAGE_TEST_DATABASE_POSTGRES13_CONNECTION_STRING', + }, + POSTGRES_9: { + name: 'Postgres 9.x', + driver: 'pg', + dockerImageName: 'postgres:9', + connectionStringEnvironmentVariableName: + 'BACKSTAGE_TEST_DATABASE_POSTGRES9_CONNECTION_STRING', + }, + MYSQL_8: { + name: 'MySQL 8.x', + driver: 'mysql2', + dockerImageName: 'mysql:8', + connectionStringEnvironmentVariableName: + 'BACKSTAGE_TEST_DATABASE_MYSQL8_CONNECTION_STRING', + }, + SQLITE_3: { + name: 'SQLite 3.x', + driver: 'sqlite3', + }, + }); diff --git a/packages/catalog-model/api-report.md b/packages/catalog-model/api-report.md index 437a0be02b..13041d9e32 100644 --- a/packages/catalog-model/api-report.md +++ b/packages/catalog-model/api-report.md @@ -190,7 +190,7 @@ export type EntityEnvelope = { // // @public export function entityEnvelopeSchemaValidator< - T extends EntityEnvelope = EntityEnvelope + T extends EntityEnvelope = EntityEnvelope, >(schema?: unknown): (data: unknown) => T; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen @@ -333,9 +333,7 @@ export function getEntityName(entity: Entity): EntityName; // Warning: (ae-missing-release-tag) "getEntitySourceLocation" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public -export function getEntitySourceLocation( - entity: Entity, -): { +export function getEntitySourceLocation(entity: Entity): { type: string; target: string; }; @@ -542,9 +540,7 @@ export function parseEntityRef( // Warning: (ae-missing-release-tag) "parseLocationReference" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public -export function parseLocationReference( - ref: string, -): { +export function parseLocationReference(ref: string): { type: string; target: string; }; diff --git a/packages/catalog-model/src/entity/policies/SchemaValidEntityPolicy.test.ts b/packages/catalog-model/src/entity/policies/SchemaValidEntityPolicy.test.ts index 21539aaba4..c263689446 100644 --- a/packages/catalog-model/src/entity/policies/SchemaValidEntityPolicy.test.ts +++ b/packages/catalog-model/src/entity/policies/SchemaValidEntityPolicy.test.ts @@ -58,7 +58,7 @@ describe('SchemaValidEntityPolicy', () => { // it('rejects wrong root type', async () => { - await expect(policy.enforce((7 as unknown) as Entity)).rejects.toThrow( + await expect(policy.enforce(7 as unknown as Entity)).rejects.toThrow( /object/, ); }); diff --git a/packages/catalog-model/src/entity/ref.ts b/packages/catalog-model/src/entity/ref.ts index 91d8547c6b..e2d9c5b203 100644 --- a/packages/catalog-model/src/entity/ref.ts +++ b/packages/catalog-model/src/entity/ref.ts @@ -18,9 +18,7 @@ import { EntityName, EntityRef } from '../types'; import { ENTITY_DEFAULT_NAMESPACE } from './constants'; import { Entity } from './Entity'; -function parseRefString( - ref: string, -): { +function parseRefString(ref: string): { kind?: string; namespace?: string; name: string; diff --git a/packages/catalog-model/src/kinds/ApiEntityV1alpha1.ts b/packages/catalog-model/src/kinds/ApiEntityV1alpha1.ts index 737037e6b2..2bcd9c7040 100644 --- a/packages/catalog-model/src/kinds/ApiEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/ApiEntityV1alpha1.ts @@ -30,6 +30,5 @@ export interface ApiEntityV1alpha1 extends Entity { }; } -export const apiEntityV1alpha1Validator = ajvCompiledJsonSchemaValidator( - schema, -); +export const apiEntityV1alpha1Validator = + ajvCompiledJsonSchemaValidator(schema); diff --git a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts index 4e08d4cce9..5312d87a35 100644 --- a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts @@ -33,6 +33,5 @@ export interface ComponentEntityV1alpha1 extends Entity { }; } -export const componentEntityV1alpha1Validator = ajvCompiledJsonSchemaValidator( - schema, -); +export const componentEntityV1alpha1Validator = + ajvCompiledJsonSchemaValidator(schema); diff --git a/packages/catalog-model/src/kinds/DomainEntityV1alpha1.ts b/packages/catalog-model/src/kinds/DomainEntityV1alpha1.ts index c2f39de321..c832f35ee0 100644 --- a/packages/catalog-model/src/kinds/DomainEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/DomainEntityV1alpha1.ts @@ -26,6 +26,5 @@ export interface DomainEntityV1alpha1 extends Entity { }; } -export const domainEntityV1alpha1Validator = ajvCompiledJsonSchemaValidator( - schema, -); +export const domainEntityV1alpha1Validator = + ajvCompiledJsonSchemaValidator(schema); diff --git a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts index 28f1503223..263ba311ad 100644 --- a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts @@ -34,6 +34,5 @@ export interface GroupEntityV1alpha1 extends Entity { }; } -export const groupEntityV1alpha1Validator = ajvCompiledJsonSchemaValidator( - schema, -); +export const groupEntityV1alpha1Validator = + ajvCompiledJsonSchemaValidator(schema); diff --git a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts index 4a37340bee..44f04b2c39 100644 --- a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts @@ -28,6 +28,5 @@ export interface LocationEntityV1alpha1 extends Entity { }; } -export const locationEntityV1alpha1Validator = ajvCompiledJsonSchemaValidator( - schema, -); +export const locationEntityV1alpha1Validator = + ajvCompiledJsonSchemaValidator(schema); diff --git a/packages/catalog-model/src/kinds/ResourceEntityV1alpha1.ts b/packages/catalog-model/src/kinds/ResourceEntityV1alpha1.ts index c8f96b87e3..211164f4c1 100644 --- a/packages/catalog-model/src/kinds/ResourceEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/ResourceEntityV1alpha1.ts @@ -29,6 +29,5 @@ export interface ResourceEntityV1alpha1 extends Entity { }; } -export const resourceEntityV1alpha1Validator = ajvCompiledJsonSchemaValidator( - schema, -); +export const resourceEntityV1alpha1Validator = + ajvCompiledJsonSchemaValidator(schema); diff --git a/packages/catalog-model/src/kinds/SystemEntityV1alpha1.ts b/packages/catalog-model/src/kinds/SystemEntityV1alpha1.ts index 7c719566ad..129e3fea50 100644 --- a/packages/catalog-model/src/kinds/SystemEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/SystemEntityV1alpha1.ts @@ -27,6 +27,5 @@ export interface SystemEntityV1alpha1 extends Entity { }; } -export const systemEntityV1alpha1Validator = ajvCompiledJsonSchemaValidator( - schema, -); +export const systemEntityV1alpha1Validator = + ajvCompiledJsonSchemaValidator(schema); diff --git a/packages/catalog-model/src/kinds/TemplateEntityV1beta2.ts b/packages/catalog-model/src/kinds/TemplateEntityV1beta2.ts index 2710fe1275..577e5ec9e2 100644 --- a/packages/catalog-model/src/kinds/TemplateEntityV1beta2.ts +++ b/packages/catalog-model/src/kinds/TemplateEntityV1beta2.ts @@ -40,6 +40,5 @@ export interface TemplateEntityV1beta2 extends Entity { }; } -export const templateEntityV1beta2Validator = ajvCompiledJsonSchemaValidator( - schema, -); +export const templateEntityV1beta2Validator = + ajvCompiledJsonSchemaValidator(schema); diff --git a/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts b/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts index 267a9f07fd..65ebdb3262 100644 --- a/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts @@ -31,6 +31,5 @@ export interface UserEntityV1alpha1 extends Entity { }; } -export const userEntityV1alpha1Validator = ajvCompiledJsonSchemaValidator( - schema, -); +export const userEntityV1alpha1Validator = + ajvCompiledJsonSchemaValidator(schema); diff --git a/packages/catalog-model/src/location/helpers.ts b/packages/catalog-model/src/location/helpers.ts index 431ee71218..91209e7a2a 100644 --- a/packages/catalog-model/src/location/helpers.ts +++ b/packages/catalog-model/src/location/helpers.ts @@ -26,9 +26,10 @@ import { LOCATION_ANNOTATION, SOURCE_LOCATION_ANNOTATION } from './annotation'; * @param ref A string-form location reference, e.g. 'url:https://host' * @returns A location reference, e.g. { type: 'url', target: 'https://host' } */ -export function parseLocationReference( - ref: string, -): { type: string; target: string } { +export function parseLocationReference(ref: string): { + type: string; + target: string; +} { if (typeof ref !== 'string') { throw new TypeError( `Unable to parse location reference '${ref}', unexpected argument ${typeof ref}`, @@ -91,9 +92,10 @@ export function stringifyLocationReference(ref: { * using the UrlReader from @backstage/backend-common. If it is not of type 'url', the caller * needs to have explicit handling of each location type or signal that it is not supported. */ -export function getEntitySourceLocation( - entity: Entity, -): { type: string; target: string } { +export function getEntitySourceLocation(entity: Entity): { + type: string; + target: string; +} { const locationRef = entity.metadata?.annotations?.[SOURCE_LOCATION_ANNOTATION] ?? entity.metadata?.annotations?.[LOCATION_ANNOTATION]; diff --git a/packages/catalog-model/src/validation/entityEnvelopeSchemaValidator.ts b/packages/catalog-model/src/validation/entityEnvelopeSchemaValidator.ts index 2fe74ea2a4..aa865bcf1c 100644 --- a/packages/catalog-model/src/validation/entityEnvelopeSchemaValidator.ts +++ b/packages/catalog-model/src/validation/entityEnvelopeSchemaValidator.ts @@ -41,7 +41,7 @@ import { compileAjvSchema, throwAjvError } from './ajv'; * @see https://github.com/backstage/backstage/tree/master/packages/catalog-model/src/schema */ export function entityEnvelopeSchemaValidator< - T extends EntityEnvelope = EntityEnvelope + T extends EntityEnvelope = EntityEnvelope, >(schema?: unknown): (data: unknown) => T { const validate = compileAjvSchema( schema ? (schema as Schema) : entityEnvelopeSchema, diff --git a/packages/cli/src/commands/versions/lint.ts b/packages/cli/src/commands/versions/lint.ts index 68d0766217..c542da6dfb 100644 --- a/packages/cli/src/commands/versions/lint.ts +++ b/packages/cli/src/commands/versions/lint.ts @@ -55,11 +55,9 @@ export default async (cmd: Command) => { lockfile.replaceVersions(result.newVersions); await lockfile.save(); } else { - const [ - newVersionsForbidden, - newVersionsAllowed, - ] = partition(result.newVersions, ({ name }) => - forbiddenDuplicatesFilter(name), + const [newVersionsForbidden, newVersionsAllowed] = partition( + result.newVersions, + ({ name }) => forbiddenDuplicatesFilter(name), ); if (newVersionsForbidden.length && !fix) { success = false; diff --git a/packages/cli/src/lib/bundler/optimization.ts b/packages/cli/src/lib/bundler/optimization.ts index 4d77f2cc73..b8164d263d 100644 --- a/packages/cli/src/lib/bundler/optimization.ts +++ b/packages/cli/src/lib/bundler/optimization.ts @@ -30,9 +30,9 @@ export const optimization = ( ...(!isParallelDefault(options.parallel) ? { minimizer: [ - (new TerserPlugin({ + new TerserPlugin({ parallel: options.parallel, - }) as unknown) as WebpackPluginInstance, + }) as unknown as WebpackPluginInstance, ], } : {}), diff --git a/packages/cli/src/lib/versioning/Lockfile.ts b/packages/cli/src/lib/versioning/Lockfile.ts index 7b23652c33..d3517e3c83 100644 --- a/packages/cli/src/lib/versioning/Lockfile.ts +++ b/packages/cli/src/lib/versioning/Lockfile.ts @@ -137,9 +137,9 @@ export class Lockfile { } // Find all versions currently in use - const versions = Array.from( - new Set(entries.map(e => e.version)), - ).sort((v1, v2) => semver.rcompare(v1, v2)); + const versions = Array.from(new Set(entries.map(e => e.version))).sort( + (v1, v2) => semver.rcompare(v1, v2), + ); // If we're not using at least 2 different versions we're done if (versions.length < 2) { diff --git a/packages/cli/src/types.d.ts b/packages/cli/src/types.d.ts index d3ef72646b..db5e508ec2 100644 --- a/packages/cli/src/types.d.ts +++ b/packages/cli/src/types.d.ts @@ -30,9 +30,7 @@ declare module '@svgr/rollup' { declare module '@rollup/plugin-yaml'; declare module 'react-dev-utils/formatWebpackMessages' { - export default function ( - stats: any, - ): { + export default function (stats: any): { errors: string[]; warnings: string[]; }; @@ -46,7 +44,8 @@ declare module 'react-dev-utils/ModuleScopePlugin' { import webpack = require('webpack'); export default class ModuleScopePlugin - implements webpack.WebpackPluginInstance { + implements webpack.WebpackPluginInstance + { constructor( appSrc: string | ReadonlyArray, allowedFiles?: ReadonlyArray, diff --git a/packages/config-loader/src/lib/transform/include.test.ts b/packages/config-loader/src/lib/transform/include.test.ts index 44bf07ab4d..91df723621 100644 --- a/packages/config-loader/src/lib/transform/include.test.ts +++ b/packages/config-loader/src/lib/transform/include.test.ts @@ -24,9 +24,11 @@ const substituteMe = '${MY_SUBSTITUTION}'; const mySubstitution = 'fooSubstitution'; const env = jest.fn(async (name: string) => { - return ({ - SECRET: 'my-secret', - } as { [name: string]: string })[name]; + return ( + { + SECRET: 'my-secret', + } as { [name: string]: string } + )[name]; }); const substitute: TransformFunc = async value => { @@ -44,14 +46,16 @@ const substitute: TransformFunc = async value => { }; const readFile = jest.fn(async (path: string) => { - const content = ({ - [resolvePath(root, 'my-secret')]: 'secret', - [resolvePath(root, 'my-data.json')]: '{"a":{"b":{"c":42}}}', - [resolvePath(root, 'my-data.yaml')]: 'some:\n yaml:\n key: 7', - [resolvePath(root, 'my-data.yml')]: 'different: { key: hello }', - [resolvePath(root, 'invalid.yaml')]: 'foo: [}', - [resolvePath(root, `${mySubstitution}/my-data.json`)]: '{"foo":"bar"}', - } as { [key: string]: string })[path]; + const content = ( + { + [resolvePath(root, 'my-secret')]: 'secret', + [resolvePath(root, 'my-data.json')]: '{"a":{"b":{"c":42}}}', + [resolvePath(root, 'my-data.yaml')]: 'some:\n yaml:\n key: 7', + [resolvePath(root, 'my-data.yml')]: 'different: { key: hello }', + [resolvePath(root, 'invalid.yaml')]: 'foo: [}', + [resolvePath(root, `${mySubstitution}/my-data.json`)]: '{"foo":"bar"}', + } as { [key: string]: string } + )[path]; if (!content) { throw new Error('File not found!'); diff --git a/packages/config-loader/src/lib/transform/substitution.test.ts b/packages/config-loader/src/lib/transform/substitution.test.ts index dc6ed47597..b03c39c174 100644 --- a/packages/config-loader/src/lib/transform/substitution.test.ts +++ b/packages/config-loader/src/lib/transform/substitution.test.ts @@ -17,10 +17,12 @@ import { createSubstitutionTransform } from './substitution'; const env = jest.fn(async (name: string) => { - return ({ - SECRET: 'my-secret', - TOKEN: 'my-token', - } as { [name: string]: string })[name]; + return ( + { + SECRET: 'my-secret', + TOKEN: 'my-token', + } as { [name: string]: string } + )[name]; }); const substituteTransform = createSubstitutionTransform(env); diff --git a/packages/config/src/reader.test.ts b/packages/config/src/reader.test.ts index ed0ca7febe..2f846fe159 100644 --- a/packages/config/src/reader.test.ts +++ b/packages/config/src/reader.test.ts @@ -64,9 +64,9 @@ function expectValidValues(config: ConfigReader) { strings: ['string1', 'string2'], }); expect(config.getConfig('nested').getString('string')).toBe('string'); - expect( - config.getOptionalConfig('nested')!.getStringArray('strings'), - ).toEqual(['string1', 'string2']); + expect(config.getOptionalConfig('nested')!.getStringArray('strings')).toEqual( + ['string1', 'string2'], + ); expect(config.getOptional('missing')).toBe(undefined); expect(config.getOptionalConfig('missing')).toBe(undefined); expect(config.getOptionalConfigArray('missing')).toBe(undefined); @@ -234,9 +234,9 @@ describe('ConfigReader', () => { expect(withLogCollector(() => config.getOptional('a'))).toMatchObject({ warn: [], }); - expect( - withLogCollector(() => config.getOptionalString('a')), - ).toMatchObject({ warn: [] }); + expect(withLogCollector(() => config.getOptionalString('a'))).toMatchObject( + { warn: [] }, + ); expect( withLogCollector(() => config.getOptionalConfigArray('b')), ).toMatchObject({ warn: [] }); diff --git a/packages/core-app-api/api-report.md b/packages/core-app-api/api-report.md index a7a3845dd7..e2c6b3a939 100644 --- a/packages/core-app-api/api-report.md +++ b/packages/core-app-api/api-report.md @@ -68,9 +68,7 @@ export class AlertApiForwarder implements AlertApi { // // @public (undocumented) export type ApiFactoryHolder = { - get( - api: ApiRef, - ): + get(api: ApiRef): | ApiFactory< T, T, @@ -86,9 +84,7 @@ export type ApiFactoryHolder = { // @public export class ApiFactoryRegistry implements ApiFactoryHolder { // (undocumented) - get( - api: ApiRef, - ): + get(api: ApiRef): | ApiFactory< T, T, @@ -105,7 +101,7 @@ export class ApiFactoryRegistry implements ApiFactoryHolder { Impl extends Api, Deps extends { [name in string]: unknown; - } + }, >(scope: ApiFactoryScope, factory: ApiFactory): boolean; } @@ -211,7 +207,7 @@ export type AppOptions = { export type AppRouteBinder = < ExternalRoutes extends { [name: string]: ExternalRouteRef; - } + }, >( externalRoutes: ExternalRoutes, targetRoutes: PartialKeys< @@ -469,7 +465,8 @@ export class OAuth2 OpenIdConnectApi, ProfileInfoApi, BackstageIdentityApi, - SessionApi { + SessionApi +{ // Warning: (ae-forgotten-export) The symbol "Options" needs to be exported by the entry point index.d.ts constructor(options: Options); // Warning: (ae-forgotten-export) The symbol "CreateOptions" needs to be exported by the entry point index.d.ts @@ -561,7 +558,8 @@ export class OneLoginAuth { // // @public (undocumented) export class SamlAuth - implements ProfileInfoApi, BackstageIdentityApi, SessionApi { + implements ProfileInfoApi, BackstageIdentityApi, SessionApi +{ // Warning: (ae-forgotten-export) The symbol "SamlSession" needs to be exported by the entry point index.d.ts constructor(sessionManager: SessionManager); // Warning: (ae-forgotten-export) The symbol "AuthApiCreateOptions" needs to be exported by the entry point index.d.ts diff --git a/packages/core-app-api/src/apis/implementations/FeatureFlagsApi/LocalStorageFeatureFlags.test.tsx b/packages/core-app-api/src/apis/implementations/FeatureFlagsApi/LocalStorageFeatureFlags.test.tsx index afc25b2e8c..1193592e96 100644 --- a/packages/core-app-api/src/apis/implementations/FeatureFlagsApi/LocalStorageFeatureFlags.test.tsx +++ b/packages/core-app-api/src/apis/implementations/FeatureFlagsApi/LocalStorageFeatureFlags.test.tsx @@ -194,8 +194,7 @@ describe('FeatureFlags', () => { it('throws an error if length is greater than 150 characters', () => { expect(() => featureFlags.registerFlag({ - name: - 'loremipsumdolorsitametconsecteturadipiscingelitnuncvitaeportaexaullamcorperturpismaurisutmattisnequemorbisediaculisauguevivamuspulvinarcursuseratblandithendreritquisqueuttinciduntmagnavestibulumblanditaugueat', + name: 'loremipsumdolorsitametconsecteturadipiscingelitnuncvitaeportaexaullamcorperturpismaurisutmattisnequemorbisediaculisauguevivamuspulvinarcursuseratblandithendreritquisqueuttinciduntmagnavestibulumblanditaugueat', pluginId: 'plugin-three', }), ).toThrow(/not exceed 150 characters/i); diff --git a/packages/core-app-api/src/apis/implementations/auth/oauth2/OAuth2.ts b/packages/core-app-api/src/apis/implementations/auth/oauth2/OAuth2.ts index 8c27e0aa63..24db8d2560 100644 --- a/packages/core-app-api/src/apis/implementations/auth/oauth2/OAuth2.ts +++ b/packages/core-app-api/src/apis/implementations/auth/oauth2/OAuth2.ts @@ -65,7 +65,8 @@ class OAuth2 OpenIdConnectApi, ProfileInfoApi, BackstageIdentityApi, - SessionApi { + SessionApi +{ static create({ discoveryApi, environment = 'development', diff --git a/packages/core-app-api/src/apis/system/ApiProvider.test.tsx b/packages/core-app-api/src/apis/system/ApiProvider.test.tsx index 5afb39a2ec..b94aea6b67 100644 --- a/packages/core-app-api/src/apis/system/ApiProvider.test.tsx +++ b/packages/core-app-api/src/apis/system/ApiProvider.test.tsx @@ -185,9 +185,10 @@ describe('ApiProvider', () => { }); describe('v1 consumer', () => { - const ApiContext = getGlobalSingleton< - Context> - >('api-context'); + const ApiContext = + getGlobalSingleton>>( + 'api-context', + ); function useMockApiV1(apiRef: ApiRef): T { const impl = useContext(ApiContext)?.atVersion(1)?.get(apiRef); diff --git a/packages/core-app-api/src/app/App.tsx b/packages/core-app-api/src/app/App.tsx index a95554709a..013e8e6a8a 100644 --- a/packages/core-app-api/src/app/App.tsx +++ b/packages/core-app-api/src/app/App.tsx @@ -216,37 +216,33 @@ export class PrivateAppImpl implements BackstageApp { [], ); - const { - routePaths, - routeParents, - routeObjects, - featureFlags, - } = useMemo(() => { - const result = traverseElementTree({ - root: children, - discoverers: [childDiscoverer, routeElementDiscoverer], - collectors: { - routePaths: routePathCollector, - routeParents: routeParentCollector, - routeObjects: routeObjectCollector, - collectedPlugins: pluginCollector, - featureFlags: featureFlagCollector, - }, - }); + const { routePaths, routeParents, routeObjects, featureFlags } = + useMemo(() => { + const result = traverseElementTree({ + root: children, + discoverers: [childDiscoverer, routeElementDiscoverer], + collectors: { + routePaths: routePathCollector, + routeParents: routeParentCollector, + routeObjects: routeObjectCollector, + collectedPlugins: pluginCollector, + featureFlags: featureFlagCollector, + }, + }); - validateRoutes(result.routePaths, result.routeParents); + validateRoutes(result.routePaths, result.routeParents); - // TODO(Rugvip): Restructure the public API so that we can get an immediate view of - // the app, rather than having to wait for the provider to render. - // For now we need to push the additional plugins we find during - // collection and then make sure we initialize things afterwards. - result.collectedPlugins.forEach(plugin => this.plugins.add(plugin)); - this.verifyPlugins(this.plugins); + // TODO(Rugvip): Restructure the public API so that we can get an immediate view of + // the app, rather than having to wait for the provider to render. + // For now we need to push the additional plugins we find during + // collection and then make sure we initialize things afterwards. + result.collectedPlugins.forEach(plugin => this.plugins.add(plugin)); + this.verifyPlugins(this.plugins); - // Initialize APIs once all plugins are available - this.getApiHolder(); - return result; - }, [children]); + // Initialize APIs once all plugins are available + this.getApiHolder(); + return result; + }, [children]); const loadedConfig = useConfigLoader( this.configLoader, @@ -314,10 +310,8 @@ export class PrivateAppImpl implements BackstageApp { } getRouter(): ComponentType<{}> { - const { - Router: RouterComponent, - SignInPage: SignInPageComponent, - } = this.components; + const { Router: RouterComponent, SignInPage: SignInPageComponent } = + this.components; // This wraps the sign-in page and waits for sign-in to be completed before rendering the app const SignInPageWrapper = ({ diff --git a/packages/core-app-api/src/app/AppContext.test.tsx b/packages/core-app-api/src/app/AppContext.test.tsx index d87bf7d228..6ce164b9f0 100644 --- a/packages/core-app-api/src/app/AppContext.test.tsx +++ b/packages/core-app-api/src/app/AppContext.test.tsx @@ -22,9 +22,10 @@ import { AppContext as AppContextV1 } from './types'; import { AppContextProvider } from './AppContext'; describe('v1 consumer', () => { - const AppContext = getGlobalSingleton< - Context> - >('app-context'); + const AppContext = + getGlobalSingleton>>( + 'app-context', + ); function useMockAppV1(): AppContextV1 { const impl = useContext(AppContext)?.atVersion(1); diff --git a/packages/core-app-api/src/app/createApp.tsx b/packages/core-app-api/src/app/createApp.tsx index b7c49939e2..1d74f93add 100644 --- a/packages/core-app-api/src/app/createApp.tsx +++ b/packages/core-app-api/src/app/createApp.tsx @@ -60,7 +60,7 @@ export const defaultConfigLoader: AppConfigLoader = async ( if (!Array.isArray(appConfig)) { throw new Error('Static configuration has invalid format'); } - const configs = (appConfig.slice() as unknown) as AppConfig[]; + const configs = appConfig.slice() as unknown as AppConfig[]; // Avoiding this string also being replaced at runtime if ( diff --git a/packages/core-app-api/src/app/types.ts b/packages/core-app-api/src/app/types.ts index 836f1b7fb0..30ce45abe9 100644 --- a/packages/core-app-api/src/app/types.ts +++ b/packages/core-app-api/src/app/types.ts @@ -105,14 +105,14 @@ type KeysWithType = { */ type PartialKeys< Map extends { [name in string]: any }, - Keys extends keyof Map + Keys extends keyof Map, > = Partial> & Required>; /** * Creates a map of target routes with matching parameters based on a map of external routes. */ type TargetRouteMap< - ExternalRoutes extends { [name: string]: ExternalRouteRef } + ExternalRoutes extends { [name: string]: ExternalRouteRef }, > = { [name in keyof ExternalRoutes]: ExternalRoutes[name] extends ExternalRouteRef< infer Params, @@ -123,7 +123,7 @@ type TargetRouteMap< }; export type AppRouteBinder = < - ExternalRoutes extends { [name: string]: ExternalRouteRef } + ExternalRoutes extends { [name: string]: ExternalRouteRef }, >( externalRoutes: ExternalRoutes, targetRoutes: PartialKeys< diff --git a/packages/core-app-api/src/extensions/extensions.tsx b/packages/core-app-api/src/extensions/extensions.tsx index 063f34c659..199430c619 100644 --- a/packages/core-app-api/src/extensions/extensions.tsx +++ b/packages/core-app-api/src/extensions/extensions.tsx @@ -28,7 +28,7 @@ const ERROR_MESSAGE = 'Import this from @backstage/core-plugin-api'; /** @deprecated Import from @backstage/core-plugin-api instead */ export function createRoutableExtension< - T extends (props: any) => JSX.Element | null + T extends (props: any) => JSX.Element | null, >(_options: { component: () => Promise; mountPoint: RouteRef; @@ -38,14 +38,14 @@ export function createRoutableExtension< /** @deprecated Import from @backstage/core-plugin-api instead */ export function createComponentExtension< - T extends (props: any) => JSX.Element | null + T extends (props: any) => JSX.Element | null, >(_options: { component: ComponentLoader }): Extension { throw new Error(ERROR_MESSAGE); } /** @deprecated Import from @backstage/core-plugin-api instead */ export function createReactExtension< - T extends (props: any) => JSX.Element | null + T extends (props: any) => JSX.Element | null, >(_options: { component: ComponentLoader; data?: Record; diff --git a/packages/core-app-api/src/lib/AuthConnector/DefaultAuthConnector.test.ts b/packages/core-app-api/src/lib/AuthConnector/DefaultAuthConnector.test.ts index 524a0c5709..ce5df9fc91 100644 --- a/packages/core-app-api/src/lib/AuthConnector/DefaultAuthConnector.test.ts +++ b/packages/core-app-api/src/lib/AuthConnector/DefaultAuthConnector.test.ts @@ -126,8 +126,7 @@ describe('DefaultAuthConnector', () => { expect(popupSpy).toBeCalledTimes(1); expect(popupSpy.mock.calls[0][0]).toMatchObject({ - url: - 'http://my-host/api/auth/my-provider/start?scope=a%20b&env=production', + url: 'http://my-host/api/auth/my-provider/start?scope=a%20b&env=production', }); await expect(sessionPromise).resolves.toEqual({ @@ -175,8 +174,7 @@ describe('DefaultAuthConnector', () => { expect(popupSpy).toBeCalledTimes(1); expect(popupSpy.mock.calls[0][0]).toMatchObject({ - url: - 'http://my-host/api/auth/my-provider/start?scope=-ab-&env=production', + url: 'http://my-host/api/auth/my-provider/start?scope=-ab-&env=production', }); }); }); diff --git a/packages/core-app-api/src/lib/AuthConnector/DefaultAuthConnector.ts b/packages/core-app-api/src/lib/AuthConnector/DefaultAuthConnector.ts index 81da04010c..d707acdc9b 100644 --- a/packages/core-app-api/src/lib/AuthConnector/DefaultAuthConnector.ts +++ b/packages/core-app-api/src/lib/AuthConnector/DefaultAuthConnector.ts @@ -61,7 +61,8 @@ function defaultJoinScopes(scopes: Set) { * via the OAuthRequestApi. */ export class DefaultAuthConnector - implements AuthConnector { + implements AuthConnector +{ private readonly discoveryApi: DiscoveryApi; private readonly environment: string; private readonly provider: AuthProvider & { id: string }; diff --git a/packages/core-app-api/src/lib/loginPopup.test.ts b/packages/core-app-api/src/lib/loginPopup.test.ts index 1eb7c3f8b9..db4d9eb8eb 100644 --- a/packages/core-app-api/src/lib/loginPopup.test.ts +++ b/packages/core-app-api/src/lib/loginPopup.test.ts @@ -30,8 +30,7 @@ describe('showLoginPopup', () => { const removeEventListenerSpy = jest.spyOn(window, 'removeEventListener'); const payloadPromise = showLoginPopup({ - url: - 'my-origin/api/backend/auth/start?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fa%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fb', + url: 'my-origin/api/backend/auth/start?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fa%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fb', name: 'test-popup', origin: 'my-origin', }); diff --git a/packages/core-app-api/src/lib/subjects.ts b/packages/core-app-api/src/lib/subjects.ts index 0391050bda..e122da819b 100644 --- a/packages/core-app-api/src/lib/subjects.ts +++ b/packages/core-app-api/src/lib/subjects.ts @@ -29,7 +29,8 @@ import ObservableImpl from 'zen-observable'; * See http://reactivex.io/documentation/subject.html */ export class PublishSubject - implements Observable, ZenObservable.SubscriptionObserver { + implements Observable, ZenObservable.SubscriptionObserver +{ private isClosed = false; private terminatingError?: Error; @@ -121,7 +122,8 @@ export class PublishSubject * See http://reactivex.io/documentation/subject.html */ export class BehaviorSubject - implements Observable, ZenObservable.SubscriptionObserver { + implements Observable, ZenObservable.SubscriptionObserver +{ private isClosed = false; private currentValue: T; private terminatingError?: Error; diff --git a/packages/core-app-api/src/lib/versionedValues.ts b/packages/core-app-api/src/lib/versionedValues.ts index 3d0a4a41ae..3b3064fc7e 100644 --- a/packages/core-app-api/src/lib/versionedValues.ts +++ b/packages/core-app-api/src/lib/versionedValues.ts @@ -29,7 +29,7 @@ export type VersionedValue = { * Creates a container for a map of versioned values that implements VersionedValue. */ export function createVersionedValueMap< - Versions extends { [version: number]: any } + Versions extends { [version: number]: any }, >(versions: Versions): VersionedValue { Object.freeze(versions); return { diff --git a/packages/core-app-api/src/routing/FlatRoutes.test.tsx b/packages/core-app-api/src/routing/FlatRoutes.test.tsx index d5201a6f57..0df296cc59 100644 --- a/packages/core-app-api/src/routing/FlatRoutes.test.tsx +++ b/packages/core-app-api/src/routing/FlatRoutes.test.tsx @@ -37,11 +37,11 @@ function makeRouteRenderer(node: ReactNode) { ({ NotFoundErrorPage: () => <>Not Found, }), - } as unknown) as AppContext + } as unknown as AppContext } > diff --git a/packages/core-app-api/src/routing/RoutingProvider.test.tsx b/packages/core-app-api/src/routing/RoutingProvider.test.tsx index 499b81a743..1b21dad5a6 100644 --- a/packages/core-app-api/src/routing/RoutingProvider.test.tsx +++ b/packages/core-app-api/src/routing/RoutingProvider.test.tsx @@ -330,9 +330,10 @@ describe('discovery', () => { }); describe('v1 consumer', () => { - const RoutingContext = getGlobalSingleton< - Context> - >('routing-context'); + const RoutingContext = + getGlobalSingleton>>( + 'routing-context', + ); function useMockRouteRefV1( routeRef: AnyRouteRef, diff --git a/packages/core-app-api/src/routing/types.ts b/packages/core-app-api/src/routing/types.ts index 6561a0da70..a12e914aba 100644 --- a/packages/core-app-api/src/routing/types.ts +++ b/packages/core-app-api/src/routing/types.ts @@ -75,7 +75,7 @@ export function isSubRouteRef( export function isExternalRouteRef< Params extends AnyParams, - Optional extends boolean + Optional extends boolean, >( routeRef: | RouteRef diff --git a/packages/core-components/src/components/DependencyGraph/DefaultNode.tsx b/packages/core-components/src/components/DependencyGraph/DefaultNode.tsx index c93651e3e0..69269d687d 100644 --- a/packages/core-components/src/components/DependencyGraph/DefaultNode.tsx +++ b/packages/core-components/src/components/DependencyGraph/DefaultNode.tsx @@ -38,10 +38,8 @@ export function DefaultNode({ node: { id } }: RenderNodeProps) { React.useLayoutEffect(() => { // set the width to the length of the ID if (idRef.current) { - let { - height: renderedHeight, - width: renderedWidth, - } = idRef.current.getBBox(); + let { height: renderedHeight, width: renderedWidth } = + idRef.current.getBBox(); renderedHeight = Math.round(renderedHeight); renderedWidth = Math.round(renderedWidth); diff --git a/packages/core-components/src/components/DependencyGraph/DependencyGraph.tsx b/packages/core-components/src/components/DependencyGraph/DependencyGraph.tsx index 89f7421d2a..bf018b13c8 100644 --- a/packages/core-components/src/components/DependencyGraph/DependencyGraph.tsx +++ b/packages/core-components/src/components/DependencyGraph/DependencyGraph.tsx @@ -132,10 +132,8 @@ export function DependencyGraph({ container.call(zoom); - const { - width: newContainerWidth, - height: newContainerHeight, - } = node.getBoundingClientRect(); + const { width: newContainerWidth, height: newContainerHeight } = + node.getBoundingClientRect(); if (containerWidth !== newContainerWidth) { setContainerWidth(newContainerWidth); } diff --git a/packages/core-components/src/components/DependencyGraph/Edge.tsx b/packages/core-components/src/components/DependencyGraph/Edge.tsx index 4e4c5ca5f7..e0f19d3536 100644 --- a/packages/core-components/src/components/DependencyGraph/Edge.tsx +++ b/packages/core-components/src/components/DependencyGraph/Edge.tsx @@ -71,10 +71,8 @@ export function Edge({ React.useLayoutEffect(() => { // set the label width to the actual rendered width to properly layout graph if (labelRef.current) { - let { - height: renderedHeight, - width: renderedWidth, - } = labelRef.current.getBBox(); + let { height: renderedHeight, width: renderedWidth } = + labelRef.current.getBBox(); renderedHeight = Math.round(renderedHeight); renderedWidth = Math.round(renderedWidth); diff --git a/packages/core-components/src/components/DependencyGraph/Node.tsx b/packages/core-components/src/components/DependencyGraph/Node.tsx index d9e8cbfb78..a5e1a62f09 100644 --- a/packages/core-components/src/components/DependencyGraph/Node.tsx +++ b/packages/core-components/src/components/DependencyGraph/Node.tsx @@ -46,10 +46,8 @@ export function Node({ React.useLayoutEffect(() => { // set the node width to the actual rendered width to properly layout graph if (nodeRef.current) { - let { - height: renderedHeight, - width: renderedWidth, - } = nodeRef.current.getBBox(); + let { height: renderedHeight, width: renderedWidth } = + nodeRef.current.getBBox(); renderedHeight = Math.round(renderedHeight); renderedWidth = Math.round(renderedWidth); diff --git a/packages/core-components/src/components/FeatureDiscovery/lib/useShowCallout.ts b/packages/core-components/src/components/FeatureDiscovery/lib/useShowCallout.ts index 617f1324ed..a507d210a7 100644 --- a/packages/core-components/src/components/FeatureDiscovery/lib/useShowCallout.ts +++ b/packages/core-components/src/components/FeatureDiscovery/lib/useShowCallout.ts @@ -38,9 +38,10 @@ function useCalloutStates(): { return { states, setState }; } -function useCalloutHasBeenSeen( - featureId: string, -): { seen: boolean | undefined; markSeen: () => void } { +function useCalloutHasBeenSeen(featureId: string): { + seen: boolean | undefined; + markSeen: () => void; +} { const { states, setState } = useCalloutStates(); const markSeen = useCallback(() => { @@ -50,9 +51,10 @@ function useCalloutHasBeenSeen( return { seen: states[featureId] === true, markSeen }; } -export function useShowCallout( - featureId: string, -): { show: boolean; hide: () => void } { +export function useShowCallout(featureId: string): { + show: boolean; + hide: () => void; +} { const { seen, markSeen } = useCalloutHasBeenSeen(featureId); return { show: seen === false, hide: markSeen }; } diff --git a/packages/core-components/src/components/StructuredMetadataTable/MetadataTable.tsx b/packages/core-components/src/components/StructuredMetadataTable/MetadataTable.tsx index b7790e38da..5740ba9500 100644 --- a/packages/core-components/src/components/StructuredMetadataTable/MetadataTable.tsx +++ b/packages/core-components/src/components/StructuredMetadataTable/MetadataTable.tsx @@ -96,14 +96,14 @@ interface StyleProps extends WithStyles { children?: React.ReactNode; } -export const MetadataList = withStyles( - listStyles, -)(({ classes, children }: StyleProps) => ( -
    {children}
-)); +export const MetadataList = withStyles(listStyles)( + ({ classes, children }: StyleProps) => ( +
    {children}
+ ), +); -export const MetadataListItem = withStyles( - listItemStyles, -)(({ classes, children }: StyleProps) => ( -
  • {children}
  • -)); +export const MetadataListItem = withStyles(listItemStyles)( + ({ classes, children }: StyleProps) => ( +
  • {children}
  • + ), +); diff --git a/packages/core-components/src/components/StructuredMetadataTable/StructuredMetadataTable.tsx b/packages/core-components/src/components/StructuredMetadataTable/StructuredMetadataTable.tsx index af56cb5b89..9b08123d1b 100644 --- a/packages/core-components/src/components/StructuredMetadataTable/StructuredMetadataTable.tsx +++ b/packages/core-components/src/components/StructuredMetadataTable/StructuredMetadataTable.tsx @@ -44,16 +44,16 @@ interface StyleProps extends WithStyles { children?: React.ReactNode; } // Sub Components -const StyledList = withStyles( - listStyle, -)(({ classes, children }: StyleProps) => ( - {children} -)); -const StyledNestedList = withStyles( - nestedListStyle, -)(({ classes, children }: StyleProps) => ( - {children} -)); +const StyledList = withStyles(listStyle)( + ({ classes, children }: StyleProps) => ( + {children} + ), +); +const StyledNestedList = withStyles(nestedListStyle)( + ({ classes, children }: StyleProps) => ( + {children} + ), +); function renderList(list: Array, nested?: boolean) { const values = list.map((item: any, index: number) => ( diff --git a/packages/core-components/src/components/TabbedLayout/RoutedTabs.tsx b/packages/core-components/src/components/TabbedLayout/RoutedTabs.tsx index 531262544c..52a2c29e2d 100644 --- a/packages/core-components/src/components/TabbedLayout/RoutedTabs.tsx +++ b/packages/core-components/src/components/TabbedLayout/RoutedTabs.tsx @@ -20,9 +20,11 @@ import { Content } from '../../layout/Content'; import { HeaderTabs } from '../../layout/HeaderTabs'; import { SubRoute } from './types'; -export function useSelectedSubRoute( - subRoutes: SubRoute[], -): { index: number; route: SubRoute; element: JSX.Element } { +export function useSelectedSubRoute(subRoutes: SubRoute[]): { + index: number; + route: SubRoute; + element: JSX.Element; +} { const params = useParams(); const routes = subRoutes.map(({ path, children }) => ({ diff --git a/packages/core-components/src/components/Table/Table.tsx b/packages/core-components/src/components/Table/Table.tsx index 6e049d1b6a..22d8bff014 100644 --- a/packages/core-components/src/components/Table/Table.tsx +++ b/packages/core-components/src/components/Table/Table.tsx @@ -285,9 +285,10 @@ export function Table({ const [filtersOpen, setFiltersOpen] = useState( calculatedInitialState.filtersOpen, ); - const toggleFilters = useCallback(() => setFiltersOpen(v => !v), [ - setFiltersOpen, - ]); + const toggleFilters = useCallback( + () => setFiltersOpen(v => !v), + [setFiltersOpen], + ); const [selectedFiltersLength, setSelectedFiltersLength] = useState(0); const [tableData, setTableData] = useState(data as any[]); const [selectedFilters, setSelectedFilters] = useState( diff --git a/packages/core-components/src/hooks/useSupportConfig.ts b/packages/core-components/src/hooks/useSupportConfig.ts index 5bab9a3c6b..5d64e38f3d 100644 --- a/packages/core-components/src/hooks/useSupportConfig.ts +++ b/packages/core-components/src/hooks/useSupportConfig.ts @@ -42,8 +42,7 @@ const DEFAULT_SUPPORT_CONFIG: SupportConfig = { { // TODO: Update to dedicated support page on backstage.io/docs title: 'Add `app.support` config key', - url: - 'https://github.com/andrewthauer/backstage/blob/master/app-config.yaml', + url: 'https://github.com/andrewthauer/backstage/blob/master/app-config.yaml', }, ], }, diff --git a/packages/core-components/src/layout/ErrorBoundary/ErrorBoundary.test.tsx b/packages/core-components/src/layout/ErrorBoundary/ErrorBoundary.test.tsx index f8adb81a2a..a1c45bff4d 100644 --- a/packages/core-components/src/layout/ErrorBoundary/ErrorBoundary.test.tsx +++ b/packages/core-components/src/layout/ErrorBoundary/ErrorBoundary.test.tsx @@ -42,18 +42,14 @@ describe('', () => { it('should render error boundary with and without error', async () => { const { error } = await withLogCollector(['error'], async () => { const apis = ApiRegistry.with(errorApiRef, new MockErrorApi()); - const { - rerender, - queryByRole, - getByRole, - getByText, - } = await renderInTestApp( - - - - - , - ); + const { rerender, queryByRole, getByRole, getByText } = + await renderInTestApp( + + + + + , + ); expect(queryByRole('alert')).not.toBeInTheDocument(); expect(getByText(/working component/i)).toBeInTheDocument(); diff --git a/packages/core-components/src/layout/Sidebar/Intro.tsx b/packages/core-components/src/layout/Sidebar/Intro.tsx index 1d46239865..14c5d9e25a 100644 --- a/packages/core-components/src/layout/Sidebar/Intro.tsx +++ b/packages/core-components/src/layout/Sidebar/Intro.tsx @@ -133,10 +133,8 @@ export const SidebarIntro = () => { starredItemsDismissed: false, recentlyViewedItemsDismissed: false, }; - const [ - dismissedIntro, - setDismissedIntro, - ] = useLocalStorage(SIDEBAR_INTRO_LOCAL_STORAGE); + const [dismissedIntro, setDismissedIntro] = + useLocalStorage(SIDEBAR_INTRO_LOCAL_STORAGE); const { starredItemsDismissed, recentlyViewedItemsDismissed } = dismissedIntro ?? {}; diff --git a/packages/core-plugin-api/api-report.md b/packages/core-plugin-api/api-report.md index da9fec915c..b87e4511d2 100644 --- a/packages/core-plugin-api/api-report.md +++ b/packages/core-plugin-api/api-report.md @@ -58,7 +58,7 @@ export type ApiFactory< Impl extends Api, Deps extends { [name in string]: unknown; - } + }, > = { api: ApiRef; deps: TypesToApiRefs; @@ -86,7 +86,7 @@ export type ApiRef = { export type ApiRefsToTypes< T extends { [key in string]: ApiRef; - } + }, > = { [key in keyof T]: ApiRefType; }; @@ -216,7 +216,7 @@ export type BackstageIdentityApi = { // @public (undocumented) export type BackstagePlugin< Routes extends AnyRoutes = {}, - ExternalRoutes extends AnyExternalRoutes = {} + ExternalRoutes extends AnyExternalRoutes = {}, > = { getId(): string; output(): PluginOutput[]; @@ -253,7 +253,7 @@ export function createApiFactory< Impl extends Api, Deps extends { [name in string]: unknown; - } + }, >(factory: ApiFactory): ApiFactory; // @public (undocumented) @@ -272,7 +272,7 @@ export function createApiRef(config: ApiRefConfig): ApiRef; // // @public (undocumented) export function createComponentExtension< - T extends (props: any) => JSX.Element | null + T extends (props: any) => JSX.Element | null, >(options: { component: ComponentLoader }): Extension; // Warning: (ae-forgotten-export) The symbol "OptionalParams" needs to be exported by the entry point index.d.ts @@ -284,7 +284,7 @@ export function createExternalRouteRef< [param in ParamKey]: string; }, Optional extends boolean = false, - ParamKey extends string = never + ParamKey extends string = never, >(options: { id: string; params?: ParamKey[]; @@ -296,7 +296,7 @@ export function createExternalRouteRef< // @public (undocumented) export function createPlugin< Routes extends AnyRoutes = {}, - ExternalRoutes extends AnyExternalRoutes = {} + ExternalRoutes extends AnyExternalRoutes = {}, >( config: PluginConfig, ): BackstagePlugin; @@ -305,7 +305,7 @@ export function createPlugin< // // @public (undocumented) export function createReactExtension< - T extends (props: any) => JSX.Element | null + T extends (props: any) => JSX.Element | null, >(options: { component: ComponentLoader; data?: Record; @@ -315,7 +315,7 @@ export function createReactExtension< // // @public (undocumented) export function createRoutableExtension< - T extends (props: any) => JSX.Element | null + T extends (props: any) => JSX.Element | null, >(options: { component: () => Promise; mountPoint: RouteRef }): Extension; // Warning: (ae-missing-release-tag) "createRouteRef" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -325,7 +325,7 @@ export function createRouteRef< Params extends { [param in ParamKey]: string; }, - ParamKey extends string = never + ParamKey extends string = never, >(config: { id?: string; params?: ParamKey[]; @@ -342,7 +342,7 @@ export function createRouteRef< // @public (undocumented) export function createSubRouteRef< Path extends string, - ParentParams extends AnyParams = never + ParentParams extends AnyParams = never, >(config: { id: string; path: Path; @@ -369,7 +369,7 @@ export interface ElementCollection { getElements< Props extends { [name: string]: unknown; - } + }, >(): Array>; selectByComponentData(query: { key: string; @@ -421,7 +421,7 @@ export type Extension = { // @public (undocumented) export type ExternalRouteRef< Params extends AnyParams = any, - Optional extends boolean = any + Optional extends boolean = any, > = { readonly [routeRefType]: 'external'; params: ParamKeys; @@ -667,7 +667,7 @@ export type PendingAuthRequest = { // @public (undocumented) export type PluginConfig< Routes extends AnyRoutes, - ExternalRoutes extends AnyExternalRoutes + ExternalRoutes extends AnyExternalRoutes, > = { id: string; apis?: Iterable; @@ -885,9 +885,7 @@ export function useRouteRefParams( // Warning: (ae-missing-release-tag) "withApis" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export function withApis( - apis: TypesToApiRefs, -):

    ( +export function withApis(apis: TypesToApiRefs):

    ( WrappedComponent: React_2.ComponentType

    , ) => { (props: React_2.PropsWithChildren>): JSX.Element; diff --git a/packages/core-plugin-api/src/apis/system/helpers.ts b/packages/core-plugin-api/src/apis/system/helpers.ts index 8e84dd6c09..547d583482 100644 --- a/packages/core-plugin-api/src/apis/system/helpers.ts +++ b/packages/core-plugin-api/src/apis/system/helpers.ts @@ -24,7 +24,7 @@ import { ApiRef, ApiFactory, TypesToApiRefs } from './types'; export function createApiFactory< Api, Impl extends Api, - Deps extends { [name in string]: unknown } + Deps extends { [name in string]: unknown }, >(factory: ApiFactory): ApiFactory; export function createApiFactory( api: ApiRef, @@ -33,7 +33,7 @@ export function createApiFactory( export function createApiFactory< Api, Impl extends Api, - Deps extends { [name in string]: unknown } + Deps extends { [name in string]: unknown }, >( factory: ApiFactory | ApiRef, instance?: Impl, diff --git a/packages/core-plugin-api/src/apis/system/types.ts b/packages/core-plugin-api/src/apis/system/types.ts index e805b6f255..a97d29fdaa 100644 --- a/packages/core-plugin-api/src/apis/system/types.ts +++ b/packages/core-plugin-api/src/apis/system/types.ts @@ -36,7 +36,7 @@ export type ApiHolder = { export type ApiFactory< Api, Impl extends Api, - Deps extends { [name in string]: unknown } + Deps extends { [name in string]: unknown }, > = { api: ApiRef; deps: TypesToApiRefs; diff --git a/packages/core-plugin-api/src/app/useApp.tsx b/packages/core-plugin-api/src/app/useApp.tsx index 1d17fb2d0f..aa323db4e2 100644 --- a/packages/core-plugin-api/src/app/useApp.tsx +++ b/packages/core-plugin-api/src/app/useApp.tsx @@ -18,9 +18,8 @@ import { useVersionedContext } from '../lib/versionedValues'; import { AppContext as AppContextV1 } from './types'; export const useApp = (): AppContextV1 => { - const versionedContext = useVersionedContext<{ 1: AppContextV1 }>( - 'app-context', - ); + const versionedContext = + useVersionedContext<{ 1: AppContextV1 }>('app-context'); const appContext = versionedContext.atVersion(1); if (!appContext) { throw new Error('AppContext v1 not available'); diff --git a/packages/core-plugin-api/src/extensions/extensions.tsx b/packages/core-plugin-api/src/extensions/extensions.tsx index 5142dccc55..73b927afc8 100644 --- a/packages/core-plugin-api/src/extensions/extensions.tsx +++ b/packages/core-plugin-api/src/extensions/extensions.tsx @@ -33,7 +33,7 @@ type ComponentLoader = // ComponentType inserts children as an optional prop whether the inner component accepts it or not, // making it impossible to make the usage of children type safe. export function createRoutableExtension< - T extends (props: any) => JSX.Element | null + T extends (props: any) => JSX.Element | null, >(options: { component: () => Promise; mountPoint: RouteRef; @@ -91,7 +91,7 @@ export function createRoutableExtension< // ComponentType inserts children as an optional prop whether the inner component accepts it or not, // making it impossible to make the usage of children type safe. export function createComponentExtension< - T extends (props: any) => JSX.Element | null + T extends (props: any) => JSX.Element | null, >(options: { component: ComponentLoader }): Extension { const { component } = options; return createReactExtension({ component }); @@ -101,7 +101,7 @@ export function createComponentExtension< // ComponentType inserts children as an optional prop whether the inner component accepts it or not, // making it impossible to make the usage of children type safe. export function createReactExtension< - T extends (props: any) => JSX.Element | null + T extends (props: any) => JSX.Element | null, >(options: { component: ComponentLoader; data?: Record; @@ -111,9 +111,9 @@ export function createReactExtension< let Component: T; if ('lazy' in options.component) { const lazyLoader = options.component.lazy; - Component = (lazy(() => + Component = lazy(() => lazyLoader().then(component => ({ default: component })), - ) as unknown) as T; + ) as unknown as T; } else { Component = options.component.sync; } diff --git a/packages/core-plugin-api/src/lib/versionedValues.ts b/packages/core-plugin-api/src/lib/versionedValues.ts index a7b7d8e3b7..7686842ecd 100644 --- a/packages/core-plugin-api/src/lib/versionedValues.ts +++ b/packages/core-plugin-api/src/lib/versionedValues.ts @@ -32,7 +32,7 @@ export type VersionedValue = { * Creates a container for a map of versioned values that implements VersionedValue. */ export function createVersionedValueMap< - Versions extends { [version: number]: any } + Versions extends { [version: number]: any }, >(versions: Versions): VersionedValue { Object.freeze(versions); return { @@ -43,7 +43,7 @@ export function createVersionedValueMap< } export function useVersionedContext< - Versions extends { [version in number]: any } + Versions extends { [version in number]: any }, >(key: string): VersionedValue { const versionedValue = useContext( getGlobalSingleton>>(key), diff --git a/packages/core-plugin-api/src/plugin/Plugin.tsx b/packages/core-plugin-api/src/plugin/Plugin.tsx index abf4bfa35c..53a53b76d0 100644 --- a/packages/core-plugin-api/src/plugin/Plugin.tsx +++ b/packages/core-plugin-api/src/plugin/Plugin.tsx @@ -26,8 +26,9 @@ import { AnyApiFactory } from '../apis'; export class PluginImpl< Routes extends AnyRoutes, - ExternalRoutes extends AnyExternalRoutes -> implements BackstagePlugin { + ExternalRoutes extends AnyExternalRoutes, +> implements BackstagePlugin +{ private storedOutput?: PluginOutput[]; constructor(private readonly config: PluginConfig) {} @@ -81,7 +82,7 @@ export class PluginImpl< export function createPlugin< Routes extends AnyRoutes = {}, - ExternalRoutes extends AnyExternalRoutes = {} + ExternalRoutes extends AnyExternalRoutes = {}, >( config: PluginConfig, ): BackstagePlugin { diff --git a/packages/core-plugin-api/src/plugin/types.ts b/packages/core-plugin-api/src/plugin/types.ts index 23ff4594a5..b3e1043efd 100644 --- a/packages/core-plugin-api/src/plugin/types.ts +++ b/packages/core-plugin-api/src/plugin/types.ts @@ -42,7 +42,7 @@ export type AnyExternalRoutes = { [name: string]: ExternalRouteRef }; export type BackstagePlugin< Routes extends AnyRoutes = {}, - ExternalRoutes extends AnyExternalRoutes = {} + ExternalRoutes extends AnyExternalRoutes = {}, > = { getId(): string; output(): PluginOutput[]; @@ -54,7 +54,7 @@ export type BackstagePlugin< export type PluginConfig< Routes extends AnyRoutes, - ExternalRoutes extends AnyExternalRoutes + ExternalRoutes extends AnyExternalRoutes, > = { id: string; apis?: Iterable; diff --git a/packages/core-plugin-api/src/routing/ExternalRouteRef.ts b/packages/core-plugin-api/src/routing/ExternalRouteRef.ts index 348c78220f..401e34773c 100644 --- a/packages/core-plugin-api/src/routing/ExternalRouteRef.ts +++ b/packages/core-plugin-api/src/routing/ExternalRouteRef.ts @@ -24,8 +24,9 @@ import { export class ExternalRouteRefImpl< Params extends AnyParams, - Optional extends boolean -> implements ExternalRouteRef { + Optional extends boolean, +> implements ExternalRouteRef +{ readonly [routeRefType] = 'external'; constructor( @@ -42,7 +43,7 @@ export class ExternalRouteRefImpl< export function createExternalRouteRef< Params extends { [param in ParamKey]: string }, Optional extends boolean = false, - ParamKey extends string = never + ParamKey extends string = never, >(options: { /** * An identifier for this route, used to identify it in error messages diff --git a/packages/core-plugin-api/src/routing/RouteRef.ts b/packages/core-plugin-api/src/routing/RouteRef.ts index 0239b57c25..31dd9ef518 100644 --- a/packages/core-plugin-api/src/routing/RouteRef.ts +++ b/packages/core-plugin-api/src/routing/RouteRef.ts @@ -32,7 +32,8 @@ export type RouteRefConfig = { }; export class RouteRefImpl - implements RouteRef { + implements RouteRef +{ readonly [routeRefType] = 'absolute'; constructor( @@ -70,7 +71,7 @@ export function createRouteRef< // ParamKey is here to make sure the Params type properly has its keys narrowed down // to only the elements of params. Defaulting to never makes sure we end up with // Param = {} if the params array is empty. - ParamKey extends string = never + ParamKey extends string = never, >(config: { /** The id of the route ref, used to identify it when printed */ id?: string; diff --git a/packages/core-plugin-api/src/routing/SubRouteRef.ts b/packages/core-plugin-api/src/routing/SubRouteRef.ts index f7e5cf0bc5..6b329dfd42 100644 --- a/packages/core-plugin-api/src/routing/SubRouteRef.ts +++ b/packages/core-plugin-api/src/routing/SubRouteRef.ts @@ -27,7 +27,8 @@ import { const PARAM_PATTERN = /^\w+$/; export class SubRouteRefImpl - implements SubRouteRef { + implements SubRouteRef +{ readonly [routeRefType] = 'sub'; constructor( @@ -55,7 +56,7 @@ type PathParams = { [name in ParamNames]: string }; */ type MergeParams< P1 extends { [param in string]: string }, - P2 extends AnyParams + P2 extends AnyParams, > = (P1[keyof P1] extends never ? {} : P1) & (P2 extends undefined ? {} : P2); /** @@ -64,14 +65,14 @@ type MergeParams< */ type MakeSubRouteRef< Params extends { [param in string]: string }, - ParentParams extends AnyParams + ParentParams extends AnyParams, > = keyof Params & keyof ParentParams extends never ? SubRouteRef>> : never; export function createSubRouteRef< Path extends string, - ParentParams extends AnyParams = never + ParentParams extends AnyParams = never, >(config: { id: string; path: Path; diff --git a/packages/core-plugin-api/src/routing/types.ts b/packages/core-plugin-api/src/routing/types.ts index 9ea1e3ff0d..5afcc72265 100644 --- a/packages/core-plugin-api/src/routing/types.ts +++ b/packages/core-plugin-api/src/routing/types.ts @@ -21,9 +21,8 @@ export type AnyParams = { [param in string]: string } | undefined; export type ParamKeys = keyof Params extends never ? [] : (keyof Params)[]; -export type OptionalParams< - Params extends { [param in string]: string } -> = Params[keyof Params] extends never ? undefined : Params; +export type OptionalParams = + Params[keyof Params] extends never ? undefined : Params; // The extra TS magic here is to require a single params argument if the RouteRef // had at least one param defined, but require 0 arguments if there are no params defined. @@ -65,7 +64,7 @@ export type SubRouteRef = { export type ExternalRouteRef< Params extends AnyParams = any, - Optional extends boolean = any + Optional extends boolean = any, > = { readonly [routeRefType]: 'external'; diff --git a/packages/core-plugin-api/src/routing/useRouteRef.tsx b/packages/core-plugin-api/src/routing/useRouteRef.tsx index 4447759b99..ed261489a4 100644 --- a/packages/core-plugin-api/src/routing/useRouteRef.tsx +++ b/packages/core-plugin-api/src/routing/useRouteRef.tsx @@ -48,9 +48,8 @@ export function useRouteRef( | ExternalRouteRef, ): RouteFunc | undefined { const sourceLocation = useLocation(); - const versionedContext = useVersionedContext<{ 1: RouteResolver }>( - 'routing-context', - ); + const versionedContext = + useVersionedContext<{ 1: RouteResolver }>('routing-context'); const resolver = versionedContext.atVersion(1); const routeFunc = useMemo( () => resolver && resolver.resolve(routeRef, sourceLocation), diff --git a/packages/dev-utils/src/devApp/render.tsx b/packages/dev-utils/src/devApp/render.tsx index e6338cd467..661a93e8b0 100644 --- a/packages/dev-utils/src/devApp/render.tsx +++ b/packages/dev-utils/src/devApp/render.tsx @@ -96,7 +96,7 @@ class DevAppBuilder { registerApi< Api, Impl extends Api, - Deps extends { [name in string]: unknown } + Deps extends { [name in string]: unknown }, >(factory: ApiFactory): DevAppBuilder { this.apis.push(factory); return this; diff --git a/packages/docgen/src/docgen/ApiDocGenerator.test.ts b/packages/docgen/src/docgen/ApiDocGenerator.test.ts index 2d6598b925..ea053b1ef4 100644 --- a/packages/docgen/src/docgen/ApiDocGenerator.test.ts +++ b/packages/docgen/src/docgen/ApiDocGenerator.test.ts @@ -186,8 +186,7 @@ describe('ApiDocGenerator', () => { type: 'method', name: 'z', path: 'MyApiType.z', - text: - 'z(a: Promise): Array', + text: 'z(a: Promise): Array', docs: ['Multiple', 'JsDoc', 'Comments'], links: [ { diff --git a/packages/docgen/src/docgen/ApiDocGenerator.ts b/packages/docgen/src/docgen/ApiDocGenerator.ts index 3199b2ddf3..32216745a2 100644 --- a/packages/docgen/src/docgen/ApiDocGenerator.ts +++ b/packages/docgen/src/docgen/ApiDocGenerator.ts @@ -127,9 +127,9 @@ export default class ApiDocGenerator { ); const docs = this.getNodeDocs(declaration); - const membersAndTypes = Array.from( - interfaceMembers.values(), - ).flatMap(fieldSymbol => this.getMemberInfo(name, fieldSymbol)); + const membersAndTypes = Array.from(interfaceMembers.values()).flatMap( + fieldSymbol => this.getMemberInfo(name, fieldSymbol), + ); const members = membersAndTypes.map(t => t.member); const dependentTypes = this.flattenTypes( @@ -174,9 +174,8 @@ export default class ApiDocGenerator { ): { member: FieldInfo; dependentTypes: TypeInfo[] } { const declaration = symbol.valueDeclaration; - const { links, infos: dependentTypes } = this.findAllTypeReferences( - declaration, - ); + const { links, infos: dependentTypes } = + this.findAllTypeReferences(declaration); let type: FieldInfo['type'] = 'prop'; if ( diff --git a/packages/docgen/src/docgen/TypeLocator.ts b/packages/docgen/src/docgen/TypeLocator.ts index 984724e667..30d240da3d 100644 --- a/packages/docgen/src/docgen/TypeLocator.ts +++ b/packages/docgen/src/docgen/TypeLocator.ts @@ -92,9 +92,7 @@ export default class TypeLocator { return result as { [key in T]: ExportedInstance[] }; } - private getExportedConstructorDeclaration( - node: ts.Node, - ): + private getExportedConstructorDeclaration(node: ts.Node): | { constructorType: ts.Type; args: ts.Expression[]; diff --git a/packages/docgen/src/docgen/TypescriptHighlighter.ts b/packages/docgen/src/docgen/TypescriptHighlighter.ts index a48e17ba66..ab70ea8110 100644 --- a/packages/docgen/src/docgen/TypescriptHighlighter.ts +++ b/packages/docgen/src/docgen/TypescriptHighlighter.ts @@ -78,9 +78,10 @@ export default class TypescriptHighlighter implements Highlighter { // Order here is important, e.g. comments must be first to avoid string literals inside comments being highlighted return TypescriptHighlighter.highlighters - .reduce((parts, highlighter) => parts.flatMap(painter(...highlighter)), [ - { text: fullText }, - ]) + .reduce( + (parts, highlighter) => parts.flatMap(painter(...highlighter)), + [{ text: fullText }], + ) .map(({ text }) => text) .join(''); } diff --git a/packages/e2e-test/src/commands/run.ts b/packages/e2e-test/src/commands/run.ts index 94bb1dd7f5..dde93341ef 100644 --- a/packages/e2e-test/src/commands/run.ts +++ b/packages/e2e-test/src/commands/run.ts @@ -403,14 +403,9 @@ async function testBackendStart(appDir: string, isPostgres: boolean) { if (isPostgres) { print('Dropping old DBs'); await Promise.all( - [ - 'catalog', - 'scaffolder', - 'auth', - 'identity', - 'proxy', - 'techdocs', - ].map(name => dropDB(`backstage_plugin_${name}`)), + ['catalog', 'scaffolder', 'auth', 'identity', 'proxy', 'techdocs'].map( + name => dropDB(`backstage_plugin_${name}`), + ), ); print('Created DBs'); } diff --git a/packages/e2e-test/src/lib/helpers.ts b/packages/e2e-test/src/lib/helpers.ts index 2485e46b31..d0e6de2cff 100644 --- a/packages/e2e-test/src/lib/helpers.ts +++ b/packages/e2e-test/src/lib/helpers.ts @@ -24,7 +24,8 @@ import { promisify } from 'util'; const execFile = promisify(execFileCb); -const EXPECTED_LOAD_ERRORS = /ECONNREFUSED|ECONNRESET|did not get to load all resources/; +const EXPECTED_LOAD_ERRORS = + /ECONNREFUSED|ECONNRESET|did not get to load all resources/; export function spawnPiped(cmd: string[], options?: SpawnOptions) { function pipeWithPrefix(stream: NodeJS.WriteStream, prefix = '') { diff --git a/packages/integration-react/src/api/ScmIntegrationsApi.ts b/packages/integration-react/src/api/ScmIntegrationsApi.ts index 982989540a..6bf2ba8a6d 100644 --- a/packages/integration-react/src/api/ScmIntegrationsApi.ts +++ b/packages/integration-react/src/api/ScmIntegrationsApi.ts @@ -27,9 +27,8 @@ export class ScmIntegrationsApi { } } -export const scmIntegrationsApiRef: ApiRef = createApiRef( - { +export const scmIntegrationsApiRef: ApiRef = + createApiRef({ id: 'integration.scmintegrations', description: 'All of the registered SCM integrations of your config', - }, -); + }); diff --git a/packages/integration/src/azure/AzureIntegration.test.ts b/packages/integration/src/azure/AzureIntegration.test.ts index 654ce47836..80cc68047f 100644 --- a/packages/integration/src/azure/AzureIntegration.test.ts +++ b/packages/integration/src/azure/AzureIntegration.test.ts @@ -51,8 +51,7 @@ describe('AzureIntegration', () => { expect( integration.resolveUrl({ url: '../a.yaml', - base: - 'https://dev.azure.com/organization/project/_git/repository?path=%2Ffolder%2Fcatalog-info.yaml', + base: 'https://dev.azure.com/organization/project/_git/repository?path=%2Ffolder%2Fcatalog-info.yaml', }), ).toBe( 'https://dev.azure.com/organization/project/_git/repository?path=%2Fa.yaml', @@ -61,8 +60,7 @@ describe('AzureIntegration', () => { expect( integration.resolveUrl({ url: '/a.yaml', - base: - 'https://dev.azure.com/organization/project/_git/repository?path=%2Ffolder%2Fcatalog-info.yaml', + base: 'https://dev.azure.com/organization/project/_git/repository?path=%2Ffolder%2Fcatalog-info.yaml', lineNumber: 14, }), ).toBe( @@ -81,8 +79,7 @@ describe('AzureIntegration', () => { expect( integration.resolveUrl({ url: 'https://absolute.com/path', - base: - 'https://dev.azure.com/organization/project/_git/repository?path=%2Fcatalog-info.yaml', + base: 'https://dev.azure.com/organization/project/_git/repository?path=%2Fcatalog-info.yaml', }), ).toBe('https://absolute.com/path'); }); diff --git a/packages/integration/src/azure/core.test.ts b/packages/integration/src/azure/core.test.ts index ab5a4bc700..9937008b61 100644 --- a/packages/integration/src/azure/core.test.ts +++ b/packages/integration/src/azure/core.test.ts @@ -43,26 +43,22 @@ describe('azure core', () => { describe('getAzureFileFetchUrl', () => { it.each([ { - url: - 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml&version=GBmaster', + url: 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml&version=GBmaster', result: 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml&version=master', }, { - url: - 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml', + url: 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml', result: 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml', }, { - url: - 'https://api.com/org-name/project-name/_git/repo-name?path=my-template.yaml', + url: 'https://api.com/org-name/project-name/_git/repo-name?path=my-template.yaml', result: 'https://api.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml', }, { - url: - 'https://api.com/org-name/project-name/_git/repo-name?path=my-template.yaml&version=GBmaster', + url: 'https://api.com/org-name/project-name/_git/repo-name?path=my-template.yaml&version=GBmaster', result: 'https://api.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml&version=master', }, diff --git a/packages/integration/src/azure/core.ts b/packages/integration/src/azure/core.ts index 5aacc09700..18de5aa1d2 100644 --- a/packages/integration/src/azure/core.ts +++ b/packages/integration/src/azure/core.ts @@ -31,13 +31,8 @@ export function getAzureFileFetchUrl(url: string): string { try { const parsedUrl = new URL(url); - const [ - empty, - userOrOrg, - project, - srcKeyword, - repoName, - ] = parsedUrl.pathname.split('/'); + const [empty, userOrOrg, project, srcKeyword, repoName] = + parsedUrl.pathname.split('/'); const path = parsedUrl.searchParams.get('path') || ''; const ref = parsedUrl.searchParams.get('version')?.substr(2); @@ -117,13 +112,8 @@ export function getAzureCommitsUrl(url: string): string { try { const parsedUrl = new URL(url); - const [ - empty, - userOrOrg, - project, - srcKeyword, - repoName, - ] = parsedUrl.pathname.split('/'); + const [empty, userOrOrg, project, srcKeyword, repoName] = + parsedUrl.pathname.split('/'); // Remove the "GB" from "GBmain" for example. const ref = parsedUrl.searchParams.get('version')?.substr(2); diff --git a/packages/integration/src/github/GitHubIntegration.test.ts b/packages/integration/src/github/GitHubIntegration.test.ts index 416618e53b..efc1de782e 100644 --- a/packages/integration/src/github/GitHubIntegration.test.ts +++ b/packages/integration/src/github/GitHubIntegration.test.ts @@ -56,8 +56,7 @@ describe('GitHubIntegration', () => { expect( integration.resolveUrl({ url: '../a.yaml', - base: - 'https://github.com/backstage/backstage/blob/master/test/README.md', + base: 'https://github.com/backstage/backstage/blob/master/test/README.md', lineNumber: 17, }), ).toBe('https://github.com/backstage/backstage/tree/master/a.yaml#L17'); @@ -65,8 +64,7 @@ describe('GitHubIntegration', () => { expect( integration.resolveUrl({ url: './', - base: - 'https://github.com/backstage/backstage/blob/master/test/README.md', + base: 'https://github.com/backstage/backstage/blob/master/test/README.md', }), ).toBe('https://github.com/backstage/backstage/tree/master/test/'); }); diff --git a/packages/integration/src/github/GithubCredentialsProvider.test.ts b/packages/integration/src/github/GithubCredentialsProvider.test.ts index 47678ddb89..f698c01bdb 100644 --- a/packages/integration/src/github/GithubCredentialsProvider.test.ts +++ b/packages/integration/src/github/GithubCredentialsProvider.test.ts @@ -232,9 +232,9 @@ describe('GithubCredentialsProvider tests', () => { ], token: 'hardcoded_token', }); - octokit.apps.listInstallations.mockResolvedValue(({ + octokit.apps.listInstallations.mockResolvedValue({ data: [], - } as unknown) as RestEndpointMethodTypes['apps']['listInstallations']['response']); + } as unknown as RestEndpointMethodTypes['apps']['listInstallations']['response']); await expect( githubProvider.getCredentials({ diff --git a/packages/integration/src/github/GithubCredentialsProvider.ts b/packages/integration/src/github/GithubCredentialsProvider.ts index ba30900358..1de19693b5 100644 --- a/packages/integration/src/github/GithubCredentialsProvider.ts +++ b/packages/integration/src/github/GithubCredentialsProvider.ts @@ -85,11 +85,8 @@ class GithubAppManager { owner: string, repo?: string, ): Promise<{ accessToken: string }> { - const { - installationId, - suspended, - repositorySelection, - } = await this.getInstallationData(owner); + const { installationId, suspended, repositorySelection } = + await this.getInstallationData(owner); if (suspended) { throw new Error( `The GitHub application for ${[owner, repo] diff --git a/packages/integration/src/gitlab/core.test.ts b/packages/integration/src/gitlab/core.test.ts index 574403d70b..f07d65e02a 100644 --- a/packages/integration/src/gitlab/core.test.ts +++ b/packages/integration/src/gitlab/core.test.ts @@ -52,37 +52,32 @@ describe('gitlab core', () => { // Project URLs { config: configWithNoToken, - url: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', + url: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', result: 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', }, { config: configWithNoToken, // Works with non URI encoded link - url: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file with spaces.yaml', + url: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file with spaces.yaml', result: 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile%20with%20spaces.yaml/raw?ref=branch', }, { config: configWithNoToken, - url: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path%20with%20spaces/to/file.yaml', + url: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path%20with%20spaces/to/file.yaml', result: 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%20with%20spaces%2Fto%2Ffile.yaml/raw?ref=branch', }, { config: configWithToken, - url: - 'https://gitlab.example.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path%20with%20spaces/to/file.yaml', + url: 'https://gitlab.example.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path%20with%20spaces/to/file.yaml', result: 'https://gitlab.example.com/api/v4/projects/12345/repository/files/my%2Fpath%20with%20spaces%2Fto%2Ffile.yaml/raw?ref=branch', }, { config: configWithNoToken, - url: - 'https://gitlab.com/groupA/teams/teamA/repoA/-/blob/branch/my/path%20with%20spaces/to/file.yaml', // Repo not in subgroup + url: 'https://gitlab.com/groupA/teams/teamA/repoA/-/blob/branch/my/path%20with%20spaces/to/file.yaml', // Repo not in subgroup result: 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%20with%20spaces%2Fto%2Ffile.yaml/raw?ref=branch', }, diff --git a/packages/integration/src/gitlab/core.ts b/packages/integration/src/gitlab/core.ts index 9b7b928059..83ab29c62e 100644 --- a/packages/integration/src/gitlab/core.ts +++ b/packages/integration/src/gitlab/core.ts @@ -68,13 +68,8 @@ export function buildRawUrl(target: string): URL { try { const url = new URL(target); - const [ - empty, - userOrOrg, - repoName, - blobKeyword, - ...restOfPath - ] = url.pathname.split('/'); + const [empty, userOrOrg, repoName, blobKeyword, ...restOfPath] = + url.pathname.split('/'); if ( empty !== '' || diff --git a/packages/integration/src/helpers.test.ts b/packages/integration/src/helpers.test.ts index 90102ce6aa..13e8694c73 100644 --- a/packages/integration/src/helpers.test.ts +++ b/packages/integration/src/helpers.test.ts @@ -57,8 +57,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: './b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', }), ).toBe( 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/b.yaml', @@ -67,8 +66,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: './b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', }), ).toBe( 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/b.yaml?at=master', @@ -77,8 +75,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: 'b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', }), ).toBe( 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/b.yaml', @@ -89,8 +86,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: '/other/b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', }), ).toBe( 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/other/b.yaml', @@ -99,8 +95,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: '/other/b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', }), ).toBe( 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/other/b.yaml?at=master', @@ -111,8 +106,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: './b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', lineNumber: 11, }), ).toBe( @@ -122,8 +116,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: 'b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', lineNumber: 12, }), ).toBe( @@ -133,8 +126,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: '/other/b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml', lineNumber: 13, }), ).toBe( @@ -144,8 +136,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: '/other/b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', lineNumber: 14, }), ).toBe( @@ -157,8 +148,7 @@ describe('defaultScmResolveUrl', () => { expect( defaultScmResolveUrl({ url: 'https://b.com/b.yaml', - base: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', + base: 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/folder/a.yaml?at=master', }), ).toBe('https://b.com/b.yaml'); }); diff --git a/packages/techdocs-common/src/stages/publish/googleStorage.ts b/packages/techdocs-common/src/stages/publish/googleStorage.ts index 9def24722a..cbf76cd3d7 100644 --- a/packages/techdocs-common/src/stages/publish/googleStorage.ts +++ b/packages/techdocs-common/src/stages/publish/googleStorage.ts @@ -176,9 +176,8 @@ export class GoogleGCSPublish implements PublisherBase { fileStreamChunks.push(chunk); }) .on('end', () => { - const techdocsMetadataJson = Buffer.concat(fileStreamChunks).toString( - 'utf-8', - ); + const techdocsMetadataJson = + Buffer.concat(fileStreamChunks).toString('utf-8'); resolve(JSON5.parse(techdocsMetadataJson)); }); }); diff --git a/packages/test-utils/src/testUtils/appWrappers.tsx b/packages/test-utils/src/testUtils/appWrappers.tsx index b884efd00d..09c9e5d0bf 100644 --- a/packages/test-utils/src/testUtils/appWrappers.tsx +++ b/packages/test-utils/src/testUtils/appWrappers.tsx @@ -92,7 +92,7 @@ export function wrapInTestApp( apis: mockApis, // Bit of a hack to make sure that the default config loader isn't used // as that would force every single test to wait for config loading. - configLoader: (false as unknown) as undefined, + configLoader: false as unknown as undefined, components: { Progress, BootErrorPage, diff --git a/plugins/api-docs/dev/index.tsx b/plugins/api-docs/dev/index.tsx index bbbfe4a516..e60647e7b9 100644 --- a/plugins/api-docs/dev/index.tsx +++ b/plugins/api-docs/dev/index.tsx @@ -30,19 +30,19 @@ import openapiApiEntity from './openapi-example-api.yaml'; import otherApiEntity from './other-example-api.yaml'; import { Content, Header, Page } from '@backstage/core-components'; -const mockEntities = ([ +const mockEntities = [ openapiApiEntity, asyncapiApiEntity, graphqlApiEntity, otherApiEntity, -] as unknown) as Entity[]; +] as unknown as Entity[]; createDevApp() .registerApi({ api: catalogApiRef, deps: {}, factory: () => - (({ + ({ async getEntities() { return { items: mockEntities.slice(), @@ -51,7 +51,7 @@ createDevApp() async getEntityByName(name: string) { return mockEntities.find(e => e.metadata.name === name); }, - } as unknown) as typeof catalogApiRef.T), + } as unknown as typeof catalogApiRef.T), }) .registerApi({ api: apiDocsConfigRef, @@ -72,7 +72,7 @@ createDevApp()

    - + @@ -85,7 +85,7 @@ createDevApp()
    - + @@ -98,7 +98,7 @@ createDevApp()
    - + @@ -111,7 +111,7 @@ createDevApp()
    - + diff --git a/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinitionWidget.tsx b/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinitionWidget.tsx index 0b8462ed6e..f32b5d01b5 100644 --- a/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinitionWidget.tsx +++ b/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinitionWidget.tsx @@ -88,13 +88,15 @@ const useStyles = makeStyles(theme => ({ '& .asyncapi__enum': { color: theme.palette.secondary.main, }, - '& .asyncapi__info, .asyncapi__channel, .asyncapi__channels > div, .asyncapi__schema, .asyncapi__channel-operations-list .asyncapi__messages-list-item .asyncapi__message, .asyncapi__message, .asyncapi__server, .asyncapi__servers > div, .asyncapi__messages > div, .asyncapi__schemas > div': { - 'background-color': 'inherit', - }, - '& .asyncapi__channel-parameters-header, .asyncapi__channel-operations-header, .asyncapi__channel-operation-oneOf-subscribe-header, .asyncapi__channel-operation-oneOf-publish-header, .asyncapi__channel-operation-message-header, .asyncapi__message-header, .asyncapi__message-header-title, .asyncapi__message-header-title > h3, .asyncapi__bindings, .asyncapi__bindings-header, .asyncapi__bindings-header > h4': { - 'background-color': 'inherit', - color: theme.palette.text.primary, - }, + '& .asyncapi__info, .asyncapi__channel, .asyncapi__channels > div, .asyncapi__schema, .asyncapi__channel-operations-list .asyncapi__messages-list-item .asyncapi__message, .asyncapi__message, .asyncapi__server, .asyncapi__servers > div, .asyncapi__messages > div, .asyncapi__schemas > div': + { + 'background-color': 'inherit', + }, + '& .asyncapi__channel-parameters-header, .asyncapi__channel-operations-header, .asyncapi__channel-operation-oneOf-subscribe-header, .asyncapi__channel-operation-oneOf-publish-header, .asyncapi__channel-operation-message-header, .asyncapi__message-header, .asyncapi__message-header-title, .asyncapi__message-header-title > h3, .asyncapi__bindings, .asyncapi__bindings-header, .asyncapi__bindings-header > h4': + { + 'background-color': 'inherit', + color: theme.palette.text.primary, + }, '& .asyncapi__additional-properties-notice': { color: theme.palette.text.hint, }, @@ -104,10 +106,11 @@ const useStyles = makeStyles(theme => ({ '& .asyncapi__schema-example-header-title': { color: theme.palette.text.secondary, }, - '& .asyncapi__message-headers-header, .asyncapi__message-payload-header, .asyncapi__server-variables-header, .asyncapi__server-security-header': { - 'background-color': 'inherit', - color: theme.palette.text.secondary, - }, + '& .asyncapi__message-headers-header, .asyncapi__message-payload-header, .asyncapi__server-variables-header, .asyncapi__server-security-header': + { + 'background-color': 'inherit', + color: theme.palette.text.secondary, + }, '& .asyncapi__table-header': { background: theme.palette.background.default, }, diff --git a/plugins/api-docs/src/components/OpenApiDefinitionWidget/OpenApiDefinitionWidget.tsx b/plugins/api-docs/src/components/OpenApiDefinitionWidget/OpenApiDefinitionWidget.tsx index 206294f931..4c22d29bc2 100644 --- a/plugins/api-docs/src/components/OpenApiDefinitionWidget/OpenApiDefinitionWidget.tsx +++ b/plugins/api-docs/src/components/OpenApiDefinitionWidget/OpenApiDefinitionWidget.tsx @@ -30,22 +30,26 @@ const useStyles = makeStyles(theme => ({ '& .scheme-container': { 'background-color': theme.palette.background.default, }, - '& .opblock-tag, .opblock-tag small, table thead tr td, table thead tr th': { - color: theme.palette.text.primary, - 'border-color': theme.palette.divider, - }, + '& .opblock-tag, .opblock-tag small, table thead tr td, table thead tr th': + { + color: theme.palette.text.primary, + 'border-color': theme.palette.divider, + }, '& section.models, section.models.is-open h4': { 'border-color': theme.palette.divider, }, - '& .opblock .opblock-summary-description, .parameter__type, table.headers td, .model-title, .model .property.primitive, section h3': { - color: theme.palette.text.secondary, - }, - '& .opblock .opblock-summary-operation-id, .opblock .opblock-summary-path, .opblock .opblock-summary-path__deprecated, .opblock .opblock-section-header h4, .parameter__name, .response-col_status, .response-col_links, .responses-inner h4, .swagger-ui .responses-inner h5, .opblock-section-header .btn, .tab li, .info li, .info p, .info table, section.models h4, .info .title, table.model tr.description, .property-row': { - color: theme.palette.text.primary, - }, - '& .opblock .opblock-section-header, .model-box, section.models .model-container': { - background: theme.palette.background.default, - }, + '& .opblock .opblock-summary-description, .parameter__type, table.headers td, .model-title, .model .property.primitive, section h3': + { + color: theme.palette.text.secondary, + }, + '& .opblock .opblock-summary-operation-id, .opblock .opblock-summary-path, .opblock .opblock-summary-path__deprecated, .opblock .opblock-section-header h4, .parameter__name, .response-col_status, .response-col_links, .responses-inner h4, .swagger-ui .responses-inner h5, .opblock-section-header .btn, .tab li, .info li, .info p, .info table, section.models h4, .info .title, table.model tr.description, .property-row': + { + color: theme.palette.text.primary, + }, + '& .opblock .opblock-section-header, .model-box, section.models .model-container': + { + background: theme.palette.background.default, + }, '& .prop-format, .parameter__in': { color: theme.palette.text.disabled, }, @@ -53,9 +57,10 @@ const useStyles = makeStyles(theme => ({ color: theme.palette.text.primary, 'border-color': theme.palette.divider, }, - '& .opblock-description-wrapper p, .opblock-external-docs-wrapper p, .opblock-title_normal p, .response-control-media-type__accept-message, .opblock .opblock-section-header>label, .scheme-container .schemes>label, .info .base-url, .model': { - color: theme.palette.text.hint, - }, + '& .opblock-description-wrapper p, .opblock-external-docs-wrapper p, .opblock-title_normal p, .response-control-media-type__accept-message, .opblock .opblock-section-header>label, .scheme-container .schemes>label, .info .base-url, .model': + { + color: theme.palette.text.hint, + }, '& .parameter__name.required:after': { color: theme.palette.warning.dark, }, diff --git a/plugins/app-backend/src/lib/config.test.ts b/plugins/app-backend/src/lib/config.test.ts index 1d5739e711..f36052116a 100644 --- a/plugins/app-backend/src/lib/config.test.ts +++ b/plugins/app-backend/src/lib/config.test.ts @@ -22,7 +22,7 @@ import { injectConfig } from './config'; jest.mock('fs-extra'); const fsMock = fs as jest.Mocked; -const readFileMock = (fsMock.readFile as unknown) as jest.MockedFunction< +const readFileMock = fsMock.readFile as unknown as jest.MockedFunction< (name: string) => Promise >; diff --git a/plugins/app-backend/src/service/router.ts b/plugins/app-backend/src/service/router.ts index 681b6335fe..297029dffc 100644 --- a/plugins/app-backend/src/service/router.ts +++ b/plugins/app-backend/src/service/router.ts @@ -104,8 +104,7 @@ export async function createRouter( // The Cache-Control header instructs the browser to not cache html files since it might // link to static assets from recently deployed versions. if ( - ((express.static.mime as unknown) as Mime).lookup(path) === - 'text/html' + (express.static.mime as unknown as Mime).lookup(path) === 'text/html' ) { res.setHeader('Cache-Control', 'no-store, max-age=0'); } diff --git a/plugins/auth-backend/api-report.md b/plugins/auth-backend/api-report.md index 1ada822262..9fb9e29a4a 100644 --- a/plugins/auth-backend/api-report.md +++ b/plugins/auth-backend/api-report.md @@ -223,9 +223,7 @@ export class OAuthEnvironmentHandler implements AuthProviderRouteHandlers { export interface OAuthHandlers { // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - handler( - req: express.Request, - ): Promise<{ + handler(req: express.Request): Promise<{ response: AuthResponse; refreshToken?: string; }>; diff --git a/plugins/auth-backend/src/identity/TokenFactory.ts b/plugins/auth-backend/src/identity/TokenFactory.ts index ae7c674a58..041a292d44 100644 --- a/plugins/auth-backend/src/identity/TokenFactory.ts +++ b/plugins/auth-backend/src/identity/TokenFactory.ts @@ -150,7 +150,7 @@ export class TokenFactory implements TokenIssuer { // the new one. This also needs to be implemented cross-service though, meaning new services // that boot up need to be able to grab an existing key to use for signing. this.logger.info(`Created new signing key ${key.kid}`); - await this.keyStore.addKey((key.toJWK(false) as unknown) as AnyJWK); + await this.keyStore.addKey(key.toJWK(false) as unknown as AnyJWK); // At this point we are allowed to start using the new key return key as JSONWebKey; diff --git a/plugins/auth-backend/src/lib/flow/authFlowHelpers.test.ts b/plugins/auth-backend/src/lib/flow/authFlowHelpers.test.ts index 5446fbd437..117f1b86e4 100644 --- a/plugins/auth-backend/src/lib/flow/authFlowHelpers.test.ts +++ b/plugins/auth-backend/src/lib/flow/authFlowHelpers.test.ts @@ -32,10 +32,10 @@ describe('oauth helpers', () => { describe('postMessageResponse', () => { const appOrigin = 'http://localhost:3000'; it('should post a message back with payload success', () => { - const mockResponse = ({ + const mockResponse = { end: jest.fn().mockReturnThis(), setHeader: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; const data: WebMessageResponse = { type: 'authorization_response', @@ -64,10 +64,10 @@ describe('oauth helpers', () => { }); it('should post a message back with payload error', () => { - const mockResponse = ({ + const mockResponse = { end: jest.fn().mockReturnThis(), setHeader: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; const data: WebMessageResponse = { type: 'authorization_response', @@ -84,13 +84,13 @@ describe('oauth helpers', () => { it('should call postMessage twice but only one of them with target *', () => { let responseBody = ''; - const mockResponse = ({ + const mockResponse = { end: jest.fn(body => { responseBody = body; return this; }), setHeader: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; const data: WebMessageResponse = { type: 'authorization_response', @@ -128,10 +128,10 @@ describe('oauth helpers', () => { }); it('handles single quotes and unicode chars safely', () => { - const mockResponse = ({ + const mockResponse = { end: jest.fn().mockReturnThis(), setHeader: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; const data: WebMessageResponse = { type: 'authorization_response', @@ -164,23 +164,23 @@ describe('oauth helpers', () => { describe('ensuresXRequestedWith', () => { it('should return false if no header present', () => { - const mockRequest = ({ + const mockRequest = { header: () => jest.fn(), - } as unknown) as express.Request; + } as unknown as express.Request; expect(ensuresXRequestedWith(mockRequest)).toBe(false); }); it('should return false if header present with incorrect value', () => { - const mockRequest = ({ + const mockRequest = { header: () => 'INVALID', - } as unknown) as express.Request; + } as unknown as express.Request; expect(ensuresXRequestedWith(mockRequest)).toBe(false); }); it('should return true if header present with correct value', () => { - const mockRequest = ({ + const mockRequest = { header: () => 'XMLHttpRequest', - } as unknown) as express.Request; + } as unknown as express.Request; expect(ensuresXRequestedWith(mockRequest)).toBe(true); }); }); diff --git a/plugins/auth-backend/src/lib/oauth/OAuthAdapter.test.ts b/plugins/auth-backend/src/lib/oauth/OAuthAdapter.test.ts index 147cf5216f..0b35ea7bc8 100644 --- a/plugins/auth-backend/src/lib/oauth/OAuthAdapter.test.ts +++ b/plugins/auth-backend/src/lib/oauth/OAuthAdapter.test.ts @@ -71,19 +71,19 @@ describe('OAuthAdapter', () => { providerInstance, oAuthProviderOptions, ); - const mockRequest = ({ + const mockRequest = { query: { scope: 'user', env: 'development', }, - } as unknown) as express.Request; + } as unknown as express.Request; - const mockResponse = ({ + const mockResponse = { cookie: jest.fn().mockReturnThis(), end: jest.fn().mockReturnThis(), setHeader: jest.fn().mockReturnThis(), statusCode: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; await oauthProvider.start(mockRequest, mockResponse); // nonce cookie checks @@ -108,20 +108,20 @@ describe('OAuthAdapter', () => { }); const state = { nonce: 'nonce', env: 'development' }; - const mockRequest = ({ + const mockRequest = { cookies: { 'test-provider-nonce': 'nonce', }, query: { state: encodeState(state), }, - } as unknown) as express.Request; + } as unknown as express.Request; - const mockResponse = ({ + const mockResponse = { cookie: jest.fn().mockReturnThis(), setHeader: jest.fn().mockReturnThis(), end: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; await oauthProvider.frameHandler(mockRequest, mockResponse); expect(mockResponse.cookie).toHaveBeenCalledTimes(1); @@ -141,20 +141,20 @@ describe('OAuthAdapter', () => { disableRefresh: true, }); - const mockRequest = ({ + const mockRequest = { cookies: { 'test-provider-nonce': 'nonce', }, query: { state: 'nonce', }, - } as unknown) as express.Request; + } as unknown as express.Request; - const mockResponse = ({ + const mockResponse = { cookie: jest.fn().mockReturnThis(), setHeader: jest.fn().mockReturnThis(), end: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; await oauthProvider.frameHandler(mockRequest, mockResponse); expect(mockResponse.cookie).toHaveBeenCalledTimes(0); @@ -166,15 +166,15 @@ describe('OAuthAdapter', () => { disableRefresh: false, }); - const mockRequest = ({ + const mockRequest = { header: () => 'XMLHttpRequest', - } as unknown) as express.Request; + } as unknown as express.Request; - const mockResponse = ({ + const mockResponse = { cookie: jest.fn().mockReturnThis(), send: jest.fn().mockReturnThis(), status: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; await oauthProvider.logout(mockRequest, mockResponse); expect(mockResponse.cookie).toHaveBeenCalledTimes(1); @@ -192,18 +192,18 @@ describe('OAuthAdapter', () => { disableRefresh: false, }); - const mockRequest = ({ + const mockRequest = { header: () => 'XMLHttpRequest', cookies: { 'test-provider-refresh-token': 'token', }, query: {}, - } as unknown) as express.Request; + } as unknown as express.Request; - const mockResponse = ({ + const mockResponse = { json: jest.fn().mockReturnThis(), status: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; await oauthProvider.refresh(mockRequest, mockResponse); expect(mockResponse.json).toHaveBeenCalledTimes(1); @@ -222,18 +222,18 @@ describe('OAuthAdapter', () => { disableRefresh: true, }); - const mockRequest = ({ + const mockRequest = { header: () => 'XMLHttpRequest', cookies: { 'test-provider-refresh-token': 'token', }, query: {}, - } as unknown) as express.Request; + } as unknown as express.Request; - const mockResponse = ({ + const mockResponse = { send: jest.fn().mockReturnThis(), status: jest.fn().mockReturnThis(), - } as unknown) as express.Response; + } as unknown as express.Response; await oauthProvider.refresh(mockRequest, mockResponse); expect(mockResponse.send).toHaveBeenCalledTimes(1); diff --git a/plugins/auth-backend/src/lib/oauth/helpers.test.ts b/plugins/auth-backend/src/lib/oauth/helpers.test.ts index 3ef8d74c13..00161ff8cf 100644 --- a/plugins/auth-backend/src/lib/oauth/helpers.test.ts +++ b/plugins/auth-backend/src/lib/oauth/helpers.test.ts @@ -21,24 +21,24 @@ describe('OAuthProvider Utils', () => { describe('verifyNonce', () => { it('should throw error if cookie nonce missing', () => { const state = { nonce: 'NONCE', env: 'development' }; - const mockRequest = ({ + const mockRequest = { cookies: {}, query: { state: encodeState(state), }, - } as unknown) as express.Request; + } as unknown as express.Request; expect(() => { verifyNonce(mockRequest, 'providera'); }).toThrowError('Auth response is missing cookie nonce'); }); it('should throw error if state nonce missing', () => { - const mockRequest = ({ + const mockRequest = { cookies: { 'providera-nonce': 'NONCE', }, query: {}, - } as unknown) as express.Request; + } as unknown as express.Request; expect(() => { verifyNonce(mockRequest, 'providera'); }).toThrowError('Invalid state passed via request'); @@ -46,14 +46,14 @@ describe('OAuthProvider Utils', () => { it('should throw error if nonce mismatch', () => { const state = { nonce: 'NONCEB', env: 'development' }; - const mockRequest = ({ + const mockRequest = { cookies: { 'providera-nonce': 'NONCEA', }, query: { state: encodeState(state), }, - } as unknown) as express.Request; + } as unknown as express.Request; expect(() => { verifyNonce(mockRequest, 'providera'); }).toThrowError('Invalid nonce'); @@ -61,14 +61,14 @@ describe('OAuthProvider Utils', () => { it('should not throw any error if nonce matches', () => { const state = { nonce: 'NONCE', env: 'development' }; - const mockRequest = ({ + const mockRequest = { cookies: { 'providera-nonce': 'NONCE', }, query: { state: encodeState(state), }, - } as unknown) as express.Request; + } as unknown as express.Request; expect(() => { verifyNonce(mockRequest, 'providera'); }).not.toThrow(); diff --git a/plugins/auth-backend/src/lib/oauth/types.ts b/plugins/auth-backend/src/lib/oauth/types.ts index 1c11f8291e..c5ece2b921 100644 --- a/plugins/auth-backend/src/lib/oauth/types.ts +++ b/plugins/auth-backend/src/lib/oauth/types.ts @@ -106,9 +106,7 @@ export interface OAuthHandlers { * Handles the redirect from the auth provider when the user has signed in. * @param {express.Request} req */ - handler( - req: express.Request, - ): Promise<{ + handler(req: express.Request): Promise<{ response: AuthResponse; refreshToken?: string; }>; diff --git a/plugins/auth-backend/src/lib/passport/PassportStrategyHelper.test.ts b/plugins/auth-backend/src/lib/passport/PassportStrategyHelper.test.ts index 48878e9fa6..f7cb500d92 100644 --- a/plugins/auth-backend/src/lib/passport/PassportStrategyHelper.test.ts +++ b/plugins/auth-backend/src/lib/passport/PassportStrategyHelper.test.ts @@ -23,7 +23,7 @@ import { executeRefreshTokenStrategy, } from './PassportStrategyHelper'; -const mockRequest = ({} as unknown) as express.Request; +const mockRequest = {} as unknown as express.Request; describe('PassportStrategyHelper', () => { class MyCustomRedirectStrategy extends passport.Strategy { diff --git a/plugins/auth-backend/src/lib/passport/PassportStrategyHelper.ts b/plugins/auth-backend/src/lib/passport/PassportStrategyHelper.ts index 313b4a79bd..a0c07943c1 100644 --- a/plugins/auth-backend/src/lib/passport/PassportStrategyHelper.ts +++ b/plugins/auth-backend/src/lib/passport/PassportStrategyHelper.ts @@ -195,7 +195,7 @@ export const executeFetchUserProfileStrategy = async ( accessToken: string, ): Promise => { return new Promise((resolve, reject) => { - const anyStrategy = (providerStrategy as unknown) as ProviderStrategy; + const anyStrategy = providerStrategy as unknown as ProviderStrategy; anyStrategy.userProfile( accessToken, (error: Error, rawProfile: passport.Profile) => { diff --git a/plugins/auth-backend/src/providers/aws-alb/provider.test.ts b/plugins/auth-backend/src/providers/aws-alb/provider.test.ts index 3785e11d39..a1606e18f2 100644 --- a/plugins/auth-backend/src/providers/aws-alb/provider.test.ts +++ b/plugins/auth-backend/src/providers/aws-alb/provider.test.ts @@ -79,22 +79,22 @@ describe('AwsALBAuthProvider', () => { getEntityByName: jest.fn(), }; - const mockRequest = ({ + const mockRequest = { header: jest.fn(() => { return 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImZvbyIsImlzcyI6ImZvbyJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.T2BNS4G-6RoiFnXc8Q8TiwdWzTpNitY8jcsGM3N3-Yo'; }), - } as unknown) as express.Request; - const mockRequestWithoutJwt = ({ + } as unknown as express.Request; + const mockRequestWithoutJwt = { header: jest.fn(() => { return undefined; }), - } as unknown) as express.Request; - const mockResponse = ({ + } as unknown as express.Request; + const mockResponse = { end: jest.fn(), header: () => jest.fn(), json: jest.fn().mockReturnThis(), status: jest.fn(), - } as unknown) as express.Response; + } as unknown as express.Response; describe('should transform to type OAuthResponse', () => { it('when JWT is valid and identity is resolved successfully', async () => { diff --git a/plugins/auth-backend/src/providers/github/provider.test.ts b/plugins/auth-backend/src/providers/github/provider.test.ts index 4e53ce4026..c1270a71dc 100644 --- a/plugins/auth-backend/src/providers/github/provider.test.ts +++ b/plugins/auth-backend/src/providers/github/provider.test.ts @@ -19,10 +19,10 @@ import { GithubAuthProvider } from './provider'; import * as helpers from '../../lib/passport/PassportStrategyHelper'; import { OAuthResult } from '../../lib/oauth'; -const mockFrameHandler = (jest.spyOn( +const mockFrameHandler = jest.spyOn( helpers, 'executeFrameHandlerStrategy', -) as unknown) as jest.MockedFunction< +) as unknown as jest.MockedFunction< () => Promise<{ result: Omit & { params: { scope: string } }; }> @@ -87,7 +87,7 @@ describe('GithubAuthProvider', () => { it('when "email" is missing, it should be able to create the profile without it', async () => { const accessToken = '19xasczxcm9n7gacn9jdgm19me'; - const fullProfile = ({ + const fullProfile = { id: 'uid-123', username: 'jimmymarkum', provider: 'github', @@ -99,7 +99,7 @@ describe('GithubAuthProvider', () => { 'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg', }, ], - } as unknown) as PassportProfile; + } as unknown as PassportProfile; const params = { scope: 'read:scope', @@ -131,7 +131,7 @@ describe('GithubAuthProvider', () => { it('when "displayName" is missing, it should be able to create the profile and map "displayName" with "username"', async () => { const accessToken = '19xasczxcm9n7gacn9jdgm19me'; - const fullProfile = ({ + const fullProfile = { id: 'uid-123', username: 'jimmymarkum', provider: 'github', @@ -143,7 +143,7 @@ describe('GithubAuthProvider', () => { 'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg', }, ], - } as unknown) as PassportProfile; + } as unknown as PassportProfile; const params = { scope: 'read:scope', diff --git a/plugins/auth-backend/src/providers/gitlab/provider.test.ts b/plugins/auth-backend/src/providers/gitlab/provider.test.ts index 2277515cc9..511a3dbc54 100644 --- a/plugins/auth-backend/src/providers/gitlab/provider.test.ts +++ b/plugins/auth-backend/src/providers/gitlab/provider.test.ts @@ -18,10 +18,10 @@ import { GitlabAuthProvider } from './provider'; import * as helpers from '../../lib/passport/PassportStrategyHelper'; import { OAuthResult } from '../../lib/oauth'; -const mockFrameHandler = (jest.spyOn( +const mockFrameHandler = jest.spyOn( helpers, 'executeFrameHandlerStrategy', -) as unknown) as jest.MockedFunction<() => Promise<{ result: OAuthResult }>>; +) as unknown as jest.MockedFunction<() => Promise<{ result: OAuthResult }>>; describe('GitlabAuthProvider', () => { it('should transform to type OAuthResponse', async () => { diff --git a/plugins/auth-backend/src/providers/google/provider.test.ts b/plugins/auth-backend/src/providers/google/provider.test.ts index 68279dc2dd..a69a7b0485 100644 --- a/plugins/auth-backend/src/providers/google/provider.test.ts +++ b/plugins/auth-backend/src/providers/google/provider.test.ts @@ -21,10 +21,10 @@ import { getVoidLogger } from '@backstage/backend-common'; import { TokenIssuer } from '../../identity/types'; import { CatalogIdentityClient } from '../../lib/catalog'; -const mockFrameHandler = (jest.spyOn( +const mockFrameHandler = jest.spyOn( helpers, 'executeFrameHandlerStrategy', -) as unknown) as jest.MockedFunction< +) as unknown as jest.MockedFunction< () => Promise<{ result: OAuthResult; privateInfo: any }> >; @@ -40,8 +40,9 @@ describe('createGoogleProvider', () => { const provider = new GoogleAuthProvider({ logger: getVoidLogger(), - catalogIdentityClient: (catalogIdentityClient as unknown) as CatalogIdentityClient, - tokenIssuer: (tokenIssuer as unknown) as TokenIssuer, + catalogIdentityClient: + catalogIdentityClient as unknown as CatalogIdentityClient, + tokenIssuer: tokenIssuer as unknown as TokenIssuer, authHandler: async ({ fullProfile }) => ({ profile: { email: fullProfile.emails![0]!.value, diff --git a/plugins/auth-backend/src/providers/microsoft/provider.test.ts b/plugins/auth-backend/src/providers/microsoft/provider.test.ts index c979bed582..429e6691b6 100644 --- a/plugins/auth-backend/src/providers/microsoft/provider.test.ts +++ b/plugins/auth-backend/src/providers/microsoft/provider.test.ts @@ -21,10 +21,10 @@ import { getVoidLogger } from '@backstage/backend-common'; import { TokenIssuer } from '../../identity/types'; import { CatalogIdentityClient } from '../../lib/catalog'; -const mockFrameHandler = (jest.spyOn( +const mockFrameHandler = jest.spyOn( helpers, 'executeFrameHandlerStrategy', -) as unknown) as jest.MockedFunction< +) as unknown as jest.MockedFunction< () => Promise<{ result: OAuthResult; privateInfo: any }> >; @@ -40,8 +40,9 @@ describe('createMicrosoftProvider', () => { const provider = new MicrosoftAuthProvider({ logger: getVoidLogger(), - catalogIdentityClient: (catalogIdentityClient as unknown) as CatalogIdentityClient, - tokenIssuer: (tokenIssuer as unknown) as TokenIssuer, + catalogIdentityClient: + catalogIdentityClient as unknown as CatalogIdentityClient, + tokenIssuer: tokenIssuer as unknown as TokenIssuer, authHandler: async ({ fullProfile }) => ({ profile: { email: fullProfile.emails![0]!.value, diff --git a/plugins/auth-backend/src/providers/microsoft/provider.ts b/plugins/auth-backend/src/providers/microsoft/provider.ts index 633844a351..26009474be 100644 --- a/plugins/auth-backend/src/providers/microsoft/provider.ts +++ b/plugins/auth-backend/src/providers/microsoft/provider.ts @@ -220,24 +220,22 @@ export const microsoftEmailSignInResolver: SignInResolver = async ( return { id: entity.metadata.name, entity, token }; }; -export const microsoftDefaultSignInResolver: SignInResolver = async ( - info, - ctx, -) => { - const { profile } = info; +export const microsoftDefaultSignInResolver: SignInResolver = + async (info, ctx) => { + const { profile } = info; - if (!profile.email) { - throw new Error('Profile contained no email'); - } + if (!profile.email) { + throw new Error('Profile contained no email'); + } - const userId = profile.email.split('@')[0]; + const userId = profile.email.split('@')[0]; - const token = await ctx.tokenIssuer.issueToken({ - claims: { sub: userId, ent: [`user:default/${userId}`] }, - }); + const token = await ctx.tokenIssuer.issueToken({ + claims: { sub: userId, ent: [`user:default/${userId}`] }, + }); - return { id: userId, token }; -}; + return { id: userId, token }; + }; export type MicrosoftProviderOptions = { /** diff --git a/plugins/auth-backend/src/providers/oidc/provider.test.ts b/plugins/auth-backend/src/providers/oidc/provider.test.ts index 8ad0adb34e..c302c44082 100644 --- a/plugins/auth-backend/src/providers/oidc/provider.test.ts +++ b/plugins/auth-backend/src/providers/oidc/provider.test.ts @@ -70,7 +70,7 @@ describe('OidcAuthProvider', () => { rest.get('https://oidc.test/.well-known/openid-configuration', handler), ); const provider = new OidcAuthProvider(clientMetadata); - const { strategy } = ((await (provider as any).implementation) as any) as { + const { strategy } = (await (provider as any).implementation) as any as { strategy: { _client: ClientMetadata; _issuer: IssuerMetadata; @@ -138,7 +138,7 @@ describe('OidcAuthProvider', () => { const req = { method: 'GET', url: 'https://oidc.test/?code=test2', - session: ({ 'oidc:oidc.test': 'test' } as any) as Session, + session: { 'oidc:oidc.test': 'test' } as any as Session, } as express.Request; await provider.handler(req); expect(requestSequence).toEqual([0, 1, 2].map(i => requests[i].url)); diff --git a/plugins/badges-backend/src/lib/BadgeBuilder/DefaultBadgeBuilder.test.ts b/plugins/badges-backend/src/lib/BadgeBuilder/DefaultBadgeBuilder.test.ts index e26d4a406b..039c8b9b77 100644 --- a/plugins/badges-backend/src/lib/BadgeBuilder/DefaultBadgeBuilder.test.ts +++ b/plugins/badges-backend/src/lib/BadgeBuilder/DefaultBadgeBuilder.test.ts @@ -42,7 +42,7 @@ describe('DefaultBadgeBuilder', () => { createBadge: () => badge, }, failbadge: { - createBadge: () => (undefined as unknown) as Badge, // force a bad return value.. + createBadge: () => undefined as unknown as Badge, // force a bad return value.. }, invalidbadge: { createBadge: () => ({ style: 'wrong' as BadgeStyle, ...badge }), diff --git a/plugins/badges/src/components/EntityBadgesDialog.tsx b/plugins/badges/src/components/EntityBadgesDialog.tsx index a1840e75c0..75caca2d9d 100644 --- a/plugins/badges/src/components/EntityBadgesDialog.tsx +++ b/plugins/badges/src/components/EntityBadgesDialog.tsx @@ -48,7 +48,11 @@ export const EntityBadgesDialog = ({ open, onClose }: Props) => { const fullScreen = useMediaQuery(theme.breakpoints.down('sm')); const badgesApi = useApi(badgesApiRef); - const { value: badges, loading, error } = useAsync(async () => { + const { + value: badges, + loading, + error, + } = useAsync(async () => { if (open && entity) { return await badgesApi.getEntityBadgeSpecs(entity); } diff --git a/plugins/catalog-backend-module-ldap/src/ldap/read.test.ts b/plugins/catalog-backend-module-ldap/src/ldap/read.test.ts index b357b6b408..49afd65c30 100644 --- a/plugins/catalog-backend-module-ldap/src/ldap/read.test.ts +++ b/plugins/catalog-backend-module-ldap/src/ldap/read.test.ts @@ -140,21 +140,7 @@ describe('readLdapUsers', () => { distinguishedName: ['dn-value'], objectGUID: [ Buffer.from([ - 68, - 2, - 125, - 190, - 209, - 0, - 94, - 73, - 133, - 33, - 230, - 174, - 234, - 195, - 160, + 68, 2, 125, 190, 209, 0, 94, 73, 133, 33, 230, 174, 234, 195, 160, 152, ]), ], @@ -286,21 +272,7 @@ describe('readLdapGroups', () => { distinguishedName: ['dn-value'], objectGUID: [ Buffer.from([ - 68, - 2, - 125, - 190, - 209, - 0, - 94, - 73, - 133, - 33, - 230, - 174, - 234, - 195, - 160, + 68, 2, 125, 190, 209, 0, 94, 73, 133, 33, 230, 174, 234, 195, 160, 152, ]), ], diff --git a/plugins/catalog-backend-module-msgraph/README.md b/plugins/catalog-backend-module-msgraph/README.md index df141901aa..5dedb800f1 100644 --- a/plugins/catalog-backend-module-msgraph/README.md +++ b/plugins/catalog-backend-module-msgraph/README.md @@ -89,9 +89,11 @@ export async function myGroupTransformer( groupPhoto?: string, ): Promise { if ( - ((group as unknown) as { - creationOptions: string[]; - }).creationOptions.includes('ProvisionGroupHomepage') + ( + group as unknown as { + creationOptions: string[]; + } + ).creationOptions.includes('ProvisionGroupHomepage') ) { return undefined; } diff --git a/plugins/catalog-backend-module-msgraph/src/microsoftGraph/client.test.ts b/plugins/catalog-backend-module-msgraph/src/microsoftGraph/client.test.ts index 2b5e72033b..cefa4a52ce 100644 --- a/plugins/catalog-backend-module-msgraph/src/microsoftGraph/client.test.ts +++ b/plugins/catalog-backend-module-msgraph/src/microsoftGraph/client.test.ts @@ -21,9 +21,10 @@ import { setupServer } from 'msw/node'; import { MicrosoftGraphClient } from './client'; describe('MicrosoftGraphClient', () => { - const confidentialClientApplication: jest.Mocked = { - acquireTokenByClientCredential: jest.fn(), - } as any; + const confidentialClientApplication: jest.Mocked = + { + acquireTokenByClientCredential: jest.fn(), + } as any; let client: MicrosoftGraphClient; const worker = setupServer(); diff --git a/plugins/catalog-backend-module-msgraph/src/microsoftGraph/read.test.ts b/plugins/catalog-backend-module-msgraph/src/microsoftGraph/read.test.ts index 929d01e128..68f7e216ea 100644 --- a/plugins/catalog-backend-module-msgraph/src/microsoftGraph/read.test.ts +++ b/plugins/catalog-backend-module-msgraph/src/microsoftGraph/read.test.ts @@ -202,14 +202,10 @@ describe('read microsoft graph', () => { 'data:image/jpeg;base64,...', ); - const { - groups, - groupMember, - groupMemberOf, - rootGroup, - } = await readMicrosoftGraphGroups(client, 'tenantid', { - groupFilter: 'securityEnabled eq false', - }); + const { groups, groupMember, groupMemberOf, rootGroup } = + await readMicrosoftGraphGroups(client, 'tenantid', { + groupFilter: 'securityEnabled eq false', + }); const expectedRootGroup = group({ metadata: { diff --git a/plugins/catalog-backend-module-msgraph/src/microsoftGraph/read.ts b/plugins/catalog-backend-module-msgraph/src/microsoftGraph/read.ts index a9e2465ad7..62513b0e10 100644 --- a/plugins/catalog-backend-module-msgraph/src/microsoftGraph/read.ts +++ b/plugins/catalog-backend-module-msgraph/src/microsoftGraph/read.ts @@ -318,14 +318,12 @@ export function resolveRelations( // Make sure every group (except root) has at least one parent. If the parent is missing, add the root. if (rootGroup) { - const tenantId = rootGroup.metadata.annotations![ - MICROSOFT_GRAPH_TENANT_ID_ANNOTATION - ]; + const tenantId = + rootGroup.metadata.annotations![MICROSOFT_GRAPH_TENANT_ID_ANNOTATION]; groups.forEach(group => { - const groupId = group.metadata.annotations![ - MICROSOFT_GRAPH_GROUP_ID_ANNOTATION - ]; + const groupId = + group.metadata.annotations![MICROSOFT_GRAPH_GROUP_ID_ANNOTATION]; if (!groupId) { return; @@ -392,15 +390,11 @@ export async function readMicrosoftGraphOrg( userFilter: options.userFilter, logger: options.logger, }); - const { - groups, - rootGroup, - groupMember, - groupMemberOf, - } = await readMicrosoftGraphGroups(client, tenantId, { - groupFilter: options?.groupFilter, - transformer: options?.groupTransformer, - }); + const { groups, rootGroup, groupMember, groupMemberOf } = + await readMicrosoftGraphGroups(client, tenantId, { + groupFilter: options?.groupFilter, + transformer: options?.groupTransformer, + }); resolveRelations(rootGroup, groups, users, groupMember, groupMemberOf); users.sort((a, b) => a.metadata.name.localeCompare(b.metadata.name)); diff --git a/plugins/catalog-backend/CHANGELOG.md b/plugins/catalog-backend/CHANGELOG.md index 07799cfad4..3849fec510 100644 --- a/plugins/catalog-backend/CHANGELOG.md +++ b/plugins/catalog-backend/CHANGELOG.md @@ -442,13 +442,11 @@ and lets the other processors take care of further processing. ```typescript - const customRepositoryParser: BitbucketRepositoryParser = async function* customRepositoryParser({ - client, - repository, - }) { - // Custom logic for interpret the matching repository. - // See defaultRepositoryParser for an example - }; + const customRepositoryParser: BitbucketRepositoryParser = + async function* customRepositoryParser({ client, repository }) { + // Custom logic for interpret the matching repository. + // See defaultRepositoryParser for an example + }; const processor = BitbucketDiscoveryProcessor.fromConfig(env.config, { parser: customRepositoryParser, @@ -920,7 +918,6 @@ spec: type: website --- - ``` This behaves now the same way as Kubernetes handles multiple documents in a single YAML file. diff --git a/plugins/catalog-backend/api-report.md b/plugins/catalog-backend/api-report.md index b6f2df602a..7286855d4e 100644 --- a/plugins/catalog-backend/api-report.md +++ b/plugins/catalog-backend/api-report.md @@ -88,9 +88,7 @@ export class AwsOrganizationCloudAccountProcessor implements CatalogProcessor { logger: Logger_2; }); // (undocumented) - extractInformationFromArn( - arn: string, - ): { + extractInformationFromArn(arn: string): { accountId: string; organizationId: string; }; @@ -596,7 +594,8 @@ export class DefaultCatalogCollator implements DocumentCollator { // // @public (undocumented) export class DefaultCatalogProcessingOrchestrator - implements CatalogProcessingOrchestrator { + implements CatalogProcessingOrchestrator +{ constructor(options: { processors: CatalogProcessor[]; integrations: ScmIntegrationRegistry; diff --git a/plugins/catalog-backend/src/catalog/DatabaseLocationsCatalog.ts b/plugins/catalog-backend/src/catalog/DatabaseLocationsCatalog.ts index fff34d1d78..e81c72a3da 100644 --- a/plugins/catalog-backend/src/catalog/DatabaseLocationsCatalog.ts +++ b/plugins/catalog-backend/src/catalog/DatabaseLocationsCatalog.ts @@ -52,12 +52,8 @@ export class DatabaseLocationsCatalog implements LocationsCatalog { } async location(id: string): Promise { - const { - message, - status, - timestamp, - ...data - } = await this.database.location(id); + const { message, status, timestamp, ...data } = + await this.database.location(id); return { currentStatus: { message, diff --git a/plugins/catalog-backend/src/database/CommonDatabase.ts b/plugins/catalog-backend/src/database/CommonDatabase.ts index 272ac08c4c..79cad3bd23 100644 --- a/plugins/catalog-backend/src/database/CommonDatabase.ts +++ b/plugins/catalog-backend/src/database/CommonDatabase.ts @@ -556,9 +556,10 @@ export class CommonDatabase implements Database { } } -function parsePagination( - input?: EntityPagination, -): { limit?: number; offset?: number } { +function parsePagination(input?: EntityPagination): { + limit?: number; + offset?: number; +} { if (!input) { return {}; } diff --git a/plugins/catalog-backend/src/ingestion/processors/AnnotateLocationEntityProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/AnnotateLocationEntityProcessor.ts index 5a0c8b8418..54079e13ff 100644 --- a/plugins/catalog-backend/src/ingestion/processors/AnnotateLocationEntityProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/AnnotateLocationEntityProcessor.ts @@ -71,9 +71,8 @@ export class AnnotateLocationEntityProcessor implements CatalogProcessor { annotations: pickBy( { [LOCATION_ANNOTATION]: stringifyLocationReference(location), - [ORIGIN_LOCATION_ANNOTATION]: stringifyLocationReference( - originLocation, - ), + [ORIGIN_LOCATION_ANNOTATION]: + stringifyLocationReference(originLocation), [VIEW_URL_ANNOTATION]: viewUrl, [EDIT_URL_ANNOTATION]: editUrl, [SOURCE_LOCATION_ANNOTATION]: sourceLocation, diff --git a/plugins/catalog-backend/src/ingestion/processors/AwsOrganizationCloudAccountProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/AwsOrganizationCloudAccountProcessor.test.ts index a3b1dfbfcb..88b033c33f 100644 --- a/plugins/catalog-backend/src/ingestion/processors/AwsOrganizationCloudAccountProcessor.test.ts +++ b/plugins/catalog-backend/src/ingestion/processors/AwsOrganizationCloudAccountProcessor.test.ts @@ -37,8 +37,7 @@ describe('AwsOrganizationCloudAccountProcessor', () => { return { Accounts: [ { - Arn: - 'arn:aws:organizations::192594491037:account/o-1vl18kc5a3/957140518395', + Arn: 'arn:aws:organizations::192594491037:account/o-1vl18kc5a3/957140518395', Name: 'testaccount', }, ], @@ -83,13 +82,11 @@ describe('AwsOrganizationCloudAccountProcessor', () => { return { Accounts: [ { - Arn: - 'arn:aws:organizations::192594491037:account/o-1vl18kc5a3/957140518395', + Arn: 'arn:aws:organizations::192594491037:account/o-1vl18kc5a3/957140518395', Name: 'testaccount', }, { - Arn: - 'arn:aws:organizations::192594491037:account/o-zzzzzzzzz/957140518395', + Arn: 'arn:aws:organizations::192594491037:account/o-zzzzzzzzz/957140518395', Name: 'testaccount2', }, ], diff --git a/plugins/catalog-backend/src/ingestion/processors/AwsOrganizationCloudAccountProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/AwsOrganizationCloudAccountProcessor.ts index beb179a0d2..655f99d14a 100644 --- a/plugins/catalog-backend/src/ingestion/processors/AwsOrganizationCloudAccountProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/AwsOrganizationCloudAccountProcessor.ts @@ -89,9 +89,10 @@ export class AwsOrganizationCloudAccountProcessor implements CatalogProcessor { .replace(/[^a-zA-Z0-9\-]/g, '-'); } - extractInformationFromArn( - arn: string, - ): { accountId: string; organizationId: string } { + extractInformationFromArn(arn: string): { + accountId: string; + organizationId: string; + } { const parts = arn.split('/'); return { diff --git a/plugins/catalog-backend/src/ingestion/processors/BitbucketDiscoveryProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/BitbucketDiscoveryProcessor.test.ts index e2b295e7ff..c067958093 100644 --- a/plugins/catalog-backend/src/ingestion/processors/BitbucketDiscoveryProcessor.test.ts +++ b/plugins/catalog-backend/src/ingestion/processors/BitbucketDiscoveryProcessor.test.ts @@ -256,15 +256,16 @@ describe('BitbucketDiscoveryProcessor', () => { }); describe('Custom repository parser', () => { - const customRepositoryParser: BitbucketRepositoryParser = async function* customRepositoryParser({}) { - yield results.location( - { - type: 'custom-location-type', - target: 'custom-target', - }, - true, - ); - }; + const customRepositoryParser: BitbucketRepositoryParser = + async function* customRepositoryParser({}) { + yield results.location( + { + type: 'custom-location-type', + target: 'custom-target', + }, + true, + ); + }; const processor = BitbucketDiscoveryProcessor.fromConfig( new ConfigReader({ diff --git a/plugins/catalog-backend/src/ingestion/processors/BitbucketDiscoveryProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/BitbucketDiscoveryProcessor.ts index 9d53b7e5b5..3b535881d9 100644 --- a/plugins/catalog-backend/src/ingestion/processors/BitbucketDiscoveryProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/BitbucketDiscoveryProcessor.ts @@ -136,9 +136,11 @@ export async function readBitbucketOrg( return result; } -function parseUrl( - urlString: string, -): { projectSearchPath: RegExp; repoSearchPath: RegExp; catalogPath: string } { +function parseUrl(urlString: string): { + projectSearchPath: RegExp; + repoSearchPath: RegExp; + catalogPath: string; +} { const url = new URL(urlString); const path = url.pathname.substr(1).split('/'); diff --git a/plugins/catalog-backend/src/ingestion/processors/GithubDiscoveryProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/GithubDiscoveryProcessor.test.ts index 467e9c1ea2..711c6fb27d 100644 --- a/plugins/catalog-backend/src/ingestion/processors/GithubDiscoveryProcessor.test.ts +++ b/plugins/catalog-backend/src/ingestion/processors/GithubDiscoveryProcessor.test.ts @@ -21,9 +21,10 @@ import { getOrganizationRepositories } from './github'; import { ConfigReader } from '@backstage/config'; jest.mock('./github'); -const mockGetOrganizationRepositories = getOrganizationRepositories as jest.MockedFunction< - typeof getOrganizationRepositories ->; +const mockGetOrganizationRepositories = + getOrganizationRepositories as jest.MockedFunction< + typeof getOrganizationRepositories + >; describe('GithubDiscoveryProcessor', () => { describe('parseUrl', () => { diff --git a/plugins/catalog-backend/src/ingestion/processors/GithubDiscoveryProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/GithubDiscoveryProcessor.ts index 2219e02406..d3064f9c39 100644 --- a/plugins/catalog-backend/src/ingestion/processors/GithubDiscoveryProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/GithubDiscoveryProcessor.ts @@ -56,8 +56,9 @@ export class GithubDiscoveryProcessor implements CatalogProcessor { return false; } - const gitHubConfig = this.integrations.github.byUrl(location.target) - ?.config; + const gitHubConfig = this.integrations.github.byUrl( + location.target, + )?.config; if (!gitHubConfig) { throw new Error( `There is no GitHub integration that matches ${location.target}. Please add a configuration entry for it under integrations.github`, @@ -110,9 +111,11 @@ export class GithubDiscoveryProcessor implements CatalogProcessor { * Helpers */ -export function parseUrl( - urlString: string, -): { org: string; repoSearchPath: RegExp; catalogPath: string } { +export function parseUrl(urlString: string): { + org: string; + repoSearchPath: RegExp; + catalogPath: string; +} { const url = new URL(urlString); const path = url.pathname.substr(1).split('/'); diff --git a/plugins/catalog-backend/src/ingestion/processors/GithubMultiOrgReaderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/GithubMultiOrgReaderProcessor.ts index 5223acba4a..ebfcaf5b5d 100644 --- a/plugins/catalog-backend/src/ingestion/processors/GithubMultiOrgReaderProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/GithubMultiOrgReaderProcessor.ts @@ -75,8 +75,9 @@ export class GithubMultiOrgReaderProcessor implements CatalogProcessor { return false; } - const gitHubConfig = this.integrations.github.byUrl(location.target) - ?.config; + const gitHubConfig = this.integrations.github.byUrl( + location.target, + )?.config; if (!gitHubConfig) { throw new Error( `There is no GitHub integration that matches ${location.target}. Please add a configuration entry for it under integrations.github`, @@ -93,12 +94,10 @@ export class GithubMultiOrgReaderProcessor implements CatalogProcessor { for (const orgConfig of orgsToProcess) { try { - const { - headers, - type: tokenType, - } = await credentialsProvider.getCredentials({ - url: `${baseUrl}/${orgConfig.name}`, - }); + const { headers, type: tokenType } = + await credentialsProvider.getCredentials({ + url: `${baseUrl}/${orgConfig.name}`, + }); const client = graphql.defaults({ baseUrl: gitHubConfig.apiBaseUrl, headers, diff --git a/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.ts index 364042f74d..3a82ff6516 100644 --- a/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.ts @@ -113,12 +113,10 @@ export class GithubOrgReaderProcessor implements CatalogProcessor { } const credentialsProvider = GithubCredentialsProvider.create(gitHubConfig); - const { - headers, - type: tokenType, - } = await credentialsProvider.getCredentials({ - url: orgUrl, - }); + const { headers, type: tokenType } = + await credentialsProvider.getCredentials({ + url: orgUrl, + }); const client = graphql.defaults({ baseUrl: gitHubConfig.apiBaseUrl, diff --git a/plugins/catalog-backend/src/ingestion/processors/LocationEntityProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/LocationEntityProcessor.test.ts index b018542fcc..c4551e30f8 100644 --- a/plugins/catalog-backend/src/ingestion/processors/LocationEntityProcessor.test.ts +++ b/plugins/catalog-backend/src/ingestion/processors/LocationEntityProcessor.test.ts @@ -26,7 +26,7 @@ import { toAbsoluteUrl } from './LocationEntityProcessor'; describe('LocationEntityProcessor', () => { describe('toAbsoluteUrl', () => { it('handles files', () => { - const integrations = ({} as unknown) as ScmIntegrationRegistry; + const integrations = {} as unknown as ScmIntegrationRegistry; const base: LocationSpec = { type: 'file', target: `some${path.sep}path${path.sep}catalog-info.yaml`, diff --git a/plugins/catalog-backend/src/ingestion/processors/bitbucket/BitbucketRepositoryParser.ts b/plugins/catalog-backend/src/ingestion/processors/bitbucket/BitbucketRepositoryParser.ts index 6f33646c54..27f07d58a2 100644 --- a/plugins/catalog-backend/src/ingestion/processors/bitbucket/BitbucketRepositoryParser.ts +++ b/plugins/catalog-backend/src/ingestion/processors/bitbucket/BitbucketRepositoryParser.ts @@ -24,17 +24,16 @@ export type BitbucketRepositoryParser = (options: { logger: Logger; }) => AsyncIterable; -export const defaultRepositoryParser: BitbucketRepositoryParser = async function* defaultRepositoryParser({ - target, -}) { - yield results.location( - { - type: 'url', - target: target, - }, - // Not all locations may actually exist, since the user defined them as a wildcard pattern. - // Thus, we emit them as optional and let the downstream processor find them while not outputting - // an error if it couldn't. - true, - ); -}; +export const defaultRepositoryParser: BitbucketRepositoryParser = + async function* defaultRepositoryParser({ target }) { + yield results.location( + { + type: 'url', + target: target, + }, + // Not all locations may actually exist, since the user defined them as a wildcard pattern. + // Thus, we emit them as optional and let the downstream processor find them while not outputting + // an error if it couldn't. + true, + ); + }; diff --git a/plugins/catalog-backend/src/ingestion/processors/github/github.ts b/plugins/catalog-backend/src/ingestion/processors/github/github.ts index 7e1ef136eb..70479110c2 100644 --- a/plugins/catalog-backend/src/ingestion/processors/github/github.ts +++ b/plugins/catalog-backend/src/ingestion/processors/github/github.ts @@ -330,7 +330,7 @@ export async function queryWithPaging< GraphqlType, OutputType, Variables extends {}, - Response = QueryResponse + Response = QueryResponse, >( client: typeof graphql, query: string, diff --git a/plugins/catalog-backend/src/ingestion/processors/util/parse.ts b/plugins/catalog-backend/src/ingestion/processors/util/parse.ts index e93b2a0200..c9c6c79311 100644 --- a/plugins/catalog-backend/src/ingestion/processors/util/parse.ts +++ b/plugins/catalog-backend/src/ingestion/processors/util/parse.ts @@ -58,11 +58,9 @@ export function* parseEntityYaml( } } -export const defaultEntityDataParser: CatalogProcessorParser = async function* defaultEntityDataParser({ - data, - location, -}) { - for (const e of parseEntityYaml(data, location)) { - yield e; - } -}; +export const defaultEntityDataParser: CatalogProcessorParser = + async function* defaultEntityDataParser({ data, location }) { + for (const e of parseEntityYaml(data, location)) { + yield e; + } + }; diff --git a/plugins/catalog-backend/src/next/ConfigLocationEntityProvider.test.ts b/plugins/catalog-backend/src/next/ConfigLocationEntityProvider.test.ts index d177b1aa32..32ce28dc1b 100644 --- a/plugins/catalog-backend/src/next/ConfigLocationEntityProvider.test.ts +++ b/plugins/catalog-backend/src/next/ConfigLocationEntityProvider.test.ts @@ -31,9 +31,9 @@ describe('ConfigLocationEntityProvider', () => { }, }); - const mockConnection = ({ + const mockConnection = { applyMutation: jest.fn(), - } as unknown) as EntityProviderConnection; + } as unknown as EntityProviderConnection; const locationProvider = new ConfigLocationEntityProvider(mockConfig); await locationProvider.connect(mockConnection); diff --git a/plugins/catalog-backend/src/next/DefaultCatalogProcessingEngine.test.ts b/plugins/catalog-backend/src/next/DefaultCatalogProcessingEngine.test.ts index b87635db85..5f3bab63e7 100644 --- a/plugins/catalog-backend/src/next/DefaultCatalogProcessingEngine.test.ts +++ b/plugins/catalog-backend/src/next/DefaultCatalogProcessingEngine.test.ts @@ -22,17 +22,17 @@ import { CatalogProcessingOrchestrator } from './processing/types'; import { Stitcher } from './stitching/Stitcher'; describe('DefaultCatalogProcessingEngine', () => { - const db = ({ + const db = { transaction: jest.fn(), getProcessableEntities: jest.fn(), updateProcessedEntity: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; const orchestrator: jest.Mocked = { process: jest.fn(), }; - const stitcher = ({ + const stitcher = { stitch: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; beforeEach(() => { jest.resetAllMocks(); diff --git a/plugins/catalog-backend/src/next/NextEntitiesCatalog.ts b/plugins/catalog-backend/src/next/NextEntitiesCatalog.ts index 7cc99210c9..e9772b4aa3 100644 --- a/plugins/catalog-backend/src/next/NextEntitiesCatalog.ts +++ b/plugins/catalog-backend/src/next/NextEntitiesCatalog.ts @@ -28,9 +28,10 @@ import { DbSearchRow, } from './database/tables'; -function parsePagination( - input?: EntityPagination, -): { limit?: number; offset?: number } { +function parsePagination(input?: EntityPagination): { + limit?: number; + offset?: number; +} { if (!input) { return {}; } diff --git a/plugins/catalog-backend/src/next/NextRouter.ts b/plugins/catalog-backend/src/next/NextRouter.ts index eb9e5247ed..849d2ee36d 100644 --- a/plugins/catalog-backend/src/next/NextRouter.ts +++ b/plugins/catalog-backend/src/next/NextRouter.ts @@ -47,13 +47,8 @@ export interface RouterOptions { export async function createNextRouter( options: RouterOptions, ): Promise { - const { - entitiesCatalog, - locationAnalyzer, - locationService, - config, - logger, - } = options; + const { entitiesCatalog, locationAnalyzer, locationService, config, logger } = + options; const router = Router(); router.use(express.json()); diff --git a/plugins/catalog-backend/src/next/database/DefaultProcessingDatabase.test.ts b/plugins/catalog-backend/src/next/database/DefaultProcessingDatabase.test.ts index e449e5580c..6a0626afc4 100644 --- a/plugins/catalog-backend/src/next/database/DefaultProcessingDatabase.test.ts +++ b/plugins/catalog-backend/src/next/database/DefaultProcessingDatabase.test.ts @@ -79,10 +79,10 @@ describe('Default Processing Database', () => { 'updates refresh state with varying location keys, %p', async databaseId => { const mockWarn = jest.fn(); - const { db } = await createDatabase(databaseId, ({ + const { db } = await createDatabase(databaseId, { debug: jest.fn(), warn: mockWarn, - } as unknown) as Logger); + } as unknown as Logger); await db.transaction(async tx => { const knexTx = tx as Knex.Transaction; diff --git a/plugins/catalog-backend/src/next/processing/DefaultCatalogProcessingOrchestrator.ts b/plugins/catalog-backend/src/next/processing/DefaultCatalogProcessingOrchestrator.ts index bb23b6afb3..d7f51807a3 100644 --- a/plugins/catalog-backend/src/next/processing/DefaultCatalogProcessingOrchestrator.ts +++ b/plugins/catalog-backend/src/next/processing/DefaultCatalogProcessingOrchestrator.ts @@ -54,7 +54,8 @@ type Context = { }; export class DefaultCatalogProcessingOrchestrator - implements CatalogProcessingOrchestrator { + implements CatalogProcessingOrchestrator +{ constructor( private readonly options: { processors: CatalogProcessor[]; diff --git a/plugins/catalog-backend/src/search/DefaultCatalogCollator.ts b/plugins/catalog-backend/src/search/DefaultCatalogCollator.ts index 7ab91560b1..1f9c68e549 100644 --- a/plugins/catalog-backend/src/search/DefaultCatalogCollator.ts +++ b/plugins/catalog-backend/src/search/DefaultCatalogCollator.ts @@ -59,23 +59,21 @@ export class DefaultCatalogCollator implements DocumentCollator { const baseUrl = await this.discovery.getBaseUrl('catalog'); const res = await fetch(`${baseUrl}/entities`); const entities: Entity[] = await res.json(); - return entities.map( - (entity: Entity): CatalogEntityDocument => { - return { - title: entity.metadata.name, - location: this.applyArgsToFormat(this.locationTemplate, { - namespace: entity.metadata.namespace || 'default', - kind: entity.kind, - name: entity.metadata.name, - }), - text: entity.metadata.description || '', - componentType: entity.spec?.type?.toString() || 'other', + return entities.map((entity: Entity): CatalogEntityDocument => { + return { + title: entity.metadata.name, + location: this.applyArgsToFormat(this.locationTemplate, { namespace: entity.metadata.namespace || 'default', kind: entity.kind, - lifecycle: (entity.spec?.lifecycle as string) || '', - owner: (entity.spec?.owner as string) || '', - }; - }, - ); + name: entity.metadata.name, + }), + text: entity.metadata.description || '', + componentType: entity.spec?.type?.toString() || 'other', + namespace: entity.metadata.namespace || 'default', + kind: entity.kind, + lifecycle: (entity.spec?.lifecycle as string) || '', + owner: (entity.spec?.owner as string) || '', + }; + }); } } diff --git a/plugins/catalog-backend/src/service/request/parseEntityTransformParams.test.ts b/plugins/catalog-backend/src/service/request/parseEntityTransformParams.test.ts index 9f867e241f..1d5d41fc03 100644 --- a/plugins/catalog-backend/src/service/request/parseEntityTransformParams.test.ts +++ b/plugins/catalog-backend/src/service/request/parseEntityTransformParams.test.ts @@ -60,8 +60,8 @@ describe('parseEntityTransformParams', () => { expect( parseEntityTransformParams({ fields: 'kind,metadata.name' })!(entity), ).toEqual({ kind: 'k', metadata: { name: 'n' } }); - expect( - parseEntityTransformParams({ fields: 'metadata' })!(entity), - ).toEqual({ metadata: { name: 'n', tags: ['t1', 't2'] } }); + expect(parseEntityTransformParams({ fields: 'metadata' })!(entity)).toEqual( + { metadata: { name: 'n', tags: ['t1', 't2'] } }, + ); }); }); diff --git a/plugins/catalog-backend/src/service/router.test.ts b/plugins/catalog-backend/src/service/router.test.ts index c4631c6c2c..8e8b91d013 100644 --- a/plugins/catalog-backend/src/service/router.test.ts +++ b/plugins/catalog-backend/src/service/router.test.ts @@ -291,10 +291,10 @@ describe('createRouter readonly disabled', () => { describe('POST /locations', () => { it('rejects malformed locations', async () => { - const spec = ({ + const spec = { typez: 'b', target: 'c', - } as unknown) as LocationSpec; + } as unknown as LocationSpec; const response = await request(app).post('/locations').send(spec); diff --git a/plugins/catalog-backend/src/service/standaloneServer.ts b/plugins/catalog-backend/src/service/standaloneServer.ts index ab8d40d74c..7e0bacde32 100644 --- a/plugins/catalog-backend/src/service/standaloneServer.ts +++ b/plugins/catalog-backend/src/service/standaloneServer.ts @@ -49,11 +49,8 @@ export async function startStandaloneServer( config, reader, }); - const { - entitiesCatalog, - locationsCatalog, - higherOrderOperation, - } = await builder.build(); + const { entitiesCatalog, locationsCatalog, higherOrderOperation } = + await builder.build(); logger.debug('Starting application server...'); const router = await createRouter({ diff --git a/plugins/catalog-backend/src/service/util.ts b/plugins/catalog-backend/src/service/util.ts index 7902458900..d2f9fa0a4c 100644 --- a/plugins/catalog-backend/src/service/util.ts +++ b/plugins/catalog-backend/src/service/util.ts @@ -52,7 +52,7 @@ export async function validateRequestBody( throw new InputError(`Malformed request: ${e}`); } - return (body as unknown) as T; + return body as unknown as T; } export function disallowReadonlyMode(readonly: boolean) { diff --git a/plugins/catalog-graphql/src/graphql/types.ts b/plugins/catalog-graphql/src/graphql/types.ts index dbcf30152f..71e40181d4 100644 --- a/plugins/catalog-graphql/src/graphql/types.ts +++ b/plugins/catalog-graphql/src/graphql/types.ts @@ -219,7 +219,7 @@ export interface SubscriptionSubscriberObject< TKey extends string, TParent, TContext, - TArgs + TArgs, > { subscribe: SubscriptionSubscribeFn< { [key in TKey]: TResult }, @@ -245,7 +245,7 @@ export type SubscriptionObject< TKey extends string, TParent, TContext, - TArgs + TArgs, > = | SubscriptionSubscriberObject | SubscriptionResolverObject; @@ -255,7 +255,7 @@ export type SubscriptionResolver< TKey extends string, TParent = {}, TContext = {}, - TArgs = {} + TArgs = {}, > = | (( ...args: any[] @@ -279,7 +279,7 @@ export type DirectiveResolverFn< TResult = {}, TParent = {}, TContext = {}, - TArgs = {} + TArgs = {}, > = ( next: NextResolverFn, parent: TParent, @@ -364,7 +364,7 @@ export interface JsonObjectScalarConfig export type EntityMetadataResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['EntityMetadata'] + ParentType = ResolversParentTypes['EntityMetadata'], > = ResolversObject<{ __resolveType: TypeResolveFn< 'DefaultEntityMetadata' | 'ComponentMetadata' | 'TemplateMetadata', @@ -393,7 +393,7 @@ export type EntityMetadataResolvers< export type DefaultEntityMetadataResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['DefaultEntityMetadata'] + ParentType = ResolversParentTypes['DefaultEntityMetadata'], > = ResolversObject<{ name?: Resolver; annotations?: Resolver; @@ -418,7 +418,7 @@ export type DefaultEntityMetadataResolvers< export type ComponentMetadataResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['ComponentMetadata'] + ParentType = ResolversParentTypes['ComponentMetadata'], > = ResolversObject<{ name?: Resolver; annotations?: Resolver; @@ -448,7 +448,7 @@ export type ComponentMetadataResolvers< export type TemplateMetadataResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['TemplateMetadata'] + ParentType = ResolversParentTypes['TemplateMetadata'], > = ResolversObject<{ name?: Resolver; annotations?: Resolver; @@ -478,7 +478,7 @@ export type TemplateMetadataResolvers< export type TemplateEntitySpecResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['TemplateEntitySpec'] + ParentType = ResolversParentTypes['TemplateEntitySpec'], > = ResolversObject<{ type?: Resolver; path?: Resolver, ParentType, ContextType>; @@ -489,7 +489,7 @@ export type TemplateEntitySpecResolvers< export type ComponentEntitySpecResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['ComponentEntitySpec'] + ParentType = ResolversParentTypes['ComponentEntitySpec'], > = ResolversObject<{ title?: Resolver; lifecycle?: Resolver; @@ -499,7 +499,7 @@ export type ComponentEntitySpecResolvers< export type LocationEntitySpecResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['LocationEntitySpec'] + ParentType = ResolversParentTypes['LocationEntitySpec'], > = ResolversObject<{ type?: Resolver; target?: Resolver, ParentType, ContextType>; @@ -509,7 +509,7 @@ export type LocationEntitySpecResolvers< export type DefaultEntitySpecResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['DefaultEntitySpec'] + ParentType = ResolversParentTypes['DefaultEntitySpec'], > = ResolversObject<{ raw?: Resolver, ParentType, ContextType>; __isTypeOf?: IsTypeOfResolverFn; @@ -517,7 +517,7 @@ export type DefaultEntitySpecResolvers< export type EntitySpecResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['EntitySpec'] + ParentType = ResolversParentTypes['EntitySpec'], > = ResolversObject<{ __resolveType: TypeResolveFn< | 'DefaultEntitySpec' @@ -531,7 +531,7 @@ export type EntitySpecResolvers< export type CatalogEntityResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['CatalogEntity'] + ParentType = ResolversParentTypes['CatalogEntity'], > = ResolversObject<{ apiVersion?: Resolver; kind?: Resolver; @@ -546,7 +546,7 @@ export type CatalogEntityResolvers< export type CatalogQueryResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['CatalogQuery'] + ParentType = ResolversParentTypes['CatalogQuery'], > = ResolversObject<{ list?: Resolver< Array, @@ -558,7 +558,7 @@ export type CatalogQueryResolvers< export type QueryResolvers< ContextType = ModuleContext, - ParentType = ResolversParentTypes['Query'] + ParentType = ResolversParentTypes['Query'], > = ResolversObject<{ catalog?: Resolver; }>; diff --git a/plugins/catalog-import/api-report.md b/plugins/catalog-import/api-report.md index ac4360f463..708ee84fd0 100644 --- a/plugins/catalog-import/api-report.md +++ b/plugins/catalog-import/api-report.md @@ -178,7 +178,7 @@ export const ImportStepper: ({ // // @public export const PreparePullRequestForm: < - TFieldValues extends Record + TFieldValues extends Record, >({ defaultValues, onSubmit, diff --git a/plugins/catalog-import/src/api/CatalogImportClient.test.ts b/plugins/catalog-import/src/api/CatalogImportClient.test.ts index e2c3f2dc47..bae363d700 100644 --- a/plugins/catalog-import/src/api/CatalogImportClient.test.ts +++ b/plugins/catalog-import/src/api/CatalogImportClient.test.ts @@ -192,7 +192,7 @@ describe('CatalogImportClient', () => { }); it('should find locations from github', async () => { - ((new Octokit().search.code as any) as jest.Mock).mockResolvedValueOnce({ + (new Octokit().search.code as any as jest.Mock).mockResolvedValueOnce({ data: { total_count: 2, items: [ @@ -248,7 +248,7 @@ describe('CatalogImportClient', () => { }); it('should find repository from github', async () => { - ((new Octokit().search.code as any) as jest.Mock).mockResolvedValueOnce({ + (new Octokit().search.code as any as jest.Mock).mockResolvedValueOnce({ data: { total_count: 0, items: [] }, }); @@ -312,7 +312,7 @@ describe('CatalogImportClient', () => { }); expect( - ((new Octokit().git.createRef as any) as jest.Mock).mock.calls[0][0], + (new Octokit().git.createRef as any as jest.Mock).mock.calls[0][0], ).toEqual({ owner: 'backstage', repo: 'backstage', @@ -320,7 +320,7 @@ describe('CatalogImportClient', () => { sha: 'any', }); expect( - ((new Octokit().repos.createOrUpdateFileContents as any) as jest.Mock) + (new Octokit().repos.createOrUpdateFileContents as any as jest.Mock) .mock.calls[0][0], ).toEqual({ owner: 'backstage', @@ -331,7 +331,7 @@ describe('CatalogImportClient', () => { branch: 'backstage-integration', }); expect( - ((new Octokit().pulls.create as any) as jest.Mock).mock.calls[0][0], + (new Octokit().pulls.create as any as jest.Mock).mock.calls[0][0], ).toEqual({ owner: 'backstage', repo: 'backstage', diff --git a/plugins/catalog-import/src/components/ImportComponentPage.tsx b/plugins/catalog-import/src/components/ImportComponentPage.tsx index f4ca144165..bf53af134f 100644 --- a/plugins/catalog-import/src/components/ImportComponentPage.tsx +++ b/plugins/catalog-import/src/components/ImportComponentPage.tsx @@ -53,8 +53,7 @@ export const ImportComponentPage = (opts: StepperProviderOpts) => { title="Register an existing component" deepLink={{ title: 'Learn more about the Software Catalog', - link: - 'https://backstage.io/docs/features/software-catalog/software-catalog-overview', + link: 'https://backstage.io/docs/features/software-catalog/software-catalog-overview', }} > diff --git a/plugins/catalog-import/src/components/ImportStepper/defaults.tsx b/plugins/catalog-import/src/components/ImportStepper/defaults.tsx index 51524dae26..054fd99895 100644 --- a/plugins/catalog-import/src/components/ImportStepper/defaults.tsx +++ b/plugins/catalog-import/src/components/ImportStepper/defaults.tsx @@ -39,9 +39,10 @@ import { ConfigApi } from '@backstage/core-plugin-api'; export type StepperProviderOpts = { pullRequest?: { disable?: boolean; - preparePullRequest?: ( - apis: StepperApis, - ) => { title?: string; body?: string }; + preparePullRequest?: (apis: StepperApis) => { + title?: string; + body?: string; + }; }; }; diff --git a/plugins/catalog-import/src/components/StepInitAnalyzeUrl/StepInitAnalyzeUrl.test.tsx b/plugins/catalog-import/src/components/StepInitAnalyzeUrl/StepInitAnalyzeUrl.test.tsx index 69f58751b8..9cc9532a3d 100644 --- a/plugins/catalog-import/src/components/StepInitAnalyzeUrl/StepInitAnalyzeUrl.test.tsx +++ b/plugins/catalog-import/src/components/StepInitAnalyzeUrl/StepInitAnalyzeUrl.test.tsx @@ -382,7 +382,7 @@ describe('', () => { ); catalogImportApi.analyzeUrl.mockReturnValueOnce( - Promise.resolve(({ type: 'unknown' } as any) as AnalyzeResult), + Promise.resolve({ type: 'unknown' } as any as AnalyzeResult), ); await act(async () => { diff --git a/plugins/catalog-import/src/components/StepPrepareCreatePullRequest/PreparePullRequestForm.tsx b/plugins/catalog-import/src/components/StepPrepareCreatePullRequest/PreparePullRequestForm.tsx index dea3b4bac9..ab3241add4 100644 --- a/plugins/catalog-import/src/components/StepPrepareCreatePullRequest/PreparePullRequestForm.tsx +++ b/plugins/catalog-import/src/components/StepPrepareCreatePullRequest/PreparePullRequestForm.tsx @@ -49,19 +49,14 @@ type Props> = Pick< * @param render render the form elements */ export const PreparePullRequestForm = < - TFieldValues extends Record + TFieldValues extends Record, >({ defaultValues, onSubmit, render, }: Props) => { - const { - handleSubmit, - watch, - control, - register, - errors, - } = useForm({ mode: 'onTouched', defaultValues }); + const { handleSubmit, watch, control, register, errors } = + useForm({ mode: 'onTouched', defaultValues }); return (
    diff --git a/plugins/catalog-react/api-report.md b/plugins/catalog-react/api-report.md index a8175c8ec2..8471a80fe5 100644 --- a/plugins/catalog-react/api-report.md +++ b/plugins/catalog-react/api-report.md @@ -516,9 +516,7 @@ export const entityRoute: RouteRef<{ // Warning: (ae-missing-release-tag) "entityRouteParams" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export function entityRouteParams( - entity: Entity, -): { +export function entityRouteParams(entity: Entity): { readonly kind: string; readonly namespace: string; readonly name: string; @@ -721,7 +719,7 @@ export const useEntityFromUrl: () => EntityLoadingStatus; // // @public (undocumented) export function useEntityListProvider< - EntityFilters extends DefaultEntityFilters = DefaultEntityFilters + EntityFilters extends DefaultEntityFilters = DefaultEntityFilters, >(): EntityListContextProps; // Warning: (ae-missing-release-tag) "useEntityOwnership" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) diff --git a/plugins/catalog-react/src/components/EntityLifecyclePicker/EntityLifecyclePicker.tsx b/plugins/catalog-react/src/components/EntityLifecyclePicker/EntityLifecyclePicker.tsx index e92918f551..398f619f3f 100644 --- a/plugins/catalog-react/src/components/EntityLifecyclePicker/EntityLifecyclePicker.tsx +++ b/plugins/catalog-react/src/components/EntityLifecyclePicker/EntityLifecyclePicker.tsx @@ -34,12 +34,8 @@ const icon = ; const checkedIcon = ; export const EntityLifecyclePicker = () => { - const { - updateFilters, - backendEntities, - filters, - queryParameters, - } = useEntityListProvider(); + const { updateFilters, backendEntities, filters, queryParameters } = + useEntityListProvider(); const queryParamLifecycles = [queryParameters.lifecycles] .flat() diff --git a/plugins/catalog-react/src/components/EntityOwnerPicker/EntityOwnerPicker.tsx b/plugins/catalog-react/src/components/EntityOwnerPicker/EntityOwnerPicker.tsx index eb2f274423..896cbc926b 100644 --- a/plugins/catalog-react/src/components/EntityOwnerPicker/EntityOwnerPicker.tsx +++ b/plugins/catalog-react/src/components/EntityOwnerPicker/EntityOwnerPicker.tsx @@ -36,12 +36,8 @@ const icon = ; const checkedIcon = ; export const EntityOwnerPicker = () => { - const { - updateFilters, - backendEntities, - filters, - queryParameters, - } = useEntityListProvider(); + const { updateFilters, backendEntities, filters, queryParameters } = + useEntityListProvider(); const queryParamOwners = [queryParameters.owners] .flat() diff --git a/plugins/catalog-react/src/components/EntityTable/columns.tsx b/plugins/catalog-react/src/components/EntityTable/columns.tsx index 37b1c383c7..27bf8854b6 100644 --- a/plugins/catalog-react/src/components/EntityTable/columns.tsx +++ b/plugins/catalog-react/src/components/EntityTable/columns.tsx @@ -134,7 +134,7 @@ export function createSystemColumn(): TableColumn { } export function createMetadataDescriptionColumn< - T extends Entity + T extends Entity, >(): TableColumn { return { title: 'Description', diff --git a/plugins/catalog-react/src/components/EntityTagPicker/EntityTagPicker.tsx b/plugins/catalog-react/src/components/EntityTagPicker/EntityTagPicker.tsx index 7171bb5ab1..78a2911946 100644 --- a/plugins/catalog-react/src/components/EntityTagPicker/EntityTagPicker.tsx +++ b/plugins/catalog-react/src/components/EntityTagPicker/EntityTagPicker.tsx @@ -34,12 +34,8 @@ const icon = ; const checkedIcon = ; export const EntityTagPicker = () => { - const { - updateFilters, - backendEntities, - filters, - queryParameters, - } = useEntityListProvider(); + const { updateFilters, backendEntities, filters, queryParameters } = + useEntityListProvider(); const queryParamTags = [queryParameters.tags] .flat() diff --git a/plugins/catalog-react/src/components/EntityTypePicker/EntityTypePicker.test.tsx b/plugins/catalog-react/src/components/EntityTypePicker/EntityTypePicker.test.tsx index fccf985f4f..903a7ba4eb 100644 --- a/plugins/catalog-react/src/components/EntityTypePicker/EntityTypePicker.test.tsx +++ b/plugins/catalog-react/src/components/EntityTypePicker/EntityTypePicker.test.tsx @@ -63,17 +63,17 @@ const entities: Entity[] = [ const apis = ApiRegistry.from([ [ catalogApiRef, - ({ + { getEntities: jest .fn() .mockImplementation(() => Promise.resolve({ items: entities })), - } as unknown) as CatalogApi, + } as unknown as CatalogApi, ], [ alertApiRef, - ({ + { post: jest.fn(), - } as unknown) as AlertApi, + } as unknown as AlertApi, ], ]); diff --git a/plugins/catalog-react/src/components/EntityTypePicker/EntityTypePicker.tsx b/plugins/catalog-react/src/components/EntityTypePicker/EntityTypePicker.tsx index 88538d1f65..ef6b30f863 100644 --- a/plugins/catalog-react/src/components/EntityTypePicker/EntityTypePicker.tsx +++ b/plugins/catalog-react/src/components/EntityTypePicker/EntityTypePicker.tsx @@ -24,12 +24,8 @@ import { Select } from '@backstage/core-components'; export const EntityTypePicker = () => { const alertApi = useApi(alertApiRef); - const { - error, - availableTypes, - selectedTypes, - setSelectedTypes, - } = useEntityTypeFilter(); + const { error, availableTypes, selectedTypes, setSelectedTypes } = + useEntityTypeFilter(); useEffect(() => { if (error) { diff --git a/plugins/catalog-react/src/components/UserListPicker/UserListPicker.tsx b/plugins/catalog-react/src/components/UserListPicker/UserListPicker.tsx index 0e764507fe..bfc55142a6 100644 --- a/plugins/catalog-react/src/components/UserListPicker/UserListPicker.tsx +++ b/plugins/catalog-react/src/components/UserListPicker/UserListPicker.tsx @@ -129,12 +129,8 @@ export const UserListPicker = ({ })) .filter(({ items }) => !!items.length); - const { - filters, - updateFilters, - backendEntities, - queryParameters, - } = useEntityListProvider(); + const { filters, updateFilters, backendEntities, queryParameters } = + useEntityListProvider(); const { isStarredEntity } = useStarredEntities(); const { isOwnedEntity } = useEntityOwnership(); @@ -166,9 +162,8 @@ export const UserListPicker = ({ // To show proper counts for each section, apply all other frontend filters _except_ the user // filter that's controlled by this picker. - const [entitiesWithoutUserFilter, setEntitiesWithoutUserFilter] = useState( - backendEntities, - ); + const [entitiesWithoutUserFilter, setEntitiesWithoutUserFilter] = + useState(backendEntities); useEffect(() => { const filterFn = reduceEntityFilters( compact(Object.values({ ...filters, user: undefined })), diff --git a/plugins/catalog-react/src/hooks/useEntity.ts b/plugins/catalog-react/src/hooks/useEntity.ts index 6fe25fb115..a7e6a09ae7 100644 --- a/plugins/catalog-react/src/hooks/useEntity.ts +++ b/plugins/catalog-react/src/hooks/useEntity.ts @@ -41,7 +41,12 @@ export const useEntityFromUrl = (): EntityLoadingStatus => { const errorApi = useApi(errorApiRef); const catalogApi = useApi(catalogApiRef); - const { value: entity, error, loading, retry: refresh } = useAsyncRetry( + const { + value: entity, + error, + loading, + retry: refresh, + } = useAsyncRetry( () => catalogApi.getEntityByName({ kind, namespace, name }), [catalogApi, kind, namespace, name], ); diff --git a/plugins/catalog-react/src/hooks/useEntityListProvider.tsx b/plugins/catalog-react/src/hooks/useEntityListProvider.tsx index 2506b55d6d..54d2fdcd47 100644 --- a/plugins/catalog-react/src/hooks/useEntityListProvider.tsx +++ b/plugins/catalog-react/src/hooks/useEntityListProvider.tsx @@ -51,7 +51,7 @@ export type DefaultEntityFilters = { }; export type EntityListContextProps< - EntityFilters extends DefaultEntityFilters = DefaultEntityFilters + EntityFilters extends DefaultEntityFilters = DefaultEntityFilters, > = { /** * The currently registered filters, adhering to the shape of DefaultEntityFilters or an extension @@ -215,7 +215,7 @@ export const EntityListProvider = ({ }; export function useEntityListProvider< - EntityFilters extends DefaultEntityFilters = DefaultEntityFilters + EntityFilters extends DefaultEntityFilters = DefaultEntityFilters, >(): EntityListContextProps { const context = useContext(EntityListContext); if (!context) diff --git a/plugins/catalog-react/src/hooks/useEntityOwnership.test.tsx b/plugins/catalog-react/src/hooks/useEntityOwnership.test.tsx index f617565e81..4edad98c12 100644 --- a/plugins/catalog-react/src/hooks/useEntityOwnership.test.tsx +++ b/plugins/catalog-react/src/hooks/useEntityOwnership.test.tsx @@ -46,8 +46,8 @@ describe('useEntityOwnership', () => { getEntityByName: jest.fn(), }; - const identityApi = (mockIdentityApi as unknown) as IdentityApi; - const catalogApi = (mockCatalogApi as unknown) as CatalogApi; + const identityApi = mockIdentityApi as unknown as IdentityApi; + const catalogApi = mockCatalogApi as unknown as CatalogApi; const Wrapper = ({ children }: { children?: React.ReactNode }) => ( { const myOwnerRefs = new Set(refs ?? []); return (entity: Entity | EntityName) => { - const entityOwnerRefs = ('metadata' in entity - ? getEntityRelations(entity, RELATION_OWNED_BY) - : [entity] + const entityOwnerRefs = ( + 'metadata' in entity + ? getEntityRelations(entity, RELATION_OWNED_BY) + : [entity] ).map(stringifyEntityRef); for (const ref of entityOwnerRefs) { if (myOwnerRefs.has(ref)) { diff --git a/plugins/catalog-react/src/hooks/useEntityTypeFilter.tsx b/plugins/catalog-react/src/hooks/useEntityTypeFilter.tsx index 5fa6b0f1a2..5a8ed6775a 100644 --- a/plugins/catalog-react/src/hooks/useEntityTypeFilter.tsx +++ b/plugins/catalog-react/src/hooks/useEntityTypeFilter.tsx @@ -53,7 +53,11 @@ export function useEntityTypeFilter(): EntityTypeReturn { // Load all valid spec.type values straight from the catalogApi, paying attention to only the // kind filter for a complete list. - const { error, loading, value: entities } = useAsync(async () => { + const { + error, + loading, + value: entities, + } = useAsync(async () => { if (kind) { const items = await catalogApi .getEntities({ diff --git a/plugins/catalog-react/src/hooks/useRelatedEntities.ts b/plugins/catalog-react/src/hooks/useRelatedEntities.ts index 83ed2baa58..6d6553c9e2 100644 --- a/plugins/catalog-react/src/hooks/useRelatedEntities.ts +++ b/plugins/catalog-react/src/hooks/useRelatedEntities.ts @@ -30,7 +30,11 @@ export function useRelatedEntities( error: Error | undefined; } { const catalogApi = useApi(catalogApiRef); - const { loading, value: entities, error } = useAsync(async () => { + const { + loading, + value: entities, + error, + } = useAsync(async () => { const relations = entity.relations && entity.relations.filter( diff --git a/plugins/catalog/src/components/SystemDiagramCard/SystemDiagramCard.tsx b/plugins/catalog/src/components/SystemDiagramCard/SystemDiagramCard.tsx index 272ad8a6d6..b3326abaab 100644 --- a/plugins/catalog/src/components/SystemDiagramCard/SystemDiagramCard.tsx +++ b/plugins/catalog/src/components/SystemDiagramCard/SystemDiagramCard.tsx @@ -158,7 +158,11 @@ export function SystemDiagramCard() { const systemEdges = new Array<{ from: string; to: string; label: string }>(); const catalogApi = useApi(catalogApiRef); - const { loading, error, value: catalogResponse } = useAsync(() => { + const { + loading, + error, + value: catalogResponse, + } = useAsync(() => { return catalogApi.getEntities({ filter: { kind: ['Component', 'API', 'Resource', 'System', 'Domain'], diff --git a/plugins/catalog/src/components/UnregisterEntityDialog/useUnregisterEntityDialogState.test.tsx b/plugins/catalog/src/components/UnregisterEntityDialog/useUnregisterEntityDialogState.test.tsx index 52b04020a9..6cc2f4b23b 100644 --- a/plugins/catalog/src/components/UnregisterEntityDialog/useUnregisterEntityDialogState.test.tsx +++ b/plugins/catalog/src/components/UnregisterEntityDialog/useUnregisterEntityDialogState.test.tsx @@ -47,7 +47,7 @@ describe('useUnregisterEntityDialogState', () => { removeLocationById: jest.fn(), removeEntityByUid: jest.fn(), }; - const catalogApi = (catalogApiMock as Partial) as CatalogApi; + const catalogApi = catalogApiMock as Partial as CatalogApi; const Wrapper = ({ children }: { children?: React.ReactNode }) => ( diff --git a/plugins/circleci/src/components/BuildWithStepsPage/BuildWithStepsPage.tsx b/plugins/circleci/src/components/BuildWithStepsPage/BuildWithStepsPage.tsx index 3cdc0eea7a..137833ee0b 100644 --- a/plugins/circleci/src/components/BuildWithStepsPage/BuildWithStepsPage.tsx +++ b/plugins/circleci/src/components/BuildWithStepsPage/BuildWithStepsPage.tsx @@ -35,7 +35,7 @@ import { Link, } from '@backstage/core-components'; -const IconLink = (IconButton as any) as typeof MaterialLink; +const IconLink = IconButton as any as typeof MaterialLink; const BuildName = ({ build }: { build?: BuildWithSteps }) => ( diff --git a/plugins/circleci/src/state/useBuildWithSteps.ts b/plugins/circleci/src/state/useBuildWithSteps.ts index c5b5bb1dee..eb3c0c1506 100644 --- a/plugins/circleci/src/state/useBuildWithSteps.ts +++ b/plugins/circleci/src/state/useBuildWithSteps.ts @@ -62,9 +62,10 @@ export function useBuildWithSteps(buildId: number) { } }; - const { loading, value, retry } = useAsyncRetry(() => getBuildWithSteps(), [ - getBuildWithSteps, - ]); + const { loading, value, retry } = useAsyncRetry( + () => getBuildWithSteps(), + [getBuildWithSteps], + ); const { startPolling, stopPolling } = useAsyncPolling( getBuildWithSteps, diff --git a/plugins/circleci/src/state/useBuilds.ts b/plugins/circleci/src/state/useBuilds.ts index 9feb16d253..a9869644a3 100644 --- a/plugins/circleci/src/state/useBuilds.ts +++ b/plugins/circleci/src/state/useBuilds.ts @@ -26,21 +26,23 @@ import { errorApiRef, useApi } from '@backstage/core-plugin-api'; const makeReadableStatus = (status: string | undefined) => { if (!status) return ''; - return ({ - retried: 'Retried', - canceled: 'Canceled', - infrastructure_fail: 'Infra fail', - timedout: 'Timedout', - not_run: 'Not run', - running: 'Running', - failed: 'Failed', - queued: 'Queued', - scheduled: 'Scheduled', - not_running: 'Not running', - no_tests: 'No tests', - fixed: 'Fixed', - success: 'Success', - } as Record)[status]; + return ( + { + retried: 'Retried', + canceled: 'Canceled', + infrastructure_fail: 'Infra fail', + timedout: 'Timedout', + not_run: 'Not run', + running: 'Running', + failed: 'Failed', + queued: 'Queued', + scheduled: 'Scheduled', + not_running: 'Not running', + no_tests: 'No tests', + fixed: 'Fixed', + success: 'Success', + } as Record + )[status]; }; const mapWorkflowDetails = (buildData: BuildSummary) => { diff --git a/plugins/cloudbuild/src/api/CloudbuildClient.ts b/plugins/cloudbuild/src/api/CloudbuildClient.ts index ce9dfb700c..cbd47e84e9 100644 --- a/plugins/cloudbuild/src/api/CloudbuildClient.ts +++ b/plugins/cloudbuild/src/api/CloudbuildClient.ts @@ -60,7 +60,8 @@ export class CloudbuildClient implements CloudbuildApi { }, ); - const builds: ActionsListWorkflowRunsForRepoResponseData = await workflowRuns.json(); + const builds: ActionsListWorkflowRunsForRepoResponseData = + await workflowRuns.json(); return builds; } diff --git a/plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunJobs.ts b/plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunJobs.ts index 9bd1ea2c82..0450d3d613 100644 --- a/plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunJobs.ts +++ b/plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunJobs.ts @@ -17,15 +17,16 @@ import { useAsync } from 'react-use'; import { ActionsListWorkflowRunsForRepoResponseData } from '../../api/types'; export const useWorkflowRunJobs = (jobsUrl?: string) => { - const jobs = useAsync(async (): Promise => { - if (jobsUrl === undefined) { - return { - builds: [], - }; - } + const jobs = + useAsync(async (): Promise => { + if (jobsUrl === undefined) { + return { + builds: [], + }; + } - const data = await fetch(jobsUrl).then(d => d.json()); - return data; - }, [jobsUrl]); + const data = await fetch(jobsUrl).then(d => d.json()); + return data; + }, [jobsUrl]); return jobs; }; diff --git a/plugins/cloudbuild/src/components/useWorkflowRuns.ts b/plugins/cloudbuild/src/components/useWorkflowRuns.ts index b1efeecbbe..3c4810d4f6 100644 --- a/plugins/cloudbuild/src/components/useWorkflowRuns.ts +++ b/plugins/cloudbuild/src/components/useWorkflowRuns.ts @@ -41,9 +41,12 @@ export function useWorkflowRuns({ projectId }: { projectId: string }) { const [page, setPage] = useState(0); const [pageSize, setPageSize] = useState(5); - const { loading, value: runs, retry, error } = useAsyncRetry< - WorkflowRun[] - >(async () => { + const { + loading, + value: runs, + retry, + error, + } = useAsyncRetry(async () => { return api .listWorkflowRuns({ projectId, diff --git a/plugins/code-coverage-backend/src/service/converter/cobertura.ts b/plugins/code-coverage-backend/src/service/converter/cobertura.ts index 429e645cf2..12893a397d 100644 --- a/plugins/code-coverage-backend/src/service/converter/cobertura.ts +++ b/plugins/code-coverage-backend/src/service/converter/cobertura.ts @@ -117,8 +117,8 @@ export class Cobertura implements Converter { const lines = [classLines, methodLines].flat().filter(Boolean); const lineHits = lines.map(l => { return { - number: parseInt((l.$.number as unknown) as string, 10), - hits: parseInt((l.$.hits as unknown) as string, 10), + number: parseInt(l.$.number as unknown as string, 10), + hits: parseInt(l.$.hits as unknown as string, 10), 'condition-coverage': l.$['condition-coverage'], branch: l.$.branch, }; diff --git a/plugins/code-coverage-backend/src/service/router.ts b/plugins/code-coverage-backend/src/service/router.ts index f28ff5e0d5..5f136cc8e9 100644 --- a/plugins/code-coverage-backend/src/service/router.ts +++ b/plugins/code-coverage-backend/src/service/router.ts @@ -189,12 +189,8 @@ export const makeRouter = async ( throw new InputError(`Unsupported coverage type '${coverageType}`); } - const { - sourceLocation, - vcs, - scmFiles, - body, - } = await utils.processCoveragePayload(entityLookup, req); + const { sourceLocation, vcs, scmFiles, body } = + await utils.processCoveragePayload(entityLookup, req); const files = converter.convert(body, scmFiles); if (!files || files.length === 0) { diff --git a/plugins/config-schema/dev/index.tsx b/plugins/config-schema/dev/index.tsx index ef31dc10ee..135449d808 100644 --- a/plugins/config-schema/dev/index.tsx +++ b/plugins/config-schema/dev/index.tsx @@ -31,7 +31,7 @@ createDevApp() factory: () => ({ schema$: () => new Observable(sub => - sub.next({ schema: (exampleSchema as unknown) as Schema }), + sub.next({ schema: exampleSchema as unknown as Schema }), ), }), }) diff --git a/plugins/cost-insights/api-report.md b/plugins/cost-insights/api-report.md index 541c2af9e0..61ee64859c 100644 --- a/plugins/cost-insights/api-report.md +++ b/plugins/cost-insights/api-report.md @@ -100,7 +100,7 @@ export enum AlertDismissReason { // @public (undocumented) export type AlertForm< A extends Alert = any, - Data = any + Data = any, > = ForwardRefExoticComponent< AlertFormProps & RefAttributes >; diff --git a/plugins/cost-insights/src/components/AlertInsights/AlertInsights.tsx b/plugins/cost-insights/src/components/AlertInsights/AlertInsights.tsx index 01711e5328..2daacda85e 100644 --- a/plugins/cost-insights/src/components/AlertInsights/AlertInsights.tsx +++ b/plugins/cost-insights/src/components/AlertInsights/AlertInsights.tsx @@ -41,10 +41,10 @@ import { ScrollAnchor } from '../../utils/scroll'; type MapLoadingtoAlerts = (isLoading: boolean) => void; -const mapLoadingToAlerts: MapLoadingToProps = ({ - dispatch, -}) => (isLoading: boolean) => - dispatch({ [DefaultLoadingAction.CostInsightsAlerts]: isLoading }); +const mapLoadingToAlerts: MapLoadingToProps = + ({ dispatch }) => + (isLoading: boolean) => + dispatch({ [DefaultLoadingAction.CostInsightsAlerts]: isLoading }); type AlertInsightsProps = { group: string; diff --git a/plugins/cost-insights/src/components/BarChart/BarChartSteps.tsx b/plugins/cost-insights/src/components/BarChart/BarChartSteps.tsx index 682cd2a485..556154d046 100644 --- a/plugins/cost-insights/src/components/BarChart/BarChartSteps.tsx +++ b/plugins/cost-insights/src/components/BarChart/BarChartSteps.tsx @@ -30,12 +30,12 @@ export const BarChartSteps = ({ onClick, }: BarChartStepsProps) => { const classes = useStyles(); - const handleOnClick = (index: number) => ( - event: React.MouseEvent, - ) => { - event.preventDefault(); - onClick(index); - }; + const handleOnClick = + (index: number) => + (event: React.MouseEvent) => { + event.preventDefault(); + onClick(index); + }; return (
    diff --git a/plugins/cost-insights/src/components/CostInsightsPage/selector.tsx b/plugins/cost-insights/src/components/CostInsightsPage/selector.tsx index caafd6ad42..d9591dbdd6 100644 --- a/plugins/cost-insights/src/components/CostInsightsPage/selector.tsx +++ b/plugins/cost-insights/src/components/CostInsightsPage/selector.tsx @@ -31,21 +31,18 @@ type CostInsightsPageLoadingProps = { dispatchReset: (loadingActions: string[]) => void; }; -export const mapLoadingToProps: MapLoadingToProps = ({ - state, - actions, - dispatch, -}) => ({ - loadingActions: actions, - loadingGroups: state[DefaultLoadingAction.UserGroups], - loadingBillingDate: state[DefaultLoadingAction.LastCompleteBillingDate], - loadingInitial: state[DefaultLoadingAction.CostInsightsInitial], - dispatchInitial: (isLoading: boolean) => - dispatch({ [DefaultLoadingAction.CostInsightsInitial]: isLoading }), - dispatchInsights: (isLoading: boolean) => - dispatch({ [DefaultLoadingAction.CostInsightsPage]: isLoading }), - dispatchNone: (loadingActions: string[]) => - dispatch(getResetState(loadingActions)), - dispatchReset: (loadingActions: string[]) => - dispatch(getResetStateWithoutInitial(loadingActions)), -}); +export const mapLoadingToProps: MapLoadingToProps = + ({ state, actions, dispatch }) => ({ + loadingActions: actions, + loadingGroups: state[DefaultLoadingAction.UserGroups], + loadingBillingDate: state[DefaultLoadingAction.LastCompleteBillingDate], + loadingInitial: state[DefaultLoadingAction.CostInsightsInitial], + dispatchInitial: (isLoading: boolean) => + dispatch({ [DefaultLoadingAction.CostInsightsInitial]: isLoading }), + dispatchInsights: (isLoading: boolean) => + dispatch({ [DefaultLoadingAction.CostInsightsPage]: isLoading }), + dispatchNone: (loadingActions: string[]) => + dispatch(getResetState(loadingActions)), + dispatchReset: (loadingActions: string[]) => + dispatch(getResetStateWithoutInitial(loadingActions)), + }); diff --git a/plugins/cost-insights/src/components/CostInsightsTabs/selector.ts b/plugins/cost-insights/src/components/CostInsightsTabs/selector.ts index c212c0bb73..59b1c9549c 100644 --- a/plugins/cost-insights/src/components/CostInsightsTabs/selector.ts +++ b/plugins/cost-insights/src/components/CostInsightsTabs/selector.ts @@ -28,24 +28,20 @@ type CostInsightsTabsLoadingProps = { dispatchReset: (loadingActions: string[]) => void; }; -export const mapFiltersToProps: MapFiltersToProps = ({ - pageFilters, - setPageFilters, -}) => ({ - ...pageFilters, - setGroup: (group: Group) => - setPageFilters({ - ...pageFilters, - group: group.id, - project: null, - }), -}); +export const mapFiltersToProps: MapFiltersToProps = + ({ pageFilters, setPageFilters }) => ({ + ...pageFilters, + setGroup: (group: Group) => + setPageFilters({ + ...pageFilters, + group: group.id, + project: null, + }), + }); -export const mapLoadingToProps: MapLoadingToProps = ({ - actions, - dispatch, -}) => ({ - loadingActions: actions, - dispatchReset: (loadingActions: string[]) => - dispatch(getResetStateWithoutInitial(loadingActions)), -}); +export const mapLoadingToProps: MapLoadingToProps = + ({ actions, dispatch }) => ({ + loadingActions: actions, + dispatchReset: (loadingActions: string[]) => + dispatch(getResetStateWithoutInitial(loadingActions)), + }); diff --git a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx index a5cd9e524e..1a4bb4ba6e 100644 --- a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx +++ b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx @@ -51,9 +51,8 @@ export const CostOverviewCard = ({ const styles = useOverviewTabsStyles(theme); const config = useConfig(); const [tabIndex, setTabIndex] = useState(0); - const { setDuration, setProject, setMetric, ...filters } = useFilters( - mapFiltersToProps, - ); + const { setDuration, setProject, setMetric, ...filters } = + useFilters(mapFiltersToProps); // Reset tabIndex if breakdowns available change useEffect(() => { diff --git a/plugins/cost-insights/src/components/ProductInsights/ProductInsights.test.tsx b/plugins/cost-insights/src/components/ProductInsights/ProductInsights.test.tsx index f90f30d2eb..7253febd71 100644 --- a/plugins/cost-insights/src/components/ProductInsights/ProductInsights.test.tsx +++ b/plugins/cost-insights/src/components/ProductInsights/ProductInsights.test.tsx @@ -170,7 +170,8 @@ describe('', () => { } it('should render each product panel', async () => { - const noComputeEngineCostsRgx = /There are no Compute Engine costs within this time frame for your team's projects./; + const noComputeEngineCostsRgx = + /There are no Compute Engine costs within this time frame for your team's projects./; const { getByText } = await renderInContext( void; -const mapLoadingToProps: MapLoadingToProps = ({ dispatch }) => ( - isLoading: boolean, -) => dispatch({ [DefaultLoadingAction.CostInsightsProducts]: isLoading }); +const mapLoadingToProps: MapLoadingToProps = + ({ dispatch }) => + (isLoading: boolean) => + dispatch({ [DefaultLoadingAction.CostInsightsProducts]: isLoading }); type ProductInsightsProps = { group: string; diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx index a75141a7a3..2b4ee4b0db 100644 --- a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx +++ b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx @@ -49,9 +49,10 @@ export type ProductInsightsCardProps = { onSelectAsync: (product: Product, duration: Duration) => Promise; }; -const mapLoadingToProps: MapLoadingToProps = ({ dispatch }) => ( - isLoading: boolean, -) => dispatch({ [DefaultLoadingAction.CostInsightsProducts]: isLoading }); +const mapLoadingToProps: MapLoadingToProps = + ({ dispatch }) => + (isLoading: boolean) => + dispatch({ [DefaultLoadingAction.CostInsightsProducts]: isLoading }); export const ProductInsightsCard = ({ initialState, diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/selector.ts b/plugins/cost-insights/src/components/ProductInsightsCard/selector.ts index c4ca0630c9..8d60253c3b 100644 --- a/plugins/cost-insights/src/components/ProductInsightsCard/selector.ts +++ b/plugins/cost-insights/src/components/ProductInsightsCard/selector.ts @@ -29,29 +29,22 @@ type ProductInsightsCardLoadingProps = { dispatchLoading: (isLoading: boolean) => void; }; -export const mapFiltersToProps = ( - product: string, -): MapFiltersToProps => ({ - pageFilters, - productFilters, - setProductFilters, -}) => ({ - ...pageFilters, - product: findAlways(productFilters, p => p.productType === product), - setProduct: (duration: Duration) => - setProductFilters( - productFilters.map(period => - period.productType === product ? { ...period, duration } : period, +export const mapFiltersToProps = + (product: string): MapFiltersToProps => + ({ pageFilters, productFilters, setProductFilters }) => ({ + ...pageFilters, + product: findAlways(productFilters, p => p.productType === product), + setProduct: (duration: Duration) => + setProductFilters( + productFilters.map(period => + period.productType === product ? { ...period, duration } : period, + ), ), - ), -}); + }); -export const mapLoadingToProps = ( - product: string, -): MapLoadingToProps => ({ - state, - dispatch, -}) => ({ - loadingProduct: state[product], - dispatchLoading: (isLoading: boolean) => dispatch({ [product]: isLoading }), -}); +export const mapLoadingToProps = + (product: string): MapLoadingToProps => + ({ state, dispatch }) => ({ + loadingProduct: state[product], + dispatchLoading: (isLoading: boolean) => dispatch({ [product]: isLoading }), + }); diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx index 367af46112..5c226d4cb3 100644 --- a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx @@ -22,14 +22,13 @@ import { } from '../../testUtils'; import { renderInTestApp } from '@backstage/test-utils'; -const MockUnlabeledDataflowAlertMultipleProjects = createMockUnlabeledDataflowData( - data => ({ +const MockUnlabeledDataflowAlertMultipleProjects = + createMockUnlabeledDataflowData(data => ({ ...data, projects: [...Array(10)].map(() => createMockUnlabeledDataflowAlertProject(), ), - }), -); + })); const MockUnlabeledDataflowAlertSingleProject = createMockUnlabeledDataflowData( data => ({ diff --git a/plugins/cost-insights/src/hooks/useFilters.tsx b/plugins/cost-insights/src/hooks/useFilters.tsx index 959b280b69..abe7a132cc 100644 --- a/plugins/cost-insights/src/hooks/useFilters.tsx +++ b/plugins/cost-insights/src/hooks/useFilters.tsx @@ -54,9 +54,8 @@ export const FilterProvider = ({ children }: PropsWithChildren<{}>) => { const groups = useGroups(); const [error, setError] = useState>(null); const [pageFilters, setPageFilters] = useState>(null); - const [productFilters, setProductFilters] = useState>( - null, - ); + const [productFilters, setProductFilters] = + useState>(null); useEffect(() => { async function setPageFiltersFromLocation() { diff --git a/plugins/cost-insights/src/hooks/useLastCompleteBillingDate.tsx b/plugins/cost-insights/src/hooks/useLastCompleteBillingDate.tsx index 471debbaac..d8236ed61a 100644 --- a/plugins/cost-insights/src/hooks/useLastCompleteBillingDate.tsx +++ b/plugins/cost-insights/src/hooks/useLastCompleteBillingDate.tsx @@ -59,9 +59,8 @@ export const BillingDateProvider = ({ children }: PropsWithChildren<{}>) => { const [error, setError] = useState>(null); const { dispatchLoadingBillingDate } = useLoading(mapLoadingToProps); - const [lastCompleteBillingDate, setLastCompeteBillingDate] = useState< - Maybe - >(null); + const [lastCompleteBillingDate, setLastCompeteBillingDate] = + useState>(null); useEffect(() => { dispatchLoadingBillingDate(true); diff --git a/plugins/cost-insights/src/plugin.ts b/plugins/cost-insights/src/plugin.ts index 17a512ae9c..08910dcbca 100644 --- a/plugins/cost-insights/src/plugin.ts +++ b/plugins/cost-insights/src/plugin.ts @@ -55,22 +55,24 @@ export const CostInsightsPage = costInsightsPlugin.provide( }), ); -export const CostInsightsProjectGrowthInstructionsPage = costInsightsPlugin.provide( - createRoutableExtension({ - component: () => - import('./components/ProjectGrowthInstructionsPage').then( - m => m.ProjectGrowthInstructionsPage, - ), - mountPoint: projectGrowthAlertRef, - }), -); +export const CostInsightsProjectGrowthInstructionsPage = + costInsightsPlugin.provide( + createRoutableExtension({ + component: () => + import('./components/ProjectGrowthInstructionsPage').then( + m => m.ProjectGrowthInstructionsPage, + ), + mountPoint: projectGrowthAlertRef, + }), + ); -export const CostInsightsLabelDataflowInstructionsPage = costInsightsPlugin.provide( - createRoutableExtension({ - component: () => - import('./components/LabelDataflowInstructionsPage').then( - m => m.LabelDataflowInstructionsPage, - ), - mountPoint: unlabeledDataflowAlertRef, - }), -); +export const CostInsightsLabelDataflowInstructionsPage = + costInsightsPlugin.provide( + createRoutableExtension({ + component: () => + import('./components/LabelDataflowInstructionsPage').then( + m => m.LabelDataflowInstructionsPage, + ), + mountPoint: unlabeledDataflowAlertRef, + }), + ); diff --git a/plugins/cost-insights/src/testUtils/loading.ts b/plugins/cost-insights/src/testUtils/loading.ts index 576415b61e..48997dc877 100644 --- a/plugins/cost-insights/src/testUtils/loading.ts +++ b/plugins/cost-insights/src/testUtils/loading.ts @@ -19,11 +19,13 @@ import { getDefaultState as getDefaultLoadingState, } from '../utils/loading'; -export const MockDefaultLoadingActions = ([ - DefaultLoadingAction.UserGroups, - DefaultLoadingAction.CostInsightsInitial, - DefaultLoadingAction.CostInsightsPage, -] as string[]).concat(MockProducts.map(product => product.kind)); +export const MockDefaultLoadingActions = ( + [ + DefaultLoadingAction.UserGroups, + DefaultLoadingAction.CostInsightsInitial, + DefaultLoadingAction.CostInsightsPage, + ] as string[] +).concat(MockProducts.map(product => product.kind)); export const mockDefaultLoadingState = getDefaultLoadingState( MockDefaultLoadingActions, diff --git a/plugins/cost-insights/src/testUtils/providers.tsx b/plugins/cost-insights/src/testUtils/providers.tsx index ee92909141..75450c0bb7 100644 --- a/plugins/cost-insights/src/testUtils/providers.tsx +++ b/plugins/cost-insights/src/testUtils/providers.tsx @@ -37,7 +37,8 @@ type PartialPropsWithChildren = PropsWithChildren>; export const MockGroups: Group[] = [{ id: 'tech' }, { id: 'mock-group' }]; -export type MockFilterProviderProps = PartialPropsWithChildren; +export type MockFilterProviderProps = + PartialPropsWithChildren; export const MockFilterProvider = ({ children, @@ -61,7 +62,8 @@ export const MockFilterProvider = ({ ); }; -export type MockLoadingProviderProps = PartialPropsWithChildren; +export type MockLoadingProviderProps = + PartialPropsWithChildren; export const MockLoadingProvider = ({ children, @@ -79,7 +81,8 @@ export const MockLoadingProvider = ({ ); }; -export type MockConfigProviderProps = PartialPropsWithChildren; +export type MockConfigProviderProps = + PartialPropsWithChildren; export const MockConfigProvider = ({ children, @@ -99,7 +102,8 @@ export const MockConfigProvider = ({ ); }; -export type MockCurrencyProviderProps = PartialPropsWithChildren; +export type MockCurrencyProviderProps = + PartialPropsWithChildren; export const MockCurrencyProvider = ({ children, @@ -120,7 +124,8 @@ export const MockCurrencyProvider = ({ ); }; -export type MockBillingDateProviderProps = PartialPropsWithChildren; +export type MockBillingDateProviderProps = + PartialPropsWithChildren; export const MockBillingDateProvider = ({ children, @@ -150,7 +155,8 @@ export const MockScrollProvider = ({ children }: MockScrollProviderProps) => { ); }; -export type MockGroupsProviderProps = PartialPropsWithChildren; +export type MockGroupsProviderProps = + PartialPropsWithChildren; export const MockGroupsProvider = ({ children, diff --git a/plugins/cost-insights/src/types/Alert.ts b/plugins/cost-insights/src/types/Alert.ts index 2ea9b30103..2f220be0e6 100644 --- a/plugins/cost-insights/src/types/Alert.ts +++ b/plugins/cost-insights/src/types/Alert.ts @@ -50,7 +50,7 @@ export type Alert = { export type AlertForm< A extends Alert = any, - Data = any + Data = any, > = ForwardRefExoticComponent< AlertFormProps & RefAttributes >; diff --git a/plugins/cost-insights/src/utils/alerts.tsx b/plugins/cost-insights/src/utils/alerts.tsx index 25680b5507..2039a5b617 100644 --- a/plugins/cost-insights/src/utils/alerts.tsx +++ b/plugins/cost-insights/src/utils/alerts.tsx @@ -30,29 +30,30 @@ export const isStatusSnoozed = createStatusHandler(AlertStatus.Snoozed); export const isStatusAccepted = createStatusHandler(AlertStatus.Accepted); export const isStatusDismissed = createStatusHandler(AlertStatus.Dismissed); -const createAlertEventHandler = ( - onEvent: 'onSnoozed' | 'onAccepted' | 'onDismissed', -) => (alert: Maybe): boolean => hasProperty(alert, onEvent); +const createAlertEventHandler = + (onEvent: 'onSnoozed' | 'onAccepted' | 'onDismissed') => + (alert: Maybe): boolean => + hasProperty(alert, onEvent); export const isSnoozeEnabled = createAlertEventHandler('onSnoozed'); export const isAcceptEnabled = createAlertEventHandler('onAccepted'); export const isDismissEnabled = createAlertEventHandler('onDismissed'); -const createFormEnabledHandler = ( - Form: 'SnoozeForm' | 'AcceptForm' | 'DismissForm', -) => (alert: Maybe): boolean => { - if (!alert) return false; - if (alert[Form] === null) return false; - switch (Form) { - case 'SnoozeForm': - return isSnoozeEnabled(alert); - case 'AcceptForm': - return isAcceptEnabled(alert); - case 'DismissForm': - return isDismissEnabled(alert); - default: - return false; - } -}; +const createFormEnabledHandler = + (Form: 'SnoozeForm' | 'AcceptForm' | 'DismissForm') => + (alert: Maybe): boolean => { + if (!alert) return false; + if (alert[Form] === null) return false; + switch (Form) { + case 'SnoozeForm': + return isSnoozeEnabled(alert); + case 'AcceptForm': + return isAcceptEnabled(alert); + case 'DismissForm': + return isDismissEnabled(alert); + default: + return false; + } + }; export const isSnoozeFormEnabled = createFormEnabledHandler('SnoozeForm'); export const isAcceptFormEnabled = createFormEnabledHandler('AcceptForm'); export const isDismissFormEnabled = createFormEnabledHandler('DismissForm'); diff --git a/plugins/cost-insights/src/utils/formatters.test.ts b/plugins/cost-insights/src/utils/formatters.test.ts index fbddcd1cb0..9fe17f277f 100644 --- a/plugins/cost-insights/src/utils/formatters.test.ts +++ b/plugins/cost-insights/src/utils/formatters.test.ts @@ -36,11 +36,7 @@ describe('date formatters', () => { it('Correctly formats values to two significant digits', () => { const values = [ - 0.00000040925, - 0.21, - 0.0000004, - 0.4139877878, - 0.00000234566, + 0.00000040925, 0.21, 0.0000004, 0.4139877878, 0.00000234566, ]; const formattedValues = values.map(val => lengthyCurrencyFormatter.format(val), diff --git a/plugins/explore/src/components/DomainExplorerContent/DomainExplorerContent.tsx b/plugins/explore/src/components/DomainExplorerContent/DomainExplorerContent.tsx index ca1a0a1a20..781d21bd91 100644 --- a/plugins/explore/src/components/DomainExplorerContent/DomainExplorerContent.tsx +++ b/plugins/explore/src/components/DomainExplorerContent/DomainExplorerContent.tsx @@ -34,7 +34,11 @@ import { useApi } from '@backstage/core-plugin-api'; const Body = () => { const catalogApi = useApi(catalogApiRef); - const { value: entities, loading, error } = useAsync(async () => { + const { + value: entities, + loading, + error, + } = useAsync(async () => { const response = await catalogApi.getEntities({ filter: { kind: 'domain' }, }); diff --git a/plugins/explore/src/components/GroupsExplorerContent/GroupsDiagram.tsx b/plugins/explore/src/components/GroupsExplorerContent/GroupsDiagram.tsx index ce09f0d268..71492c3520 100644 --- a/plugins/explore/src/components/GroupsExplorerContent/GroupsDiagram.tsx +++ b/plugins/explore/src/components/GroupsExplorerContent/GroupsDiagram.tsx @@ -119,7 +119,11 @@ export function GroupsDiagram() { const catalogApi = useApi(catalogApiRef); const organizationName = configApi.getOptionalString('organization.name') ?? 'Backstage'; - const { loading, error, value: catalogResponse } = useAsync(() => { + const { + loading, + error, + value: catalogResponse, + } = useAsync(() => { return catalogApi.getEntities({ filter: { kind: ['Group'], diff --git a/plugins/explore/src/components/ToolExplorerContent/ToolExplorerContent.tsx b/plugins/explore/src/components/ToolExplorerContent/ToolExplorerContent.tsx index afeeb28f6e..ec532f3004 100644 --- a/plugins/explore/src/components/ToolExplorerContent/ToolExplorerContent.tsx +++ b/plugins/explore/src/components/ToolExplorerContent/ToolExplorerContent.tsx @@ -33,7 +33,11 @@ import { useApi } from '@backstage/core-plugin-api'; const Body = () => { const exploreToolsConfigApi = useApi(exploreToolsConfigRef); - const { value: tools, loading, error } = useAsync(async () => { + const { + value: tools, + loading, + error, + } = useAsync(async () => { return await exploreToolsConfigApi.getTools(); }, [exploreToolsConfigApi]); diff --git a/plugins/fossa/dev/index.tsx b/plugins/fossa/dev/index.tsx index 83fa209c31..018d3e3acb 100644 --- a/plugins/fossa/dev/index.tsx +++ b/plugins/fossa/dev/index.tsx @@ -135,7 +135,7 @@ createDevApp() api: catalogApiRef, deps: {}, factory: () => - (({ + ({ getEntities: async () => { await new Promise(r => setTimeout(r, 1000)); @@ -148,7 +148,7 @@ createDevApp() ], }; }, - } as Partial) as any), + } as Partial as any), }) .addPage({ title: 'Entity Content', diff --git a/plugins/gcp-projects/src/components/ProjectDetailsPage/ProjectDetailsPage.tsx b/plugins/gcp-projects/src/components/ProjectDetailsPage/ProjectDetailsPage.tsx index 0acc191e8a..f5da97b7eb 100644 --- a/plugins/gcp-projects/src/components/ProjectDetailsPage/ProjectDetailsPage.tsx +++ b/plugins/gcp-projects/src/components/ProjectDetailsPage/ProjectDetailsPage.tsx @@ -59,7 +59,11 @@ const DetailsPage = () => { const api = useApi(gcpApiRef); const classes = useStyles(); - const { loading, error, value: details } = useAsync( + const { + loading, + error, + value: details, + } = useAsync( async () => api.getProject( decodeURIComponent(location.search.split('projectId=')[1]), diff --git a/plugins/git-release-manager/src/api/GitReleaseClient.ts b/plugins/git-release-manager/src/api/GitReleaseClient.ts index b0f1a163a9..948c77b47a 100644 --- a/plugins/git-release-manager/src/api/GitReleaseClient.ts +++ b/plugins/git-release-manager/src/api/GitReleaseClient.ts @@ -37,9 +37,8 @@ export class GitReleaseClient implements GitReleaseApi { }) { this.githubAuthApi = githubAuthApi; - const gitHubIntegrations = ScmIntegrations.fromConfig( - configApi, - ).github.list(); + const gitHubIntegrations = + ScmIntegrations.fromConfig(configApi).github.list(); const { host, apiBaseUrl } = this.getGithubIntegrationConfig({ gitHubIntegrations, }); @@ -555,15 +554,11 @@ export interface GitReleaseApi { owners: string[]; }>; - getRepositories: (args: { - owner: OwnerRepo['owner']; - }) => Promise<{ + getRepositories: (args: { owner: OwnerRepo['owner'] }) => Promise<{ repositories: string[]; }>; - getUser: ( - args: OwnerRepo, - ) => Promise<{ + getUser: (args: OwnerRepo) => Promise<{ user: { username: string; email?: string; @@ -589,9 +584,7 @@ export interface GitReleaseApi { }[]; }>; - getLatestRelease: ( - args: OwnerRepo, - ) => Promise<{ + getLatestRelease: (args: OwnerRepo) => Promise<{ latestRelease: { targetCommitish: string; tagName: string; @@ -602,9 +595,7 @@ export interface GitReleaseApi { } | null; }>; - getRepository: ( - args: OwnerRepo, - ) => Promise<{ + getRepository: (args: OwnerRepo) => Promise<{ repository: { pushPermissions: boolean | undefined; defaultBranch: string; @@ -765,9 +756,7 @@ export interface GitReleaseApi { /** * Get all tags in descending order */ - getAllTags: ( - args: OwnerRepo, - ) => Promise<{ + getAllTags: (args: OwnerRepo) => Promise<{ tags: Array<{ tagName: string; tagSha: string; @@ -775,9 +764,7 @@ export interface GitReleaseApi { }>; }>; - getAllReleases: ( - args: OwnerRepo, - ) => Promise<{ + getAllReleases: (args: OwnerRepo) => Promise<{ releases: Array<{ id: number; name: string | null; diff --git a/plugins/git-release-manager/src/features/CreateReleaseCandidate/CreateReleaseCandidate.tsx b/plugins/git-release-manager/src/features/CreateReleaseCandidate/CreateReleaseCandidate.tsx index 7f24241e66..6400f63b40 100644 --- a/plugins/git-release-manager/src/features/CreateReleaseCandidate/CreateReleaseCandidate.tsx +++ b/plugins/git-release-manager/src/features/CreateReleaseCandidate/CreateReleaseCandidate.tsx @@ -80,18 +80,14 @@ export const CreateReleaseCandidate = ({ ); }, [semverBumpLevel, setReleaseCandidateGitInfo, latestRelease, project]); - const { - progress, - responseSteps, - run, - runInvoked, - } = useCreateReleaseCandidate({ - defaultBranch, - latestRelease, - releaseCandidateGitInfo, - project, - onSuccess, - }); + const { progress, responseSteps, run, runInvoked } = + useCreateReleaseCandidate({ + defaultBranch, + latestRelease, + releaseCandidateGitInfo, + project, + onSuccess, + }); if (responseSteps.length > 0) { return ( { // FIXME: Performance improvement opportunity: Convert to object lookup - const commitExistsOnReleaseBranch = !!gitDataResponse.value?.recentCommitsOnReleaseBranch.find( - releaseBranchCommit => - releaseBranchCommit.sha === commit.sha || - // The selected patch commit's sha is included in the commit message, - // which means it's part of a previous patch - releaseBranchCommit.commit.message.includes( - getPatchCommitSuffix({ commitSha: commit.sha }), - ), - ); + const commitExistsOnReleaseBranch = + !!gitDataResponse.value?.recentCommitsOnReleaseBranch.find( + releaseBranchCommit => + releaseBranchCommit.sha === commit.sha || + // The selected patch commit's sha is included in the commit message, + // which means it's part of a previous patch + releaseBranchCommit.commit.message.includes( + getPatchCommitSuffix({ commitSha: commit.sha }), + ), + ); const hasNoParent = !commit.firstParentSha; return ( diff --git a/plugins/git-release-manager/src/features/Patch/hooks/usePatch.ts b/plugins/git-release-manager/src/features/Patch/hooks/usePatch.ts index a2cbb7aefb..338fa2a2d1 100644 --- a/plugins/git-release-manager/src/features/Patch/hooks/usePatch.ts +++ b/plugins/git-release-manager/src/features/Patch/hooks/usePatch.ts @@ -54,12 +54,8 @@ export function usePatch({ }: UsePatch): CardHook { const pluginApiClient = useApi(gitReleaseManagerApiRef); const { user } = useUserContext(); - const { - responseSteps, - addStepToResponseSteps, - asyncCatcher, - abortIfError, - } = useResponseSteps(); + const { responseSteps, addStepToResponseSteps, asyncCatcher, abortIfError } = + useResponseSteps(); const releaseBranchName = latestRelease.targetCommitish; diff --git a/plugins/git-release-manager/src/features/PromoteRc/hooks/usePromoteRc.ts b/plugins/git-release-manager/src/features/PromoteRc/hooks/usePromoteRc.ts index f3a87d3c74..232bc0b744 100644 --- a/plugins/git-release-manager/src/features/PromoteRc/hooks/usePromoteRc.ts +++ b/plugins/git-release-manager/src/features/PromoteRc/hooks/usePromoteRc.ts @@ -45,12 +45,8 @@ export function usePromoteRc({ const pluginApiClient = useApi(gitReleaseManagerApiRef); const { user } = useUserContext(); const { project } = useProjectContext(); - const { - responseSteps, - addStepToResponseSteps, - asyncCatcher, - abortIfError, - } = useResponseSteps(); + const { responseSteps, addStepToResponseSteps, asyncCatcher, abortIfError } = + useResponseSteps(); /** * (1) Fetch most recent release branch commit diff --git a/plugins/git-release-manager/src/features/Stats/Info/InDepth/InDepth.tsx b/plugins/git-release-manager/src/features/Stats/Info/InDepth/InDepth.tsx index 8d3862ab1e..b55b0a79b2 100644 --- a/plugins/git-release-manager/src/features/Stats/Info/InDepth/InDepth.tsx +++ b/plugins/git-release-manager/src/features/Stats/Info/InDepth/InDepth.tsx @@ -31,12 +31,8 @@ import { useReleaseStatsContext } from '../../contexts/ReleaseStatsContext'; export function InDepth() { const { releaseStats } = useReleaseStatsContext(); - const { - averageReleaseTime, - progress, - releaseCommitPairs, - run, - } = useGetReleaseTimes(); + const { averageReleaseTime, progress, releaseCommitPairs, run } = + useGetReleaseTimes(); const skipped = Object.keys(releaseStats.releases).length - releaseCommitPairs.length; diff --git a/plugins/git-release-manager/src/features/Stats/Info/hooks/useGetReleaseTimes.tsx b/plugins/git-release-manager/src/features/Stats/Info/hooks/useGetReleaseTimes.tsx index 8707fc0920..35cb3bc411 100644 --- a/plugins/git-release-manager/src/features/Stats/Info/hooks/useGetReleaseTimes.tsx +++ b/plugins/git-release-manager/src/features/Stats/Info/hooks/useGetReleaseTimes.tsx @@ -80,19 +80,16 @@ export function useGetReleaseTimes() { }, [averageReleaseTime.length, releaseCommitPairs.length]); async function getAndSetReleaseTime({ pairIndex }: { pairIndex: number }) { - const { baseVersion, startCommit, endCommit } = releaseCommitPairs[ - pairIndex - ]; + const { baseVersion, startCommit, endCommit } = + releaseCommitPairs[pairIndex]; - const { - startDate: startCommitCreatedAt, - endDate: endCommitCreatedAt, - } = await getTagDates({ - pluginApiClient, - project, - startTag: startCommit, - endTag: endCommit, - }); + const { startDate: startCommitCreatedAt, endDate: endCommitCreatedAt } = + await getTagDates({ + pluginApiClient, + project, + startTag: startCommit, + endTag: endCommit, + }); const releaseTime: ReleaseTime = { version: baseVersion, diff --git a/plugins/git-release-manager/src/features/Stats/helpers/getTagDates.ts b/plugins/git-release-manager/src/features/Stats/helpers/getTagDates.ts index ef274be259..38d1d51604 100644 --- a/plugins/git-release-manager/src/features/Stats/helpers/getTagDates.ts +++ b/plugins/git-release-manager/src/features/Stats/helpers/getTagDates.ts @@ -65,21 +65,19 @@ export const getTagDates = async ({ } if (startTag.tagType === 'tag' && endTag.tagType === 'tag') { - const [ - { tag: startTagResponse }, - { tag: endTagResponse }, - ] = await Promise.all([ - pluginApiClient.getTag({ - owner: project.owner, - repo: project.repo, - tagSha: startTag.tagSha, - }), - pluginApiClient.getTag({ - owner: project.owner, - repo: project.repo, - tagSha: endTag.tagSha, - }), - ]); + const [{ tag: startTagResponse }, { tag: endTagResponse }] = + await Promise.all([ + pluginApiClient.getTag({ + owner: project.owner, + repo: project.repo, + tagSha: startTag.tagSha, + }), + pluginApiClient.getTag({ + owner: project.owner, + repo: project.repo, + tagSha: endTag.tagSha, + }), + ]); return { startDate: startTagResponse.date, diff --git a/plugins/git-release-manager/src/helpers/tagParts/getCalverTagParts.ts b/plugins/git-release-manager/src/helpers/tagParts/getCalverTagParts.ts index 776d1d15dd..9f007938ed 100644 --- a/plugins/git-release-manager/src/helpers/tagParts/getCalverTagParts.ts +++ b/plugins/git-release-manager/src/helpers/tagParts/getCalverTagParts.ts @@ -22,7 +22,8 @@ export type CalverTagParts = { patch: number; }; -export const calverRegexp = /(rc|version)-([0-9]{4}\.[0-9]{2}\.[0-9]{2})_([0-9]+)/; +export const calverRegexp = + /(rc|version)-([0-9]{4}\.[0-9]{2}\.[0-9]{2})_([0-9]+)/; export function getCalverTagParts(tag: string) { const match = tag.match(calverRegexp); diff --git a/plugins/git-release-manager/src/hooks/useVersioningStrategyMatchesRepoTags.ts b/plugins/git-release-manager/src/hooks/useVersioningStrategyMatchesRepoTags.ts index 5d1e7670be..1a40712c8c 100644 --- a/plugins/git-release-manager/src/hooks/useVersioningStrategyMatchesRepoTags.ts +++ b/plugins/git-release-manager/src/hooks/useVersioningStrategyMatchesRepoTags.ts @@ -28,9 +28,8 @@ export const useVersioningStrategyMatchesRepoTags = ({ latestReleaseTagName?: string; repositoryName?: string; }) => { - const [versioningStrategyMatches, setVersioningStrategyMatches] = useState( - false, - ); + const [versioningStrategyMatches, setVersioningStrategyMatches] = + useState(false); useEffect(() => { setVersioningStrategyMatches(false); diff --git a/plugins/git-release-manager/src/types/helpers.ts b/plugins/git-release-manager/src/types/helpers.ts index b6cadecdf5..17110b7e7c 100644 --- a/plugins/git-release-manager/src/types/helpers.ts +++ b/plugins/git-release-manager/src/types/helpers.ts @@ -18,8 +18,7 @@ export type UnboxPromise> = T extends Promise ? U : never; -export type UnboxReturnedPromise< - T extends (...args: any) => Promise -> = UnboxPromise>; +export type UnboxReturnedPromise Promise> = + UnboxPromise>; export type UnboxArray = T extends (infer U)[] ? U : T; diff --git a/plugins/github-actions/src/components/WorkflowRunsTable/WorkflowRunsTable.tsx b/plugins/github-actions/src/components/WorkflowRunsTable/WorkflowRunsTable.tsx index 8f1aff780d..51f26bf5d7 100644 --- a/plugins/github-actions/src/components/WorkflowRunsTable/WorkflowRunsTable.tsx +++ b/plugins/github-actions/src/components/WorkflowRunsTable/WorkflowRunsTable.tsx @@ -159,15 +159,13 @@ export const WorkflowRunsTable = ({ config.getOptionalConfigArray('integrations.github') ?? [], )[0].host; const [owner, repo] = (projectName ?? '/').split('/'); - const [ - { runs, ...tableProps }, - { retry, setPage, setPageSize }, - ] = useWorkflowRuns({ - hostname, - owner, - repo, - branch, - }); + const [{ runs, ...tableProps }, { retry, setPage, setPageSize }] = + useWorkflowRuns({ + hostname, + owner, + repo, + branch, + }); const githubHost = hostname || 'github.com'; diff --git a/plugins/github-actions/src/components/useWorkflowRuns.ts b/plugins/github-actions/src/components/useWorkflowRuns.ts index 4610db07e9..eb343601bd 100644 --- a/plugins/github-actions/src/components/useWorkflowRuns.ts +++ b/plugins/github-actions/src/components/useWorkflowRuns.ts @@ -57,9 +57,12 @@ export function useWorkflowRuns({ const [page, setPage] = useState(0); const [pageSize, setPageSize] = useState(initialPageSize); - const { loading, value: runs, retry, error } = useAsyncRetry< - WorkflowRun[] - >(async () => { + const { + loading, + value: runs, + retry, + error, + } = useAsyncRetry(async () => { // GitHub API pagination count starts from 1 const workflowRunsData = await api.listWorkflowRuns({ hostname, diff --git a/plugins/github-actions/src/plugin.ts b/plugins/github-actions/src/plugin.ts index 89333e52d5..6d5b3ce0a6 100644 --- a/plugins/github-actions/src/plugin.ts +++ b/plugins/github-actions/src/plugin.ts @@ -56,14 +56,17 @@ export const EntityLatestGithubActionRunCard = githubActionsPlugin.provide( }), ); -export const EntityLatestGithubActionsForBranchCard = githubActionsPlugin.provide( - createComponentExtension({ - component: { - lazy: () => - import('./components/Cards').then(m => m.LatestWorkflowsForBranchCard), - }, - }), -); +export const EntityLatestGithubActionsForBranchCard = + githubActionsPlugin.provide( + createComponentExtension({ + component: { + lazy: () => + import('./components/Cards').then( + m => m.LatestWorkflowsForBranchCard, + ), + }, + }), + ); export const EntityRecentGithubActionsRunsCard = githubActionsPlugin.provide( createComponentExtension({ diff --git a/plugins/github-deployments/src/components/GithubDeploymentsCard.tsx b/plugins/github-deployments/src/components/GithubDeploymentsCard.tsx index 19cc9ac6e8..c01cd98a45 100644 --- a/plugins/github-deployments/src/components/GithubDeploymentsCard.tsx +++ b/plugins/github-deployments/src/components/GithubDeploymentsCard.tsx @@ -50,7 +50,12 @@ const GithubDeploymentsComponent = ({ const api = useApi(githubDeploymentsApiRef); const [owner, repo] = projectSlug.split('/'); - const { loading, value, error, retry: reload } = useAsyncRetry( + const { + loading, + value, + error, + retry: reload, + } = useAsyncRetry( async () => await api.listDeployments({ host, diff --git a/plugins/graphiql/src/index.ts b/plugins/graphiql/src/index.ts index 8efb4461d7..e4d8a32a05 100644 --- a/plugins/graphiql/src/index.ts +++ b/plugins/graphiql/src/index.ts @@ -25,4 +25,5 @@ export { export { GraphiQLPage as Router } from './components'; export * from './lib/api'; export * from './route-refs'; -export const GraphiQLIcon: IconComponent = GraphiQLIconComponent as IconComponent; +export const GraphiQLIcon: IconComponent = + GraphiQLIconComponent as IconComponent; diff --git a/plugins/graphiql/src/lib/storage/StorageBucket.test.ts b/plugins/graphiql/src/lib/storage/StorageBucket.test.ts index 16c5df0f8a..efc196727d 100644 --- a/plugins/graphiql/src/lib/storage/StorageBucket.test.ts +++ b/plugins/graphiql/src/lib/storage/StorageBucket.test.ts @@ -42,7 +42,7 @@ describe('StorageBucket', () => { removeItem: jest.fn(), }; const bucket = StorageBucket.forStorage( - (mockStorage as unknown) as Storage, + mockStorage as unknown as Storage, 'my-bucket', ); diff --git a/plugins/ilert/src/components/ILertCard/ILertCard.tsx b/plugins/ilert/src/components/ILertCard/ILertCard.tsx index 8581c717b4..a014c265c2 100644 --- a/plugins/ilert/src/components/ILertCard/ILertCard.tsx +++ b/plugins/ilert/src/components/ILertCard/ILertCard.tsx @@ -69,14 +69,10 @@ export const ILertCard = () => { }, ] = useIncidents(false, true, alertSource); - const [ - isNewIncidentModalOpened, - setIsNewIncidentModalOpened, - ] = React.useState(false); - const [ - isMaintenanceModalOpened, - setIsMaintenanceModalOpened, - ] = React.useState(false); + const [isNewIncidentModalOpened, setIsNewIncidentModalOpened] = + React.useState(false); + const [isMaintenanceModalOpened, setIsMaintenanceModalOpened] = + React.useState(false); if (error) { if (error instanceof AuthenticationError) { diff --git a/plugins/ilert/src/components/Incident/IncidentActionsMenu.tsx b/plugins/ilert/src/components/Incident/IncidentActionsMenu.tsx index 8d167819d4..46ebc03ba3 100644 --- a/plugins/ilert/src/components/Incident/IncidentActionsMenu.tsx +++ b/plugins/ilert/src/components/Incident/IncidentActionsMenu.tsx @@ -44,10 +44,8 @@ export const IncidentActionsMenu = ({ const [anchorEl, setAnchorEl] = React.useState(null); const callback = onIncidentChanged || ((_: Incident): void => {}); const setProcessing = setIsLoading || ((_: boolean): void => {}); - const [ - isAssignIncidentModalOpened, - setIsAssignIncidentModalOpened, - ] = React.useState(false); + const [isAssignIncidentModalOpened, setIsAssignIncidentModalOpened] = + React.useState(false); const [{ incidentActions, isLoading }] = useIncidentActions( incident, diff --git a/plugins/ilert/src/components/OnCallSchedulesPage/OnCallSchedulesPage.tsx b/plugins/ilert/src/components/OnCallSchedulesPage/OnCallSchedulesPage.tsx index 2cde7a0bf2..0e6bb28e36 100644 --- a/plugins/ilert/src/components/OnCallSchedulesPage/OnCallSchedulesPage.tsx +++ b/plugins/ilert/src/components/OnCallSchedulesPage/OnCallSchedulesPage.tsx @@ -26,10 +26,8 @@ import { } from '@backstage/core-components'; export const OnCallSchedulesPage = () => { - const [ - { onCallSchedules, isLoading, error }, - { refetchOnCallSchedules }, - ] = useOnCallSchedules(); + const [{ onCallSchedules, isLoading, error }, { refetchOnCallSchedules }] = + useOnCallSchedules(); if (error) { if (error instanceof AuthenticationError) { diff --git a/plugins/ilert/src/hooks/useAlertSource.ts b/plugins/ilert/src/hooks/useAlertSource.ts index c26aecff6a..4e74b9e857 100644 --- a/plugins/ilert/src/hooks/useAlertSource.ts +++ b/plugins/ilert/src/hooks/useAlertSource.ts @@ -28,13 +28,10 @@ export const useAlertSource = (integrationKey: string) => { null, ); const [isAlertSourceLoading, setIsAlertSourceLoading] = React.useState(false); - const [ - uptimeMonitor, - setUptimeMonitor, - ] = React.useState(null); - const [isUptimeMonitorLoading, setIsUptimeMonitorLoading] = React.useState( - false, - ); + const [uptimeMonitor, setUptimeMonitor] = + React.useState(null); + const [isUptimeMonitorLoading, setIsUptimeMonitorLoading] = + React.useState(false); const fetchAlertSourceCall = async () => { try { @@ -54,10 +51,10 @@ export const useAlertSource = (integrationKey: string) => { } }; - const { - error: alertSourceError, - retry: alertSourceRetry, - } = useAsyncRetry(fetchAlertSourceCall, [integrationKey]); + const { error: alertSourceError, retry: alertSourceRetry } = useAsyncRetry( + fetchAlertSourceCall, + [integrationKey], + ); const fetchUptimeMonitorCall = async () => { try { @@ -77,10 +74,8 @@ export const useAlertSource = (integrationKey: string) => { } }; - const { - error: uptimeMonitorError, - retry: uptimeMonitorRetry, - } = useAsyncRetry(fetchUptimeMonitorCall, [alertSource]); + const { error: uptimeMonitorError, retry: uptimeMonitorRetry } = + useAsyncRetry(fetchUptimeMonitorCall, [alertSource]); const retry = () => { alertSourceRetry(); diff --git a/plugins/ilert/src/hooks/useAssignIncident.ts b/plugins/ilert/src/hooks/useAssignIncident.ts index d43f6dca6d..2b6935fc8c 100644 --- a/plugins/ilert/src/hooks/useAssignIncident.ts +++ b/plugins/ilert/src/hooks/useAssignIncident.ts @@ -27,10 +27,8 @@ export const useAssignIncident = (incident: Incident | null, open: boolean) => { const [incidentRespondersList, setIncidentRespondersList] = React.useState< IncidentResponder[] >([]); - const [ - incidentResponder, - setIncidentResponder, - ] = React.useState(null); + const [incidentResponder, setIncidentResponder] = + React.useState(null); const [isLoading, setIsLoading] = React.useState(false); const { error, retry } = useAsyncRetry(async () => { diff --git a/plugins/ilert/src/hooks/useUptimeMonitors.ts b/plugins/ilert/src/hooks/useUptimeMonitors.ts index 6efaf86be8..fc4707c2a4 100644 --- a/plugins/ilert/src/hooks/useUptimeMonitors.ts +++ b/plugins/ilert/src/hooks/useUptimeMonitors.ts @@ -50,15 +50,13 @@ export const useUptimeMonitors = () => { const onUptimeMonitorChanged = (newUptimeMonitor: UptimeMonitor) => { setUptimeMonitorsList( - uptimeMonitorsList.map( - (uptimeMonitor: UptimeMonitor): UptimeMonitor => { - if (newUptimeMonitor.id === uptimeMonitor.id) { - return newUptimeMonitor; - } + uptimeMonitorsList.map((uptimeMonitor: UptimeMonitor): UptimeMonitor => { + if (newUptimeMonitor.id === uptimeMonitor.id) { + return newUptimeMonitor; + } - return uptimeMonitor; - }, - ), + return uptimeMonitor; + }), ); }; diff --git a/plugins/jenkins-backend/src/service/jenkinsApi.test.ts b/plugins/jenkins-backend/src/service/jenkinsApi.test.ts index 380a65f895..d1c4705225 100644 --- a/plugins/jenkins-backend/src/service/jenkinsApi.test.ts +++ b/plugins/jenkins-backend/src/service/jenkinsApi.test.ts @@ -92,8 +92,7 @@ describe('JenkinsApi', () => { result: 'success', displayName: '#7', fullDisplayName: 'Example jobName » Example Build #7', - url: - 'https://jenkins.example.com/job/example-jobName/job/exampleBuild', + url: 'https://jenkins.example.com/job/example-jobName/job/exampleBuild', number: 7, status: 'success', source: {}, @@ -280,8 +279,7 @@ describe('JenkinsApi', () => { result: 'success', displayName: '#7', fullDisplayName: 'Example jobName » Example Build #7', - url: - 'https://jenkins.example.com/job/example-jobName/job/exampleBuild/7/', + url: 'https://jenkins.example.com/job/example-jobName/job/exampleBuild/7/', number: 7, }, }; diff --git a/plugins/jenkins-backend/src/service/jenkinsApi.ts b/plugins/jenkins-backend/src/service/jenkinsApi.ts index 7df5c5db1d..fac8c95564 100644 --- a/plugins/jenkins-backend/src/service/jenkinsApi.ts +++ b/plugins/jenkins-backend/src/service/jenkinsApi.ts @@ -255,9 +255,7 @@ export class JenkinsApiImpl { return scmInfo; } - private getTestReport( - build: JenkinsBuild, - ): { + private getTestReport(build: JenkinsBuild): { total: number; passed: number; skipped: number; diff --git a/plugins/jenkins-backend/src/service/jenkinsInfoProvider.test.ts b/plugins/jenkins-backend/src/service/jenkinsInfoProvider.test.ts index 7c4761a19a..7d1615ac27 100644 --- a/plugins/jenkins-backend/src/service/jenkinsInfoProvider.test.ts +++ b/plugins/jenkins-backend/src/service/jenkinsInfoProvider.test.ts @@ -20,9 +20,9 @@ import { ConfigReader } from '@backstage/config'; import { Entity, EntityName } from '@backstage/catalog-model'; describe('DefaultJenkinsInfoProvider', () => { - const mockCatalog: jest.Mocked = ({ + const mockCatalog: jest.Mocked = { getEntityByName: jest.fn(), - } as any) as jest.Mocked; + } as any as jest.Mocked; const entityRef: EntityName = { kind: 'Component', diff --git a/plugins/jenkins-backend/src/service/jenkinsInfoProvider.ts b/plugins/jenkins-backend/src/service/jenkinsInfoProvider.ts index 1f316aa6bc..50875cde99 100644 --- a/plugins/jenkins-backend/src/service/jenkinsInfoProvider.ts +++ b/plugins/jenkins-backend/src/service/jenkinsInfoProvider.ts @@ -82,9 +82,8 @@ export class DefaultJenkinsInfoProvider implements JenkinsInfoProvider { } // lookup `[jenkinsName#]jobFullName` from entity annotation - const jenkinsAndJobName = DefaultJenkinsInfoProvider.getEntityAnnotationValue( - entity, - ); + const jenkinsAndJobName = + DefaultJenkinsInfoProvider.getEntityAnnotationValue(entity); if (!jenkinsAndJobName) { throw new Error( `Couldn't find jenkins annotation (${ diff --git a/plugins/jenkins-backend/src/service/router.ts b/plugins/jenkins-backend/src/service/router.ts index cd250aea31..273086b5ff 100644 --- a/plugins/jenkins-backend/src/service/router.ts +++ b/plugins/jenkins-backend/src/service/router.ts @@ -75,13 +75,8 @@ export async function createRouter( router.get( '/v1/entity/:namespace/:kind/:name/job/:jobFullName/:buildNumber', async (request, response) => { - const { - namespace, - kind, - name, - jobFullName, - buildNumber, - } = request.params; + const { namespace, kind, name, jobFullName, buildNumber } = + request.params; const jenkinsInfo = await jenkinsInfoProvider.getInstance({ entityRef: { diff --git a/plugins/jenkins/src/components/useBuildWithSteps.ts b/plugins/jenkins/src/components/useBuildWithSteps.ts index c73a116aae..64b3bf2535 100644 --- a/plugins/jenkins/src/components/useBuildWithSteps.ts +++ b/plugins/jenkins/src/components/useBuildWithSteps.ts @@ -49,9 +49,10 @@ export function useBuildWithSteps({ } }, [buildNumber, jobFullName, entity, api, errorApi]); - const { loading, value, retry } = useAsyncRetry(() => getBuildWithSteps(), [ - getBuildWithSteps, - ]); + const { loading, value, retry } = useAsyncRetry( + () => getBuildWithSteps(), + [getBuildWithSteps], + ); const { startPolling, stopPolling } = useAsyncPolling( getBuildWithSteps, diff --git a/plugins/jenkins/src/components/useBuilds.ts b/plugins/jenkins/src/components/useBuilds.ts index 820cb099a1..b0959671e1 100644 --- a/plugins/jenkins/src/components/useBuilds.ts +++ b/plugins/jenkins/src/components/useBuilds.ts @@ -53,7 +53,11 @@ export function useBuilds({ branch }: { branch?: string } = {}) { } }; - const { loading, value: projects, retry } = useAsyncRetry(async () => { + const { + loading, + value: projects, + retry, + } = useAsyncRetry(async () => { try { const build = await api.getProjects({ entity: getEntityName(entity), diff --git a/plugins/kubernetes-backend/src/kubernetes-auth-translator/AwsIamKubernetesAuthTranslator.ts b/plugins/kubernetes-backend/src/kubernetes-auth-translator/AwsIamKubernetesAuthTranslator.ts index 101bed32a3..9d582d50d4 100644 --- a/plugins/kubernetes-backend/src/kubernetes-auth-translator/AwsIamKubernetesAuthTranslator.ts +++ b/plugins/kubernetes-backend/src/kubernetes-auth-translator/AwsIamKubernetesAuthTranslator.ts @@ -21,11 +21,13 @@ import { KubernetesAuthTranslator } from './types'; const base64 = (str: string) => Buffer.from(str.toString(), 'binary').toString('base64'); const prepend = (prep: string) => (str: string) => prep + str; -const replace = (search: string | RegExp, substitution: string) => ( - str: string, -) => str.replace(search, substitution); -const pipe = (fns: ReadonlyArray) => (thing: string): string => - fns.reduce((val, fn) => fn(val), thing); +const replace = + (search: string | RegExp, substitution: string) => (str: string) => + str.replace(search, substitution); +const pipe = + (fns: ReadonlyArray) => + (thing: string): string => + fns.reduce((val, fn) => fn(val), thing); const removePadding = replace(/=+$/, ''); const makeUrlSafe = pipe([replace('+', '-'), replace('/', '_')]); @@ -36,11 +38,12 @@ type SigningCreds = { }; export class AwsIamKubernetesAuthTranslator - implements KubernetesAuthTranslator { + implements KubernetesAuthTranslator +{ validCredentials(creds: SigningCreds): boolean { - return ((creds?.accessKeyId && + return (creds?.accessKeyId && creds?.secretAccessKey && - creds?.sessionToken) as unknown) as boolean; + creds?.sessionToken) as unknown as boolean; } awsGetCredentials = async (): Promise => { diff --git a/plugins/kubernetes-backend/src/kubernetes-auth-translator/GoogleKubernetesAuthTranslator.ts b/plugins/kubernetes-backend/src/kubernetes-auth-translator/GoogleKubernetesAuthTranslator.ts index eacba4d3e1..8c74945ec7 100644 --- a/plugins/kubernetes-backend/src/kubernetes-auth-translator/GoogleKubernetesAuthTranslator.ts +++ b/plugins/kubernetes-backend/src/kubernetes-auth-translator/GoogleKubernetesAuthTranslator.ts @@ -19,7 +19,8 @@ import { GKEClusterDetails } from '../types/types'; import { KubernetesRequestBody } from '@backstage/plugin-kubernetes-common'; export class GoogleKubernetesAuthTranslator - implements KubernetesAuthTranslator { + implements KubernetesAuthTranslator +{ async decorateClusterDetailsWithAuth( clusterDetails: GKEClusterDetails, requestBody: KubernetesRequestBody, diff --git a/plugins/kubernetes-backend/src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.test.ts b/plugins/kubernetes-backend/src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.test.ts index 2d900b0bd1..33592b1c41 100644 --- a/plugins/kubernetes-backend/src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.test.ts +++ b/plugins/kubernetes-backend/src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.test.ts @@ -24,23 +24,20 @@ describe('getKubernetesAuthTranslatorInstance', () => { const sut = KubernetesAuthTranslatorGenerator; it('can return an auth translator for google auth', () => { - const authTranslator: KubernetesAuthTranslator = sut.getKubernetesAuthTranslatorInstance( - 'google', - ); + const authTranslator: KubernetesAuthTranslator = + sut.getKubernetesAuthTranslatorInstance('google'); expect(authTranslator instanceof GoogleKubernetesAuthTranslator).toBe(true); }); it('can return an auth translator for aws auth', () => { - const authTranslator: KubernetesAuthTranslator = sut.getKubernetesAuthTranslatorInstance( - 'aws', - ); + const authTranslator: KubernetesAuthTranslator = + sut.getKubernetesAuthTranslatorInstance('aws'); expect(authTranslator instanceof AwsIamKubernetesAuthTranslator).toBe(true); }); it('can return an auth translator for serviceAccount auth', () => { - const authTranslator: KubernetesAuthTranslator = sut.getKubernetesAuthTranslatorInstance( - 'serviceAccount', - ); + const authTranslator: KubernetesAuthTranslator = + sut.getKubernetesAuthTranslatorInstance('serviceAccount'); expect( authTranslator instanceof ServiceAccountKubernetesAuthTranslator, ).toBe(true); diff --git a/plugins/kubernetes-backend/src/kubernetes-auth-translator/ServiceAccountKubernetesAuthTranslator.ts b/plugins/kubernetes-backend/src/kubernetes-auth-translator/ServiceAccountKubernetesAuthTranslator.ts index 1c3add3c0d..6e5b8b9558 100644 --- a/plugins/kubernetes-backend/src/kubernetes-auth-translator/ServiceAccountKubernetesAuthTranslator.ts +++ b/plugins/kubernetes-backend/src/kubernetes-auth-translator/ServiceAccountKubernetesAuthTranslator.ts @@ -19,7 +19,8 @@ import { ServiceAccountClusterDetails } from '../types/types'; import { KubernetesRequestBody } from '@backstage/plugin-kubernetes-common'; export class ServiceAccountKubernetesAuthTranslator - implements KubernetesAuthTranslator { + implements KubernetesAuthTranslator +{ async decorateClusterDetailsWithAuth( clusterDetails: ServiceAccountClusterDetails, // To ignore TS6133 linting error where it detects 'requestBody' is declared but its value is never read. diff --git a/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.ts b/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.ts index 0931d775d3..fb1876733d 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.ts @@ -71,15 +71,15 @@ export class KubernetesFanOutHandler { 'backstage.io/kubernetes-id' ] || requestBody.entity?.metadata?.name; - const clusterDetails: ClusterDetails[] = await this.serviceLocator.getClustersByServiceId( - entityName, - ); + const clusterDetails: ClusterDetails[] = + await this.serviceLocator.getClustersByServiceId(entityName); // Execute all of these async actions simultaneously/without blocking sequentially as no common object is modified by them const promises: Promise[] = clusterDetails.map(cd => { - const kubernetesAuthTranslator: KubernetesAuthTranslator = KubernetesAuthTranslatorGenerator.getKubernetesAuthTranslatorInstance( - cd.authProvider, - ); + const kubernetesAuthTranslator: KubernetesAuthTranslator = + KubernetesAuthTranslatorGenerator.getKubernetesAuthTranslatorInstance( + cd.authProvider, + ); return kubernetesAuthTranslator.decorateClusterDetailsWithAuth( cd, requestBody, diff --git a/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts b/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts index 76c3b0aac0..e17b47e17a 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts @@ -167,10 +167,9 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { labelSelector, ).then(r => ({ type: type, resources: r })); case 'services': - return this.fetchServicesForService( - clusterDetails, - labelSelector, - ).then(r => ({ type: type, resources: r })); + return this.fetchServicesForService(clusterDetails, labelSelector).then( + r => ({ type: type, resources: r }), + ); case 'horizontalpodautoscalers': return this.fetchHorizontalPodAutoscalersForService( clusterDetails, @@ -192,9 +191,8 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { customResource: CustomResource, labelSelector: string, ): Promise { - const customObjects = this.kubernetesClientProvider.getCustomObjectsClient( - clusterDetails, - ); + const customObjects = + this.kubernetesClientProvider.getCustomObjectsClient(clusterDetails); return customObjects .listClusterCustomObject( @@ -217,18 +215,20 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { client: Clients, ) => Promise<{ body: { items: Array }; response: http.IncomingMessage }>, ): Promise> { - const core = this.kubernetesClientProvider.getCoreClientByClusterDetails( - clusterDetails, - ); - const apps = this.kubernetesClientProvider.getAppsClientByClusterDetails( - clusterDetails, - ); - const autoscaling = this.kubernetesClientProvider.getAutoscalingClientByClusterDetails( - clusterDetails, - ); - const networkingBeta1 = this.kubernetesClientProvider.getNetworkingBeta1Client( - clusterDetails, - ); + const core = + this.kubernetesClientProvider.getCoreClientByClusterDetails( + clusterDetails, + ); + const apps = + this.kubernetesClientProvider.getAppsClientByClusterDetails( + clusterDetails, + ); + const autoscaling = + this.kubernetesClientProvider.getAutoscalingClientByClusterDetails( + clusterDetails, + ); + const networkingBeta1 = + this.kubernetesClientProvider.getNetworkingBeta1Client(clusterDetails); this.logger.debug(`calling cluster=${clusterDetails.name}`); return fn({ core, apps, autoscaling, networkingBeta1 }).then(({ body }) => { diff --git a/plugins/kubernetes-backend/src/service/router.ts b/plugins/kubernetes-backend/src/service/router.ts index 8a1f2fe627..4792ae708f 100644 --- a/plugins/kubernetes-backend/src/service/router.ts +++ b/plugins/kubernetes-backend/src/service/router.ts @@ -71,9 +71,8 @@ export const makeRouter = ( const serviceId = req.params.serviceId; const requestBody: KubernetesRequestBody = req.body; try { - const response = await kubernetesFanOutHandler.getKubernetesObjectsByEntity( - requestBody, - ); + const response = + await kubernetesFanOutHandler.getKubernetesObjectsByEntity(requestBody); res.json(response); } catch (e) { logger.error( diff --git a/plugins/kubernetes/src/components/CustomResources/ArgoRollouts/Rollout.test.tsx b/plugins/kubernetes/src/components/CustomResources/ArgoRollouts/Rollout.test.tsx index 15e8237d3b..f3e1d47479 100644 --- a/plugins/kubernetes/src/components/CustomResources/ArgoRollouts/Rollout.test.tsx +++ b/plugins/kubernetes/src/components/CustomResources/ArgoRollouts/Rollout.test.tsx @@ -58,10 +58,10 @@ describe('Rollout', () => { it('should render Paused Rollout with pause text', async () => { const wrapper = kubernetesProviders(groupedResources, new Set([])); - (pausedRollout.status.pauseConditions[0] - .startTime as any) = DateTime.local() - // millis * secs * mins = 45 mins - .minus(Duration.fromMillis(1000 * 60 * 45)); + (pausedRollout.status.pauseConditions[0].startTime as any) = + DateTime.local() + // millis * secs * mins = 45 mins + .minus(Duration.fromMillis(1000 * 60 * 45)); const { getByText } = render( wrapper( diff --git a/plugins/kubernetes/src/hooks/useKubernetesObjects.test.ts b/plugins/kubernetes/src/hooks/useKubernetesObjects.test.ts index 0acbef8af3..1d46eb14ea 100644 --- a/plugins/kubernetes/src/hooks/useKubernetesObjects.test.ts +++ b/plugins/kubernetes/src/hooks/useKubernetesObjects.test.ts @@ -94,12 +94,10 @@ describe('useKubernetesObjects', () => { it('should return objects', async () => { (useApi as any).mockReturnValue({ getClusters: mockGetClusters.mockResolvedValue(getClustersResponse), - getObjectsByEntity: mockGetObjectsByEntity.mockResolvedValue( - mockResponse, - ), - decorateRequestBodyForAuth: mockDecorateRequestBodyForAuth.mockResolvedValue( - entityWithAuthToken, - ), + getObjectsByEntity: + mockGetObjectsByEntity.mockResolvedValue(mockResponse), + decorateRequestBodyForAuth: + mockDecorateRequestBodyForAuth.mockResolvedValue(entityWithAuthToken), }); const { result, waitForNextUpdate } = renderHook(() => useKubernetesObjects(entity), @@ -118,9 +116,8 @@ describe('useKubernetesObjects', () => { getObjectsByEntity: mockGetObjectsByEntity.mockRejectedValue({ message: 'some error', }), - decorateRequestBodyForAuth: mockDecorateRequestBodyForAuth.mockResolvedValue( - entityWithAuthToken, - ), + decorateRequestBodyForAuth: + mockDecorateRequestBodyForAuth.mockResolvedValue(entityWithAuthToken), }); const { result, waitForNextUpdate } = renderHook(() => useKubernetesObjects(entity), @@ -157,9 +154,10 @@ describe('useKubernetesObjects', () => { it('should return error when decorateRequestBodyForAuth throws', async () => { (useApi as any).mockReturnValue({ getClusters: mockGetClusters.mockResolvedValue(getClustersResponse), - decorateRequestBodyForAuth: mockDecorateRequestBodyForAuth.mockRejectedValue( - { message: 'some-error' }, - ), + decorateRequestBodyForAuth: + mockDecorateRequestBodyForAuth.mockRejectedValue({ + message: 'some-error', + }), getObjectsByEntity: mockGetObjectsByEntity, }); const { result, waitForNextUpdate } = renderHook(() => diff --git a/plugins/kubernetes/src/hooks/useKubernetesObjects.ts b/plugins/kubernetes/src/hooks/useKubernetesObjects.ts index 0c4fbdef54..4f19816296 100644 --- a/plugins/kubernetes/src/hooks/useKubernetesObjects.ts +++ b/plugins/kubernetes/src/hooks/useKubernetesObjects.ts @@ -59,10 +59,11 @@ export const useKubernetesObjects = (entity: Entity): KubernetesObjects => { for (const authProviderStr of authProviders) { // Multiple asyncs done sequentially instead of all at once to prevent same requestBody from being modified simultaneously try { - requestBody = await kubernetesAuthProvidersApi.decorateRequestBodyForAuth( - authProviderStr, - requestBody, - ); + requestBody = + await kubernetesAuthProvidersApi.decorateRequestBodyForAuth( + authProviderStr, + requestBody, + ); } catch (e) { setError(e.message); return; diff --git a/plugins/kubernetes/src/kubernetes-auth-provider/KubernetesAuthProviders.ts b/plugins/kubernetes/src/kubernetes-auth-provider/KubernetesAuthProviders.ts index 118d5904a4..dfe0d746d1 100644 --- a/plugins/kubernetes/src/kubernetes-auth-provider/KubernetesAuthProviders.ts +++ b/plugins/kubernetes/src/kubernetes-auth-provider/KubernetesAuthProviders.ts @@ -44,9 +44,8 @@ export class KubernetesAuthProviders implements KubernetesAuthProvidersApi { authProvider: string, requestBody: KubernetesRequestBody, ): Promise { - const kubernetesAuthProvider: - | KubernetesAuthProvider - | undefined = this.kubernetesAuthProviderMap.get(authProvider); + const kubernetesAuthProvider: KubernetesAuthProvider | undefined = + this.kubernetesAuthProviderMap.get(authProvider); if (kubernetesAuthProvider) { return await kubernetesAuthProvider.decorateRequestBodyForAuth( requestBody, diff --git a/plugins/kubernetes/src/kubernetes-auth-provider/ServiceAccountKubernetesAuthProvider.ts b/plugins/kubernetes/src/kubernetes-auth-provider/ServiceAccountKubernetesAuthProvider.ts index 8f766152a0..5671112ac8 100644 --- a/plugins/kubernetes/src/kubernetes-auth-provider/ServiceAccountKubernetesAuthProvider.ts +++ b/plugins/kubernetes/src/kubernetes-auth-provider/ServiceAccountKubernetesAuthProvider.ts @@ -18,7 +18,8 @@ import { KubernetesAuthProvider } from './types'; import { KubernetesRequestBody } from '@backstage/plugin-kubernetes-common'; export class ServiceAccountKubernetesAuthProvider - implements KubernetesAuthProvider { + implements KubernetesAuthProvider +{ async decorateRequestBodyForAuth( requestBody: KubernetesRequestBody, ): Promise { diff --git a/plugins/kubernetes/src/kubernetes-auth-provider/types.ts b/plugins/kubernetes/src/kubernetes-auth-provider/types.ts index fb6f773d84..3c5564e7cc 100644 --- a/plugins/kubernetes/src/kubernetes-auth-provider/types.ts +++ b/plugins/kubernetes/src/kubernetes-auth-provider/types.ts @@ -23,13 +23,12 @@ export interface KubernetesAuthProvider { ): Promise; } -export const kubernetesAuthProvidersApiRef = createApiRef( - { +export const kubernetesAuthProvidersApiRef = + createApiRef({ id: 'plugin.kubernetes-auth-providers.service', description: 'Used by the Kubernetes plugin to fetch KubernetesAuthProviders', - }, -); + }); export interface KubernetesAuthProvidersApi { decorateRequestBodyForAuth( diff --git a/plugins/lighthouse/src/components/AuditList/AuditListTable.tsx b/plugins/lighthouse/src/components/AuditList/AuditListTable.tsx index ef9ec34a6a..10f29f3fd5 100644 --- a/plugins/lighthouse/src/components/AuditList/AuditListTable.tsx +++ b/plugins/lighthouse/src/components/AuditList/AuditListTable.tsx @@ -69,9 +69,8 @@ export const AuditListTable = ({ items }: { items: Website[] }) => { const auditStatus = response.lastAudit.status; if (auditStatus === 'COMPLETED' || auditStatus === 'FAILED') { const newWebsiteData = websiteState.slice(0); - newWebsiteData[ - newWebsiteData.findIndex(w => w.url === response.url) - ] = response; + newWebsiteData[newWebsiteData.findIndex(w => w.url === response.url)] = + response; setWebsiteState(newWebsiteData); } }); diff --git a/plugins/lighthouse/src/components/AuditView/index.test.tsx b/plugins/lighthouse/src/components/AuditView/index.test.tsx index 0614f5f183..8a8146199d 100644 --- a/plugins/lighthouse/src/components/AuditView/index.test.tsx +++ b/plugins/lighthouse/src/components/AuditView/index.test.tsx @@ -37,9 +37,8 @@ import * as data from '../../__fixtures__/website-response.json'; import AuditView from './index'; import { ApiProvider, ApiRegistry } from '@backstage/core-app-api'; -const { useParams }: { useParams: jest.Mock } = jest.requireMock( - 'react-router-dom', -); +const { useParams }: { useParams: jest.Mock } = + jest.requireMock('react-router-dom'); const websiteResponse = data as Website; describe('AuditView', () => { diff --git a/plugins/lighthouse/src/components/AuditView/index.tsx b/plugins/lighthouse/src/components/AuditView/index.tsx index 7f9e7e7113..30f7b61eb9 100644 --- a/plugins/lighthouse/src/components/AuditView/index.tsx +++ b/plugins/lighthouse/src/components/AuditView/index.tsx @@ -123,7 +123,11 @@ export const AuditViewContent = () => { const classes = useStyles(); const navigate = useNavigate(); - const { loading, error, value: nextValue } = useAsync( + const { + loading, + error, + value: nextValue, + } = useAsync( async () => await lighthouseApi.getWebsiteForAuditId(params.id), [params.id], ); diff --git a/plugins/lighthouse/src/components/Cards/LastLighthouseAuditCard.test.tsx b/plugins/lighthouse/src/components/Cards/LastLighthouseAuditCard.test.tsx index 48eec99b0a..9a9ac7781e 100644 --- a/plugins/lighthouse/src/components/Cards/LastLighthouseAuditCard.test.tsx +++ b/plugins/lighthouse/src/components/Cards/LastLighthouseAuditCard.test.tsx @@ -93,7 +93,9 @@ describe('', () => { describe('where a category score is not a number', () => { beforeEach(() => { entityWebsite = { ...entityWebsite }; - (entityWebsite.lastAudit as AuditCompleted).categories.accessibility.score = NaN; + ( + entityWebsite.lastAudit as AuditCompleted + ).categories.accessibility.score = NaN; }); afterEach(() => { diff --git a/plugins/lighthouse/src/components/CreateAudit/index.test.tsx b/plugins/lighthouse/src/components/CreateAudit/index.test.tsx index 6bdf6d779f..ca078c7e84 100644 --- a/plugins/lighthouse/src/components/CreateAudit/index.test.tsx +++ b/plugins/lighthouse/src/components/CreateAudit/index.test.tsx @@ -35,9 +35,8 @@ import CreateAudit from './index'; import { ApiProvider, ApiRegistry } from '@backstage/core-app-api'; import { ErrorApi, errorApiRef } from '@backstage/core-plugin-api'; -const { useNavigate }: { useNavigate: jest.Mock } = jest.requireMock( - 'react-router-dom', -); +const { useNavigate }: { useNavigate: jest.Mock } = + jest.requireMock('react-router-dom'); const createAuditResponse = data as Audit; // TODO add act() to these tests without breaking them! diff --git a/plugins/lighthouse/src/hooks/useWebsiteForEntity.ts b/plugins/lighthouse/src/hooks/useWebsiteForEntity.ts index dc6695eccc..1ea1e3f8e4 100644 --- a/plugins/lighthouse/src/hooks/useWebsiteForEntity.ts +++ b/plugins/lighthouse/src/hooks/useWebsiteForEntity.ts @@ -27,9 +27,10 @@ export const useWebsiteForEntity = () => { entity.metadata.annotations?.[LIGHTHOUSE_WEBSITE_URL_ANNOTATION] ?? ''; const lighthouseApi = useApi(lighthouseApiRef); const errorApi = useApi(errorApiRef); - const response = useAsync(() => lighthouseApi.getWebsiteByUrl(websiteUrl), [ - websiteUrl, - ]); + const response = useAsync( + () => lighthouseApi.getWebsiteByUrl(websiteUrl), + [websiteUrl], + ); if (response.error) { errorApi.post(response.error); } diff --git a/plugins/org/src/components/Cards/Group/MembersList/MembersListCard.tsx b/plugins/org/src/components/Cards/Group/MembersList/MembersListCard.tsx index 31b5c3f5c0..862fc51aa7 100644 --- a/plugins/org/src/components/Cards/Group/MembersList/MembersListCard.tsx +++ b/plugins/org/src/components/Cards/Group/MembersList/MembersListCard.tsx @@ -128,7 +128,11 @@ export const MembersListCard = (_props: { }; const pageSize = 50; - const { loading, error, value: members } = useAsync(async () => { + const { + loading, + error, + value: members, + } = useAsync(async () => { const membersList = await catalogApi.getEntities({ filter: { kind: 'User' }, }); diff --git a/plugins/pagerduty/src/components/Escalation/EscalationPolicy.tsx b/plugins/pagerduty/src/components/Escalation/EscalationPolicy.tsx index 7dc3c3d118..9cbdddca17 100644 --- a/plugins/pagerduty/src/components/Escalation/EscalationPolicy.tsx +++ b/plugins/pagerduty/src/components/Escalation/EscalationPolicy.tsx @@ -32,7 +32,11 @@ type Props = { export const EscalationPolicy = ({ policyId }: Props) => { const api = useApi(pagerDutyApiRef); - const { value: users, loading, error } = useAsync(async () => { + const { + value: users, + loading, + error, + } = useAsync(async () => { const oncalls = await api.getOnCallByPolicyId(policyId); const usersItem = oncalls .sort((a, b) => a.escalation_level - b.escalation_level) diff --git a/plugins/pagerduty/src/components/PagerDutyCard/index.tsx b/plugins/pagerduty/src/components/PagerDutyCard/index.tsx index 7d370d9b87..5c0c18135e 100644 --- a/plugins/pagerduty/src/components/PagerDutyCard/index.tsx +++ b/plugins/pagerduty/src/components/PagerDutyCard/index.tsx @@ -55,7 +55,11 @@ export const PagerDutyCard = () => { setRefreshIncidents(x => !x); }, []); - const { value: service, loading, error } = useAsync(async () => { + const { + value: service, + loading, + error, + } = useAsync(async () => { const services = await api.getServiceByIntegrationKey( integrationKey as string, ); diff --git a/plugins/pagerduty/src/components/TriggerDialog/TriggerDialog.test.tsx b/plugins/pagerduty/src/components/TriggerDialog/TriggerDialog.test.tsx index 3e873d704c..444e820b98 100644 --- a/plugins/pagerduty/src/components/TriggerDialog/TriggerDialog.test.tsx +++ b/plugins/pagerduty/src/components/TriggerDialog/TriggerDialog.test.tsx @@ -92,9 +92,8 @@ describe('TriggerDialog', () => { }); expect(mockTriggerAlarmFn).toHaveBeenCalled(); expect(mockTriggerAlarmFn).toHaveBeenCalledWith({ - integrationKey: entity!.metadata!.annotations![ - 'pagerduty.com/integration-key' - ], + integrationKey: + entity!.metadata!.annotations!['pagerduty.com/integration-key'], source: window.location.toString(), description, userName: 'guest@example.com', diff --git a/plugins/rollbar-backend/api-report.md b/plugins/rollbar-backend/api-report.md index ecac80237f..6ac27447d8 100644 --- a/plugins/rollbar-backend/api-report.md +++ b/plugins/rollbar-backend/api-report.md @@ -15,9 +15,7 @@ export function createRouter(options: RouterOptions): Promise; // Warning: (ae-missing-release-tag) "getRequestHeaders" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export function getRequestHeaders( - token: string, -): { +export function getRequestHeaders(token: string): { headers: { 'X-Rollbar-Access-Token': string; }; diff --git a/plugins/rollbar/src/components/RollbarProject/RollbarProject.tsx b/plugins/rollbar/src/components/RollbarProject/RollbarProject.tsx index edb2afc0ca..ef7cc155b1 100644 --- a/plugins/rollbar/src/components/RollbarProject/RollbarProject.tsx +++ b/plugins/rollbar/src/components/RollbarProject/RollbarProject.tsx @@ -24,9 +24,8 @@ type Props = { }; export const RollbarProject = ({ entity }: Props) => { - const { items, organization, project, loading, error } = useTopActiveItems( - entity, - ); + const { items, organization, project, loading, error } = + useTopActiveItems(entity); return ( catalogApi.getEntityByName({ kind: 'Component', namespace, name }), [catalogApi, namespace, name], ); diff --git a/plugins/scaffolder-backend/api-report.md b/plugins/scaffolder-backend/api-report.md index baf85bce63..f763904fe7 100644 --- a/plugins/scaffolder-backend/api-report.md +++ b/plugins/scaffolder-backend/api-report.md @@ -171,7 +171,7 @@ export function createRouter(options: RouterOptions): Promise; export const createTemplateAction: < Input extends Partial<{ [name: string]: JsonValue | Partial | undefined; - }> + }>, >( templateAction: TemplateAction, ) => TemplateAction; diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/register.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/register.test.ts index fff2b28ff0..68e2450ca0 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/register.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/register.test.ts @@ -39,7 +39,7 @@ describe('catalog:register', () => { const action = createCatalogRegisterAction({ integrations, - catalogClient: (catalogClient as unknown) as CatalogApi, + catalogClient: catalogClient as unknown as CatalogApi, }); const mockContext = { diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/register.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/register.ts index 72b86cbf79..70170b8b90 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/register.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/register.ts @@ -76,10 +76,8 @@ export function createCatalogRegisterAction(options: { if ('catalogInfoUrl' in input) { catalogInfoUrl = input.catalogInfoUrl; } else { - const { - repoContentsUrl, - catalogInfoPath = '/catalog-info.yaml', - } = input; + const { repoContentsUrl, catalogInfoPath = '/catalog-info.yaml' } = + input; const integration = integrations.byUrl(repoContentsUrl); if (!integration) { throw new InputError( diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/createBuiltinActions.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/createBuiltinActions.ts index b3d1460270..5a16ef9a55 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/createBuiltinActions.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/createBuiltinActions.ts @@ -46,13 +46,8 @@ export const createBuiltinActions = (options: { containerRunner: ContainerRunner; config: Config; }) => { - const { - reader, - integrations, - containerRunner, - catalogClient, - config, - } = options; + const { reader, integrations, containerRunner, catalogClient, config } = + options; return [ createFetchPlainAction({ diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/debug/log.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/debug/log.test.ts index efcd1507ef..38c50afecc 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/debug/log.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/debug/log.test.ts @@ -22,9 +22,9 @@ import { createDebugLogAction } from './log'; import { join } from 'path'; describe('debug:log', () => { - const logStream = ({ + const logStream = { write: jest.fn(), - } as jest.Mocked>) as jest.Mocked; + } as jest.Mocked> as jest.Mocked; const mockTmpDir = os.tmpdir(); const mockContext = { diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/plain.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/plain.test.ts index 1a4428e3f0..0ef095bf79 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/plain.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/plain.test.ts @@ -56,8 +56,7 @@ describe('fetch:plain', () => { action.handler({ ...mockContext, input: { - url: - 'https://github.com/backstage/community/tree/main/backstage-community-sessions/assets', + url: 'https://github.com/backstage/community/tree/main/backstage-community-sessions/assets', targetPath: '/foobar', }, }), @@ -70,8 +69,7 @@ describe('fetch:plain', () => { await action.handler({ ...mockContext, input: { - url: - 'https://github.com/backstage/community/tree/main/backstage-community-sessions/assets', + url: 'https://github.com/backstage/community/tree/main/backstage-community-sessions/assets', targetPath: 'lol', }, }); diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.test.ts index bd2beae47a..aa13141f55 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.test.ts @@ -75,8 +75,8 @@ describe('fetch:template', () => { mockFs(); action = createFetchTemplateAction({ - reader: (Symbol('UrlReader') as unknown) as UrlReader, - integrations: (Symbol('Integrations') as unknown) as ScmIntegrations, + reader: Symbol('UrlReader') as unknown as UrlReader, + integrations: Symbol('Integrations') as unknown as ScmIntegrations, }); }); @@ -100,7 +100,7 @@ describe('fetch:template', () => { it('throws if copyWithoutRender parameter is not an array', async () => { await expect(() => action.handler( - mockContext({ copyWithoutRender: ('abc' as unknown) as string[] }), + mockContext({ copyWithoutRender: 'abc' as unknown as string[] }), ), ).rejects.toThrowError(/copyWithoutRender must be an array/i); }); diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/azure.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/azure.test.ts index a242863ac7..0af8b7b975 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/azure.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/azure.test.ts @@ -58,7 +58,7 @@ describe('publish:azure', () => { getGitApi: jest.fn().mockReturnValue(mockGitClient), }; - ((WebApi as unknown) as jest.Mock).mockImplementation(() => mockGitApi); + (WebApi as unknown as jest.Mock).mockImplementation(() => mockGitApi); beforeEach(() => { jest.restoreAllMocks(); @@ -209,9 +209,8 @@ describe('publish:azure', () => { }, }); - const customAuthorIntegrations = ScmIntegrations.fromConfig( - customAuthorConfig, - ); + const customAuthorIntegrations = + ScmIntegrations.fromConfig(customAuthorConfig); const customAuthorAction = createPublishAzureAction({ integrations: customAuthorIntegrations, config: customAuthorConfig, @@ -246,9 +245,8 @@ describe('publish:azure', () => { }, }); - const customAuthorIntegrations = ScmIntegrations.fromConfig( - customAuthorConfig, - ); + const customAuthorIntegrations = + ScmIntegrations.fromConfig(customAuthorConfig); const customAuthorAction = createPublishAzureAction({ integrations: customAuthorIntegrations, config: customAuthorConfig, diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/bitbucket.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/bitbucket.test.ts index ebdd28260c..180b6cc579 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/bitbucket.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/bitbucket.test.ts @@ -149,8 +149,7 @@ describe('publish:bitbucket', () => { links: { self: [ { - href: - 'https://bitbucket.mycompany.com/projects/project/repos/repo', + href: 'https://bitbucket.mycompany.com/projects/project/repos/repo', }, ], clone: [ @@ -363,9 +362,8 @@ describe('publish:bitbucket', () => { }, }); - const customAuthorIntegrations = ScmIntegrations.fromConfig( - customAuthorConfig, - ); + const customAuthorIntegrations = + ScmIntegrations.fromConfig(customAuthorConfig); const customAuthorAction = createPublishBitbucketAction({ integrations: customAuthorIntegrations, config: customAuthorConfig, @@ -430,9 +428,8 @@ describe('publish:bitbucket', () => { }, }); - const customAuthorIntegrations = ScmIntegrations.fromConfig( - customAuthorConfig, - ); + const customAuthorIntegrations = + ScmIntegrations.fromConfig(customAuthorConfig); const customAuthorAction = createPublishBitbucketAction({ integrations: customAuthorIntegrations, config: customAuthorConfig, diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/github.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/github.test.ts index 173e44848b..5e948b52b1 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/github.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/github.test.ts @@ -229,9 +229,8 @@ describe('publish:github', () => { }, }); - const customAuthorIntegrations = ScmIntegrations.fromConfig( - customAuthorConfig, - ); + const customAuthorIntegrations = + ScmIntegrations.fromConfig(customAuthorConfig); const customAuthorAction = createPublishGithubAction({ integrations: customAuthorIntegrations, config: customAuthorConfig, @@ -273,9 +272,8 @@ describe('publish:github', () => { }, }); - const customAuthorIntegrations = ScmIntegrations.fromConfig( - customAuthorConfig, - ); + const customAuthorIntegrations = + ScmIntegrations.fromConfig(customAuthorConfig); const customAuthorAction = createPublishGithubAction({ integrations: customAuthorIntegrations, config: customAuthorConfig, diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts index 1c46e80d03..408ec243e7 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts @@ -73,9 +73,8 @@ export const defaultClientFactory = async ({ throw new InputError(`No integration for host ${host}`); } - const credentialsProvider = GithubCredentialsProvider.create( - integrationConfig, - ); + const credentialsProvider = + GithubCredentialsProvider.create(integrationConfig); if (!credentialsProvider) { throw new InputError( diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/gitlab.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/gitlab.test.ts index d76f838797..2cd27da359 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/gitlab.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/gitlab.test.ts @@ -194,9 +194,8 @@ describe('publish:gitlab', () => { }, }); - const customAuthorIntegrations = ScmIntegrations.fromConfig( - customAuthorConfig, - ); + const customAuthorIntegrations = + ScmIntegrations.fromConfig(customAuthorConfig); const customAuthorAction = createPublishGitlabAction({ integrations: customAuthorIntegrations, config: customAuthorConfig, @@ -239,9 +238,8 @@ describe('publish:gitlab', () => { }, }); - const customAuthorIntegrations = ScmIntegrations.fromConfig( - customAuthorConfig, - ); + const customAuthorIntegrations = + ScmIntegrations.fromConfig(customAuthorConfig); const customAuthorAction = createPublishGitlabAction({ integrations: customAuthorIntegrations, config: customAuthorConfig, diff --git a/plugins/scaffolder-backend/src/scaffolder/tasks/DatabaseTaskStore.ts b/plugins/scaffolder-backend/src/scaffolder/tasks/DatabaseTaskStore.ts index b48941e3d4..09cba596b1 100644 --- a/plugins/scaffolder-backend/src/scaffolder/tasks/DatabaseTaskStore.ts +++ b/plugins/scaffolder-backend/src/scaffolder/tasks/DatabaseTaskStore.ts @@ -153,11 +153,7 @@ export class DatabaseTaskStore implements TaskStore { } } - async listStaleTasks({ - timeoutS, - }: { - timeoutS: number; - }): Promise<{ + async listStaleTasks({ timeoutS }: { timeoutS: number }): Promise<{ tasks: { taskId: string }[]; }> { const rawRows = await this.db('tasks') diff --git a/plugins/scaffolder-backend/src/scaffolder/tasks/types.ts b/plugins/scaffolder-backend/src/scaffolder/tasks/types.ts index e61d989bc3..3b1805f117 100644 --- a/plugins/scaffolder-backend/src/scaffolder/tasks/types.ts +++ b/plugins/scaffolder-backend/src/scaffolder/tasks/types.ts @@ -112,9 +112,7 @@ export interface TaskStore { eventBody: JsonObject; }): Promise; heartbeatTask(taskId: string): Promise; - listStaleTasks(options: { - timeoutS: number; - }): Promise<{ + listStaleTasks(options: { timeoutS: number }): Promise<{ tasks: { taskId: string }[]; }>; diff --git a/plugins/scaffolder/api-report.md b/plugins/scaffolder/api-report.md index 1be7e8fec8..690cba285b 100644 --- a/plugins/scaffolder/api-report.md +++ b/plugins/scaffolder/api-report.md @@ -72,9 +72,7 @@ export const RepoUrlPickerFieldExtension: () => null; // @public (undocumented) export interface ScaffolderApi { // (undocumented) - getIntegrationsList(options: { - allowedHosts: string[]; - }): Promise< + getIntegrationsList(options: { allowedHosts: string[] }): Promise< { type: string; title: string; @@ -125,9 +123,7 @@ export class ScaffolderClient implements ScaffolderApi { scmIntegrationsApi: ScmIntegrationRegistry; }); // (undocumented) - getIntegrationsList(options: { - allowedHosts: string[]; - }): Promise< + getIntegrationsList(options: { allowedHosts: string[] }): Promise< { type: string; title: string; diff --git a/plugins/scaffolder/src/components/ActionsPage/ActionsPage.tsx b/plugins/scaffolder/src/components/ActionsPage/ActionsPage.tsx index 78960c8297..caddadfd2e 100644 --- a/plugins/scaffolder/src/components/ActionsPage/ActionsPage.tsx +++ b/plugins/scaffolder/src/components/ActionsPage/ActionsPage.tsx @@ -95,7 +95,7 @@ export const ActionsPage = () => { return Object.entries(properties).map(entry => { const [key] = entry; - const props = (entry[1] as unknown) as JSONSchema; + const props = entry[1] as unknown as JSONSchema; const codeClassname = classNames(classes.code, { [classes.codeRequired]: input.required?.includes(key), }); @@ -145,7 +145,7 @@ export const ActionsPage = () => { <> {name} {input.map((i, index) => ( -
    {renderTable((i as unknown) as JSONSchema)}
    +
    {renderTable(i as unknown as JSONSchema)}
    ))} ); diff --git a/plugins/scaffolder/src/components/FavouriteTemplate/FavouriteTemplate.tsx b/plugins/scaffolder/src/components/FavouriteTemplate/FavouriteTemplate.tsx index 3b8c165697..d158315130 100644 --- a/plugins/scaffolder/src/components/FavouriteTemplate/FavouriteTemplate.tsx +++ b/plugins/scaffolder/src/components/FavouriteTemplate/FavouriteTemplate.tsx @@ -57,10 +57,10 @@ export const favouriteTemplateIcon = (isStarred: boolean) => export const FavouriteTemplate = (props: Props) => { const classes = useStyles(); const { toggleStarredEntity, isStarredEntity } = useStarredEntities(); - const isStarred = useMemo(() => isStarredEntity(props.entity), [ - isStarredEntity, - props.entity, - ]); + const isStarred = useMemo( + () => isStarredEntity(props.entity), + [isStarredEntity, props.entity], + ); return ( ['schema']; uiSchema: FormProps['uiSchema'] } { +export function transformSchemaToProps(inputSchema: JsonObject): { + schema: FormProps['schema']; + uiSchema: FormProps['uiSchema']; +} { inputSchema.type = inputSchema.type || 'object'; const schema = JSON.parse(JSON.stringify(inputSchema)); delete schema.title; // Rendered separately diff --git a/plugins/scaffolder/src/components/TemplatePage/TemplatePage.test.tsx b/plugins/scaffolder/src/components/TemplatePage/TemplatePage.test.tsx index 51e1ee5fbc..e42bcbdbdc 100644 --- a/plugins/scaffolder/src/components/TemplatePage/TemplatePage.test.tsx +++ b/plugins/scaffolder/src/components/TemplatePage/TemplatePage.test.tsx @@ -161,21 +161,17 @@ describe('TemplatePage', () => { ], }); - const { - findByText, - findByLabelText, - findAllByRole, - findByRole, - } = await renderInTestApp( - - - , - { - mountedRoutes: { - '/create/actions': rootRouteRef, + const { findByText, findByLabelText, findAllByRole, findByRole } = + await renderInTestApp( + + + , + { + mountedRoutes: { + '/create/actions': rootRouteRef, + }, }, - }, - ); + ); expect(await findByText('Fill in some steps')).toBeInTheDocument(); diff --git a/plugins/scaffolder/src/components/TemplateTypePicker/TemplateTypePicker.test.tsx b/plugins/scaffolder/src/components/TemplateTypePicker/TemplateTypePicker.test.tsx index baeefc7d99..ba448dd22e 100644 --- a/plugins/scaffolder/src/components/TemplateTypePicker/TemplateTypePicker.test.tsx +++ b/plugins/scaffolder/src/components/TemplateTypePicker/TemplateTypePicker.test.tsx @@ -65,17 +65,17 @@ const entities: Entity[] = [ const apis = ApiRegistry.from([ [ catalogApiRef, - ({ + { getEntities: jest .fn() .mockImplementation(() => Promise.resolve({ items: entities })), - } as unknown) as CatalogApi, + } as unknown as CatalogApi, ], [ alertApiRef, - ({ + { post: jest.fn(), - } as unknown) as AlertApi, + } as unknown as AlertApi, ], ]); diff --git a/plugins/scaffolder/src/components/TemplateTypePicker/TemplateTypePicker.tsx b/plugins/scaffolder/src/components/TemplateTypePicker/TemplateTypePicker.tsx index b547af6143..7151446f4f 100644 --- a/plugins/scaffolder/src/components/TemplateTypePicker/TemplateTypePicker.tsx +++ b/plugins/scaffolder/src/components/TemplateTypePicker/TemplateTypePicker.tsx @@ -38,13 +38,8 @@ const useStyles = makeStyles(theme => ({ export const TemplateTypePicker = () => { const classes = useStyles(); const alertApi = useApi(alertApiRef); - const { - error, - loading, - availableTypes, - selectedTypes, - setSelectedTypes, - } = useEntityTypeFilter(); + const { error, loading, availableTypes, selectedTypes, setSelectedTypes } = + useEntityTypeFilter(); if (loading) return ; diff --git a/plugins/scaffolder/src/components/fields/EntityPicker/EntityPicker.test.tsx b/plugins/scaffolder/src/components/fields/EntityPicker/EntityPicker.test.tsx index 380a5e810e..f293969dff 100644 --- a/plugins/scaffolder/src/components/fields/EntityPicker/EntityPicker.test.tsx +++ b/plugins/scaffolder/src/components/fields/EntityPicker/EntityPicker.test.tsx @@ -69,14 +69,14 @@ describe('', () => { describe('without allowedKinds', () => { beforeEach(() => { uiSchema = { 'ui:options': {} }; - props = ({ + props = { onChange, schema, required, uiSchema, rawErrors, formData, - } as unknown) as FieldProps; + } as unknown as FieldProps; catalogApi.getEntities.mockResolvedValue({ items: entities }); }); @@ -109,14 +109,14 @@ describe('', () => { describe('with allowedKinds', () => { beforeEach(() => { uiSchema = { 'ui:options': { allowedKinds: ['User'] } }; - props = ({ + props = { onChange, schema, required, uiSchema, rawErrors, formData, - } as unknown) as FieldProps; + } as unknown as FieldProps; catalogApi.getEntities.mockResolvedValue({ items: entities }); }); diff --git a/plugins/scaffolder/src/components/fields/OwnerPicker/OwnerPicker.test.tsx b/plugins/scaffolder/src/components/fields/OwnerPicker/OwnerPicker.test.tsx index 5e47f9f0f9..18d6fd7e5c 100644 --- a/plugins/scaffolder/src/components/fields/OwnerPicker/OwnerPicker.test.tsx +++ b/plugins/scaffolder/src/components/fields/OwnerPicker/OwnerPicker.test.tsx @@ -66,14 +66,14 @@ describe('', () => { describe('without allowedKinds', () => { beforeEach(() => { uiSchema = { 'ui:options': {} }; - props = ({ + props = { onChange, schema, required, uiSchema, rawErrors, formData, - } as unknown) as FieldProps; + } as unknown as FieldProps; catalogApi.getEntities.mockResolvedValue({ items: entities }); }); @@ -96,14 +96,14 @@ describe('', () => { describe('with allowedKinds', () => { beforeEach(() => { uiSchema = { 'ui:options': { allowedKinds: ['User'] } }; - props = ({ + props = { onChange, schema, required, uiSchema, rawErrors, formData, - } as unknown) as FieldProps; + } as unknown as FieldProps; catalogApi.getEntities.mockResolvedValue({ items: entities }); }); diff --git a/plugins/scaffolder/src/components/fields/RepoUrlPicker/validation.test.ts b/plugins/scaffolder/src/components/fields/RepoUrlPicker/validation.test.ts index 1ea66e7df9..d47285bf56 100644 --- a/plugins/scaffolder/src/components/fields/RepoUrlPicker/validation.test.ts +++ b/plugins/scaffolder/src/components/fields/RepoUrlPicker/validation.test.ts @@ -19,9 +19,9 @@ import { FieldValidation } from '@rjsf/core'; describe('RepoPicker Validation', () => { const fieldValidator = () => - (({ + ({ addError: jest.fn(), - } as unknown) as FieldValidation); + } as unknown as FieldValidation); it('validates when no repo', () => { const mockFieldValidation = fieldValidator(); diff --git a/plugins/search-backend-module-pg/src/database/DatabaseDocumentStore.test.ts b/plugins/search-backend-module-pg/src/database/DatabaseDocumentStore.test.ts index 6f5075f112..b860faca6a 100644 --- a/plugins/search-backend-module-pg/src/database/DatabaseDocumentStore.test.ts +++ b/plugins/search-backend-module-pg/src/database/DatabaseDocumentStore.test.ts @@ -297,18 +297,18 @@ describe('DatabaseDocumentStore', () => { await store.transaction(async tx => { await store.prepareInsert(tx); await store.insertDocuments(tx, 'my-type', [ - ({ + { title: 'Lorem Ipsum', text: 'Hello World', myField: 'this', location: 'LOCATION-1', - } as unknown) as IndexableDocument, - ({ + } as unknown as IndexableDocument, + { title: 'Dolor sit amet', text: 'Hello World', myField: 'that', location: 'LOCATION-1', - } as unknown) as IndexableDocument, + } as unknown as IndexableDocument, { title: 'Hello World', text: 'Around the world', @@ -349,18 +349,18 @@ describe('DatabaseDocumentStore', () => { await store.transaction(async tx => { await store.prepareInsert(tx); await store.insertDocuments(tx, 'my-type', [ - ({ + { title: 'Lorem Ipsum', text: 'Hello World', myField: 'this', location: 'LOCATION-1', - } as unknown) as IndexableDocument, - ({ + } as unknown as IndexableDocument, + { title: 'Dolor sit amet', text: 'Hello World', myField: 'that', location: 'LOCATION-1', - } as unknown) as IndexableDocument, + } as unknown as IndexableDocument, { title: 'Hello World', text: 'Around the world', @@ -411,20 +411,20 @@ describe('DatabaseDocumentStore', () => { await store.transaction(async tx => { await store.prepareInsert(tx); await store.insertDocuments(tx, 'my-type', [ - ({ + { title: 'Lorem Ipsum', text: 'Hello World', myField: 'this', otherField: 'another', location: 'LOCATION-1', - } as unknown) as IndexableDocument, - ({ + } as unknown as IndexableDocument, + { title: 'Dolor sit amet', text: 'Hello World', myField: 'this', otherField: 'unknown', location: 'LOCATION-1', - } as unknown) as IndexableDocument, + } as unknown as IndexableDocument, ]); await store.completeInsert(tx, 'my-type'); }); @@ -461,18 +461,18 @@ describe('DatabaseDocumentStore', () => { await store.transaction(async tx => { await store.prepareInsert(tx); await store.insertDocuments(tx, 'my-type', [ - ({ + { title: 'Lorem Ipsum', text: 'Hello World', myField: 'this', location: 'LOCATION-1', - } as unknown) as IndexableDocument, - ({ + } as unknown as IndexableDocument, + { title: 'Dolor sit amet', text: 'Hello World', myField: 'this', location: 'LOCATION-1', - } as unknown) as IndexableDocument, + } as unknown as IndexableDocument, ]); await store.completeInsert(tx, 'my-type'); }); @@ -485,22 +485,22 @@ describe('DatabaseDocumentStore', () => { expect(rows).toEqual([ { - document: ({ + document: { title: 'Lorem Ipsum', text: 'Hello World', myField: 'this', location: 'LOCATION-1', - } as unknown) as IndexableDocument, + } as unknown as IndexableDocument, rank: expect.any(Number), type: 'my-type', }, { - document: ({ + document: { title: 'Dolor sit amet', text: 'Hello World', myField: 'this', location: 'LOCATION-1', - } as unknown) as IndexableDocument, + } as unknown as IndexableDocument, rank: expect.any(Number), type: 'my-type', }, diff --git a/plugins/search/src/components/LegacySearchPage/LegacySearchResult.tsx b/plugins/search/src/components/LegacySearchPage/LegacySearchResult.tsx index 95148c1a76..5efce583fd 100644 --- a/plugins/search/src/components/LegacySearchPage/LegacySearchResult.tsx +++ b/plugins/search/src/components/LegacySearchPage/LegacySearchResult.tsx @@ -138,7 +138,11 @@ export const SearchResult = ({ searchQuery }: SearchResultProps) => { const [filteredResults, setFilteredResults] = useState([]); - const { loading, error, value: results } = useAsync(async () => { + const { + loading, + error, + value: results, + } = useAsync(async () => { const entities = await catalogApi.getEntities(); return entities.items.map((entity: Entity) => ({ name: entity.metadata.name, diff --git a/plugins/splunk-on-call/src/components/EntitySplunkOnCallCard.tsx b/plugins/splunk-on-call/src/components/EntitySplunkOnCallCard.tsx index 98a706d67f..5a645f0559 100644 --- a/plugins/splunk-on-call/src/components/EntitySplunkOnCallCard.tsx +++ b/plugins/splunk-on-call/src/components/EntitySplunkOnCallCard.tsx @@ -92,7 +92,11 @@ export const EntitySplunkOnCallCard = () => { setShowDialog(x => !x); }, []); - const { value: usersAndTeam, loading, error } = useAsync(async () => { + const { + value: usersAndTeam, + loading, + error, + } = useAsync(async () => { const allUsers = await api.getUsers(); const usersHashMap = allUsers.reduce( (map: Record, obj: User) => { diff --git a/plugins/splunk-on-call/src/components/Escalation/EscalationPolicy.tsx b/plugins/splunk-on-call/src/components/Escalation/EscalationPolicy.tsx index 53b37b0a7a..066fa954ad 100644 --- a/plugins/splunk-on-call/src/components/Escalation/EscalationPolicy.tsx +++ b/plugins/splunk-on-call/src/components/Escalation/EscalationPolicy.tsx @@ -56,7 +56,11 @@ export const EscalationPolicy = ({ users, team }: Props) => { const classes = useStyles(); const api = useApi(splunkOnCallApiRef); - const { value: userNames, loading, error } = useAsync(async () => { + const { + value: userNames, + loading, + error, + } = useAsync(async () => { const oncalls = await api.getOnCallUsers(); const teamUsernames = oncalls .filter(oncall => oncall.team?.name === team) diff --git a/plugins/splunk-on-call/src/components/Incident/IncidentListItem.tsx b/plugins/splunk-on-call/src/components/Incident/IncidentListItem.tsx index fac8f5e2f7..21bc7c35d2 100644 --- a/plugins/splunk-on-call/src/components/Incident/IncidentListItem.tsx +++ b/plugins/splunk-on-call/src/components/Incident/IncidentListItem.tsx @@ -160,17 +160,15 @@ export const IncidentListItem = ({ return incident.monitorName; }; - const [ - { value: resolveValue, error: resolveError }, - handleResolveIncident, - ] = useAsyncFn( - async ({ incidentId, incidentType }: TriggerAlarmRequest) => - await api.incidentAction({ - routingKey: team, - incidentType, - incidentId, - }), - ); + const [{ value: resolveValue, error: resolveError }, handleResolveIncident] = + useAsyncFn( + async ({ incidentId, incidentType }: TriggerAlarmRequest) => + await api.incidentAction({ + routingKey: team, + incidentType, + incidentId, + }), + ); const [ { value: acknowledgeValue, error: acknowledgeError }, diff --git a/plugins/tech-radar/src/components/RadarLegend/RadarLegend.tsx b/plugins/tech-radar/src/components/RadarLegend/RadarLegend.tsx index ca55eb0c9d..b9bc6a59a6 100644 --- a/plugins/tech-radar/src/components/RadarLegend/RadarLegend.tsx +++ b/plugins/tech-radar/src/components/RadarLegend/RadarLegend.tsx @@ -271,13 +271,8 @@ const RadarLegend = (props: Props): JSX.Element => { return segments; }; - const { - quadrants, - rings, - entries, - onEntryMouseEnter, - onEntryMouseLeave, - } = props; + const { quadrants, rings, entries, onEntryMouseEnter, onEntryMouseLeave } = + props; const segments: Segments = setupSegments(entries); diff --git a/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.ts b/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.ts index 7c176da9fb..0368553ea4 100644 --- a/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.ts +++ b/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.ts @@ -85,46 +85,44 @@ export class DefaultTechDocsCollator implements DocumentCollator { const docPromises = entities.items .filter(it => it.metadata?.annotations?.['backstage.io/techdocs-ref']) .map((entity: Entity) => - limit( - async (): Promise => { - const entityInfo = { - kind: entity.kind, - namespace: entity.metadata.namespace || 'default', - name: entity.metadata.name, - }; + limit(async (): Promise => { + const entityInfo = { + kind: entity.kind, + namespace: entity.metadata.namespace || 'default', + name: entity.metadata.name, + }; - try { - const searchIndexResponse = await fetch( - DefaultTechDocsCollator.constructDocsIndexUrl( - techDocsBaseUrl, - entityInfo, - ), - ); - const searchIndex = await searchIndexResponse.json(); + try { + const searchIndexResponse = await fetch( + DefaultTechDocsCollator.constructDocsIndexUrl( + techDocsBaseUrl, + entityInfo, + ), + ); + const searchIndex = await searchIndexResponse.json(); - return searchIndex.docs.map((doc: MkSearchIndexDoc) => ({ - title: unescape(doc.title), - text: unescape(doc.text || ''), - location: this.applyArgsToFormat(this.locationTemplate, { - ...entityInfo, - path: doc.location, - }), + return searchIndex.docs.map((doc: MkSearchIndexDoc) => ({ + title: unescape(doc.title), + text: unescape(doc.text || ''), + location: this.applyArgsToFormat(this.locationTemplate, { ...entityInfo, - componentType: entity.spec?.type?.toString() || 'other', - lifecycle: (entity.spec?.lifecycle as string) || '', - owner: - entity.relations?.find(r => r.type === RELATION_OWNED_BY) - ?.target?.name || '', - })); - } catch (e) { - this.logger.warn( - `Failed to retrieve tech docs search index for entity ${entityInfo.namespace}/${entityInfo.kind}/${entityInfo.name}`, - e, - ); - return []; - } - }, - ), + path: doc.location, + }), + ...entityInfo, + componentType: entity.spec?.type?.toString() || 'other', + lifecycle: (entity.spec?.lifecycle as string) || '', + owner: + entity.relations?.find(r => r.type === RELATION_OWNED_BY) + ?.target?.name || '', + })); + } catch (e) { + this.logger.warn( + `Failed to retrieve tech docs search index for entity ${entityInfo.namespace}/${entityInfo.kind}/${entityInfo.name}`, + e, + ); + return []; + } + }), ); return (await Promise.all(docPromises)).flat(); } diff --git a/plugins/techdocs/src/client.test.ts b/plugins/techdocs/src/client.test.ts index 982c9496b2..aa57c97c65 100644 --- a/plugins/techdocs/src/client.test.ts +++ b/plugins/techdocs/src/client.test.ts @@ -21,9 +21,8 @@ import { NotFoundError } from '@backstage/errors'; import EventSource from 'eventsource'; import { TechDocsStorageClient } from './client'; -const MockedEventSource: jest.MockedClass< - typeof EventSource -> = EventSource as any; +const MockedEventSource: jest.MockedClass = + EventSource as any; jest.mock('eventsource'); @@ -91,9 +90,7 @@ describe('TechDocsStorageClient', () => { await storageApi.syncEntityDocs(mockEntity); - expect( - MockedEventSource, - ).toBeCalledWith( + expect(MockedEventSource).toBeCalledWith( 'http://backstage:9191/api/techdocs/sync/default/Component/test-component', { withCredentials: true, headers: {} }, ); @@ -119,9 +116,7 @@ describe('TechDocsStorageClient', () => { await storageApi.syncEntityDocs(mockEntity); - expect( - MockedEventSource, - ).toBeCalledWith( + expect(MockedEventSource).toBeCalledWith( 'http://backstage:9191/api/techdocs/sync/default/Component/test-component', { withCredentials: true, headers: { Authorization: 'Bearer token' } }, ); diff --git a/plugins/techdocs/src/components/DocsResultListItem/DocsResultListItem.test.tsx b/plugins/techdocs/src/components/DocsResultListItem/DocsResultListItem.test.tsx index 41de2fefe4..b87b4a4162 100644 --- a/plugins/techdocs/src/components/DocsResultListItem/DocsResultListItem.test.tsx +++ b/plugins/techdocs/src/components/DocsResultListItem/DocsResultListItem.test.tsx @@ -26,8 +26,7 @@ jest.mock('react-text-truncate', () => { const validResult = { location: 'https://backstage.io/docs', title: 'Documentation', - text: - 'Backstage is an open-source developer portal that puts the developer experience first.', + text: 'Backstage is an open-source developer portal that puts the developer experience first.', kind: 'library', namespace: '', name: 'Backstage', diff --git a/plugins/techdocs/src/home/components/TechDocsCustomHome.tsx b/plugins/techdocs/src/home/components/TechDocsCustomHome.tsx index 649d69ed8a..e2623fe81f 100644 --- a/plugins/techdocs/src/home/components/TechDocsCustomHome.tsx +++ b/plugins/techdocs/src/home/components/TechDocsCustomHome.tsx @@ -124,7 +124,11 @@ export const TechDocsCustomHome = ({ const catalogApi: CatalogApi = useApi(catalogApiRef); const configApi: ConfigApi = useApi(configApiRef); - const { value: entities, loading, error } = useAsync(async () => { + const { + value: entities, + loading, + error, + } = useAsync(async () => { const response = await catalogApi.getEntities({ filter: { 'metadata.annotations.backstage.io/techdocs-ref': CATALOG_FILTER_EXISTS, diff --git a/plugins/techdocs/src/reader/components/Reader.test.tsx b/plugins/techdocs/src/reader/components/Reader.test.tsx index 7824754231..2dc2773048 100644 --- a/plugins/techdocs/src/reader/components/Reader.test.tsx +++ b/plugins/techdocs/src/reader/components/Reader.test.tsx @@ -34,9 +34,8 @@ jest.mock('react-router-dom', () => { }; }); -const { useParams }: { useParams: jest.Mock } = jest.requireMock( - 'react-router-dom', -); +const { useParams }: { useParams: jest.Mock } = + jest.requireMock('react-router-dom'); describe('', () => { it('should render Reader content', async () => { @@ -44,11 +43,12 @@ describe('', () => { entityId: 'Component::backstage', }); - const scmIntegrationsApi: ScmIntegrationsApi = ScmIntegrationsApi.fromConfig( - new ConfigReader({ - integrations: {}, - }), - ); + const scmIntegrationsApi: ScmIntegrationsApi = + ScmIntegrationsApi.fromConfig( + new ConfigReader({ + integrations: {}, + }), + ); const techdocsStorageApi: Partial = {}; const apiRegistry = ApiRegistry.from([ diff --git a/plugins/techdocs/src/reader/components/TechDocsNotFound.tsx b/plugins/techdocs/src/reader/components/TechDocsNotFound.tsx index 430b8e6c05..4bc7d4fa59 100644 --- a/plugins/techdocs/src/reader/components/TechDocsNotFound.tsx +++ b/plugins/techdocs/src/reader/components/TechDocsNotFound.tsx @@ -23,9 +23,8 @@ type Props = { }; export const TechDocsNotFound = ({ errorMessage }: Props) => { - const techdocsBuilder = useApi(configApiRef).getOptionalString( - 'techdocs.builder', - ); + const techdocsBuilder = + useApi(configApiRef).getOptionalString('techdocs.builder'); let additionalInfo = ''; if (techdocsBuilder !== 'local') { diff --git a/plugins/techdocs/src/reader/components/TechDocsPage.test.tsx b/plugins/techdocs/src/reader/components/TechDocsPage.test.tsx index 1d80683d63..53b8590eb5 100644 --- a/plugins/techdocs/src/reader/components/TechDocsPage.test.tsx +++ b/plugins/techdocs/src/reader/components/TechDocsPage.test.tsx @@ -45,9 +45,8 @@ jest.mock('./TechDocsPageHeader', () => { }; }); -const { useParams }: { useParams: jest.Mock } = jest.requireMock( - 'react-router-dom', -); +const { useParams }: { useParams: jest.Mock } = + jest.requireMock('react-router-dom'); describe('', () => { it('should render techdocs page', async () => { @@ -55,11 +54,12 @@ describe('', () => { entityId: 'Component::backstage', }); - const scmIntegrationsApi: ScmIntegrationsApi = ScmIntegrationsApi.fromConfig( - new ConfigReader({ - integrations: {}, - }), - ); + const scmIntegrationsApi: ScmIntegrationsApi = + ScmIntegrationsApi.fromConfig( + new ConfigReader({ + integrations: {}, + }), + ); const techdocsApi: Partial = { getEntityMetadata: () => Promise.resolve({ diff --git a/plugins/xcmetrics/src/components/OverviewComponent/OverviewComponent.tsx b/plugins/xcmetrics/src/components/OverviewComponent/OverviewComponent.tsx index 6fa3abda2e..b293c2a99c 100644 --- a/plugins/xcmetrics/src/components/OverviewComponent/OverviewComponent.tsx +++ b/plugins/xcmetrics/src/components/OverviewComponent/OverviewComponent.tsx @@ -33,10 +33,11 @@ import { overviewColumns } from '../BuildTableColumns'; export const OverviewComponent = () => { const client = useApi(xcmetricsApiRef); - const { value: builds, loading, error } = useAsync( - async () => client.getBuilds(), - [], - ); + const { + value: builds, + loading, + error, + } = useAsync(async () => client.getBuilds(), []); if (loading) { return ; diff --git a/plugins/xcmetrics/src/components/OverviewTrendsComponent/OverviewTrendsComponent.tsx b/plugins/xcmetrics/src/components/OverviewTrendsComponent/OverviewTrendsComponent.tsx index 2c4a04d582..52ac632cc3 100644 --- a/plugins/xcmetrics/src/components/OverviewTrendsComponent/OverviewTrendsComponent.tsx +++ b/plugins/xcmetrics/src/components/OverviewTrendsComponent/OverviewTrendsComponent.tsx @@ -54,12 +54,14 @@ export const OverviewTrendsComponent = () => { const theme = useTheme(); const classes = useStyles(); const client = useApi(xcmetricsApiRef); - const buildCountsResult = useAsync(async () => client.getBuildCounts(days), [ - days, - ]); - const buildTimesResult = useAsync(async () => client.getBuildTimes(days), [ - days, - ]); + const buildCountsResult = useAsync( + async () => client.getBuildCounts(days), + [days], + ); + const buildTimesResult = useAsync( + async () => client.getBuildTimes(days), + [days], + ); if (buildCountsResult.loading && buildTimesResult.loading) { return ; diff --git a/plugins/xcmetrics/src/components/StatusCellComponent/StatusCellComponent.tsx b/plugins/xcmetrics/src/components/StatusCellComponent/StatusCellComponent.tsx index b0537c53b7..1ecc324683 100644 --- a/plugins/xcmetrics/src/components/StatusCellComponent/StatusCellComponent.tsx +++ b/plugins/xcmetrics/src/components/StatusCellComponent/StatusCellComponent.tsx @@ -28,10 +28,11 @@ interface TooltipContentProps { const TooltipContent = ({ buildId }: TooltipContentProps) => { const client = useApi(xcmetricsApiRef); - const { value: build, loading, error } = useAsync( - async () => client.getBuild(buildId), - [], - ); + const { + value: build, + loading, + error, + } = useAsync(async () => client.getBuild(buildId), []); if (error) { return
    {error.message}
    ; diff --git a/plugins/xcmetrics/src/components/StatusMatrixComponent/StatusMatrixComponent.tsx b/plugins/xcmetrics/src/components/StatusMatrixComponent/StatusMatrixComponent.tsx index 3a6c7e1618..503c0b7ed4 100644 --- a/plugins/xcmetrics/src/components/StatusMatrixComponent/StatusMatrixComponent.tsx +++ b/plugins/xcmetrics/src/components/StatusMatrixComponent/StatusMatrixComponent.tsx @@ -48,10 +48,11 @@ export const StatusMatrixComponent = () => { const classes = useStyles(); const [measureRef, { width: rootWidth }] = useMeasure(); const client = useApi(xcmetricsApiRef); - const { value: builds, loading, error } = useAsync( - async () => client.getBuildStatuses(300), - [], - ); + const { + value: builds, + loading, + error, + } = useAsync(async () => client.getBuildStatuses(300), []); if (error) { return {error.message}; diff --git a/scripts/api-extractor.ts b/scripts/api-extractor.ts index 21c61599a4..ab5f063fb4 100644 --- a/scripts/api-extractor.ts +++ b/scripts/api-extractor.ts @@ -50,17 +50,16 @@ const { } = require('@rushstack/node-core-library/lib/PackageJsonLookup'); const old = PackageJsonLookup.prototype.tryGetPackageJsonFilePathFor; -PackageJsonLookup.prototype.tryGetPackageJsonFilePathFor = function tryGetPackageJsonFilePathForPatch( - path: string, -) { - if ( - path.includes('@material-ui') && - !dirname(path).endsWith('@material-ui') - ) { - return undefined; - } - return old.call(this, path); -}; +PackageJsonLookup.prototype.tryGetPackageJsonFilePathFor = + function tryGetPackageJsonFilePathForPatch(path: string) { + if ( + path.includes('@material-ui') && + !dirname(path).endsWith('@material-ui') + ) { + return undefined; + } + return old.call(this, path); + }; /** * Another monkey patch where we apply prettier to the API reports. This has to be patched into @@ -73,15 +72,14 @@ const { const originalGenerateReviewFileContent = ApiReportGenerator.generateReviewFileContent; -ApiReportGenerator.generateReviewFileContent = function decoratedGenerateReviewFileContent( - ...args -) { - const content = originalGenerateReviewFileContent.apply(this, args); - return prettier.format(content, { - ...require('@spotify/prettier-config'), - parser: 'markdown', - }); -}; +ApiReportGenerator.generateReviewFileContent = + function decoratedGenerateReviewFileContent(...args) { + const content = originalGenerateReviewFileContent.apply(this, args); + return prettier.format(content, { + ...require('@spotify/prettier-config'), + parser: 'markdown', + }); + }; const PACKAGE_ROOTS = ['packages', 'plugins']; @@ -218,9 +216,11 @@ async function runApiExtraction({ // The `packageFolder` needs to point to the location within `dist-types` in order for relative // paths to be logged. Unfortunately the `prepare` method above derives it from the `packageJsonFullPath`, // which needs to point to the actual file, so we override `packageFolder` afterwards. - (extractorConfig as { - packageFolder: string; - }).packageFolder = packageFolder; + ( + extractorConfig as { + packageFolder: string; + } + ).packageFolder = packageFolder; if (!compilerState) { compilerState = CompilerState.create(extractorConfig, { diff --git a/scripts/verify-links.js b/scripts/verify-links.js index d62aa75526..25bdaa2ac3 100755 --- a/scripts/verify-links.js +++ b/scripts/verify-links.js @@ -139,9 +139,8 @@ async function findExternalDocsLinks(dir) { const match = content.match(/---(?:\r|\n|.)*^id: (.*)$/m); // Both docs with an id and without should remove trailing /index - const realPath = (match - ? joinPath(dirname(url), match[1]) - : url.replace(/\.md$/, '') + const realPath = ( + match ? joinPath(dirname(url), match[1]) : url.replace(/\.md$/, '') ).replace(/\/index$/, ''); paths.set(url, realPath);