Skip to content

Commit 05494e7

Browse files
ericapisaniErica Pisanikodiakhq[bot]
authored
chore: convert repository to Typescript (#109)
* chore: [ts-migrate] Init tsconfig.json file Co-authored-by: ts-migrate <> * chore: [ts-migrate] Rename files from JS/JSX to TS/TSX Co-authored-by: ts-migrate <> * chore: Convert JS files to TS * chore: Update snapshot file to use Typescript file extension * chore: Remove ts-migrate dependency now that project has been converted to Typescript * chore: Add Jest Typescript types. Remove ts-expect-error comments that were introduced during initial migration with the ts-migrate tool now that the types are available in the project. * chore: Make changes needed to remove the last ts-expect-error comments Co-authored-by: Erica Pisani <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
1 parent 6358e44 commit 05494e7

12 files changed

+459
-471
lines changed

package.json

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
"@babel/eslint-parser": "^7.16.5",
2727
"@babel/eslint-plugin": "^7.16.5",
2828
"@netlify/eslint-config-node": "^5.1.8",
29+
"@types/jest": "^27.4.1",
2930
"babel-preset-gatsby-package": "^2.5.0",
3031
"cross-env": "^7.0.3",
3132
"gatsby": "^4.5.3",
@@ -51,7 +52,8 @@
5152
"url": "https://github.com/netlify/gatsby-plugin-netlify.git"
5253
},
5354
"scripts": {
54-
"build": "babel src --out-dir . --ignore \"**/__tests__\"",
55+
"build": "tsc && cd src/__tests__ && tsc",
56+
"clean": "tsc --build --clean",
5557
"prepare": "cross-env NODE_ENV=production npm run build",
5658
"prepublishOnly": "npm run prepare",
5759
"format": "npm run format:code && npm run format:other",
@@ -60,7 +62,7 @@
6062
"lint": "eslint --ext .js,.jsx,.ts,.tsx .",
6163
"prettier": "prettier \"**/*.{md,css,scss,yaml,yml}\"",
6264
"test": "jest",
63-
"watch": "babel -w src --out-dir . --ignore \"**/__tests__\""
65+
"watch": "tsc --watch"
6466
},
6567
"engines": {
6668
"node": ">=12.13.0"

src/__tests__/build-headers-program.js renamed to src/__tests__/build-headers-program.ts

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -171,17 +171,20 @@ const createPluginData = async () => {
171171
],
172172
},
173173
pathPrefix: ``,
174-
publicFolder: (...files) => join(tmpDir, ...files),
174+
publicFolder: (...files: any[]) => join(tmpDir, ...files),
175175
}
176176
}
177177

