Skip to content

chore: fix linting errors #116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,14 @@ module.exports = {
env: {
jest: true,
},
overrides: [
{
// Tests use lots of nested callbacks
files: ['**/__tests__/*.ts'],
rules: {
'max-nested-callbacks': 'off',
'import/first': 'off',
},
},
],
}
6 changes: 4 additions & 2 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const rules = require('@netlify/eslint-config-node/.prettierrc.json')

module.exports = {
...require("@netlify/eslint-config-node/.prettierrc.json"),
endOfLine: "auto",
...rules,
endOfLine: 'auto',
}
43 changes: 19 additions & 24 deletions src/__tests__/gatsby-node.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,25 @@
jest.mock('../plugin-data', () => {
return {
__esModule: true,
default: jest.fn().mockReturnValue({
publicFolder: jest.fn().mockReturnValue('mock-file-path'),
}),
}
})
jest.mock('../build-headers-program', () => {
return {
__esModule: true,
default: jest.fn(),
}
})
jest.mock('fs-extra', () => {
return {
__esModule: true,
default: jest.fn(),
existsSync: jest.fn(),
readFile: jest.fn(),
writeFile: jest.fn(),
}
})
jest.mock('../plugin-data', () => ({
__esModule: true,
default: jest.fn().mockReturnValue({
publicFolder: jest.fn().mockReturnValue('mock-file-path'),
}),
}))
jest.mock('../build-headers-program', () => ({
__esModule: true,
default: jest.fn(),
}))
jest.mock('fs-extra', () => ({
__esModule: true,
default: jest.fn(),
existsSync: jest.fn(),
readFile: jest.fn(),
writeFile: jest.fn(),
}))

// Importing writeFile here gives us access to the mocked method to assert the correct content is written to the file within test cases
import { writeFile } from 'fs-extra'
import { testPluginOptionsSchema } from 'gatsby-plugin-utils'

import { pluginOptionsSchema, onPostBuild } from '../gatsby-node'

