Skip to content

Commit

Permalink
Forbid use of implicit any
Browse files Browse the repository at this point in the history
  • Loading branch information
matthieusieben committed Nov 15, 2024
1 parent 6bd421c commit c4b687d
Show file tree
Hide file tree
Showing 103 changed files with 626 additions and 268 deletions.
30 changes: 30 additions & 0 deletions .changeset/eighty-carrots-arrive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
"@atproto/oauth-client-browser-example": patch
"@atproto-labs/handle-resolver-node": patch
"@atproto-labs/simple-store-memory": patch
"@atproto/oauth-client-browser": patch
"@atproto/oauth-provider": patch
"@atproto-labs/fetch-node": patch
"@atproto/oauth-client": patch
"@atproto/oauth-types": patch
"@atproto-labs/fetch": patch
"@atproto/xrpc-server": patch
"@atproto/common-web": patch
"@atproto/dev-env": patch
"@atproto/lex-cli": patch
"@atproto/lexicon": patch
"@atproto/common": patch
"@atproto/syntax": patch
"@atproto/bsync": patch
"@atproto/ozone": patch
"@atproto/bsky": patch
"@atproto/repo": patch
"@atproto/sync": patch
"@atproto/xrpc": patch
"@atproto/api": patch
"@atproto/aws": patch
"@atproto/did": patch
"@atproto/pds": patch
---

Fix "implicit any" types
5 changes: 5 additions & 0 deletions .changeset/eleven-dolphins-rhyme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@atproto/common-web": patch
---

Expose isCid utility function
5 changes: 5 additions & 0 deletions .changeset/twelve-trainers-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@atproto/lexicon": patch
---

Small performance improvements
4 changes: 2 additions & 2 deletions packages/api/src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ export class Agent extends XrpcClient {
})

// assemble a map of labeler dids to the interpreted label value definitions
const labelDefs = {}
const labelDefs: Record<string, InterpretedLabelValueDefinition[]> = {}
if (labelers.data) {
for (const labeler of labelers.data
.views as AppBskyLabelerDefs.LabelerViewDetailed[]) {
Expand Down Expand Up @@ -1531,7 +1531,7 @@ export class Agent extends XrpcClient {
.filter((pref) => !AppBskyActorDefs.isSavedFeedsPref(pref))
.concat([feedsPref])
})
return res
return res!
}

