Skip to content

Commit 41c5717

Browse files
committed
types: fix misc. util types
This requires the fixes in netlify/build#6104.
1 parent e3a7df7 commit 41c5717

File tree

11 files changed

+68
-100
lines changed

11 files changed

+68
-100
lines changed

src/commands/base-command.ts

-1
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,6 @@ export default class BaseCommand extends Command {
410410
const authLink = `${webUI}/authorize?response_type=ticket&ticket=${ticket.id}`
411411

412412
log(`Opening ${authLink}`)
413-
// @ts-expect-error TS(2345) FIXME: Argument of type '{ url: string; }' is not assigna... Remove this comment to see the full error message
414413
await openBrowser({ url: authLink })
415414

416415
const accessToken = await pollForToken({

src/commands/deploy/deploy.ts

+11-19
Original file line numberDiff line numberDiff line change
@@ -207,24 +207,14 @@ const validateFolders = async ({
207207
return { deployFolderStat, functionsFolderStat }
208208
}
209209

210-
/**
211-
* @param {object} config
212-
* @param {string} config.deployFolder
213-
* @param {*} config.site
214-
* @returns
215-
*/
216-
// @ts-expect-error TS(7031) FIXME: Binding element 'deployFolder' implicitly has an '... Remove this comment to see the full error message
217-
const getDeployFilesFilter = ({ deployFolder, site }) => {
210+
const getDeployFilesFilter = ({ deployFolder, site }: { deployFolder: string; site: { root: string } }) => {
218211
// site.root === deployFolder can happen when users run `netlify deploy --dir .`
219212
// in that specific case we don't want to publish the repo node_modules
220213
// when site.root !== deployFolder the behaviour matches our buildbot
221214
const skipNodeModules = site.root === deployFolder
222215

223-
/**
224-
* @param {string} filename
225-
*/
226-
// @ts-expect-error TS(7006) FIXME: Parameter 'filename' implicitly has an 'any' type.
227-
return (filename) => {
216+
return (filename: string) => {
217+
// TODO(serhalp) Per types, this should not be possible. Confirm and remove this check.
228218
if (filename == null) {
229219
return false
230220
}
@@ -269,16 +259,20 @@ const prepareProductionDeploy = async ({ api, siteData }) => {
269259
log('Deploying to main site URL...')
270260
}
271261

272-
// @ts-expect-error TS(7006) FIXME: Parameter 'actual' implicitly has an 'any' type.
273-
const hasErrorMessage = (actual, expected) => {
262+
const hasErrorMessage = (actual: unknown, expected: string): boolean => {
274263
if (typeof actual === 'string') {
275264
return actual.includes(expected)
276265
}
277266
return false
278267
}
279268

280-
// @ts-expect-error TS(7031) FIXME: Binding element 'error_' implicitly has an 'any' t... Remove this comment to see the full error message
281-
const reportDeployError = ({ error_, failAndExit }) => {
269+
const reportDeployError = ({
270+
error_,
271+
failAndExit,
272+
}: {
273+
error_: (Error & { json?: Record<string, unknown>; status?: number }) | any
274+
failAndExit: (errorOrMessage: Error | string) => void
275+
}) => {
282276
switch (true) {
283277
case error_.name === 'JSONHTTPError': {
284278
const message = error_?.json?.message ?? ''
@@ -488,7 +482,6 @@ const runDeploy = async ({
488482

489483
const { headers } = await parseAllHeaders({
490484
configHeaders: config.headers,
491-
// @ts-expect-error TS(2322) FIXME: Type 'string' is not assignable to type 'never'.
492485
headersFiles: [headersPath],
493486
minimal: true,
494487
})
@@ -906,7 +899,6 @@ export const deploy = async (options: OptionValues, command: BaseCommand) => {
906899

907900
if (options.open) {
908901
const urlToOpen = deployToProduction ? results.siteUrl : results.deployUrl
909-
// @ts-expect-error TS(2345) FIXME: Argument of type '{ url: any; }' is not assignable... Remove this comment to see the full error message
910902
await openBrowser({ url: urlToOpen })
911903
exit()
912904
}

src/commands/open/open-admin.ts

-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ export const openAdmin = async (options: OptionValues, command: BaseCommand) =>
1212
log(`Opening "${siteInfo.name}" site admin UI:`)
1313
log(`> ${siteInfo.admin_url}`)
1414

15-
// @ts-expect-error TS(2345) FIXME: Argument of type '{ url: any; }' is not assignable... Remove this comment to see the full error message
1615
await openBrowser({ url: siteInfo.admin_url })
1716
exit()
1817
}

src/commands/open/open-site.ts

-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ export const openSite = async (options: OptionValues, command: BaseCommand) => {
1313
log(`Opening "${siteInfo.name}" site url:`)
1414
log(`> ${url}`)
1515

16-
// @ts-expect-error TS(2345) FIXME: Argument of type '{ url: any; }' is not assignable... Remove this comment to see the full error message
1716
await openBrowser({ url })
1817
exit()
1918
}

src/utils/gh-auth.ts

-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ export const authWithNetlify = async () => {
8181
})
8282
const url = `${webUI}/cli?${urlParams.toString()}`
8383

84-
// @ts-expect-error TS(2345) FIXME: Argument of type '{ url: string; }' is not assigna... Remove this comment to see the full error message
8584
await openBrowser({ url })
8685

8786
return deferredPromise

src/utils/headers.ts

+20-26
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,40 @@
1-
import { parseAllHeaders } from '@netlify/headers-parser'
1+
import { type Header, type MinimalHeader, parseAllHeaders } from '@netlify/headers-parser'
22

33
import { NETLIFYDEVERR, log } from './command-helpers.js'
44

55
/**
66
* Get the matching headers for `path` given a set of `rules`.
7-
*
8-
* @param {Object<string,Object<string,string[]>>!} headers
9-
* The rules to use for matching.
10-
*
11-
* @param {string!} path
12-
* The path to match against.
13-
*
14-
* @returns {Object<string,string[]>}
157
*/
16-
// @ts-expect-error TS(7006) FIXME: Parameter 'headers' implicitly has an 'any' type.
17-
export const headersForPath = function (headers, path) {
18-
// @ts-expect-error TS(7031) FIXME: Binding element 'forRegExp' implicitly has an 'any... Remove this comment to see the full error message
19-
const matchingHeaders = headers.filter(({ forRegExp }) => forRegExp.test(path)).map(getHeaderValues)
20-
const headersRules = Object.assign({}, ...matchingHeaders)
8+
export const headersForPath = function (headers: Header[], path: string) {
9+
const matchingHeaders = headers.filter(({ forRegExp }) => forRegExp.test(path)).map(({ values }) => values)
10+
const headersRules = { ...matchingHeaders }
2111
return headersRules
2212
}
2313

24-
// @ts-expect-error TS(7031) FIXME: Binding element 'values' implicitly has an 'any' t... Remove this comment to see the full error message
25-
const getHeaderValues = function ({ values }) {
26-
return values
27-
}
28-
29-
// @ts-expect-error TS(7031) FIXME: Binding element 'configPath' implicitly has an 'an... Remove this comment to see the full error message
30-
export const parseHeaders = async function ({ config, configPath, headersFiles }): Promise<Header[]> {
14+
export const parseHeaders = async function ({
15+
config,
16+
configPath,
17+
headersFiles,
18+
}: {
19+
config?:
20+
| undefined
21+
| {
22+
headers?: undefined | MinimalHeader[]
23+
}
24+
configPath?: undefined | string
25+
headersFiles?: undefined | string[]
26+
}): Promise<Header[]> {
3127
const { errors, headers } = await parseAllHeaders({
3228
headersFiles,
3329
netlifyConfigPath: configPath,
3430
minimal: false,
3531
configHeaders: config?.headers || [],
3632
})
3733
handleHeadersErrors(errors)
38-
return headers
34+
return headers as Header[]
3935
}
4036

41-
// @ts-expect-error TS(7006) FIXME: Parameter 'errors' implicitly has an 'any' type.
42-
const handleHeadersErrors = function (errors) {
37+
const handleHeadersErrors = function (errors: Error[]): void {
4338
if (errors.length === 0) {
4439
return
4540
}
@@ -48,8 +43,7 @@ const handleHeadersErrors = function (errors) {
4843
log(NETLIFYDEVERR, `Headers syntax errors:\n${errorMessage}`)
4944
}
5045

51-
// @ts-expect-error TS(7031) FIXME: Binding element 'message' implicitly has an 'any' ... Remove this comment to see the full error message
52-
const getErrorMessage = function ({ message }) {
46+
const getErrorMessage = function ({ message }: Error): string {
5347
return message
5448
}
5549

src/utils/open-browser.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const unableToOpenBrowserMessage = function ({ message, url }: BrowserUnableMess
1919
}
2020

2121
type OpenBrowsrProps = {
22-
silentBrowserNoneError: boolean
22+
silentBrowserNoneError?: boolean
2323
url: string
2424
}
2525

src/utils/proxy.ts

+22-37
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ import generateETag from 'etag'
1818
import getAvailablePort from 'get-port'
1919
import httpProxy from 'http-proxy'
2020
import { createProxyMiddleware } from 'http-proxy-middleware'
21-
import { jwtDecode } from 'jwt-decode'
21+
import { jwtDecode, type JwtPayload } from 'jwt-decode'
2222
import { locatePath } from 'locate-path'
23-
import { Match } from 'netlify-redirector'
23+
import type { Match } from 'netlify-redirector'
2424
import pFilter from 'p-filter'
2525
import throttle from 'lodash/throttle.js'
2626

@@ -102,8 +102,7 @@ const injectHtml = async function (
102102
return await compressResponseBody(bodyWithInjections, proxyRes.headers['content-encoding'])
103103
}
104104

105-
// @ts-expect-error TS(7006) FIXME: Parameter 'errorBuffer' implicitly has an 'any' ty... Remove this comment to see the full error message
106-
const formatEdgeFunctionError = (errorBuffer, acceptsHtml) => {
105+
const formatEdgeFunctionError = (errorBuffer: Buffer<ArrayBufferLike>, acceptsHtml: boolean): string => {
107106
const {
108107
error: { message, name, stack },
109108
} = JSON.parse(errorBuffer.toString())
@@ -156,13 +155,11 @@ const isEndpointExists = async function (endpoint: string, origin: string) {
156155
}
157156
}
158157

159-
// @ts-expect-error TS(7006) FIXME: Parameter 'match' implicitly has an 'any' type.
160-
const isExternal = function (match) {
161-
return match.to && match.to.match(/^https?:\/\//)
158+
const isExternal = function (match: Match) {
159+
return 'to' in match && match.to.match(/^https?:\/\//)
162160
}
163161

164-
// @ts-expect-error TS(7031) FIXME: Binding element 'hash' implicitly has an 'any' typ... Remove this comment to see the full error message
165-
const stripOrigin = function ({ hash, pathname, search }) {
162+
const stripOrigin = function ({ hash, pathname, search }: URL): string {
166163
return `${pathname}${search}${hash}`
167164
}
168165

@@ -189,21 +186,18 @@ const proxyToExternalUrl = function ({
189186
return handler(req, res, () => {})
190187
}
191188

192-
// @ts-expect-error TS(7031) FIXME: Binding element 'addonUrl' implicitly has an 'any'... Remove this comment to see the full error message
193-
const handleAddonUrl = function ({ addonUrl, req, res }) {
189+
const handleAddonUrl = function ({ addonUrl, req, res }: { req: Request; res: ServerResponse; addonUrl: string }) {
194190
const dest = new URL(addonUrl)
195191
const destURL = stripOrigin(dest)
196192

197193
return proxyToExternalUrl({ req, res, dest, destURL })
198194
}
199195

200-
// @ts-expect-error TS(7006) FIXME: Parameter 'match' implicitly has an 'any' type.
201-
const isRedirect = function (match) {
202-
return match.status && match.status >= 300 && match.status <= 400
196+
const isRedirect = function (match: Match) {
197+
return 'status' in match && match.status >= 300 && match.status <= 400
203198
}
204199

205-
// @ts-expect-error TS(7006) FIXME: Parameter 'publicFolder' implicitly has an 'any' t... Remove this comment to see the full error message
206-
const render404 = async function (publicFolder) {
200+
const render404 = async function (publicFolder: string) {
207201
const maybe404Page = path.resolve(publicFolder, '404.html')
208202
try {
209203
const isFile = await isFileAsync(maybe404Page)
@@ -219,8 +213,7 @@ const render404 = async function (publicFolder) {
219213
// Used as an optimization to avoid dual lookups for missing assets
220214
const assetExtensionRegExp = /\.(html?|png|jpg|js|css|svg|gif|ico|woff|woff2)$/
221215

222-
// @ts-expect-error TS(7006) FIXME: Parameter 'url' implicitly has an 'any' type.
223-
const alternativePathsFor = function (url) {
216+
const alternativePathsFor = function (url: string) {
224217
if (isFunction(true, url)) {
225218
return []
226219
}
@@ -317,9 +310,9 @@ const serveRedirect = async function ({
317310
req.url = '/.netlify/non-existent-path'
318311

319312
if (token) {
320-
let jwtValue = {}
313+
let jwtValue: JwtPayload = {}
321314
try {
322-
jwtValue = jwtDecode(token) || {}
315+
jwtValue = jwtDecode(token)
323316
} catch (error) {
324317
// @ts-expect-error TS(2571) FIXME: Object is of type 'unknown'.
325318
console.warn(NETLIFYDEVWARN, 'Error while decoding JWT provided in request', error.message)
@@ -328,7 +321,6 @@ const serveRedirect = async function ({
328321
return
329322
}
330323

331-
// @ts-expect-error TS(2339) FIXME: Property 'exp' does not exist on type '{}'.
332324
if ((jwtValue.exp || 0) < Math.round(Date.now() / MILLISEC_TO_SEC)) {
333325
console.warn(NETLIFYDEVWARN, 'Expired JWT provided in request', req.url)
334326
} else {
@@ -462,10 +454,9 @@ const serveRedirect = async function ({
462454
return proxy.web(req, res, options)
463455
}
464456

465-
// @ts-expect-error TS(7006) FIXME: Parameter 'req' implicitly has an 'any' type.
466-
const reqToURL = function (req, pathname) {
457+
const reqToURL = function (req: Request, pathname: undefined | string) {
467458
return new URL(
468-
pathname,
459+
pathname ?? '',
469460
`${req.protocol || (req.headers.scheme && `${req.headers.scheme}:`) || 'http:'}//${
470461
req.headers.host || req.hostname
471462
}`,
@@ -612,10 +603,8 @@ const initializeProxy = async function ({
612603
})
613604
}
614605

615-
// @ts-expect-error TS(7034) FIXME: Variable 'responseData' implicitly has type 'any[]... Remove this comment to see the full error message
616-
const responseData = []
617-
// @ts-expect-error TS(2345) FIXME: Argument of type 'string | undefined' is not assig... Remove this comment to see the full error message
618-
const requestURL = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`)
606+
const responseData: Uint8Array[] = []
607+
const requestURL = new URL(req.url ?? '', `http://${req.headers.host || '127.0.0.1'}`)
619608
const headersRules = headersForPath(headers, requestURL.pathname)
620609

621610
const htmlInjections =
@@ -649,11 +638,10 @@ const initializeProxy = async function ({
649638
}
650639

651640
proxyRes.on('data', function onData(data) {
652-
responseData.push(data)
641+
responseData.push(data as Uint8Array)
653642
})
654643

655644
proxyRes.on('end', async function onEnd() {
656-
// @ts-expect-error TS(7005) FIXME: Variable 'responseData' implicitly has an 'any[]' ... Remove this comment to see the full error message
657645
let responseBody = Buffer.concat(responseData)
658646

659647
// @ts-expect-error TS(2339) FIXME: Property 'proxyOptions' does not exist on type 'In... Remove this comment to see the full error message
@@ -684,7 +672,7 @@ const initializeProxy = async function ({
684672
const isUncaughtError = proxyRes.headers['x-nf-uncaught-error'] === '1'
685673

686674
if (isEdgeFunctionsRequest(req) && isUncaughtError) {
687-
const acceptsHtml = req.headers && req.headers.accept && req.headers.accept.includes('text/html')
675+
const acceptsHtml = req.headers?.accept?.includes('text/html') ?? false
688676
const decompressedBody = await decompressResponseBody(responseBody, proxyRes.headers['content-encoding'])
689677
const formattedBody = formatEdgeFunctionError(decompressedBody, acceptsHtml)
690678
const errorResponse = acceptsHtml
@@ -777,16 +765,13 @@ const onRequest = async (
777765
if (functionMatch) {
778766
// Setting an internal header with the function name so that we don't
779767
// have to match the URL again in the functions server.
780-
/** @type {Record<string, string>} */
781-
const headers = {}
768+
const headers: Record<string, string> = {}
782769

783770
if (functionMatch.func) {
784-
// @ts-expect-error TS(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
785771
headers[NFFunctionName] = functionMatch.func.name
786772
}
787773

788774
if (functionMatch.route) {
789-
// @ts-expect-error TS(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
790775
headers[NFFunctionRoute] = functionMatch.route.pattern
791776
}
792777

@@ -815,7 +800,7 @@ const onRequest = async (
815800
if (match) {
816801
// We don't want to generate an ETag for 3xx redirects.
817802
// @ts-expect-error TS(7031) FIXME: Binding element 'statusCode' implicitly has an 'an... Remove this comment to see the full error message
818-
req[shouldGenerateETag] = ({ statusCode }) => statusCode < 300 || statusCode >= 400
803+
req[shouldGenerateETag] = ({ statusCode }: { statusCode: number }) => statusCode < 300 || statusCode >= 400
819804

820805
return serveRedirect({ req, res, proxy, imageProxy, match, options, siteInfo, env, functionsRegistry })
821806
}
@@ -824,7 +809,7 @@ const onRequest = async (
824809
// generate an ETag unless we're rendering an error page. The only way for
825810
// us to know that is by looking at the status code
826811
// @ts-expect-error TS(7031) FIXME: Binding element 'statusCode' implicitly has an 'an... Remove this comment to see the full error message
827-
req[shouldGenerateETag] = ({ statusCode }) => statusCode >= 200 && statusCode < 300
812+
req[shouldGenerateETag] = ({ statusCode }: { statusCode: number }) => statusCode >= 200 && statusCode < 300
828813

829814
const hasFormSubmissionHandler: boolean =
830815
functionsRegistry && getFormHandler({ functionsRegistry, logWarning: false })

0 commit comments

Comments
 (0)