describe(`gatsby-node.js`, () => {
Expand All @@ -46,7 +41,7 @@ describe(`gatsby-node.js`, () => {
mergeSecurityHeaders: `this should be a boolean`,
mergeLinkHeaders: `this should be a boolean`,
mergeCachingHeaders: `this should be a boolean`,
transformHeaders: (too, many, args) => ``,
transformHeaders: (too, many, args) => [too, many, args],
generateMatchPathRewrites: `this should be a boolean`,
})

Expand Down
14 changes: 8 additions & 6 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import _ from "lodash"
import _ from 'lodash'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One day we should see if we can remove lodash. The gatsby codebase is littered with pointless use of it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call. I've added a draft ticket to the board.


// Gatsby values
export const BUILD_HTML_STAGE = `build-html`
Expand All @@ -7,17 +7,19 @@ export const BUILD_CSS_STAGE = `build-css`
// Plugin values
export const NETLIFY_HEADERS_FILENAME = `_headers`

// Default options including transform to manipulate headers for
// sorting and rewrites for client only paths
export const DEFAULT_OPTIONS = {
headers: {},
mergeSecurityHeaders: true,
mergeLinkHeaders: true,
mergeCachingHeaders: true,
transformHeaders: _.identity, // optional transform for manipulating headers for sorting, etc
generateMatchPathRewrites: true, // generate rewrites for client only paths
transformHeaders: _.identity,
generateMatchPathRewrites: true,
}

export const SECURITY_HEADERS = {
"/*": [
'/*': [
`X-Frame-Options: DENY`,
`X-XSS-Protection: 1; mode=block`,
`X-Content-Type-Options: nosniff`,
Expand All @@ -28,8 +30,8 @@ export const SECURITY_HEADERS = {
export const IMMUTABLE_CACHING_HEADER = `Cache-Control: public, max-age=31536000, immutable`

export const CACHING_HEADERS = {
"/static/*": [IMMUTABLE_CACHING_HEADER],
"/sw.js": [`Cache-Control: no-cache`],
'/static/*': [IMMUTABLE_CACHING_HEADER],
'/sw.js': [`Cache-Control: no-cache`],
}

export const LINK_REGEX = /^(Link: <\/)(.+)(>;.+)/
Expand Down
9 changes: 2 additions & 7 deletions src/create-redirects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ export default async function writeRedirectsFile(pluginData: any, redirects: any
const value = rest[key]

if (typeof value === `string` && value.includes(` `)) {
console.warn(
`Invalid redirect value "${value}" specified for key "${key}". ` + `Values should not contain spaces.`,
)
console.warn(`Invalid redirect value "${value}" specified for key "${key}". Values should not contain spaces.`)
} else if (NETLIFY_REDIRECT_KEYWORDS_ALLOWLIST.has(key)) {
pieces.push(`${key}=${value}`)
}
Expand All @@ -49,10 +47,7 @@ export default async function writeRedirectsFile(pluginData: any, redirects: any
return pieces.join(` `)
})

rewrites = rewrites.map(({
fromPath,
toPath
}: any) => `${fromPath} ${toPath} 200`)
rewrites = rewrites.map(({ fromPath, toPath }: any) => `${fromPath} ${toPath} 200`)

let commentFound = false

Expand Down
20 changes: 5 additions & 15 deletions src/gatsby-node.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// https://www.netlify.com/docs/headers-and-basic-auth/

import { promises as fs } from 'fs'
import { join } from 'path'

import { writeFile } from 'fs-extra'
import { generatePageDataPath } from 'gatsby-core-utils'
import WebpackAssetsManifest from 'webpack-assets-manifest'

Expand All @@ -14,9 +13,7 @@ import makePluginData from './plugin-data'
const assetsManifest = {}

/** @type {import("gatsby").GatsbyNode["pluginOptionsSchema"]} */
export const pluginOptionsSchema = ({
Joi
}: any) => {
export const pluginOptionsSchema = ({ Joi }: any) => {
const MATCH_ALL_KEYS = /^/

// headers is a specific type used by Netlify: https://www.gatsbyjs.com/plugins/gatsby-plugin-netlify/#headers
Expand Down Expand Up @@ -44,10 +41,7 @@ export const pluginOptionsSchema = ({
// Inject a webpack plugin to get the file manifests so we can translate all link headers
/** @type {import("gatsby").GatsbyNode["onCreateWebpackConfig"]} */

export const onCreateWebpackConfig = ({
actions,
stage
}: any) => {
export const onCreateWebpackConfig = ({ actions, stage }: any) => {
if (stage !== BUILD_HTML_STAGE && stage !== BUILD_CSS_STAGE) {
return
}
Expand All @@ -63,11 +57,7 @@ export const onCreateWebpackConfig = ({
}

/** @type {import("gatsby").GatsbyNode["onPostBuild"]} */
export const onPostBuild = async ({
store,
pathPrefix,
reporter
}: any, userPluginOptions: any) => {
export const onPostBuild = async ({ store, pathPrefix, reporter }: any, userPluginOptions: any) => {
const pluginData = makePluginData(store, assetsManifest, pathPrefix)
const pluginOptions = { ...DEFAULT_OPTIONS, ...userPluginOptions }

Expand Down Expand Up @@ -113,7 +103,7 @@ export const onPostBuild = async ({

if (!needsFunctions) {
reporter.info(`[gatsby-plugin-netlify] No Netlify functions needed. Skipping...`)
await fs.writeFile(join(program.directory, `.cache`, `.nf-skip-gatsby-functions`), ``)
await writeFile(join(program.directory, `.cache`, `.nf-skip-gatsby-functions`), ``)
}

await Promise.all([
Expand Down
14 changes: 9 additions & 5 deletions src/plugin-data.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import path from "path"
import path from 'path'

export function buildPrefixer(prefix: any, ...paths: any[]) {
return (...subpaths: any[]) => path.join(prefix, ...paths, ...subpaths);
}
const buildPrefixer =
(prefix: any, ...paths: any[]) =>
(...subpaths: any[]) =>
path.join(prefix, ...paths, ...subpaths)

// This function assembles data across the manifests and store to match a similar
// shape of `static-entry.js`. With it, we can build headers that point to the correct
// hashed filenames and ensure we pull in the componentChunkName.
export default function makePluginData(store: any, assetsManifest: any, pathPrefix: any) {
const makePluginData = (store: any, assetsManifest: any, pathPrefix: any) => {
const { program, pages, components } = store.getState()
const publicFolder = buildPrefixer(program.directory, `public`)
// eslint-disable-next-line node/global-require, import/no-dynamic-require, @typescript-eslint/no-var-requires
const stats = require(publicFolder(`webpack.stats.json`))
// Get all the files, not just the first
const chunkManifest = stats.assetsByChunkName
Expand All @@ -25,3 +27,5 @@ export default function makePluginData(store: any, assetsManifest: any, pathPref
publicFolder,
}
}

export { makePluginData as default, buildPrefixer }
Loading