private async updateSavedFeedsV2Preferences(
Expand Down
14 changes: 9 additions & 5 deletions packages/api/src/moderation/decision.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,15 @@ export class ModerationDecision {

addLabel(target: LabelTarget, label: Label, opts: ModerationOpts) {
// look up the label definition
const labelDef = CUSTOM_LABEL_VALUE_RE.test(label.val)
? opts.labelDefs?.[label.src]?.find(
(def) => def.identifier === label.val,
) || LABELS[label.val]
: LABELS[label.val]
const labelDef =
(CUSTOM_LABEL_VALUE_RE.test(label.val)
? opts.labelDefs?.[label.src]?.find(
(def) => def.identifier === label.val,
)
: undefined) ||
(Object.hasOwn(LABELS, label.val)
? LABELS[label.val as keyof typeof LABELS]
: undefined)
if (!labelDef) {
// ignore labels we don't understand
return
Expand Down
3 changes: 2 additions & 1 deletion packages/api/tests/atp-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3341,4 +3341,5 @@ describe('agent', () => {
})
})

const byType = (a, b) => a.$type.localeCompare(b.$type)
const byType = (a: { $type: string }, b: { $type: string }) =>
a.$type.localeCompare(b.$type)
8 changes: 8 additions & 0 deletions packages/api/tests/dispatcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -449,16 +449,19 @@ describe('AtpAgent', () => {
const agent2 = new AtpAgent({ service: `http://localhost:${port}` })

const res1 = await agent.com.atproto.server.describeServer()
// @ts-expect-error unspecced
expect(res1.data['atproto-accept-labelers']).toEqual(
`${BSKY_LABELER_DID};redact`,
)

AtpAgent.configure({ appLabelers: ['did:plc:test1', 'did:plc:test2'] })
const res2 = await agent.com.atproto.server.describeServer()
// @ts-expect-error unspecced
expect(res2.data['atproto-accept-labelers']).toEqual(
'did:plc:test1;redact, did:plc:test2;redact',
)
const res3 = await agent2.com.atproto.server.describeServer()
// @ts-expect-error unspecced
expect(res3.data['atproto-accept-labelers']).toEqual(
'did:plc:test1;redact, did:plc:test2;redact',
)
Expand All @@ -476,12 +479,14 @@ describe('AtpAgent', () => {

agent.configureLabelers(['did:plc:test1'])
const res1 = await agent.com.atproto.server.describeServer()
// @ts-expect-error unspecced
expect(res1.data['atproto-accept-labelers']).toEqual(
`${BSKY_LABELER_DID};redact, did:plc:test1`,
)

agent.configureLabelers(['did:plc:test1', 'did:plc:test2'])
const res2 = await agent.com.atproto.server.describeServer()
// @ts-expect-error unspecced
expect(res2.data['atproto-accept-labelers']).toEqual(
`${BSKY_LABELER_DID};redact, did:plc:test1, did:plc:test2`,
)
Expand All @@ -497,17 +502,20 @@ describe('AtpAgent', () => {
const agent = new AtpAgent({ service: `http://localhost:${port}` })

const res1 = await agent.com.atproto.server.describeServer()
// @ts-expect-error unspecced
expect(res1.data['atproto-proxy']).toBeFalsy()

agent.configureProxy('did:plc:test1#atproto_labeler')
const res2 = await agent.com.atproto.server.describeServer()
// @ts-expect-error unspecced
expect(res2.data['atproto-proxy']).toEqual(
'did:plc:test1#atproto_labeler',
)

const res3 = await agent
.withProxy('atproto_labeler', 'did:plc:test2')
.com.atproto.server.describeServer()
// @ts-expect-error unspecced
expect(res3.data['atproto-proxy']).toEqual(
'did:plc:test2#atproto_labeler',
)
Expand Down
1 change: 1 addition & 0 deletions packages/api/tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"noPropertyAccessFromIndexSignature": false,
"noUnusedLocals": false
},
"include": ["./src"]
Expand Down
3 changes: 2 additions & 1 deletion packages/api/tsconfig.tests.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"rootDir": ".",
"types": ["jest", "./jest.d.ts"],
"noEmit": true,
"noUnusedLocals": false
"noUnusedLocals": false,
"noPropertyAccessFromIndexSignature": false
},
"include": ["./tests"]
}
1 change: 1 addition & 0 deletions packages/aws/src/s3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ export class S3BlobStore implements BlobStore {
}

const handleErr = (err: unknown) => {
// @ts-expect-error (implicit any)
if (err?.['Code'] === 'NoSuchKey') {
throw new BlobNotFoundError()
} else {
Expand Down
1 change: 1 addition & 0 deletions packages/bsky/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
"@bufbuild/protoc-gen-es": "^1.5.0",
"@connectrpc/protoc-gen-connect-es": "^1.1.4",
"@did-plc/server": "^0.0.1",
"@types/compression": "^1.7.5",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/express-serve-static-core": "^4.17.36",
Expand Down
4 changes: 3 additions & 1 deletion packages/bsky/src/api/app/bsky/feed/getAuthorFeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ export const skeleton = async (inputs: {
actorDid: did,
limit: params.limit,
cursor: params.cursor,
feedType: FILTER_TO_FEED_TYPE[params.filter],
feedType: Object.hasOwn(FILTER_TO_FEED_TYPE, params.filter)
? FILTER_TO_FEED_TYPE[params.filter as keyof typeof FILTER_TO_FEED_TYPE]
: undefined,
})

let items: FeedItem[] = res.items.map((item) => ({
Expand Down
2 changes: 1 addition & 1 deletion packages/bsky/src/api/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type ResHeaderOpts = {
export const resHeaders = (
opts: Partial<ResHeaderOpts>,
): Record<string, string> => {
const headers = {}
const headers: Record<string, string> = {}
if (opts.labelers) {
headers[ATPROTO_CONTENT_LABELERS] = formatLabelerHeader(opts.labelers)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/bsky/src/cache/read-through.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export class ReadThroughCache<T> {
if (opts?.revalidate) {
return this.fetchAndCacheMany(keys)
}
let cached: Record<string, string>
let cached: Record<string, string | undefined>
try {
cached = await this.redis.getMulti(keys)
} catch (err) {
Expand Down
2 changes: 1 addition & 1 deletion packages/bsky/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ export class ServerConfig {
function stripUndefineds(
obj: Record<string, unknown>,
): Record<string, unknown> {
const result = {}
const result: Record<string, unknown> = {}
Object.entries(obj).forEach(([key, val]) => {
if (val !== undefined) {
result[key] = val
Expand Down
2 changes: 1 addition & 1 deletion packages/bsky/src/data-plane/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const createDataPlaneClient = (
const client = randomElement(remainingClients)
assert(client, 'no clients available')
try {
return await client.lib[method.localName](...args)
return await (client.lib as any)[method.localName](...args)
} catch (err) {
if (
err instanceof ConnectError &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,18 @@ export async function up(db: Kysely<unknown>): Promise<void> {
db,
)
} catch (err: unknown) {
// The "if not exists" isn't bulletproof against races, and we see test suites racing to
// create the extension. So we can just ignore errors indicating the extension already exists.
if (!err?.['detail']?.includes?.('(pg_trgm) already exists')) throw err
if (
err instanceof Error &&
'detail' in err &&
Array.isArray(err.detail) &&
err.detail.includes('(pg_trgm) already exists')
) {
// The "if not exists" isn't bulletproof against races, and we see test suites racing to
// create the extension. So we can just ignore errors indicating the extension already exists.
return
}

throw err
}

// duplicateRecords
Expand Down
5 changes: 3 additions & 2 deletions packages/bsky/src/data-plane/server/db/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
DummyDriver,
DynamicModule,
ExpressionBuilder,
Kysely,
RawBuilder,
SelectQueryBuilder,
sql,
Expand Down Expand Up @@ -31,7 +32,7 @@ export const softDeleted = (actorOrRecord: { takedownRef: string | null }) => {
export const countAll = sql<number>`count(*)`

// For use with doUpdateSet()
export const excluded = <T>(db: DatabaseSchema, col) => {
export const excluded = <T>(db: DatabaseSchema, col: string) => {
return sql<T>`${db.dynamic.ref(`excluded.${col}`)}`
}

Expand All @@ -49,7 +50,7 @@ export const dummyDialect = {
createDriver() {
return new DummyDriver()
},
createIntrospector(db) {
createIntrospector(db: Kysely<any>) {
return new SqliteIntrospector(db)
},
createQueryCompiler() {
Expand Down
15 changes: 9 additions & 6 deletions packages/bsky/src/data-plane/server/indexing/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { sql } from 'kysely'
import { ExpressionBuilder, sql } from 'kysely'
import { CID } from 'multiformats/cid'
import { AtpAgent, ComAtprotoSyncGetLatestCommit } from '@atproto/api'
import {
Expand All @@ -13,6 +13,7 @@ import { IdResolver, getPds } from '@atproto/identity'
import { DAY, HOUR } from '@atproto/common'
import { ValidationError } from '@atproto/lexicon'
import { Database } from '../db'
import { DatabaseSchemaType } from '../db/database-schema'
import { Actor } from '../db/tables/actor'
import * as Post from './plugins/post'
import * as Threadgate from './plugins/thread-gate'
Expand Down Expand Up @@ -246,10 +247,10 @@ export class IndexingService {
}

findIndexerForCollection(collection: string) {
const indexers = Object.values(
this.records as Record<string, RecordProcessor<unknown, unknown>>,
)
return indexers.find((indexer) => indexer.collection === collection)
const indexers = Object.values(this.records)
return indexers.find((indexer) => indexer.collection === collection) as
| RecordProcessor<unknown, unknown>
| undefined
}

async updateActorStatus(did: string, active: boolean, status: string = '') {
Expand Down Expand Up @@ -325,7 +326,9 @@ export class IndexingService {
.where('creator', '=', did)
.execute()
// posts
const postByUser = (qb) =>
const postByUser = (
qb: ExpressionBuilder<DatabaseSchemaType, keyof DatabaseSchemaType>,
) =>
qb
.selectFrom('post')
.where('post.creator', '=', did)
Expand Down
6 changes: 3 additions & 3 deletions packages/bsky/src/data-plane/server/indexing/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Insertable } from 'kysely'
import { CID } from 'multiformats/cid'
import { AtUri } from '@atproto/syntax'
import { chunkArray } from '@atproto/common'
import { jsonStringToLex, stringifyLex } from '@atproto/lexicon'
import { jsonStringToLex, LexValue, stringifyLex } from '@atproto/lexicon'
import { lexicons } from '../../../lexicon/lexicons'
import { Database } from '../db'
import DatabaseSchema from '../db/database-schema'
Expand Down Expand Up @@ -75,7 +75,7 @@ export class RecordProcessor<T, S> {
uri: uri.toString(),
cid: cid.toString(),
did: uri.host,
json: stringifyLex(obj),
json: stringifyLex(obj as LexValue),
indexedAt: timestamp,
})
.onConflict((oc) => oc.doNothing())
Expand Down Expand Up @@ -127,7 +127,7 @@ export class RecordProcessor<T, S> {
.where('uri', '=', uri.toString())
.set({
cid: cid.toString(),
json: stringifyLex(obj),
json: stringifyLex(obj as LexValue),
indexedAt: timestamp,
})
.execute()
Expand Down
8 changes: 4 additions & 4 deletions packages/bsky/src/data-plane/server/routes/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export default (db: Database): Partial<ServiceImpl<typeof Service>> => ({
const row = byDid[did]
const chatDeclaration = parseRecordBytes(
chatDeclarations.records[i].record,
)
) as any
return {
exists: !!row,
handle: row?.handle ?? undefined,
Expand All @@ -68,11 +68,11 @@ export default (db: Database): Partial<ServiceImpl<typeof Service>> => ({
if (handles.length === 0) {
return { dids: [] }
}
const res = await db.db
const res = (await db.db
.selectFrom('actor')
.where('handle', 'in', handles)
.selectAll()
.execute()
.select(['did', 'handle'])
.execute()) as { did: string; handle: string }[]
const byHandle = keyBy(res, 'handle')
const dids = handles.map((handle) => byHandle[handle]?.did ?? '')
return { dids }
Expand Down
9 changes: 7 additions & 2 deletions packages/bsky/src/hydration/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { CID } from 'multiformats/cid'
import * as ui8 from 'uint8arrays'
import { lexicons } from '../lexicon/lexicons'
import { Record } from '../proto/bsky_pb'
import { isTypeofObject, JsonValue } from '@atproto/common'

export class HydrationMap<T> extends Map<string, T | null> implements Merges {
merge(map: HydrationMap<T>): this {
Expand Down Expand Up @@ -83,8 +84,12 @@ export const parseRecord = <T extends UnknownRecord>(
}

const isValidRecord = (json: unknown) => {
const lexRecord = jsonToLex(json)
if (typeof lexRecord?.['$type'] !== 'string') {
const lexRecord = jsonToLex(json as JsonValue)
if (
!isTypeofObject(lexRecord) ||
!('$type' in lexRecord) ||
typeof lexRecord['$type'] !== 'string'
) {
return false
}
try {
Expand Down
2 changes: 1 addition & 1 deletion packages/bsky/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const httpLogger: ReturnType<typeof subsystemLogger> =
export const loggerMiddleware = pinoHttp({
logger: httpLogger,
serializers: {
err: (err: unknown) => ({
err: (err: any) => ({
code: err?.['code'],
message: err?.['message'],
}),
Expand Down
Loading

0 comments on commit c4b687d

Please sign in to comment.