Skip to content

Commit 53f8838

Browse files
authored
chore: migrate to TypeScript strict in Payload package - #4/4 (#12733)
Important: An intentional effort is being made during migration to not modify runtime behavior. This implies that there will be several assertions, non-null assertions, and @ts-expect-error. This philosophy applies only to migrating old code to TypeScript strict, not to writing new code. For a more detailed justification for this reasoning, see #11840 (comment). In this PR, instead of following the approach of migrating a subset of files, I'm migrating all files by disabling specific rules. The first commits are named after the rule being disabled. With this PR, the migration of the payload package is complete 🚀
1 parent 96f417b commit 53f8838

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

71 files changed

+349
-489
lines changed

packages/payload/package.json

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@
7474
"build": "rimraf .dist && rimraf tsconfig.tsbuildinfo && pnpm copyfiles && pnpm build:types && pnpm build:swc && pnpm build:esbuild",
7575
"build:esbuild": "echo skipping esbuild",
7676
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
77-
"build:types": "concurrently --group \"tsc --emitDeclarationOnly --outDir dist\" \"tsc-strict\"",
77+
"build:types": "tsc --emitDeclarationOnly --outDir dist",
7878
"clean": "rimraf -g {dist,*.tsbuildinfo}",
7979
"clean:cache": "rimraf node_modules/.cache",
8080
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
@@ -124,15 +124,13 @@
124124
"@types/pluralize": "0.0.33",
125125
"@types/uuid": "10.0.0",
126126
"@types/ws": "^8.5.10",
127-
"concurrently": "9.1.2",
128127
"copyfiles": "2.4.1",
129128
"cross-env": "7.0.3",
130129
"esbuild": "0.25.5",
131130
"graphql-http": "^1.22.0",
132131
"react-datepicker": "7.6.0",
133132
"rimraf": "6.0.1",
134-
"sharp": "0.32.6",
135-
"typescript-strict-plugin": "2.4.4"
133+
"sharp": "0.32.6"
136134
},
137135
"peerDependencies": {
138136
"graphql": "^16.8.1"

packages/payload/src/auth/crypto.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
// @ts-strict-ignore
21
import crypto from 'crypto'
32

43
const algorithm = 'aes-256-ctr'
54

65
export function encrypt(text: string): string {
76
const iv = crypto.randomBytes(16)
8-
const cipher = crypto.createCipheriv(algorithm, this.secret, iv)
7+
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
8+
const secret = this.secret
9+
const cipher = crypto.createCipheriv(algorithm, secret, iv)
910

1011
const encrypted = Buffer.concat([cipher.update(text), cipher.final()])
1112

@@ -19,7 +20,9 @@ export function decrypt(hash: string): string {
1920
const iv = hash.slice(0, 32)
2021
const content = hash.slice(32)
2122

22-
const decipher = crypto.createDecipheriv(algorithm, this.secret, Buffer.from(iv, 'hex'))
23+
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
24+
const secret = this.secret
25+
const decipher = crypto.createDecipheriv(algorithm, secret, Buffer.from(iv, 'hex'))
2326

2427
const decrypted = Buffer.concat([decipher.update(Buffer.from(content, 'hex')), decipher.final()])
2528

packages/payload/src/auth/operations/unlock.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// @ts-strict-ignore
21
import { status as httpStatus } from 'http-status'
32

43
import type {
@@ -94,7 +93,7 @@ export const unlockOperation = async <TSlug extends CollectionSlug>(
9493
where: whereConstraint,
9594
})
9695

97-
let result
96+
let result: boolean | null = null
9897

9998
if (user) {
10099
await resetLoginAttempts({
@@ -112,7 +111,7 @@ export const unlockOperation = async <TSlug extends CollectionSlug>(
112111
await commitTransaction(req)
113112
}
114113

115-
return result
114+
return result!
116115
} catch (error: unknown) {
117116
await killTransaction(req)
118117
throw error

packages/payload/src/auth/strategies/local/authenticate.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// @ts-strict-ignore
22
import crypto from 'crypto'
3+
// @ts-expect-error - no types available
34
import scmp from 'scmp'
45

56
import type { TypeWithID } from '../../../collections/config/types.js'

packages/payload/src/bin/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export const bin = async () => {
6969
}
7070

7171
const userBinScript = Array.isArray(config.bin)
72-
? config.bin.find(({ key }) => key === script)
72+
? config.bin.find(({ key }: { key: string }) => key === script)
7373
: false
7474

7575
if (userBinScript) {

packages/payload/src/bin/migrate.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// @ts-strict-ignore
21
import type { ParsedArgs } from 'minimist'
32

43
import type { SanitizedConfig } from '../config/types.js'
@@ -97,7 +96,8 @@ export const migrate = async ({ config, parsedArgs }: Args): Promise<void> => {
9796
skipEmpty,
9897
})
9998
} catch (err) {
100-
throw new Error(`Error creating migration: ${err.message}`)
99+
const error = err instanceof Error ? err.message : 'Unknown error'
100+
throw new Error(`Error creating migration: ${error}`)
101101
}
102102
break
103103
case 'migrate:down':

packages/payload/src/collections/config/client.ts

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
// @ts-strict-ignore
2-
import type { I18nClient } from '@payloadcms/translations'
1+
import type { I18nClient, TFunction } from '@payloadcms/translations'
32

43
import type { StaticDescription } from '../../admin/types.js'
54
import type { ImportMap } from '../../bin/generateImportMap/index.js'
@@ -139,7 +138,7 @@ export const createClientCollectionConfig = ({
139138
clientCollection.admin.description = collection.admin.description
140139
}
141140
} else if (typeof collection.admin.description === 'function') {
142-
const description = collection.admin.description({ t: i18n.t })
141+
const description = collection.admin.description({ t: i18n.t as TFunction })
143142
if (description) {
144143
clientCollection.admin.description = description
145144
}
@@ -159,7 +158,8 @@ export const createClientCollectionConfig = ({
159158
}
160159
break
161160
default:
162-
clientCollection.admin[adminKey] = collection.admin[adminKey]
161+
;(clientCollection as any).admin[adminKey] =
162+
collection.admin[adminKey as keyof SanitizedCollectionConfig['admin']]
163163
}
164164
}
165165
break
@@ -215,11 +215,11 @@ export const createClientCollectionConfig = ({
215215
clientCollection.labels = {
216216
plural:
217217
typeof collection.labels.plural === 'function'
218-
? collection.labels.plural({ i18n, t: i18n.t })
218+
? collection.labels.plural({ i18n, t: i18n.t as TFunction })
219219
: collection.labels.plural,
220220
singular:
221221
typeof collection.labels.singular === 'function'
222-
? collection.labels.singular({ i18n, t: i18n.t })
222+
? collection.labels.singular({ i18n, t: i18n.t as TFunction })
223223
: collection.labels.singular,
224224
}
225225
break
@@ -241,13 +241,14 @@ export const createClientCollectionConfig = ({
241241
return sanitizedSize
242242
})
243243
} else {
244-
clientCollection.upload[uploadKey] = collection.upload[uploadKey]
244+
;(clientCollection.upload as any)[uploadKey] =
245+
collection.upload[uploadKey as keyof SanitizedUploadConfig]
245246
}
246247
}
247248
break
248249

249250
default:
250-
clientCollection[key] = collection[key]
251+
;(clientCollection as any)[key] = collection[key as keyof SanitizedCollectionConfig]
251252
}
252253
}
253254

packages/payload/src/collections/dataloader.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// @ts-strict-ignore
21
import type { BatchLoadFn } from 'dataloader'
32

43
import DataLoader from 'dataloader'
@@ -22,7 +21,7 @@ import { isValidID } from '../utilities/isValidID.js'
2221

2322
const batchAndLoadDocs =
2423
(req: PayloadRequest): BatchLoadFn<string, TypeWithID> =>
25-
async (keys: string[]): Promise<TypeWithID[]> => {
24+
async (keys: readonly string[]): Promise<TypeWithID[]> => {
2625
const { payload } = req
2726

2827
// Create docs array of same length as keys, using null as value
@@ -47,7 +46,7 @@ const batchAndLoadDocs =
4746
*
4847
**/
4948

50-
const batchByFindArgs = {}
49+
const batchByFindArgs: Record<string, string[]> = {}
5150

5251
for (const key of keys) {
5352
const [

packages/payload/src/collections/operations/delete.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// @ts-strict-ignore
21
import { status as httpStatus } from 'http-status'
32

43
import type { AccessResult } from '../../config/types.js'
@@ -271,7 +270,7 @@ export const deleteOperation = async <
271270
} catch (error) {
272271
errors.push({
273272
id: doc.id,
274-
message: error.message,
273+
message: error instanceof Error ? error.message : 'Unknown error',
275274
})
276275
}
277276
return null

packages/payload/src/collections/operations/findVersions.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// @ts-strict-ignore
1+
import type { AccessResult } from '../../config/types.js'
22
import type { PaginatedDocs } from '../../database/types.js'
33
import type { PayloadRequest, PopulateType, SelectType, Sort, Where } from '../../types/index.js'
44
import type { TypeWithVersion } from '../../versions/types.js'
@@ -54,7 +54,7 @@ export const findVersionsOperation = async <TData extends TypeWithVersion<TData>
5454
// Access
5555
// /////////////////////////////////////
5656

57-
let accessResults
57+
let accessResults!: AccessResult
5858

5959
if (!overrideAccess) {
6060
accessResults = await executeAccess({ req }, collectionConfig.access.readVersions)

0 commit comments

Comments
 (0)