178-
jest.mock(`fs-extra`, () => ({
179-
...jest.requireActual(`fs-extra`),
180-
existsSync: jest.fn(),
181-
}))
178+
jest.mock(`fs-extra`, () => {
179+
const actualFsExtra = jest.requireActual(`fs-extra`)
180+
return {
181+
...actualFsExtra,
182+
existsSync: jest.fn(),
183+
}
184+
})
182185
// eslint-disable-next-line max-lines-per-function
183186
describe(`build-headers-program`, () => {
184-
let reporter
187+
let reporter: any
185188

186189
beforeEach(() => {
187190
reporter = {
@@ -213,7 +216,7 @@ describe(`build-headers-program`, () => {
213216
it(`with manifest['pages-manifest']`, async () => {
214217
const pluginData = await createPluginData()
215218

216-
existsSync.mockImplementation((path) => !path.includes(`page-data.json`) && !path.includes(`app-data.json`))
219+
existsSync.mockImplementation((path: any) => !path.includes(`page-data.json`) && !path.includes(`app-data.json`))
217220

218221
// gatsby < 2.9 uses page-manifest
219222
pluginData.manifest[`pages-manifest`] = [`pages-manifest-ab11f09e0ca7ecd3b43e.js`]
@@ -244,7 +247,7 @@ describe(`build-headers-program`, () => {
244247
...DEFAULT_OPTIONS,
245248
mergeCachingHeaders: true,
246249
}
247-
existsSync.mockImplementation((path) => !path.includes(`app-data.json`))
250+
existsSync.mockImplementation((path: any) => !path.includes(`app-data.json`))
248251

249252
await buildHeadersProgram(pluginData, pluginOptions, reporter)
250253

File renamed without changes.

src/__tests__/tsconfig.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"extends": "../../tsconfig.json",
3+
"compilerOptions": {
4+
"noEmit": true,
5+
}
6+
}

src/build-headers-program.js renamed to src/build-headers-program.ts

Lines changed: 80 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@ import {
1616
PAGE_DATA_DIR,
1717
} from './constants'
1818

19-
const getHeaderName = (header) => {
19+
const getHeaderName = (header: any) => {
2020
const matches = header.match(/^([^:]+):/)
2121
return matches && matches[1]
2222
}
2323

24-
const validHeaders = (headers, reporter) => {
24+
const validHeaders = (headers: any, reporter: any) => {
2525
if (!headers || !_.isObject(headers)) {
2626
return false
2727
}
@@ -40,20 +40,20 @@ const validHeaders = (headers, reporter) => {
4040
)
4141
}
4242

43-
const linkTemplate = (assetPath, type = `script`) =>
43+
const linkTemplate = (assetPath: any, type = `script`) =>
4444
`Link: <${assetPath}>; rel=preload; as=${type}${type === `fetch` ? `; crossorigin` : ``}`
4545

46-
const pathChunkName = (path) => {
46+
const pathChunkName = (path: any) => {
4747
const name = path === `/` ? `index` : kebabHash(path)
4848
return `path---${name}`
4949
}
5050

51-
const getPageDataPath = (path) => {
51+
const getPageDataPath = (path: any) => {
5252
const fixedPagePath = path === `/` ? `index` : path
5353
return posix.join(`page-data`, fixedPagePath, `page-data.json`)
5454
}
5555

56-
const getScriptPath = (file, manifest) => {
56+
const getScriptPath = (file: any, manifest: any) => {
5757
const chunk = manifest[file]
5858

5959
if (!chunk) {
@@ -71,14 +71,19 @@ const getScriptPath = (file, manifest) => {
7171
})
7272
}
7373

74-
const getLinkHeaders = (filesByType, pathPrefix) =>
75-
Object.entries(filesByType).flatMap(([type, files]) =>
74+
const getLinkHeaders = (filesByType: any, pathPrefix: any) =>
75+
Object.entries(filesByType).flatMap(([type, files]: [string, Array<string>]) =>
7676
files.map((file) => linkTemplate(`${pathPrefix}/${file}`, type)),
7777
)
7878

79-
const headersPath = (pathPrefix, path) => `${pathPrefix}${path}`
79+
const headersPath = (pathPrefix: any, path: any) => `${pathPrefix}${path}`
8080

81-
const preloadHeadersByPage = ({ pages, manifest, pathPrefix, publicFolder }) => {
81+
const preloadHeadersByPage = ({
82+
pages,
83+
manifest,
84+
pathPrefix,
85+
publicFolder
86+
}: any) => {
8287
const linksByPage = {}
8388

8489
const appDataPath = publicFolder(PAGE_DATA_DIR, `app-data.json`)
@@ -91,7 +96,7 @@ const preloadHeadersByPage = ({ pages, manifest, pathPrefix, publicFolder }) =>
9196
hasPageData = existsSync(pageDataPath)
9297
}
9398

94-
pages.forEach((page) => {
99+
pages.forEach((page: any) => {
95100
const scripts = _.flatMap(COMMON_BUNDLES, (file) => getScriptPath(file, manifest))
96101
scripts.push(
97102
...getScriptPath(pathChunkName(page.path), manifest),
@@ -119,8 +124,8 @@ const preloadHeadersByPage = ({ pages, manifest, pathPrefix, publicFolder }) =>
119124
return linksByPage
120125
}
121126

122-
const defaultMerge = (...headers) => {
123-
const unionMerge = (objValue, srcValue) => {
127+
const defaultMerge = (...headers: any[]) => {
128+
const unionMerge = (objValue: any, srcValue: any) => {
124129
if (Array.isArray(objValue)) {
125130
return _.union(objValue, srcValue)
126131
}
@@ -130,18 +135,18 @@ const defaultMerge = (...headers) => {
130135
return _.mergeWith({}, ...headers, unionMerge)
131136
}
132137

133-
const headersMerge = (userHeaders, defaultHeaders) => {
138+
const headersMerge = (userHeaders: any, defaultHeaders: any) => {
134139
const merged = {}
135140
Object.keys(defaultHeaders).forEach((path) => {
136141
if (!userHeaders[path]) {
137142
merged[path] = defaultHeaders[path]
138143
return
139144
}
140145
const headersMap = {}
141-
defaultHeaders[path].forEach((header) => {
146+
defaultHeaders[path].forEach((header: any) => {
142147
headersMap[getHeaderName(header)] = header
143148
})
144-
userHeaders[path].forEach((header) => {
149+
userHeaders[path].forEach((header: any) => {
145150
// override if exists
146151
headersMap[getHeaderName(header)] = header
147152
})
@@ -155,34 +160,32 @@ const headersMerge = (userHeaders, defaultHeaders) => {
155160
return merged
156161
}
157162

158-
const transformLink = (manifest, publicFolder, pathPrefix) => (header) =>
159-
header.replace(LINK_REGEX, (__, prefix, file, suffix) => {
160-
const hashed = manifest[file]
161-
if (hashed) {
162-
return `${prefix}${pathPrefix}${hashed}${suffix}`
163-
}
164-
if (existsSync(publicFolder(file))) {
165-
return `${prefix}${pathPrefix}${file}${suffix}`
166-
}
167-
throw new Error(
168-
`Could not find the file specified in the Link header \`${header}\`.` +
169-
`The gatsby-plugin-netlify is looking for a matching file (with or without a ` +
170-
`webpack hash). Check the public folder and your gatsby-config.js to ensure you are ` +
171-
`pointing to a public file.`,
172-
)
173-
})
163+
const transformLink = (manifest: any, publicFolder: any, pathPrefix: any) => (header: any) => header.replace(LINK_REGEX, (__: any, prefix: any, file: any, suffix: any) => {
164+
const hashed = manifest[file]
165+
if (hashed) {
166+
return `${prefix}${pathPrefix}${hashed}${suffix}`
167+
}
168+
if (existsSync(publicFolder(file))) {
169+
return `${prefix}${pathPrefix}${file}${suffix}`
170+
}
171+
throw new Error(
172+
`Could not find the file specified in the Link header \`${header}\`.` +
173+
`The gatsby-plugin-netlify is looking for a matching file (with or without a ` +
174+
`webpack hash). Check the public folder and your gatsby-config.js to ensure you are ` +
175+
`pointing to a public file.`,
176+
)
177+
})
174178

175179
// Writes out headers file format, with two spaces for indentation
176180
// https://www.netlify.com/docs/headers-and-basic-auth/
177-
const stringifyHeaders = (headers) =>
178-
Object.entries(headers).reduce((text, [path, headerList]) => {
179-
const headersString = headerList.reduce((accum, header) => `${accum} ${header}\n`, ``)
180-
return `${text}${path}\n${headersString}`
181-
}, ``)
181+
const stringifyHeaders = (headers: any) => Object.entries(headers).reduce((text, [path, headerList]: [string, Array<string>]) => {
182+
const headersString = headerList.reduce((accum, header) => `${accum} ${header}\n`, ``)
183+
return `${text}${path}\n${headersString}`
184+
}, ``)
182185

183186
// program methods
184187

185-
const validateUserOptions = (pluginOptions, reporter) => (headers) => {
188+
const validateUserOptions = (pluginOptions: any, reporter: any) => (headers: any) => {
186189
if (!validHeaders(headers, reporter)) {
187190
throw new Error(
188191
`The "headers" option to gatsby-plugin-netlify is in the wrong shape. ` +
@@ -192,7 +195,7 @@ const validateUserOptions = (pluginOptions, reporter) => (headers) => {
192195
)
193196
}
194197

195-
;[`mergeSecurityHeaders`, `mergeLinkHeaders`, `mergeCachingHeaders`].forEach((mergeOption) => {
198+
[`mergeSecurityHeaders`, `mergeLinkHeaders`, `mergeCachingHeaders`].forEach((mergeOption) => {
196199
if (!_.isBoolean(pluginOptions[mergeOption])) {
197200
throw new TypeError(
198201
`The "${mergeOption}" option to gatsby-plugin-netlify must be a boolean. Check your gatsby-config.js.`,
@@ -212,18 +215,23 @@ const validateUserOptions = (pluginOptions, reporter) => (headers) => {
212215
}
213216

214217
const mapUserLinkHeaders =
215-
({ manifest, pathPrefix, publicFolder }) =>
216-
(headers) =>
217-
Object.fromEntries(
218-
Object.entries(headers).map(([path, headerList]) => [
219-
path,
220-
headerList.map(transformLink(manifest, publicFolder, pathPrefix)),
221-
]),
222-
)
218+
({
219+
manifest,
220+
pathPrefix,
221+
publicFolder
222+
}: any) =>
223+
(headers: any) => Object.fromEntries(
224+
Object.entries(headers).map(([path, headerList]: [string, Array<string>]) => [
225+
path,
226+
headerList.map(transformLink(manifest, publicFolder, pathPrefix)),
227+
]),
228+
)
223229

224230
const mapUserLinkAllPageHeaders =
225-
(pluginData, { allPageHeaders }) =>
226-
(headers) => {
231+
(pluginData: any, {
232+
allPageHeaders
233+
}: any) =>
234+
(headers: any) => {
227235
if (!allPageHeaders) {
228236
return headers
229237
}
@@ -233,7 +241,7 @@ const mapUserLinkAllPageHeaders =
233241
const headersList = allPageHeaders.map(transformLink(manifest, publicFolder, pathPrefix))
234242

235243
const duplicateHeadersByPage = {}
236-
pages.forEach((page) => {
244+
pages.forEach((page: any) => {
237245
const pathKey = headersPath(pathPrefix, page.path)
238246
duplicateHeadersByPage[pathKey] = headersList
239247
})
@@ -242,8 +250,10 @@ const mapUserLinkAllPageHeaders =
242250
}
243251

244252
const applyLinkHeaders =
245-
(pluginData, { mergeLinkHeaders }) =>
246-
(headers) => {
253+
(pluginData: any, {
254+
mergeLinkHeaders
255+
}: any) =>
256+
(headers: any) => {
247257
if (!mergeLinkHeaders) {
248258
return headers
249259
}
@@ -260,8 +270,10 @@ const applyLinkHeaders =
260270
}
261271

262272
const applySecurityHeaders =
263-
({ mergeSecurityHeaders }) =>
264-
(headers) => {
273+
({
274+
mergeSecurityHeaders
275+
}: any) =>
276+
(headers: any) => {
265277
if (!mergeSecurityHeaders) {
266278
return headers
267279
}
@@ -270,8 +282,10 @@ const applySecurityHeaders =
270282
}
271283

272284
const applyCachingHeaders =
273-
(pluginData, { mergeCachingHeaders }) =>
274-
(headers) => {
285+
(pluginData: any, {
286+
mergeCachingHeaders
287+
}: any) =>
288+
(headers: any) => {
275289
if (!mergeCachingHeaders) {
276290
return headers
277291
}
@@ -301,18 +315,20 @@ const applyCachingHeaders =
301315
}
302316

303317
const applyTransfromHeaders =
304-
({ transformHeaders }) =>
305-
(headers) =>
306-
_.mapValues(headers, transformHeaders)
318+
({
319+
transformHeaders
320+
}: any) =>
321+
(headers: any) => _.mapValues(headers, transformHeaders)
307322

308-
const transformToString = (headers) => `${HEADER_COMMENT}\n\n${stringifyHeaders(headers)}`
323+
const transformToString = (headers: any) => `${HEADER_COMMENT}\n\n${stringifyHeaders(headers)}`
309324

310325
const writeHeadersFile =
311-
({ publicFolder }) =>
312-
(contents) =>
313-
writeFile(publicFolder(NETLIFY_HEADERS_FILENAME), contents)
326+
({
327+
publicFolder
328+
}: any) =>
329+
(contents: any) => writeFile(publicFolder(NETLIFY_HEADERS_FILENAME), contents)
314330

315-
const buildHeadersProgram = (pluginData, pluginOptions, reporter) =>
331+
const buildHeadersProgram = (pluginData: any, pluginOptions: any, reporter: any) =>
316332
_.flow(
317333
validateUserOptions(pluginOptions, reporter),
318334
mapUserLinkHeaders(pluginData),
File renamed without changes.

src/create-redirects.js renamed to src/create-redirects.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { existsSync, readFile, writeFile } from 'fs-extra'
33
import { HEADER_COMMENT } from './constants'
44

55
// eslint-disable-next-line max-statements
6-
export default async function writeRedirectsFile(pluginData, redirects, rewrites) {
6+
export default async function writeRedirectsFile(pluginData: any, redirects: any, rewrites: any) {
77
const { publicFolder } = pluginData
88

99
if (redirects.length === 0 && rewrites.length === 0) return null
@@ -22,7 +22,7 @@ export default async function writeRedirectsFile(pluginData, redirects, rewrites
2222
])
2323

2424
// Map redirect data to the format Netlify expects
25-
redirects = redirects.map((redirect) => {
25+
redirects = redirects.map((redirect: any) => {
2626
const { fromPath, isPermanent, redirectInBrowser, force, toPath, statusCode, ...rest } = redirect
2727

2828
let status = isPermanent ? `301` : `302`
@@ -49,7 +49,10 @@ export default async function writeRedirectsFile(pluginData, redirects, rewrites
4949
return pieces.join(` `)
5050
})
5151

52-
rewrites = rewrites.map(({ fromPath, toPath }) => `${fromPath} ${toPath} 200`)
52+
rewrites = rewrites.map(({
53+
fromPath,
54+
toPath
55+
}: any) => `${fromPath} ${toPath} 200`)
5356

5457
let commentFound = false
5558

0 commit comments

Comments
 (0)