diff --git a/deprecated-packages/gatsby-image/README.md b/deprecated-packages/gatsby-image/README.md index 8377cd65b21f2..cd9471bf0e511 100644 --- a/deprecated-packages/gatsby-image/README.md +++ b/deprecated-packages/gatsby-image/README.md @@ -400,7 +400,7 @@ While you could achieve a similar effect with plain CSS media queries, `gatsby-i | `fluid` | `object` / `array` | Data returned from the `fluid` query. When prop is an array it has to be combined with `media` keys, allows for art directing `fluid` images. | | `fadeIn` | `bool` | Defaults to fading in the image on load | | `durationFadeIn` | `number` | fading duration is set up to 500ms by default | -| `title` | `string` | Passed to the `img` element | | +| `title` | `string` | Passed to the `img` element | | `alt` | `string` | Passed to the `img` element. Defaults to an empty string `alt=""` | | `crossOrigin` | `string` | Passed to the `img` element | | `className` | `string` / `object` | Passed to the wrapper element. Object is needed to support Glamor's css prop | diff --git a/docs/docs/conceptual/gatsby-for-ecommerce.md b/docs/docs/conceptual/gatsby-for-ecommerce.md index eb19b1c4dbce8..e0db9d70c8178 100644 --- a/docs/docs/conceptual/gatsby-for-ecommerce.md +++ b/docs/docs/conceptual/gatsby-for-ecommerce.md @@ -44,13 +44,11 @@ E-commerce tends to have a number of specific requirements. When building a Gats - Check out our [e-commerce demo](https://shopify-demo.gatsbyjs.com/) built with our Shopify Starter, a proof of concept showcasing 10,000 products and 30,000 SKUs (variants). Clone our Shopify Starter, host it on Gatsby and connect it to your own Shopify data to develop your own proof of concept in as little as an hour. - - [What is Headless Commerce?](https://www.bigcommerce.com/articles/headless-commerce/#unlocking-flexibility-examples-of-headless-commerce-in-action), an overview from BigCommerce. - [Gatsby Shopify Starter](https://shopify-demo.gatsbyjs.com/) - Sell Things Fast With Gatsby and Shopify by Trevor Harmon [blog post](https://thetrevorharmon.com/blog/sell-things-fast-with-gatsby-and-shopify), [video](https://www.youtube.com/watch?v=tUtuGAFOjYI&t=16m59s) and [GitHub repo](https://github.com/thetrevorharmon/sell-things-fast/) diff --git a/docs/docs/conceptual/graphql-concepts.md b/docs/docs/conceptual/graphql-concepts.md index 01e28103dc345..e638cd18b8ede 100644 --- a/docs/docs/conceptual/graphql-concepts.md +++ b/docs/docs/conceptual/graphql-concepts.md @@ -257,7 +257,7 @@ export const markdownFrontmatterFragment = graphql` They can then be used in any GraphQL query after that! ```graphql -query($path: String!) { +query ($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { ...MarkdownFrontmatter } diff --git a/docs/docs/how-to/adding-common-features/adding-search.md b/docs/docs/how-to/adding-common-features/adding-search.md index 65d76b630814a..da7493bae03a9 100644 --- a/docs/docs/how-to/adding-common-features/adding-search.md +++ b/docs/docs/how-to/adding-common-features/adding-search.md @@ -10,7 +10,7 @@ There are three required components for adding search to your Gatsby website: th | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Search index** | The search index is a copy of your data stored in a search-friendly format. An index is for optimizing speed and performance when executing a search query. Without an index, every search would need to scan every page in your site—which quickly becomes inefficient. | | **Search engine** | The search engine indexes your content, takes a search query, runs it through the index, and returns any matching documents. Search engines can be hosted services (like Algolia) or open-source that you can self-host (like Elastic) | -| **Search UI** | A UI component on your site that allows users to write search queries and view the results of each query. Some search providers provide out of the box React components that you can drop into Gatsby sites. | | +| **Search UI** | A UI component on your site that allows users to write search queries and view the results of each query. Some search providers provide out of the box React components that you can drop into Gatsby sites. | ## Adding search to your site diff --git a/docs/docs/how-to/images-and-media/importing-assets-into-files.md b/docs/docs/how-to/images-and-media/importing-assets-into-files.md index 9be848dc1ec16..8639fcfb5c883 100644 --- a/docs/docs/how-to/images-and-media/importing-assets-into-files.md +++ b/docs/docs/how-to/images-and-media/importing-assets-into-files.md @@ -129,7 +129,7 @@ Hi, this is a great article. In an article template component file, you can then query for the attachments: ```graphql -query($slug: String!) { +query ($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { diff --git a/docs/docs/reference/config-files/gatsby-config.md b/docs/docs/reference/config-files/gatsby-config.md index 91a0d555e5736..70f4afe5a484c 100644 --- a/docs/docs/reference/config-files/gatsby-config.md +++ b/docs/docs/reference/config-files/gatsby-config.md @@ -214,7 +214,7 @@ You may need to install the appropriate file transformer (in this case [YAML](/p Gatsby then uses this mapping when creating the GraphQL schema to enable you to query data from both sources: ```graphql -query($slug: String!) { +query ($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html fields { diff --git a/docs/docs/sourcing-from-builder-io.md b/docs/docs/sourcing-from-builder-io.md index 9ea683d5ff62d..2c8f52808f6b4 100644 --- a/docs/docs/sourcing-from-builder-io.md +++ b/docs/docs/sourcing-from-builder-io.md @@ -48,7 +48,7 @@ For example to get the entries from your models `myHeader`, `myFooter`: Or you can query by urlPath for your page models: ```graphql -query($path: String!) { +query ($path: String!) { allBuilderModels { myPageModel( target: { urlPath: $path } diff --git a/examples/using-remark/src/pages/2018-01-27---custom-components/index.md b/examples/using-remark/src/pages/2018-01-27---custom-components/index.md index 3e61c17334a16..fe8a62ecacccd 100644 --- a/examples/using-remark/src/pages/2018-01-27---custom-components/index.md +++ b/examples/using-remark/src/pages/2018-01-27---custom-components/index.md @@ -108,7 +108,7 @@ In order to display this component within a Markdown file, you'll need to add a }) export const renderAst = (ast: any): JSX.Element => { - return (processor.stringify(ast) as unknown) as JSX.Element + return processor.stringify(ast) as unknown as JSX.Element } ``` diff --git a/package.json b/package.json index c92ead5feeac9..23553c21fc650 100644 --- a/package.json +++ b/package.json @@ -36,11 +36,11 @@ "danger": "^10.6.4", "date-fns": "^1.30.1", "dictionary-en": "^3.1.0", - "eslint": "^7.28.0", + "eslint": "^7.32.0", "eslint-config-google": "^0.14.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-filenames": "^1.3.2", - "eslint-plugin-flowtype": "^5.7.2", + "eslint-plugin-flowtype": "^5.9.0", "eslint-plugin-import": "^2.23.4", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-prettier": "^3.4.0", @@ -64,7 +64,7 @@ "npm-packlist": "^2.1.5", "npm-run-all": "4.1.5", "plop": "^1.9.1", - "prettier": "2.1.2", + "prettier": "2.3.2", "remark": "^13.0.0", "remark-cli": "^9.0.0", "remark-frontmatter": "^3.0.0", diff --git a/packages/babel-plugin-remove-graphql-queries/src/index.ts b/packages/babel-plugin-remove-graphql-queries/src/index.ts index f53331b73dd27..8796903791c16 100644 --- a/packages/babel-plugin-remove-graphql-queries/src/index.ts +++ b/packages/babel-plugin-remove-graphql-queries/src/index.ts @@ -138,8 +138,10 @@ function getTagImport(tag: NodePath): NodePath | null { path.isVariableDeclarator() && (path.get(`init`) as NodePath).isCallExpression() && (path.get(`init.callee`) as NodePath).isIdentifier({ name: `require` }) && - ((path.get(`init`) as NodePath).node - .arguments[0] as StringLiteral).value === `gatsby` + ( + (path.get(`init`) as NodePath).node + .arguments[0] as StringLiteral + ).value === `gatsby` ) { const id = path.get(`id`) as NodePath if (id.isObjectPattern()) { @@ -294,9 +296,8 @@ export default function ({ types: t }): PluginObj { ) ) // Add import - const importDefaultSpecifier = t.importDefaultSpecifier( - identifier - ) + const importDefaultSpecifier = + t.importDefaultSpecifier(identifier) const importDeclaration = t.importDeclaration( [importDefaultSpecifier], t.stringLiteral( @@ -337,9 +338,9 @@ export default function ({ types: t }): PluginObj { // cannot remove all 'gatsby' imports. if (path2.node.callee.type !== `MemberExpression`) { // Remove imports to useStaticQuery - const importPath = (path2.scope.getBinding( - `useStaticQuery` - ) as Binding).path + const importPath = ( + path2.scope.getBinding(`useStaticQuery`) as Binding + ).path const parent = importPath.parentPath if (importPath.isImportSpecifier()) if ( @@ -356,9 +357,8 @@ export default function ({ types: t }): PluginObj { ) // Add import - const importDefaultSpecifier = t.importDefaultSpecifier( - identifier - ) + const importDefaultSpecifier = + t.importDefaultSpecifier(identifier) const importDeclaration = t.importDeclaration( [importDefaultSpecifier], t.stringLiteral( diff --git a/packages/babel-preset-gatsby/src/optimize-hook-destructuring.ts b/packages/babel-preset-gatsby/src/optimize-hook-destructuring.ts index b0783435f6267..310e8c1eca415 100644 --- a/packages/babel-preset-gatsby/src/optimize-hook-destructuring.ts +++ b/packages/babel-preset-gatsby/src/optimize-hook-destructuring.ts @@ -6,7 +6,8 @@ import { Program } from "@babel/types" const isHook = /^use[A-Z]/ // matches only built-in hooks provided by React et al -const isBuiltInHook = /^use(Callback|Context|DebugValue|Effect|ImperativeHandle|LayoutEffect|Memo|Reducer|Ref|State)$/ +const isBuiltInHook = + /^use(Callback|Context|DebugValue|Effect|ImperativeHandle|LayoutEffect|Memo|Reducer|Ref|State)$/ interface IState { opts?: { diff --git a/packages/gatsby-admin/src/pages/plugins.tsx b/packages/gatsby-admin/src/pages/plugins.tsx index 251fdcdaefa46..57bc354e37dfa 100644 --- a/packages/gatsby-admin/src/pages/plugins.tsx +++ b/packages/gatsby-admin/src/pages/plugins.tsx @@ -107,9 +107,8 @@ export default function PluginView( }, }) - const { fetching: fetchingNpmData, data: npmData } = useNpmPackageData( - pluginName - ) + const { fetching: fetchingNpmData, data: npmData } = + useNpmPackageData(pluginName) const [{ fetching: updatingGatsbyPlugin }, updateGatsbyPlugin] = useMutation(` mutation updateGatsbyPlugin( @@ -147,10 +146,8 @@ export default function PluginView( } `) - const [ - { fetching: installingGatsbyPlugin }, - installGatsbyPlugin, - ] = useMutation(` + const [{ fetching: installingGatsbyPlugin }, installGatsbyPlugin] = + useMutation(` mutation installGatsbyPlugin($name: String!) { createNpmPackage(npmPackage: { name: $name, diff --git a/packages/gatsby-cli/src/create-cli.ts b/packages/gatsby-cli/src/create-cli.ts index 37ea86a4718fb..7fa623f401faa 100644 --- a/packages/gatsby-cli/src/create-cli.ts +++ b/packages/gatsby-cli/src/create-cli.ts @@ -21,14 +21,14 @@ import { whoami } from "./whoami" import { getPackageManager, setPackageManager } from "./util/package-manager" import reporter from "./reporter" -const handlerP = (fn: (args: yargs.Arguments) => void) => ( - args: yargs.Arguments -): void => { - Promise.resolve(fn(args)).then( - () => process.exit(0), - err => report.panic(err) - ) -} +const handlerP = + (fn: (args: yargs.Arguments) => void) => + (args: yargs.Arguments): void => { + Promise.resolve(fn(args)).then( + () => process.exit(0), + err => report.panic(err) + ) + } function buildLocalCommands(cli: yargs.Argv, isLocalSite: boolean): void { const defaultHost = `localhost` diff --git a/packages/gatsby-cli/src/reporter/__tests__/patch-console.ts b/packages/gatsby-cli/src/reporter/__tests__/patch-console.ts index 72d1cb43127e9..98e56297d2abd 100644 --- a/packages/gatsby-cli/src/reporter/__tests__/patch-console.ts +++ b/packages/gatsby-cli/src/reporter/__tests__/patch-console.ts @@ -8,7 +8,7 @@ describe(`patchConsole`, () => { info: jest.fn(), } - patchConsole((reporter as unknown) as typeof gatsbyReporter) + patchConsole(reporter as unknown as typeof gatsbyReporter) ;[`info`, `log`, `warn`].forEach(method => { describe(method, () => { beforeEach(reporter[method].mockReset) diff --git a/packages/gatsby-cli/src/reporter/loggers/ink/components/utils.tsx b/packages/gatsby-cli/src/reporter/loggers/ink/components/utils.tsx index b3b4a19ba2cca..b8300cfb13ceb 100644 --- a/packages/gatsby-cli/src/reporter/loggers/ink/components/utils.tsx +++ b/packages/gatsby-cli/src/reporter/loggers/ink/components/utils.tsx @@ -1,11 +1,11 @@ import React, { FunctionComponent } from "react" import { Text, TextProps } from "ink" -export const createLabel = ( - text: string, - color: string -): FunctionComponent => (...props): JSX.Element => ( - - {text} - -) +export const createLabel = + (text: string, color: string): FunctionComponent => + (...props): JSX.Element => + ( + + {text} + + ) diff --git a/packages/gatsby-cli/src/reporter/loggers/ink/context.tsx b/packages/gatsby-cli/src/reporter/loggers/ink/context.tsx index fec4636bdf404..d34f855a80954 100644 --- a/packages/gatsby-cli/src/reporter/loggers/ink/context.tsx +++ b/packages/gatsby-cli/src/reporter/loggers/ink/context.tsx @@ -7,20 +7,20 @@ import { IGatsbyState } from "gatsby/src/redux/types" // to not use it's own store temporarily. // By the time this is actually running, it will become an `IGatsbyState` const StoreStateContext = createContext( - (getStore().getState() as any) as IGatsbyState + getStore().getState() as any as IGatsbyState ) export const StoreStateProvider: React.FC = ({ children, }): React.ReactElement => { const [state, setState] = useState( - (getStore().getState() as any) as IGatsbyState + getStore().getState() as any as IGatsbyState ) useLayoutEffect( () => onLogAction(() => { - setState((getStore().getState() as any) as IGatsbyState) + setState(getStore().getState() as any as IGatsbyState) }), [] ) diff --git a/packages/gatsby-cli/src/reporter/redux/__tests__/integration.ts b/packages/gatsby-cli/src/reporter/redux/__tests__/integration.ts index 2881ba847566b..ebdb167fed0ea 100644 --- a/packages/gatsby-cli/src/reporter/redux/__tests__/integration.ts +++ b/packages/gatsby-cli/src/reporter/redux/__tests__/integration.ts @@ -20,11 +20,8 @@ describe(`integration`, () => { }) test(`Doesn't dispatch pre-emptive SUCCESS `, async () => { - const { - createPendingActivity, - endActivity, - startActivity, - } = internalActions + const { createPendingActivity, endActivity, startActivity } = + internalActions startActivity({ id: `activity-1`, diff --git a/packages/gatsby-cli/src/reporter/redux/actions.ts b/packages/gatsby-cli/src/reporter/redux/actions.ts index 2ef9916515c60..c1b1a29da7db1 100644 --- a/packages/gatsby-cli/src/reporter/redux/actions.ts +++ b/packages/gatsby-cli/src/reporter/redux/actions.ts @@ -6,16 +6,24 @@ import * as actions from "./internal-actions" const boundActions = bindActionCreators( actions, - (dispatch as any) as Dispatch + dispatch as any as Dispatch ) export const createLog = boundActions.createLog as typeof actions.createLog -export const createPendingActivity = boundActions.createPendingActivity as typeof actions.createPendingActivity +export const createPendingActivity = + boundActions.createPendingActivity as typeof actions.createPendingActivity export const setStatus = boundActions.setStatus as typeof actions.setStatus -export const startActivity = boundActions.startActivity as typeof actions.startActivity -export const endActivity = boundActions.endActivity as typeof actions.endActivity -export const updateActivity = boundActions.updateActivity as typeof actions.updateActivity -export const setActivityErrored = boundActions.setActivityErrored as typeof actions.setActivityErrored -export const setActivityStatusText = boundActions.setActivityStatusText as typeof actions.setActivityStatusText -export const setActivityTotal = boundActions.setActivityTotal as typeof actions.setActivityTotal -export const activityTick = boundActions.activityTick as typeof actions.activityTick +export const startActivity = + boundActions.startActivity as typeof actions.startActivity +export const endActivity = + boundActions.endActivity as typeof actions.endActivity +export const updateActivity = + boundActions.updateActivity as typeof actions.updateActivity +export const setActivityErrored = + boundActions.setActivityErrored as typeof actions.setActivityErrored +export const setActivityStatusText = + boundActions.setActivityStatusText as typeof actions.setActivityStatusText +export const setActivityTotal = + boundActions.setActivityTotal as typeof actions.setActivityTotal +export const activityTick = + boundActions.activityTick as typeof actions.activityTick diff --git a/packages/gatsby-cli/src/reporter/redux/diagnostics.ts b/packages/gatsby-cli/src/reporter/redux/diagnostics.ts index 37373f30bccac..a40a8d50c489c 100644 --- a/packages/gatsby-cli/src/reporter/redux/diagnostics.ts +++ b/packages/gatsby-cli/src/reporter/redux/diagnostics.ts @@ -114,7 +114,8 @@ export function createStructuredLoggingDiagnosticsMiddleware( // using nextTick here to prevent infinite recursion (report.warn would // result in another call of this function and so on) process.nextTick(() => { - const activitiesDiagnosticsMessage = generateStuckStatusDiagnosticMessage() + const activitiesDiagnosticsMessage = + generateStuckStatusDiagnosticMessage() reporter.warn( `This is just diagnostic information (enabled by GATSBY_DIAGNOSTIC_STUCK_STATUS_TIMEOUT):\n\nThere was activity since last diagnostic message. Log action:\n\n${JSON.stringify( action, @@ -175,7 +176,8 @@ export function createStructuredLoggingDiagnosticsMiddleware( context: { activities: inProgressActivities(), status: store.getState().logs.status, - stuckStatusDiagnosticMessage: generateStuckStatusDiagnosticMessage(), + stuckStatusDiagnosticMessage: + generateStuckStatusDiagnosticMessage(), stuckStatusWatchdogTimeoutDelay, }, }) diff --git a/packages/gatsby-cli/src/reporter/redux/index.ts b/packages/gatsby-cli/src/reporter/redux/index.ts index 6f629d9401d85..0e479b3054c13 100644 --- a/packages/gatsby-cli/src/reporter/redux/index.ts +++ b/packages/gatsby-cli/src/reporter/redux/index.ts @@ -12,9 +12,8 @@ let store: Store<{ logs: IGatsbyCLIState }> = createStore( {} ) -const diagnosticsMiddleware = createStructuredLoggingDiagnosticsMiddleware( - store -) +const diagnosticsMiddleware = + createStructuredLoggingDiagnosticsMiddleware(store) export type GatsbyCLIStore = typeof store type StoreListener = (store: GatsbyCLIStore) => void diff --git a/packages/gatsby-cli/src/reporter/redux/internal-actions.ts b/packages/gatsby-cli/src/reporter/redux/internal-actions.ts index c36c9f28ad546..81c53467b7150 100644 --- a/packages/gatsby-cli/src/reporter/redux/internal-actions.ts +++ b/packages/gatsby-cli/src/reporter/redux/internal-actions.ts @@ -51,38 +51,37 @@ let pendingStatus: ActivityStatuses | "" = `` // where technically we are "done" (all activities are done). // We don't want to emit multiple SET_STATUS events that would toggle between // IN_PROGRESS and SUCCESS/FAILED in short succession in those cases. -export const setStatus = ( - status: ActivityStatuses | "", - force: boolean = false -) => (dispatch: Dispatch): void => { - const currentStatus = getStore().getState().logs.status +export const setStatus = + (status: ActivityStatuses | "", force: boolean = false) => + (dispatch: Dispatch): void => { + const currentStatus = getStore().getState().logs.status - if (cancelDelayedSetStatus) { - cancelDelayedSetStatus() - cancelDelayedSetStatus = null - } + if (cancelDelayedSetStatus) { + cancelDelayedSetStatus() + cancelDelayedSetStatus = null + } - if ( - status !== currentStatus && - (status === ActivityStatuses.InProgress || force || weShouldExit) - ) { - dispatch({ - type: Actions.SetStatus, - payload: status, - }) - pendingStatus = `` - } else { - // use pending status if truthy, fallback to current status if we don't have pending status - const pendingOrCurrentStatus = pendingStatus || currentStatus + if ( + status !== currentStatus && + (status === ActivityStatuses.InProgress || force || weShouldExit) + ) { + dispatch({ + type: Actions.SetStatus, + payload: status, + }) + pendingStatus = `` + } else { + // use pending status if truthy, fallback to current status if we don't have pending status + const pendingOrCurrentStatus = pendingStatus || currentStatus - if (status !== pendingOrCurrentStatus) { - pendingStatus = status - cancelDelayedSetStatus = delayedCall(() => { - setStatus(status, true)(dispatch) - }, 1000) + if (status !== pendingOrCurrentStatus) { + pendingStatus = status + cancelDelayedSetStatus = delayedCall(() => { + setStatus(status, true)(dispatch) + }, 1000) + } } } -} export const createLog = ({ level, diff --git a/packages/gatsby-cli/src/reporter/reporter.ts b/packages/gatsby-cli/src/reporter/reporter.ts index 2c3b8c0ab82fd..6a73baace178b 100644 --- a/packages/gatsby-cli/src/reporter/reporter.ts +++ b/packages/gatsby-cli/src/reporter/reporter.ts @@ -148,9 +148,9 @@ class Reporter { // reporter.error([Error]); } else if (Array.isArray(errorMeta)) { // when we get an array of messages, call this function once for each error - return errorMeta.map(errorItem => this.error(errorItem)) as Array< - IStructuredError - > + return errorMeta.map(errorItem => + this.error(errorItem) + ) as Array // 4. // reporter.error(errorMeta); } else if (typeof errorMeta === `object`) { diff --git a/packages/gatsby-cli/src/structured-errors/__tests__/construct-error.ts b/packages/gatsby-cli/src/structured-errors/__tests__/construct-error.ts index f1342e3694f27..5285c7b8843ca 100644 --- a/packages/gatsby-cli/src/structured-errors/__tests__/construct-error.ts +++ b/packages/gatsby-cli/src/structured-errors/__tests__/construct-error.ts @@ -6,10 +6,9 @@ let log let processExit beforeEach(() => { log = jest.spyOn(console, `log`).mockImplementation(() => {}) - processExit = ((jest.spyOn( - process, - `exit` - ) as unknown) as jest.Mock).mockImplementation(() => {}) + processExit = ( + jest.spyOn(process, `exit`) as unknown as jest.Mock + ).mockImplementation(() => {}) log.mockReset() processExit.mockReset() @@ -17,7 +16,7 @@ beforeEach(() => { afterAll(() => { ;(console.log as jest.Mock).mockClear() - ;((process.exit as unknown) as jest.Mock).mockClear() + ;(process.exit as unknown as jest.Mock).mockClear() }) test(`it exits on invalid error schema`, () => { diff --git a/packages/gatsby-cli/src/structured-errors/error-schema.ts b/packages/gatsby-cli/src/structured-errors/error-schema.ts index af4b233a9c87e..306da6d31bdee 100644 --- a/packages/gatsby-cli/src/structured-errors/error-schema.ts +++ b/packages/gatsby-cli/src/structured-errors/error-schema.ts @@ -6,8 +6,8 @@ export const Position: Joi.ObjectSchema = Joi.object().keys({ column: Joi.number(), }) -export const errorSchema: Joi.ObjectSchema = Joi.object().keys( - { +export const errorSchema: Joi.ObjectSchema = + Joi.object().keys({ code: Joi.string(), text: Joi.string(), stack: Joi.array() @@ -37,5 +37,4 @@ export const errorSchema: Joi.ObjectSchema = Joi.object().keys group: Joi.string(), panicOnBuild: Joi.boolean(), pluginName: Joi.string(), - } -) + }) diff --git a/packages/gatsby-codemods/src/transforms/gatsby-plugin-image.js b/packages/gatsby-codemods/src/transforms/gatsby-plugin-image.js index cf79756330384..b7abcad7a42af 100644 --- a/packages/gatsby-codemods/src/transforms/gatsby-plugin-image.js +++ b/packages/gatsby-codemods/src/transforms/gatsby-plugin-image.js @@ -183,10 +183,8 @@ export function updateImport(babel) { } const query = node.quasi?.quasis?.[0]?.value?.raw if (query) { - const { - ast: transformedGraphQLQuery, - hasChanged, - } = processGraphQLQuery(query, state) + const { ast: transformedGraphQLQuery, hasChanged } = + processGraphQLQuery(query, state) if (hasChanged) { node.quasi.quasis[0].value.raw = graphql.print( @@ -203,10 +201,8 @@ export function updateImport(babel) { const query = node.arguments?.[0].quasis?.[0]?.value?.raw if (query) { - const { - ast: transformedGraphQLQuery, - hasChanged, - } = processGraphQLQuery(query, state) + const { ast: transformedGraphQLQuery, hasChanged } = + processGraphQLQuery(query, state) if (hasChanged) { node.arguments[0].quasis[0].value.raw = graphql.print( @@ -390,10 +386,8 @@ function processGraphQLQuery(query, state) { if (!sharpField) { return } - const [ - fixedOrFluidField, - ] = sharpField.selectionSet.selections.filter(({ name }) => - propNames.includes(name?.value) + const [fixedOrFluidField] = sharpField.selectionSet.selections.filter( + ({ name }) => propNames.includes(name?.value) ) if (!fixedOrFluidField) { diff --git a/packages/gatsby-core-utils/src/create-require-from-path.ts b/packages/gatsby-core-utils/src/create-require-from-path.ts index 9eb6955565ca6..41def521e04f9 100644 --- a/packages/gatsby-core-utils/src/create-require-from-path.ts +++ b/packages/gatsby-core-utils/src/create-require-from-path.ts @@ -13,8 +13,9 @@ const fallback = (filename: string): NodeRequire => { const mod = new Module(filename) as Module & IModulePrivateMethods mod.filename = filename - mod.paths = (Module as typeof Module & - IModulePrivateMethods)._nodeModulePaths(path.dirname(filename)) + mod.paths = ( + Module as typeof Module & IModulePrivateMethods + )._nodeModulePaths(path.dirname(filename)) mod._compile(`module.exports = require;`, filename) return mod.exports diff --git a/packages/gatsby-core-utils/src/site-metadata.ts b/packages/gatsby-core-utils/src/site-metadata.ts index e42e6896591a2..8d72b2d8f2280 100644 --- a/packages/gatsby-core-utils/src/site-metadata.ts +++ b/packages/gatsby-core-utils/src/site-metadata.ts @@ -24,9 +24,7 @@ export async function updateSiteMetadata( } } - return createServiceLock( - metadata.sitePath, - `metadata`, - metadata - ).then(unlock => unlock?.()) + return createServiceLock(metadata.sitePath, `metadata`, metadata).then( + unlock => unlock?.() + ) } diff --git a/packages/gatsby-dev-cli/src/__tests__/watch.js b/packages/gatsby-dev-cli/src/__tests__/watch.js index 9277cc1cc6f2b..03d0d1be15d08 100644 --- a/packages/gatsby-dev-cli/src/__tests__/watch.js +++ b/packages/gatsby-dev-cli/src/__tests__/watch.js @@ -286,10 +286,12 @@ const monoRepoPackages = [ `gatsby-transformer-yaml`, ] -const mockDepsChanges = packagesWithChangedDeps => ({ packageName }) => - Promise.resolve({ - didDepsChanged: packagesWithChangedDeps.includes(packageName), - }) +const mockDepsChanges = + packagesWithChangedDeps => + ({ packageName }) => + Promise.resolve({ + didDepsChanged: packagesWithChangedDeps.includes(packageName), + }) jest.mock(`../utils/check-deps-changes`, () => { return { diff --git a/packages/gatsby-dev-cli/src/watch.js b/packages/gatsby-dev-cli/src/watch.js index 58f26d13adf9e..68d9eb3c4a4a5 100644 --- a/packages/gatsby-dev-cli/src/watch.js +++ b/packages/gatsby-dev-cli/src/watch.js @@ -256,10 +256,8 @@ async function watch( waitFor.add(didDepsChangedPromise) } - const { - didDepsChanged, - packageNotInstalled, - } = await didDepsChangedPromise + const { didDepsChanged, packageNotInstalled } = + await didDepsChangedPromise if (packageNotInstalled) { anyPackageNotInstalled = true diff --git a/packages/gatsby-link/src/__tests__/index.js b/packages/gatsby-link/src/__tests__/index.js index fba2a5b6ce8e1..e6f37f4f26821 100644 --- a/packages/gatsby-link/src/__tests__/index.js +++ b/packages/gatsby-link/src/__tests__/index.js @@ -240,9 +240,10 @@ describe(``, () => { const { link } = setup({ linkProps: { to, replace: false } }) link.click() - expect( - global.___navigate - ).toHaveBeenCalledWith(`${global.__BASE_PATH__}${to}`, { replace: false }) + expect(global.___navigate).toHaveBeenCalledWith( + `${global.__BASE_PATH__}${to}`, + { replace: false } + ) }) it(`respects force enabling replace`, () => { @@ -251,9 +252,10 @@ describe(``, () => { const { link } = setup({ linkProps: { to, replace: true } }) link.click() - expect( - global.___navigate - ).toHaveBeenCalledWith(`${global.__BASE_PATH__}${to}`, { replace: true }) + expect(global.___navigate).toHaveBeenCalledWith( + `${global.__BASE_PATH__}${to}`, + { replace: true } + ) }) it(`does not replace history when navigating away`, () => { @@ -274,9 +276,10 @@ describe(``, () => { const { link } = setup({ linkProps: { to } }) link.click() - expect( - global.___navigate - ).toHaveBeenCalledWith(`${global.__BASE_PATH__}${to}`, { replace: true }) + expect(global.___navigate).toHaveBeenCalledWith( + `${global.__BASE_PATH__}${to}`, + { replace: true } + ) }) }) }) diff --git a/packages/gatsby-plugin-catch-links/src/__tests__/catch-links.js b/packages/gatsby-plugin-catch-links/src/__tests__/catch-links.js index ba262b04ca03a..3294e0dced05a 100644 --- a/packages/gatsby-plugin-catch-links/src/__tests__/catch-links.js +++ b/packages/gatsby-plugin-catch-links/src/__tests__/catch-links.js @@ -190,17 +190,15 @@ describe(`the author might be forcing navigation`, () => { expect(catchLinks.authorIsForcingNavigation(testAnchor)).toBe(true) }) test(`target=_parent`, () => { - const testAnchor = separateBrowsingContext.contentDocument.createElement( - `a` - ) + const testAnchor = + separateBrowsingContext.contentDocument.createElement(`a`) testAnchor.setAttribute(`target`, `_parent`) expect(catchLinks.authorIsForcingNavigation(testAnchor)).toBe(true) }) test(`target=_top`, () => { - const testAnchor = separateBrowsingContext.contentDocument.createElement( - `a` - ) + const testAnchor = + separateBrowsingContext.contentDocument.createElement(`a`) testAnchor.setAttribute(`target`, `_top`) expect(catchLinks.authorIsForcingNavigation(testAnchor)).toBe(true) @@ -232,9 +230,8 @@ describe(`anchor target attribute looks like _self if`, () => { expect(catchLinks.anchorsTargetIsEquivalentToSelf(testAnchor)).toBe(true) }) it(`is set to _parent, but window = window.parent`, () => { - const testAnchor = separateBrowsingContext.contentDocument.createElement( - `a` - ) + const testAnchor = + separateBrowsingContext.contentDocument.createElement(`a`) testAnchor.setAttribute(`target`, `_parent`) document.body.appendChild(testAnchor) @@ -244,9 +241,8 @@ describe(`anchor target attribute looks like _self if`, () => { testAnchor.remove() }) it(`is set to _top, but window = window.top`, () => { - const testAnchor = separateBrowsingContext.contentDocument.createElement( - `a` - ) + const testAnchor = + separateBrowsingContext.contentDocument.createElement(`a`) testAnchor.setAttribute(`target`, `_top`) document.body.appendChild(testAnchor) diff --git a/packages/gatsby-plugin-catch-links/src/catch-links.js b/packages/gatsby-plugin-catch-links/src/catch-links.js index d529ed820c31f..8dba13bddf974 100644 --- a/packages/gatsby-plugin-catch-links/src/catch-links.js +++ b/packages/gatsby-plugin-catch-links/src/catch-links.js @@ -105,76 +105,76 @@ export const hashShouldBeFollowed = (origin, destination) => /* Don't catch links pointed to the same page but with a hash. */ destination.pathname === origin.pathname) -export const routeThroughBrowserOrApp = ( - hrefHandler, - pluginOptions -) => event => { - if (window.___failedResources) return true +export const routeThroughBrowserOrApp = + (hrefHandler, pluginOptions) => event => { + if (window.___failedResources) return true - if (userIsForcingNavigation(event)) return true + if (userIsForcingNavigation(event)) return true - if (navigationWasHandledElsewhere(event)) return true + if (navigationWasHandledElsewhere(event)) return true - const clickedAnchor = findClosestAnchor(event.target) - if (clickedAnchor == null) return true + const clickedAnchor = findClosestAnchor(event.target) + if (clickedAnchor == null) return true - if (authorIsForcingNavigation(clickedAnchor)) return true + if (authorIsForcingNavigation(clickedAnchor)) return true - // IE clears the host value if the anchor href changed after creation, e.g. - // in React. Creating a new anchor element to ensure host value is present - const destination = document.createElement(`a`) + // IE clears the host value if the anchor href changed after creation, e.g. + // in React. Creating a new anchor element to ensure host value is present + const destination = document.createElement(`a`) - // https://html.spec.whatwg.org/multipage/links.html#concept-hyperlink-url-set - // If clickedAnchor has no href attribute like `example`, the href getter returns empty string. - if (clickedAnchor.href !== ``) { - destination.href = clickedAnchor.href - } + // https://html.spec.whatwg.org/multipage/links.html#concept-hyperlink-url-set + // If clickedAnchor has no href attribute like `example`, the href getter returns empty string. + if (clickedAnchor.href !== ``) { + destination.href = clickedAnchor.href + } - if ( - `SVGAnimatedString` in window && - clickedAnchor.href instanceof SVGAnimatedString - ) { - destination.href = clickedAnchor.href.animVal - } + if ( + `SVGAnimatedString` in window && + clickedAnchor.href instanceof SVGAnimatedString + ) { + destination.href = clickedAnchor.href.animVal + } - // In IE, the default port is included in the anchor host but excluded from - // the location host. This affects the ability to directly compare - // location host to anchor host. For example: http://example.com would - // have a location.host of 'example.com' and an destination.host of - // 'example.com:80' Creating anchor from the location.href to normalize the - // host value. - const origin = document.createElement(`a`) - origin.href = window.location.href + // In IE, the default port is included in the anchor host but excluded from + // the location host. This affects the ability to directly compare + // location host to anchor host. For example: http://example.com would + // have a location.host of 'example.com' and an destination.host of + // 'example.com:80' Creating anchor from the location.href to normalize the + // host value. + const origin = document.createElement(`a`) + origin.href = window.location.href - if (urlsAreOnSameOrigin(origin, destination) === false) return true + if (urlsAreOnSameOrigin(origin, destination) === false) return true - // Regex to test pathname against pathPrefix - const pathStartRegEx = new RegExp(`^${escapeStringRegexp(withPrefix(`/`))}`) + // Regex to test pathname against pathPrefix + const pathStartRegEx = new RegExp(`^${escapeStringRegexp(withPrefix(`/`))}`) - if (pathIsNotHandledByApp(destination, pathStartRegEx)) return true + if (pathIsNotHandledByApp(destination, pathStartRegEx)) return true - if (hashShouldBeFollowed(origin, destination)) return true + if (hashShouldBeFollowed(origin, destination)) return true - if (pluginOptions.excludePattern) { - const excludeRegex = new RegExp(pluginOptions.excludePattern) - if (excludeRegex.test(destination.pathname)) { - return true + if (pluginOptions.excludePattern) { + const excludeRegex = new RegExp(pluginOptions.excludePattern) + if (excludeRegex.test(destination.pathname)) { + return true + } } - } - event.preventDefault() + event.preventDefault() - // See issue #8907: destination.pathname already includes pathPrefix added - // by gatsby-transformer-remark but gatsby-link.navigate needs href without - const destinationPathname = slashedPathname(destination.pathname).replace( - pathStartRegEx, - `/` - ) + // See issue #8907: destination.pathname already includes pathPrefix added + // by gatsby-transformer-remark but gatsby-link.navigate needs href without + const destinationPathname = slashedPathname(destination.pathname).replace( + pathStartRegEx, + `/` + ) - hrefHandler(`${destinationPathname}${destination.search}${destination.hash}`) + hrefHandler( + `${destinationPathname}${destination.search}${destination.hash}` + ) - return false -} + return false + } export default function (root, pluginOptions, cb) { const clickHandler = routeThroughBrowserOrApp(cb, pluginOptions) diff --git a/packages/gatsby-plugin-gatsby-cloud/src/build-headers-program.js b/packages/gatsby-plugin-gatsby-cloud/src/build-headers-program.js index 659af19296fc5..1c802a4f226ff 100644 --- a/packages/gatsby-plugin-gatsby-cloud/src/build-headers-program.js +++ b/packages/gatsby-plugin-gatsby-cloud/src/build-headers-program.js @@ -208,125 +208,131 @@ function stringifyHeaders(headers) { // program methods -const mapUserLinkHeaders = ({ - manifest, - pathPrefix, - publicFolder, -}) => headers => - _.mapValues(headers, headerList => - _.map(headerList, transformLink(manifest, publicFolder, pathPrefix)) - ) - -const mapUserLinkAllPageHeaders = ( - pluginData, - { allPageHeaders } -) => headers => { - if (!allPageHeaders) { - return headers - } +const mapUserLinkHeaders = + ({ manifest, pathPrefix, publicFolder }) => + headers => + _.mapValues(headers, headerList => + _.map(headerList, transformLink(manifest, publicFolder, pathPrefix)) + ) - const { pages, manifest, publicFolder, pathPrefix } = pluginData +const mapUserLinkAllPageHeaders = + (pluginData, { allPageHeaders }) => + headers => { + if (!allPageHeaders) { + return headers + } - const headersList = _.map( - allPageHeaders, - transformLink(manifest, publicFolder, pathPrefix) - ) + const { pages, manifest, publicFolder, pathPrefix } = pluginData - const duplicateHeadersByPage = {} - pages.forEach(page => { - const pathKey = headersPath(pathPrefix, page.path) - duplicateHeadersByPage[pathKey] = headersList - }) + const headersList = _.map( + allPageHeaders, + transformLink(manifest, publicFolder, pathPrefix) + ) - return defaultMerge(headers, duplicateHeadersByPage) -} + const duplicateHeadersByPage = {} + pages.forEach(page => { + const pathKey = headersPath(pathPrefix, page.path) + duplicateHeadersByPage[pathKey] = headersList + }) -const applyLinkHeaders = (pluginData, { mergeLinkHeaders }) => headers => { - if (!mergeLinkHeaders) { - return headers + return defaultMerge(headers, duplicateHeadersByPage) } - const { pages, manifest, pathPrefix, publicFolder } = pluginData - const perPageHeaders = preloadHeadersByPage({ - pages, - manifest, - pathPrefix, - publicFolder, - }) +const applyLinkHeaders = + (pluginData, { mergeLinkHeaders }) => + headers => { + if (!mergeLinkHeaders) { + return headers + } - return defaultMerge(headers, perPageHeaders) -} + const { pages, manifest, pathPrefix, publicFolder } = pluginData + const perPageHeaders = preloadHeadersByPage({ + pages, + manifest, + pathPrefix, + publicFolder, + }) -const applySecurityHeaders = ({ mergeSecurityHeaders }) => headers => { - if (!mergeSecurityHeaders) { - return headers + return defaultMerge(headers, perPageHeaders) } - return headersMerge(headers, SECURITY_HEADERS) -} +const applySecurityHeaders = + ({ mergeSecurityHeaders }) => + headers => { + if (!mergeSecurityHeaders) { + return headers + } -const applyCachingHeaders = ( - pluginData, - { mergeCachingHeaders } -) => headers => { - if (!mergeCachingHeaders) { - return headers + return headersMerge(headers, SECURITY_HEADERS) } - let chunks = [] - // Gatsby v3.5 added componentChunkName to store().components - // So we prefer to pull chunk names off that as it gets very expensive to loop - // over large numbers of pages. - const isComponentChunkSet = !!pluginData.components.entries()?.next() - ?.value[1]?.componentChunkName - if (isComponentChunkSet) { - chunks = [...pluginData.components.values()].map(c => c.componentChunkName) - } else { - chunks = Array.from(pluginData.pages.values()).map( - page => page.componentChunkName - ) - } +const applyCachingHeaders = + (pluginData, { mergeCachingHeaders }) => + headers => { + if (!mergeCachingHeaders) { + return headers + } - chunks.push(`pages-manifest`, `app`) + let chunks = [] + // Gatsby v3.5 added componentChunkName to store().components + // So we prefer to pull chunk names off that as it gets very expensive to loop + // over large numbers of pages. + const isComponentChunkSet = !!pluginData.components.entries()?.next() + ?.value[1]?.componentChunkName + if (isComponentChunkSet) { + chunks = [...pluginData.components.values()].map( + c => c.componentChunkName + ) + } else { + chunks = Array.from(pluginData.pages.values()).map( + page => page.componentChunkName + ) + } - const files = [].concat(...chunks.map(chunk => pluginData.manifest[chunk])) + chunks.push(`pages-manifest`, `app`) - const cachingHeaders = {} + const files = [].concat(...chunks.map(chunk => pluginData.manifest[chunk])) - files.forEach(file => { - if (typeof file === `string`) { - cachingHeaders[`/` + file] = [IMMUTABLE_CACHING_HEADER] - } - }) + const cachingHeaders = {} - return defaultMerge(headers, cachingHeaders, CACHING_HEADERS) -} + files.forEach(file => { + if (typeof file === `string`) { + cachingHeaders[`/` + file] = [IMMUTABLE_CACHING_HEADER] + } + }) -const applyTransfromHeaders = ({ transformHeaders }) => headers => - _.mapValues(headers, transformHeaders) - -const writeHeadersFile = ({ publicFolder }) => contents => - new Promise((resolve, reject) => { - const contentsStr = JSON.stringify(contents) - const writeStream = createWriteStream(publicFolder(HEADERS_FILENAME)) - const chunkSize = 10000 - const numChunks = Math.ceil(contentsStr.length / chunkSize) - - for (let i = 0; i < numChunks; i++) { - writeStream.write( - contentsStr.slice( - i * chunkSize, - Math.min((i + 1) * chunkSize, contentsStr.length) + return defaultMerge(headers, cachingHeaders, CACHING_HEADERS) + } + +const applyTransfromHeaders = + ({ transformHeaders }) => + headers => + _.mapValues(headers, transformHeaders) + +const writeHeadersFile = + ({ publicFolder }) => + contents => + new Promise((resolve, reject) => { + const contentsStr = JSON.stringify(contents) + const writeStream = createWriteStream(publicFolder(HEADERS_FILENAME)) + const chunkSize = 10000 + const numChunks = Math.ceil(contentsStr.length / chunkSize) + + for (let i = 0; i < numChunks; i++) { + writeStream.write( + contentsStr.slice( + i * chunkSize, + Math.min((i + 1) * chunkSize, contentsStr.length) + ) ) - ) - } + } - writeStream.end() - writeStream.on(`finish`, () => { - resolve() + writeStream.end() + writeStream.on(`finish`, () => { + resolve() + }) + writeStream.on(`error`, reject) }) - writeStream.on(`error`, reject) - }) export default function buildHeadersProgram( pluginData, diff --git a/packages/gatsby-plugin-graphql-config/src/gatsby-node.ts b/packages/gatsby-plugin-graphql-config/src/gatsby-node.ts index f20607a9f336d..a20af5dd15e35 100644 --- a/packages/gatsby-plugin-graphql-config/src/gatsby-node.ts +++ b/packages/gatsby-plugin-graphql-config/src/gatsby-node.ts @@ -41,31 +41,32 @@ async function cacheGraphQLConfig(program: IStateProgram): Promise { } } -const createFragmentCacheHandler = ( - cacheDirectory: string, - store: GatsbyReduxStore -) => async (): Promise => { - try { - const currentDefinitions = store.getState().definitions +const createFragmentCacheHandler = + (cacheDirectory: string, store: GatsbyReduxStore) => + async (): Promise => { + try { + const currentDefinitions = store.getState().definitions - const fragmentString = Array.from(currentDefinitions.entries()) - .filter(([_, def]) => def.isFragment) - .map(([_, def]) => `# ${def.filePath}\n${def.printedAst}`) - .join(`\n`) + const fragmentString = Array.from(currentDefinitions.entries()) + .filter(([_, def]) => def.isFragment) + .map(([_, def]) => `# ${def.filePath}\n${def.printedAst}`) + .join(`\n`) - await fs.writeFile( - join(cacheDirectory, `fragments.graphql`), - fragmentString - ) + await fs.writeFile( + join(cacheDirectory, `fragments.graphql`), + fragmentString + ) - console.log(`[gatsby-plugin-graphql-config] wrote fragments file to .cache`) - } catch (err) { - console.error( - `[gatsby-plugin-graphql-config] failed writing fragments file to .cache` - ) - console.error(err) + console.log( + `[gatsby-plugin-graphql-config] wrote fragments file to .cache` + ) + } catch (err) { + console.error( + `[gatsby-plugin-graphql-config] failed writing fragments file to .cache` + ) + console.error(err) + } } -} const cacheSchema = async ( cacheDirectory: string, @@ -86,13 +87,12 @@ const cacheSchema = async ( } } -const createSchemaCacheHandler = ( - cacheDirectory: string, - store: GatsbyReduxStore -) => async (): Promise => { - const { schema } = store.getState() - await cacheSchema(cacheDirectory, schema) -} +const createSchemaCacheHandler = + (cacheDirectory: string, store: GatsbyReduxStore) => + async (): Promise => { + const { schema } = store.getState() + await cacheSchema(cacheDirectory, schema) + } export async function onPostBootstrap({ store, diff --git a/packages/gatsby-plugin-image/src/__tests__/image-utils.ts b/packages/gatsby-plugin-image/src/__tests__/image-utils.ts index 1e734d1c4ec97..38eb0f8758e59 100644 --- a/packages/gatsby-plugin-image/src/__tests__/image-utils.ts +++ b/packages/gatsby-plugin-image/src/__tests__/image-utils.ts @@ -59,10 +59,10 @@ describe(`the image data helper`, () => { const generateImageSource = `this should be a function` expect(() => - generateImageData(({ + generateImageData({ ...args, generateImageSource, - } as any) as IGatsbyImageHelperArgs) + } as any as IGatsbyImageHelperArgs) ).toThrow() }) @@ -132,10 +132,10 @@ describe(`the image data helper`, () => { }) it(`warns if there's no plugin name`, () => { - generateImageData(({ + generateImageData({ ...args, pluginName: undefined, - } as any) as IGatsbyImageHelperArgs) + } as any as IGatsbyImageHelperArgs) expect(args.reporter?.warn).toHaveBeenCalledWith( `[gatsby-plugin-image] "generateImageData" was not passed a plugin name` ) diff --git a/packages/gatsby-plugin-image/src/components/__tests__/gatsby-image.browser.tsx b/packages/gatsby-plugin-image/src/components/__tests__/gatsby-image.browser.tsx index 47f61c4f83e94..552654e0fc14a 100644 --- a/packages/gatsby-plugin-image/src/components/__tests__/gatsby-image.browser.tsx +++ b/packages/gatsby-plugin-image/src/components/__tests__/gatsby-image.browser.tsx @@ -4,7 +4,12 @@ import { render, waitFor } from "@testing-library/react" import * as hooks from "../hooks" // Prevents terser for bailing because we're not in a babel plugin -jest.mock(`../../../macros/terser.macro`, () => (strs): string => strs.join(``)) +jest.mock( + `../../../macros/terser.macro`, + () => + (strs): string => + strs.join(``) +) describe(`GatsbyImage browser`, () => { let beforeHydrationContent: HTMLDivElement diff --git a/packages/gatsby-plugin-image/src/components/__tests__/gatsby-image.server.tsx b/packages/gatsby-plugin-image/src/components/__tests__/gatsby-image.server.tsx index a580b5c011a67..9e5ca230d7069 100644 --- a/packages/gatsby-plugin-image/src/components/__tests__/gatsby-image.server.tsx +++ b/packages/gatsby-plugin-image/src/components/__tests__/gatsby-image.server.tsx @@ -5,7 +5,12 @@ import { IGatsbyImageData } from "../gatsby-image.browser" import { SourceProps } from "../picture" // Prevents terser for bailing because we're not in a babel plugin -jest.mock(`../../../macros/terser.macro`, () => (strs): string => strs.join(``)) +jest.mock( + `../../../macros/terser.macro`, + () => + (strs): string => + strs.join(``) +) describe(`GatsbyImage server`, () => { beforeEach(() => { diff --git a/packages/gatsby-plugin-image/src/components/__tests__/hooks.ts b/packages/gatsby-plugin-image/src/components/__tests__/hooks.ts index dcd29aebebb85..87d5d13433e86 100644 --- a/packages/gatsby-plugin-image/src/components/__tests__/hooks.ts +++ b/packages/gatsby-plugin-image/src/components/__tests__/hooks.ts @@ -166,11 +166,11 @@ describe(`The image helper functions`, () => { }) it(`returns undefined when passed a number`, () => { - expect(getImage((1 as any) as Node)).toBeUndefined() + expect(getImage(1 as any as Node)).toBeUndefined() }) it(`returns undefined when passed undefined`, () => { - expect(getImage((undefined as any) as Node)).toBeUndefined() + expect(getImage(undefined as any as Node)).toBeUndefined() }) }) @@ -191,11 +191,11 @@ describe(`The image helper functions`, () => { expect(getSrc(node)).toBeUndefined() }) it(`returns undefined when passed undefined`, () => { - expect(getSrc((undefined as any) as Node)).toBeUndefined() + expect(getSrc(undefined as any as Node)).toBeUndefined() }) it(`returns undefined when passed a number`, () => { - expect(getSrc((1 as any) as Node)).toBeUndefined() + expect(getSrc(1 as any as Node)).toBeUndefined() }) }) @@ -217,11 +217,11 @@ describe(`The image helper functions`, () => { }) it(`returns undefined when passed undefined`, () => { - expect(getSrcSet((undefined as any) as Node)).toBeUndefined() + expect(getSrcSet(undefined as any as Node)).toBeUndefined() }) it(`returns undefined when passed a number`, () => { - expect(getSrcSet((1 as any) as Node)).toBeUndefined() + expect(getSrcSet(1 as any as Node)).toBeUndefined() }) }) }) diff --git a/packages/gatsby-plugin-image/src/components/gatsby-image.browser.tsx b/packages/gatsby-plugin-image/src/components/gatsby-image.browser.tsx index 23bc923c21a66..ac9266ee48adc 100644 --- a/packages/gatsby-plugin-image/src/components/gatsby-image.browser.tsx +++ b/packages/gatsby-plugin-image/src/components/gatsby-image.browser.tsx @@ -267,33 +267,32 @@ class GatsbyImageHydrator extends Component< } } -export const GatsbyImage: FunctionComponent = function GatsbyImage( - props -) { - if (!props.image) { - if (process.env.NODE_ENV === `development`) { - console.warn(`[gatsby-plugin-image] Missing image prop`) +export const GatsbyImage: FunctionComponent = + function GatsbyImage(props) { + if (!props.image) { + if (process.env.NODE_ENV === `development`) { + console.warn(`[gatsby-plugin-image] Missing image prop`) + } + return null } - return null - } - if (!gatsbyImageIsInstalled()) { - console.error( - `[gatsby-plugin-image] You're missing out on some cool performance features. Please add "gatsby-plugin-image" to your gatsby-config.js` - ) + if (!gatsbyImageIsInstalled()) { + console.error( + `[gatsby-plugin-image] You're missing out on some cool performance features. Please add "gatsby-plugin-image" to your gatsby-config.js` + ) + } + const { className, class: classSafe, backgroundColor, image } = props + const { width, height, layout } = image + const propsKey = JSON.stringify([ + width, + height, + layout, + className, + classSafe, + backgroundColor, + ]) + return } - const { className, class: classSafe, backgroundColor, image } = props - const { width, height, layout } = image - const propsKey = JSON.stringify([ - width, - height, - layout, - className, - classSafe, - backgroundColor, - ]) - return -} GatsbyImage.propTypes = propTypes diff --git a/packages/gatsby-plugin-image/src/components/gatsby-image.server.tsx b/packages/gatsby-plugin-image/src/components/gatsby-image.server.tsx index d37fcaff1c7e6..40d6cab111edf 100644 --- a/packages/gatsby-plugin-image/src/components/gatsby-image.server.tsx +++ b/packages/gatsby-plugin-image/src/components/gatsby-image.server.tsx @@ -21,116 +21,117 @@ export const GatsbyImageHydrator: FunctionComponent<{ return {children} } -export const GatsbyImage: FunctionComponent = function GatsbyImage({ - as, - className, - class: preactClass, - style, - image, - loading = `lazy`, - imgClassName, - imgStyle, - backgroundColor, - objectFit, - objectPosition, - ...props -}) { - if (!image) { - console.warn(`[gatsby-plugin-image] Missing image prop`) - return null - } - if (preactClass) { - className = preactClass - } - imgStyle = { +export const GatsbyImage: FunctionComponent = + function GatsbyImage({ + as, + className, + class: preactClass, + style, + image, + loading = `lazy`, + imgClassName, + imgStyle, + backgroundColor, objectFit, objectPosition, - backgroundColor, - ...imgStyle, - } + ...props + }) { + if (!image) { + console.warn(`[gatsby-plugin-image] Missing image prop`) + return null + } + if (preactClass) { + className = preactClass + } + imgStyle = { + objectFit, + objectPosition, + backgroundColor, + ...imgStyle, + } - const { - width, - height, - layout, - images, - placeholder, - backgroundColor: placeholderBackgroundColor, - } = image + const { + width, + height, + layout, + images, + placeholder, + backgroundColor: placeholderBackgroundColor, + } = image - const { style: wStyle, className: wClass, ...wrapperProps } = getWrapperProps( - width, - height, - layout - ) + const { + style: wStyle, + className: wClass, + ...wrapperProps + } = getWrapperProps(width, height, layout) - const cleanedImages: IGatsbyImageData["images"] = { - fallback: undefined, - sources: [], - } - if (images.fallback) { - cleanedImages.fallback = { - ...images.fallback, - srcSet: images.fallback.srcSet - ? removeNewLines(images.fallback.srcSet) - : undefined, + const cleanedImages: IGatsbyImageData["images"] = { + fallback: undefined, + sources: [], } - } - - if (images.sources) { - cleanedImages.sources = images.sources.map(source => { - return { - ...source, - srcSet: removeNewLines(source.srcSet), + if (images.fallback) { + cleanedImages.fallback = { + ...images.fallback, + srcSet: images.fallback.srcSet + ? removeNewLines(images.fallback.srcSet) + : undefined, } - }) - } + } - return ( - - - + if (images.sources) { + cleanedImages.sources = images.sources.map(source => { + return { + ...source, + srcSet: removeNewLines(source.srcSet), + } + }) + } - )} - // When eager is set we want to start the isLoading state on true (we want to load the img without react) - {...getMainProps( - loading === `eager`, - false, - cleanedImages, - loading, - undefined, - undefined, - undefined, - imgStyle - )} - /> - - - ) -} + return ( + + + + + )} + // When eager is set we want to start the isLoading state on true (we want to load the img without react) + {...getMainProps( + loading === `eager`, + false, + cleanedImages, + loading, + undefined, + undefined, + undefined, + imgStyle + )} + /> + + + ) + } export const altValidator: PropTypes.Validator = ( props: GatsbyImageProps, diff --git a/packages/gatsby-plugin-image/src/components/layout-wrapper.tsx b/packages/gatsby-plugin-image/src/components/layout-wrapper.tsx index bf1f352809d67..0634d223a6dfe 100644 --- a/packages/gatsby-plugin-image/src/components/layout-wrapper.tsx +++ b/packages/gatsby-plugin-image/src/components/layout-wrapper.tsx @@ -93,19 +93,17 @@ const Sizer: FunctionComponent = function Sizer({ return null } -export const LayoutWrapper: FunctionComponent = function LayoutWrapper({ - children, - ...props -}) { - return ( - - - {children} +export const LayoutWrapper: FunctionComponent = + function LayoutWrapper({ children, ...props }) { + return ( + + + {children} - { - // eslint-disable-next-line no-undef - SERVER && - } - - ) -} + { + // eslint-disable-next-line no-undef + SERVER && + } + + ) + } diff --git a/packages/gatsby-plugin-image/src/components/lazy-hydrate.tsx b/packages/gatsby-plugin-image/src/components/lazy-hydrate.tsx index 7156b37998867..84c6051a93b0a 100644 --- a/packages/gatsby-plugin-image/src/components/lazy-hydrate.tsx +++ b/packages/gatsby-plugin-image/src/components/lazy-hydrate.tsx @@ -113,7 +113,7 @@ export function lazyHydrate( // @ts-ignore react 18 typings hydrated.current.render(null) } else { - ReactDOM.render((null as unknown) as ReactElement, root.current) + ReactDOM.render(null as unknown as ReactElement, root.current) } } } diff --git a/packages/gatsby-plugin-image/src/components/placeholder.tsx b/packages/gatsby-plugin-image/src/components/placeholder.tsx index 667f3b57ed980..ef99e5ba78368 100644 --- a/packages/gatsby-plugin-image/src/components/placeholder.tsx +++ b/packages/gatsby-plugin-image/src/components/placeholder.tsx @@ -7,25 +7,23 @@ export type PlaceholderProps = ImgHTMLAttributes & { sources?: Array } -export const Placeholder: FunctionComponent = function Placeholder({ - fallback, - ...props -}) { - if (fallback) { - return ( - - ) - } else { - return
+export const Placeholder: FunctionComponent = + function Placeholder({ fallback, ...props }) { + if (fallback) { + return ( + + ) + } else { + return
+ } } -} Placeholder.displayName = `Placeholder` Placeholder.propTypes = { diff --git a/packages/gatsby-plugin-image/src/components/static-image.server.tsx b/packages/gatsby-plugin-image/src/components/static-image.server.tsx index 452380cff080e..83e45b333dda3 100644 --- a/packages/gatsby-plugin-image/src/components/static-image.server.tsx +++ b/packages/gatsby-plugin-image/src/components/static-image.server.tsx @@ -61,9 +61,8 @@ export function _getStaticImage( } } -const StaticImage: React.FC< - IStaticImageProps & IPrivateProps -> = _getStaticImage(GatsbyImageServer) +const StaticImage: React.FC = + _getStaticImage(GatsbyImageServer) const checkDimensionProps: PropTypes.Validator = ( props: IStaticImageProps & IPrivateProps, diff --git a/packages/gatsby-plugin-image/src/components/static-image.tsx b/packages/gatsby-plugin-image/src/components/static-image.tsx index b2305d83a1d7f..26ad187443ae6 100644 --- a/packages/gatsby-plugin-image/src/components/static-image.tsx +++ b/packages/gatsby-plugin-image/src/components/static-image.tsx @@ -14,9 +14,8 @@ interface IPrivateProps { __error?: string } -const StaticImage: React.FC< - IStaticImageProps & IPrivateProps -> = _getStaticImage(GatsbyImageBrowser) +const StaticImage: React.FC = + _getStaticImage(GatsbyImageBrowser) StaticImage.displayName = `StaticImage` StaticImage.propTypes = propTypes diff --git a/packages/gatsby-plugin-image/src/image-utils.ts b/packages/gatsby-plugin-image/src/image-utils.ts index 9f15f21dbf05a..300459dc1a948 100644 --- a/packages/gatsby-plugin-image/src/image-utils.ts +++ b/packages/gatsby-plugin-image/src/image-utils.ts @@ -6,18 +6,7 @@ import { IGatsbyImageData } from "." const DEFAULT_PIXEL_DENSITIES = [0.25, 0.5, 1, 2] export const DEFAULT_BREAKPOINTS = [750, 1080, 1366, 1920] export const EVERY_BREAKPOINT = [ - 320, - 654, - 768, - 1024, - 1366, - 1600, - 1920, - 2048, - 2560, - 3440, - 3840, - 4096, + 320, 654, 768, 1024, 1366, 1600, 1920, 2048, 2560, 3440, 3840, 4096, ] const DEFAULT_FLUID_WIDTH = 800 const DEFAULT_FIXED_WIDTH = 800 diff --git a/packages/gatsby-plugin-image/src/node-apis/image-processing.ts b/packages/gatsby-plugin-image/src/node-apis/image-processing.ts index 6758aa54a9ed9..c89e01717f25d 100644 --- a/packages/gatsby-plugin-image/src/node-apis/image-processing.ts +++ b/packages/gatsby-plugin-image/src/node-apis/image-processing.ts @@ -94,8 +94,8 @@ export async function writeImages({ if (isRemoteURL(src)) { let createRemoteFileNode try { - createRemoteFileNode = require(`gatsby-source-filesystem`) - .createRemoteFileNode + createRemoteFileNode = + require(`gatsby-source-filesystem`).createRemoteFileNode } catch (e) { reporter.panic(`Please install gatsby-source-filesystem`) } diff --git a/packages/gatsby-plugin-image/src/node-apis/parser.ts b/packages/gatsby-plugin-image/src/node-apis/parser.ts index d2913cc592511..1f476808fa495 100644 --- a/packages/gatsby-plugin-image/src/node-apis/parser.ts +++ b/packages/gatsby-plugin-image/src/node-apis/parser.ts @@ -88,11 +88,11 @@ export const extractStaticImageProps = ( ) { return } - const image = (evaluateImageAttributes( + const image = evaluateImageAttributes( // There's a conflict between the definition of NodePath in @babel/core and @babel/traverse - (nodePath as unknown) as NodePath, + nodePath as unknown as NodePath, onError - ) as unknown) as IStaticImageProps + ) as unknown as IStaticImageProps images.set(hashOptions(image), image) }, }) diff --git a/packages/gatsby-plugin-image/src/node-apis/watcher.ts b/packages/gatsby-plugin-image/src/node-apis/watcher.ts index fa7e05d1f5fd7..8d54b7d5a8f74 100644 --- a/packages/gatsby-plugin-image/src/node-apis/watcher.ts +++ b/packages/gatsby-plugin-image/src/node-apis/watcher.ts @@ -26,23 +26,20 @@ export function watchImage({ // We use a shared watcher, but only create it if needed if (!watcher) { watcher = chokidar.watch(fullPath) - watcher.on( - `change`, - async (path: string): Promise => { - reporter.verbose(`Image changed: ${path}`) - const node = await createImageNode({ - fullPath: path, - createNodeId, - createNode, - reporter, - }) - if (!node) { - reporter.warn(`Could not process image ${path}`) - return - } - await updateImages({ node, cache, pathPrefix, reporter }) + watcher.on(`change`, async (path: string): Promise => { + reporter.verbose(`Image changed: ${path}`) + const node = await createImageNode({ + fullPath: path, + createNodeId, + createNode, + reporter, + }) + if (!node) { + reporter.warn(`Could not process image ${path}`) + return } - ) + await updateImages({ node, cache, pathPrefix, reporter }) + }) } else { // If we already have a watcher, just add this image to it watcher.add(fullPath) diff --git a/packages/gatsby-plugin-mdx/gatsby/on-create-node.js b/packages/gatsby-plugin-mdx/gatsby/on-create-node.js index ddfdb381407b2..1768c91ddb6af 100644 --- a/packages/gatsby-plugin-mdx/gatsby/on-create-node.js +++ b/packages/gatsby-plugin-mdx/gatsby/on-create-node.js @@ -124,26 +124,23 @@ async function onCreateNodeLessBabel( ) { const { createNode, createParentChildLink } = actions - const { - mdxNode, - scopeIdentifiers, - scopeImports, - } = await createMdxNodeLessBabel({ - id: createNodeId(`${node.id} >>> Mdx`), - node, - content, - getNode, - getNodes, - getNodesByType, - reporter, - cache, - pathPrefix, - options, - loadNodeContent, - actions, - createNodeId, - ...helpers, - }) + const { mdxNode, scopeIdentifiers, scopeImports } = + await createMdxNodeLessBabel({ + id: createNodeId(`${node.id} >>> Mdx`), + node, + content, + getNode, + getNodes, + getNodesByType, + reporter, + cache, + pathPrefix, + options, + loadNodeContent, + actions, + createNodeId, + ...helpers, + }) createNode(mdxNode) createParentChildLink({ parent: node, child: mdxNode }) diff --git a/packages/gatsby-plugin-mdx/utils/babel-plugin-html-attr-to-jsx-attr.js b/packages/gatsby-plugin-mdx/utils/babel-plugin-html-attr-to-jsx-attr.js index 51379b2f774b4..c209ede55f278 100644 --- a/packages/gatsby-plugin-mdx/utils/babel-plugin-html-attr-to-jsx-attr.js +++ b/packages/gatsby-plugin-mdx/utils/babel-plugin-html-attr-to-jsx-attr.js @@ -523,13 +523,12 @@ const jsxAttributeFromHTMLAttributeVisitor = { // node.node.value.type !== "JSXExpressionContainer" ) { const styleArray = [] - styleToObject(node.node.value.extra.rawValue, function ( - name, - value, - declaration - ) { - styleArray.push([camelCaseCSS(name), value]) - }) + styleToObject( + node.node.value.extra.rawValue, + function (name, value, declaration) { + styleArray.push([camelCaseCSS(name), value]) + } + ) node.node.value = t.jSXExpressionContainer( t.objectExpression( styleArray.map(([key, value]) => diff --git a/packages/gatsby-plugin-mdx/utils/create-mdx-node.js b/packages/gatsby-plugin-mdx/utils/create-mdx-node.js index 9bfa77a59a443..e7cf7d7fa4eb9 100644 --- a/packages/gatsby-plugin-mdx/utils/create-mdx-node.js +++ b/packages/gatsby-plugin-mdx/utils/create-mdx-node.js @@ -51,17 +51,13 @@ async function createMdxNodeExtraBabel({ id, node, content }) { } async function createMdxNodeLessBabel({ id, node, content, ...helpers }) { - const { - frontmatter, - scopeImports, - scopeExports, - scopeIdentifiers, - } = await findImportsExports({ - mdxNode: node, - rawInput: content, - absolutePath: node.absolutePath, - ...helpers, - }) + const { frontmatter, scopeImports, scopeExports, scopeIdentifiers } = + await findImportsExports({ + mdxNode: node, + rawInput: content, + absolutePath: node.absolutePath, + ...helpers, + }) const mdxNode = { id, diff --git a/packages/gatsby-plugin-mdx/utils/gen-mdx.js b/packages/gatsby-plugin-mdx/utils/gen-mdx.js index 38ed9459eadc0..97a115fdca4bf 100644 --- a/packages/gatsby-plugin-mdx/utils/gen-mdx.js +++ b/packages/gatsby-plugin-mdx/utils/gen-mdx.js @@ -112,8 +112,8 @@ export const _frontmatter = ${JSON.stringify(data)}` * cache * }); */ - const gatsbyRemarkPluginsAsremarkPlugins = await getSourcePluginsAsRemarkPlugins( - { + const gatsbyRemarkPluginsAsremarkPlugins = + await getSourcePluginsAsRemarkPlugins({ gatsbyRemarkPlugins: options.gatsbyRemarkPlugins, mdxNode: node, // files, @@ -128,8 +128,7 @@ export const _frontmatter = ${JSON.stringify(data)}` generateHTML: ast => mdx(ast, options), }, ...helpers, - } - ) + }) debug(`running mdx`) const code = await mdx(content, { @@ -213,8 +212,8 @@ async function findImports({ }) { const { content } = grayMatter(node.rawBody) - const gatsbyRemarkPluginsAsremarkPlugins = await getSourcePluginsAsRemarkPlugins( - { + const gatsbyRemarkPluginsAsremarkPlugins = + await getSourcePluginsAsRemarkPlugins({ gatsbyRemarkPlugins: options.gatsbyRemarkPlugins, mdxNode: node, getNode, @@ -228,8 +227,7 @@ async function findImports({ generateHTML: ast => mdx(ast, options), }, ...helpers, - } - ) + }) const compilerOptions = { filepath: node.fileAbsolutePath, @@ -293,8 +291,8 @@ async function findImportsExports({ }) { const { data: frontmatter, content } = grayMatter(rawInput) - const gatsbyRemarkPluginsAsRemarkPlugins = await getSourcePluginsAsRemarkPlugins( - { + const gatsbyRemarkPluginsAsRemarkPlugins = + await getSourcePluginsAsRemarkPlugins({ gatsbyRemarkPlugins: options.gatsbyRemarkPlugins, mdxNode, getNode, @@ -308,8 +306,7 @@ async function findImportsExports({ generateHTML: ast => mdx(ast, options), }, ...helpers, - } - ) + }) const compilerOptions = { filepath: absolutePath, diff --git a/packages/gatsby-plugin-mdx/utils/render-html.js b/packages/gatsby-plugin-mdx/utils/render-html.js index 7c51f7b144369..16d1080b211fd 100644 --- a/packages/gatsby-plugin-mdx/utils/render-html.js +++ b/packages/gatsby-plugin-mdx/utils/render-html.js @@ -64,8 +64,10 @@ exports.mdxHTMLLoader = ({ cache, reporter, store }) => reporter.warn(`gatsby-plugin-mdx\n` + info.warnings) } - const renderMdxBody = require(path.join(outputPath, `output.js`)) - .default + const renderMdxBody = require(path.join( + outputPath, + `output.js` + )).default resolve( keys.map(({ body }) => diff --git a/packages/gatsby-plugin-netlify/src/build-headers-program.js b/packages/gatsby-plugin-netlify/src/build-headers-program.js index cdb3fcbe56138..1e58d7fb09682 100644 --- a/packages/gatsby-plugin-netlify/src/build-headers-program.js +++ b/packages/gatsby-plugin-netlify/src/build-headers-program.js @@ -241,108 +241,114 @@ const validateUserOptions = (pluginOptions, reporter) => headers => { return headers } -const mapUserLinkHeaders = ({ - manifest, - pathPrefix, - publicFolder, -}) => headers => - _.mapValues(headers, headerList => - _.map(headerList, transformLink(manifest, publicFolder, pathPrefix)) - ) - -const mapUserLinkAllPageHeaders = ( - pluginData, - { allPageHeaders } -) => headers => { - if (!allPageHeaders) { - return headers - } +const mapUserLinkHeaders = + ({ manifest, pathPrefix, publicFolder }) => + headers => + _.mapValues(headers, headerList => + _.map(headerList, transformLink(manifest, publicFolder, pathPrefix)) + ) - const { pages, manifest, publicFolder, pathPrefix } = pluginData +const mapUserLinkAllPageHeaders = + (pluginData, { allPageHeaders }) => + headers => { + if (!allPageHeaders) { + return headers + } - const headersList = _.map( - allPageHeaders, - transformLink(manifest, publicFolder, pathPrefix) - ) + const { pages, manifest, publicFolder, pathPrefix } = pluginData - const duplicateHeadersByPage = {} - pages.forEach(page => { - const pathKey = headersPath(pathPrefix, page.path) - duplicateHeadersByPage[pathKey] = headersList - }) + const headersList = _.map( + allPageHeaders, + transformLink(manifest, publicFolder, pathPrefix) + ) - return defaultMerge(headers, duplicateHeadersByPage) -} + const duplicateHeadersByPage = {} + pages.forEach(page => { + const pathKey = headersPath(pathPrefix, page.path) + duplicateHeadersByPage[pathKey] = headersList + }) -const applyLinkHeaders = (pluginData, { mergeLinkHeaders }) => headers => { - if (!mergeLinkHeaders) { - return headers + return defaultMerge(headers, duplicateHeadersByPage) } - const { pages, manifest, pathPrefix, publicFolder } = pluginData - const perPageHeaders = preloadHeadersByPage({ - pages, - manifest, - pathPrefix, - publicFolder, - }) +const applyLinkHeaders = + (pluginData, { mergeLinkHeaders }) => + headers => { + if (!mergeLinkHeaders) { + return headers + } - return defaultMerge(headers, perPageHeaders) -} + const { pages, manifest, pathPrefix, publicFolder } = pluginData + const perPageHeaders = preloadHeadersByPage({ + pages, + manifest, + pathPrefix, + publicFolder, + }) -const applySecurityHeaders = ({ mergeSecurityHeaders }) => headers => { - if (!mergeSecurityHeaders) { - return headers + return defaultMerge(headers, perPageHeaders) } - return headersMerge(headers, SECURITY_HEADERS) -} +const applySecurityHeaders = + ({ mergeSecurityHeaders }) => + headers => { + if (!mergeSecurityHeaders) { + return headers + } -const applyCachingHeaders = ( - pluginData, - { mergeCachingHeaders } -) => headers => { - if (!mergeCachingHeaders) { - return headers + return headersMerge(headers, SECURITY_HEADERS) } - let chunks = [] - // Gatsby v3.5 added componentChunkName to store().components - // So we prefer to pull chunk names off that as it gets very expensive to loop - // over large numbers of pages. - const isComponentChunkSet = !!pluginData.components.entries()?.next() - ?.value[1]?.componentChunkName - if (isComponentChunkSet) { - chunks = [...pluginData.components.values()].map(c => c.componentChunkName) - } else { - chunks = Array.from(pluginData.pages.values()).map( - page => page.componentChunkName - ) - } +const applyCachingHeaders = + (pluginData, { mergeCachingHeaders }) => + headers => { + if (!mergeCachingHeaders) { + return headers + } - chunks.push(`pages-manifest`, `app`) + let chunks = [] + // Gatsby v3.5 added componentChunkName to store().components + // So we prefer to pull chunk names off that as it gets very expensive to loop + // over large numbers of pages. + const isComponentChunkSet = !!pluginData.components.entries()?.next() + ?.value[1]?.componentChunkName + if (isComponentChunkSet) { + chunks = [...pluginData.components.values()].map( + c => c.componentChunkName + ) + } else { + chunks = Array.from(pluginData.pages.values()).map( + page => page.componentChunkName + ) + } - const files = [].concat(...chunks.map(chunk => pluginData.manifest[chunk])) + chunks.push(`pages-manifest`, `app`) - const cachingHeaders = {} + const files = [].concat(...chunks.map(chunk => pluginData.manifest[chunk])) - files.forEach(file => { - if (typeof file === `string`) { - cachingHeaders[`/` + file] = [IMMUTABLE_CACHING_HEADER] - } - }) + const cachingHeaders = {} - return defaultMerge(headers, cachingHeaders, CACHING_HEADERS) -} + files.forEach(file => { + if (typeof file === `string`) { + cachingHeaders[`/` + file] = [IMMUTABLE_CACHING_HEADER] + } + }) + + return defaultMerge(headers, cachingHeaders, CACHING_HEADERS) + } -const applyTransfromHeaders = ({ transformHeaders }) => headers => - _.mapValues(headers, transformHeaders) +const applyTransfromHeaders = + ({ transformHeaders }) => + headers => + _.mapValues(headers, transformHeaders) const transformToString = headers => `${HEADER_COMMENT}\n\n${stringifyHeaders(headers)}` -const writeHeadersFile = ({ publicFolder }) => contents => - writeFile(publicFolder(NETLIFY_HEADERS_FILENAME), contents) +const writeHeadersFile = + ({ publicFolder }) => + contents => + writeFile(publicFolder(NETLIFY_HEADERS_FILENAME), contents) export default function buildHeadersProgram( pluginData, diff --git a/packages/gatsby-plugin-offline/README.md b/packages/gatsby-plugin-offline/README.md index b9c0b40eb6863..5bdd40e5075f5 100644 --- a/packages/gatsby-plugin-offline/README.md +++ b/packages/gatsby-plugin-offline/README.md @@ -153,7 +153,8 @@ const options = { }, { // Add runtime caching of various other page resources - urlPattern: /^https?:.*\.(png|jpg|jpeg|webp|svg|gif|tiff|js|woff|woff2|json|css)$/, + urlPattern: + /^https?:.*\.(png|jpg|jpeg|webp|svg|gif|tiff|js|woff|woff2|json|css)$/, handler: `StaleWhileRevalidate`, }, { diff --git a/packages/gatsby-plugin-offline/src/__tests__/gatsby-node.js b/packages/gatsby-plugin-offline/src/__tests__/gatsby-node.js index 339ab7233f904..4d6c02c0a37d0 100644 --- a/packages/gatsby-plugin-offline/src/__tests__/gatsby-node.js +++ b/packages/gatsby-plugin-offline/src/__tests__/gatsby-node.js @@ -187,7 +187,8 @@ describe(`pluginOptionsSchema`, () => { handler: `StaleWhileRevalidate`, }, { - urlPattern: /^https?:.*\.(png|jpg|jpeg|webp|svg|gif|tiff|js|woff|woff2|json|css)$/, + urlPattern: + /^https?:.*\.(png|jpg|jpeg|webp|svg|gif|tiff|js|woff|woff2|json|css)$/, handler: `StaleWhileRevalidate`, }, { diff --git a/packages/gatsby-plugin-offline/src/gatsby-node.js b/packages/gatsby-plugin-offline/src/gatsby-node.js index 01e8456f917e7..dacba3f556c75 100644 --- a/packages/gatsby-plugin-offline/src/gatsby-node.js +++ b/packages/gatsby-plugin-offline/src/gatsby-node.js @@ -147,7 +147,8 @@ exports.onPostBuild = ( }, { // Add runtime caching of various other page resources - urlPattern: /^https?:.*\.(png|jpg|jpeg|webp|avif|svg|gif|tiff|js|woff|woff2|json|css)$/, + urlPattern: + /^https?:.*\.(png|jpg|jpeg|webp|avif|svg|gif|tiff|js|woff|woff2|json|css)$/, handler: `StaleWhileRevalidate`, }, { diff --git a/packages/gatsby-plugin-page-creator/src/create-pages-from-collection-builder.ts b/packages/gatsby-plugin-page-creator/src/create-pages-from-collection-builder.ts index e4df3d023b42b..ab4cf59461f5a 100644 --- a/packages/gatsby-plugin-page-creator/src/create-pages-from-collection-builder.ts +++ b/packages/gatsby-plugin-page-creator/src/create-pages-from-collection-builder.ts @@ -91,7 +91,7 @@ ${errors.map(error => error.message).join(`\n`)}`.trim(), // 2. Get the nodes out of the data. We very much expect data to come back in a known shape: // data = { [key: string]: { nodes: Array } } - const nodes = (Object.values(Object.values(data)[0])[0] as any) as Array< + const nodes = Object.values(Object.values(data)[0])[0] as any as Array< Record> > diff --git a/packages/gatsby-plugin-page-creator/src/extract-query.ts b/packages/gatsby-plugin-page-creator/src/extract-query.ts index 6b9823d48076a..6487352ee3335 100644 --- a/packages/gatsby-plugin-page-creator/src/extract-query.ts +++ b/packages/gatsby-plugin-page-creator/src/extract-query.ts @@ -63,18 +63,19 @@ function extractUrlParamsForQuery(createdPath: string): string { } return parts - .reduce>((queryParts: Array, part: string): Array< - string - > => { - if (part.includes(`{`) && part.includes(`}`)) { - const fields = extractField(part) - const derived = fields.map(f => deriveNesting(f)) + .reduce>( + (queryParts: Array, part: string): Array => { + if (part.includes(`{`) && part.includes(`}`)) { + const fields = extractField(part) + const derived = fields.map(f => deriveNesting(f)) - return queryParts.concat(derived) - } + return queryParts.concat(derived) + } - return queryParts - }, []) + return queryParts + }, + [] + ) .join(`,`) } diff --git a/packages/gatsby-plugin-preact/src/gatsby-node.js b/packages/gatsby-plugin-preact/src/gatsby-node.js index 963d43c0e1881..ea404d651f469 100644 --- a/packages/gatsby-plugin-preact/src/gatsby-node.js +++ b/packages/gatsby-plugin-preact/src/gatsby-node.js @@ -45,10 +45,11 @@ exports.onCreateWebpackConfig = ({ stage, actions, getConfig }) => { webpackConfig.optimization.splitChunks.cacheGroups.framework.test // replace react libs with preact - webpackConfig.optimization.splitChunks.cacheGroups.framework.test = module => - /(? + /(? { const setAdapter = a => (adapter = a) const resetAdapter = () => (adapter = console.log) - const prepend = tag => (...args) => adapter(tag, ...args) + const prepend = + tag => + (...args) => + adapter(tag, ...args) return { setAdapter, diff --git a/packages/gatsby-plugin-sharp/src/gatsby-node.js b/packages/gatsby-plugin-sharp/src/gatsby-node.js index 63ef17195a242..fa175f47cf250 100644 --- a/packages/gatsby-plugin-sharp/src/gatsby-node.js +++ b/packages/gatsby-plugin-sharp/src/gatsby-node.js @@ -60,10 +60,8 @@ exports.onCreateDevServer = async ({ app, cache, reporter }) => { // and postpone all other operations // This speeds up the loading of lazy images in the browser and // also helps to free up the browser connection queue earlier. - const { - matchingJob, - jobWithRemainingOperations, - } = splitOperationsByRequestedFile(cacheResult, pathOnDisk) + const { matchingJob, jobWithRemainingOperations } = + splitOperationsByRequestedFile(cacheResult, pathOnDisk) await _unstable_createJob(matchingJob, { reporter }) await removeCachedValue(cache, decodedURI) diff --git a/packages/gatsby-plugin-sharp/src/index.js b/packages/gatsby-plugin-sharp/src/index.js index 72b3c8c35206d..c9c3df1dbc069 100644 --- a/packages/gatsby-plugin-sharp/src/index.js +++ b/packages/gatsby-plugin-sharp/src/index.js @@ -165,15 +165,8 @@ function lazyJobsEnabled() { function queueImageResizing({ file, args = {}, reporter }) { const fullOptions = healOptions(getPluginOptions(), args, file.extension) - const { - src, - width, - height, - aspectRatio, - relativePath, - outputDir, - options, - } = prepareQueue({ file, args: createTransformObject(fullOptions) }) + const { src, width, height, aspectRatio, relativePath, outputDir, options } = + prepareQueue({ file, args: createTransformObject(fullOptions) }) // Create job and add it to the queue, the queue will be processed inside gatsby-node.js const finishedPromise = createJob( diff --git a/packages/gatsby-plugin-sharp/src/trace-svg.js b/packages/gatsby-plugin-sharp/src/trace-svg.js index df7db5b1df961..f94ca2fe8dc36 100644 --- a/packages/gatsby-plugin-sharp/src/trace-svg.js +++ b/packages/gatsby-plugin-sharp/src/trace-svg.js @@ -149,10 +149,11 @@ exports.notMemoizedtraceSVG = async ({ file, args, fileArgs, reporter }) => { let memoizedPrepareTraceSVGInputFile let memoizedTraceSVG const createMemoizedFunctions = () => { - exports.memoizedPrepareTraceSVGInputFile = memoizedPrepareTraceSVGInputFile = _.memoize( - exports.notMemoizedPrepareTraceSVGInputFile, - ({ tmpFilePath }) => tmpFilePath - ) + exports.memoizedPrepareTraceSVGInputFile = memoizedPrepareTraceSVGInputFile = + _.memoize( + exports.notMemoizedPrepareTraceSVGInputFile, + ({ tmpFilePath }) => tmpFilePath + ) exports.memoizedTraceSVG = memoizedTraceSVG = _.memoize( exports.notMemoizedtraceSVG, diff --git a/packages/gatsby-plugin-sitemap/README.md b/packages/gatsby-plugin-sitemap/README.md index 7c066731e81d1..63f3f2fb2a7c3 100644 --- a/packages/gatsby-plugin-sitemap/README.md +++ b/packages/gatsby-plugin-sitemap/README.md @@ -153,9 +153,9 @@ is needed. **Returns**: string - - uri of the page without domain or protocol -| Param | Type | Description | -| ----- | ------------------- | ------------------- | -| page | object | string | Array Item returned from resolvePages | +| Param | Type | Description | +| ----- | ------------------- | ------------------------------------- | +| page | object | Array Item returned from resolvePages | diff --git a/packages/gatsby-plugin-sitemap/src/__tests__/gatsby-node.js b/packages/gatsby-plugin-sitemap/src/__tests__/gatsby-node.js index 44f11c269e478..4e5ac3cbf1bb4 100644 --- a/packages/gatsby-plugin-sitemap/src/__tests__/gatsby-node.js +++ b/packages/gatsby-plugin-sitemap/src/__tests__/gatsby-node.js @@ -51,10 +51,8 @@ describe(`gatsby-plugin-sitemap Node API`, () => { { graphql, pathPrefix, reporter }, await schema.validateAsync({}) ) - const { - destinationDir, - sourceData, - } = sitemap.simpleSitemapAndIndex.mock.calls[0][0] + const { destinationDir, sourceData } = + sitemap.simpleSitemapAndIndex.mock.calls[0][0] expect(destinationDir).toEqual(path.join(`public`, `sitemap`)) expect(sourceData).toMatchSnapshot() }) @@ -110,10 +108,8 @@ describe(`gatsby-plugin-sitemap Node API`, () => { await schema.validateAsync(options) ) - const { - destinationDir, - sourceData, - } = sitemap.simpleSitemapAndIndex.mock.calls[0][0] + const { destinationDir, sourceData } = + sitemap.simpleSitemapAndIndex.mock.calls[0][0] expect(destinationDir).toEqual(path.join(`public`, `custom-folder`)) expect(sourceData).toMatchSnapshot() diff --git a/packages/gatsby-plugin-sitemap/src/gatsby-node.js b/packages/gatsby-plugin-sitemap/src/gatsby-node.js index 0021f33b17449..8f7d6e0818760 100644 --- a/packages/gatsby-plugin-sitemap/src/gatsby-node.js +++ b/packages/gatsby-plugin-sitemap/src/gatsby-node.js @@ -22,10 +22,8 @@ exports.onPostBuild = async ( const { data: queryRecords, errors } = await graphql(query) // resolvePages and resolveSiteUrl are allowed to be sync or async. The Promise.resolve handles each possibility - const siteUrl = await Promise.resolve( - resolveSiteUrl(queryRecords) - ).catch(err => - reporter.panic(`${REPORTER_PREFIX} Error resolving Site URL`, err) + const siteUrl = await Promise.resolve(resolveSiteUrl(queryRecords)).catch( + err => reporter.panic(`${REPORTER_PREFIX} Error resolving Site URL`, err) ) if (errors) { @@ -35,10 +33,8 @@ exports.onPostBuild = async ( ) } - const allPages = await Promise.resolve( - resolvePages(queryRecords) - ).catch(err => - reporter.panic(`${REPORTER_PREFIX} Error resolving Pages`, err) + const allPages = await Promise.resolve(resolvePages(queryRecords)).catch( + err => reporter.panic(`${REPORTER_PREFIX} Error resolving Pages`, err) ) if (!Array.isArray(allPages)) { diff --git a/packages/gatsby-plugin-styletron/src/index.js b/packages/gatsby-plugin-styletron/src/index.js index acdf96978379c..9e78c1b237bf7 100644 --- a/packages/gatsby-plugin-styletron/src/index.js +++ b/packages/gatsby-plugin-styletron/src/index.js @@ -6,9 +6,8 @@ module.exports = (() => options => { if (!memoizedValue) { let instance if (typeof window !== `undefined` && window.document.createElement) { - const styleElements = document.getElementsByClassName( - `_styletron_hydrate_` - ) + const styleElements = + document.getElementsByClassName(`_styletron_hydrate_`) instance = new Client({ hydrate: styleElements, ...options }) } else { instance = new Server(options) diff --git a/packages/gatsby-plugin-subfont/README.md b/packages/gatsby-plugin-subfont/README.md index 4f0117656b0ff..d0050d3e0d4a0 100644 --- a/packages/gatsby-plugin-subfont/README.md +++ b/packages/gatsby-plugin-subfont/README.md @@ -38,7 +38,7 @@ See [subfont](https://github.com/Munter/subfont/blob/4b5a59afd17008ca35b6c32b52e | --------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------- | | `root` | `public` | Path to your web root | | `canonicalRoot` | | URI root where the site will be deployed. Must be either an absolute, a protocol-relative, or a root-relative url | -| `output` | | Directory where results should be written to | | | +| `output` | | Directory where results should be written to | | `fallbacks` | `true` | Include fallbacks so the original font will be loaded when dynamic content gets injected at runtime. | | `dynamic` | `false` | Also trace the usage of fonts in a headless browser with JavaScript enabled | | `inPlace` | `true` | Modify HTML-files in-place. Only use on build artifacts | diff --git a/packages/gatsby-recipes/src/providers/gatsby/plugin.js b/packages/gatsby-recipes/src/providers/gatsby/plugin.js index 68b0f68a67bc7..6f1425a99f717 100644 --- a/packages/gatsby-recipes/src/providers/gatsby/plugin.js +++ b/packages/gatsby-recipes/src/providers/gatsby/plugin.js @@ -347,9 +347,8 @@ class BabelPluginAddPluginsToGatsbyConfig { if (shouldAdd) { if (t.isCallExpression(pluginNodes.value)) { - const plugins = pluginNodes.value.callee.object.elements.map( - getPlugin - ) + const plugins = + pluginNodes.value.callee.object.elements.map(getPlugin) const matches = plugins.filter(plugin => { if (!key) { return plugin.name === pluginOrThemeName @@ -367,8 +366,8 @@ class BabelPluginAddPluginsToGatsbyConfig { pluginNodes.value.callee.object.elements.push(pluginNode) } else { - pluginNodes.value.callee.object.elements = pluginNodes.value.callee.object.elements.map( - node => { + pluginNodes.value.callee.object.elements = + pluginNodes.value.callee.object.elements.map(node => { const plugin = getPlugin(node) if (plugin.key !== key) { @@ -384,8 +383,7 @@ class BabelPluginAddPluginsToGatsbyConfig { options, key, }) - } - ) + }) } } else { const plugins = pluginNodes.value.elements.map(getPlugin) @@ -429,8 +427,8 @@ class BabelPluginAddPluginsToGatsbyConfig { } } else { if (t.isCallExpression(pluginNodes.value)) { - pluginNodes.value.callee.object.elements = pluginNodes.value.callee.object.elements.filter( - node => { + pluginNodes.value.callee.object.elements = + pluginNodes.value.callee.object.elements.filter(node => { const plugin = getPlugin(node) if (key) { @@ -438,8 +436,7 @@ class BabelPluginAddPluginsToGatsbyConfig { } return plugin.name !== pluginOrThemeName - } - ) + }) } else { pluginNodes.value.elements = pluginNodes.value.elements.filter( node => { diff --git a/packages/gatsby-recipes/src/renderer/render.js b/packages/gatsby-recipes/src/renderer/render.js index 22a72766f8acd..f46138883a523 100644 --- a/packages/gatsby-recipes/src/renderer/render.js +++ b/packages/gatsby-recipes/src/renderer/render.js @@ -67,13 +67,8 @@ const ResourceComponent = ({ children, ...props }) => { - const { - mode, - resultCache, - inFlightCache, - blockedResources, - queue, - } = useGlobals() + const { mode, resultCache, inFlightCache, blockedResources, queue } = + useGlobals() const step = useRecipeStep() const parentResourceContext = useParentResourceContext() diff --git a/packages/gatsby-remark-copy-linked-files/src/index.js b/packages/gatsby-remark-copy-linked-files/src/index.js index 837f9457ab19a..35f766e60d50c 100644 --- a/packages/gatsby-remark-copy-linked-files/src/index.js +++ b/packages/gatsby-remark-copy-linked-files/src/index.js @@ -271,11 +271,9 @@ module.exports = ( ).forEach(processUrl) // Handle video poster. - extractUrlAttributeAndElement( - $(`video[poster]`), - `poster` - ).forEach(extractedUrlAttributeAndElement => - processUrl({ ...extractedUrlAttributeAndElement, isRequired: true }) + extractUrlAttributeAndElement($(`video[poster]`), `poster`).forEach( + extractedUrlAttributeAndElement => + processUrl({ ...extractedUrlAttributeAndElement, isRequired: true }) ) // Handle audio tags. diff --git a/packages/gatsby-source-contentful/src/__tests__/gatsby-node.js b/packages/gatsby-source-contentful/src/__tests__/gatsby-node.js index c040cc37831bb..1b6a3c2f488b5 100644 --- a/packages/gatsby-source-contentful/src/__tests__/gatsby-node.js +++ b/packages/gatsby-source-contentful/src/__tests__/gatsby-node.js @@ -332,8 +332,8 @@ describe(`gatsby-node`, () => { .mockImplementationOnce(startersBlogFixture.initialSync) .mockImplementationOnce(startersBlogFixture.createBlogPost) - const createdBlogEntry = startersBlogFixture.createBlogPost() - .currentSyncData.entries[0] + const createdBlogEntry = + startersBlogFixture.createBlogPost().currentSyncData.entries[0] const createdBlogEntryIds = locales.map(locale => normalize.makeId({ spaceId: createdBlogEntry.sys.space.sys.id, @@ -407,8 +407,8 @@ describe(`gatsby-node`, () => { .mockImplementationOnce(startersBlogFixture.createBlogPost) .mockImplementationOnce(startersBlogFixture.updateBlogPost) - const updatedBlogEntry = startersBlogFixture.updateBlogPost() - .currentSyncData.entries[0] + const updatedBlogEntry = + startersBlogFixture.updateBlogPost().currentSyncData.entries[0] const updatedBlogEntryIds = locales.map(locale => normalize.makeId({ spaceId: updatedBlogEntry.sys.space.sys.id, @@ -499,8 +499,8 @@ describe(`gatsby-node`, () => { .mockImplementationOnce(startersBlogFixture.createBlogPost) .mockImplementationOnce(startersBlogFixture.removeBlogPost) - const removedBlogEntry = startersBlogFixture.removeBlogPost() - .currentSyncData.deletedEntries[0] + const removedBlogEntry = + startersBlogFixture.removeBlogPost().currentSyncData.deletedEntries[0] const normalizedType = removedBlogEntry.sys.type.startsWith(`Deleted`) ? removedBlogEntry.sys.type.substring(`Deleted`.length) : removedBlogEntry.sys.type @@ -592,8 +592,8 @@ describe(`gatsby-node`, () => { .mockImplementationOnce(startersBlogFixture.createBlogPost) .mockImplementationOnce(startersBlogFixture.removeAsset) - const removedAssetEntry = startersBlogFixture.createBlogPost() - .currentSyncData.entries[0] + const removedAssetEntry = + startersBlogFixture.createBlogPost().currentSyncData.entries[0] const removedAssetEntryIds = locales.map(locale => normalize.makeId({ spaceId: removedAssetEntry.sys.space.sys.id, diff --git a/packages/gatsby-source-contentful/src/gatsby-node.js b/packages/gatsby-source-contentful/src/gatsby-node.js index efa1fb000467b..5f83bc7996a96 100644 --- a/packages/gatsby-source-contentful/src/gatsby-node.js +++ b/packages/gatsby-source-contentful/src/gatsby-node.js @@ -24,7 +24,8 @@ const restrictedNodeFields = [ `parent`, ] -exports.setFieldsOnGraphQLNodeType = require(`./extend-node-type`).extendNodeType +exports.setFieldsOnGraphQLNodeType = + require(`./extend-node-type`).extendNodeType const validateContentfulAccess = async pluginOptions => { if (process.env.NODE_ENV === `test`) return undefined diff --git a/packages/gatsby-source-contentful/src/normalize.js b/packages/gatsby-source-contentful/src/normalize.js index 944609a942fa8..82a31c9afadd7 100644 --- a/packages/gatsby-source-contentful/src/normalize.js +++ b/packages/gatsby-source-contentful/src/normalize.js @@ -28,8 +28,10 @@ const buildFallbackChain = locales => { ) return localesFallback } -const makeGetLocalizedField = ({ locale, localesFallback }) => field => - getLocalizedField({ field, locale, localesFallback }) +const makeGetLocalizedField = + ({ locale, localesFallback }) => + field => + getLocalizedField({ field, locale, localesFallback }) exports.getLocalizedField = getLocalizedField exports.buildFallbackChain = buildFallbackChain @@ -45,11 +47,10 @@ const makeId = ({ spaceId, id, currentLocale, defaultLocale, type }) => { exports.makeId = makeId -const makeMakeId = ({ currentLocale, defaultLocale, createNodeId }) => ( - spaceId, - id, - type -) => createNodeId(makeId({ spaceId, id, currentLocale, defaultLocale, type })) +const makeMakeId = + ({ currentLocale, defaultLocale, createNodeId }) => + (spaceId, id, type) => + createNodeId(makeId({ spaceId, id, currentLocale, defaultLocale, type })) exports.buildEntryList = ({ contentTypeItems, mergedSyncData }) => { // Create buckets for each type sys.id that we care about (we will always want an array for each, even if its empty) @@ -344,9 +345,8 @@ exports.createNodesForContentType = ({ ) }) if (resolvableEntryItemFieldValue.length !== 0) { - entryItemFields[ - `${entryItemFieldKey}___NODE` - ] = resolvableEntryItemFieldValue + entryItemFields[`${entryItemFieldKey}___NODE`] = + resolvableEntryItemFieldValue } delete entryItemFields[entryItemFieldKey] diff --git a/packages/gatsby-source-drupal/src/gatsby-node.js b/packages/gatsby-source-drupal/src/gatsby-node.js index 9fed56f5ce4de..e604f72035d3d 100644 --- a/packages/gatsby-source-drupal/src/gatsby-node.js +++ b/packages/gatsby-source-drupal/src/gatsby-node.js @@ -443,9 +443,8 @@ exports.sourceNodes = async ( const fileNodes = [...nodes.values()].filter(isFileNode) if (fileNodes.length) { - const downloadingFilesActivity = reporter.activityTimer( - `Remote file download` - ) + const downloadingFilesActivity = + reporter.activityTimer(`Remote file download`) downloadingFilesActivity.start() try { await asyncPool(concurrentFileRequests, fileNodes, async node => { diff --git a/packages/gatsby-source-drupal/src/utils.js b/packages/gatsby-source-drupal/src/utils.js index 6b49be12f2922..e1eabe12da023 100644 --- a/packages/gatsby-source-drupal/src/utils.js +++ b/packages/gatsby-source-drupal/src/utils.js @@ -165,11 +165,10 @@ const handleWebhookUpdate = async ( const nodeFieldName = `${newNode.internal.type}___NODE` removedReferencedNodes.forEach(referencedNode => { - referencedNode.relationships[ - nodeFieldName - ] = referencedNode.relationships[nodeFieldName].filter( - id => id !== newNode.id - ) + referencedNode.relationships[nodeFieldName] = + referencedNode.relationships[nodeFieldName].filter( + id => id !== newNode.id + ) }) // see what nodes are newly referenced, and make sure to call `createNode` on them diff --git a/packages/gatsby-source-mongodb/README.md b/packages/gatsby-source-mongodb/README.md index 4eba70416b101..3f10bcfafebaf 100644 --- a/packages/gatsby-source-mongodb/README.md +++ b/packages/gatsby-source-mongodb/README.md @@ -91,7 +91,7 @@ The GraphQL query to get the transformed markdown would look something like this. ```graphql -query($id: String!) { +query ($id: String!) { mongodbCloudDocuments(id: { eq: $id }) { id name diff --git a/packages/gatsby-source-shopify/src/create-schema-customization.ts b/packages/gatsby-source-shopify/src/create-schema-customization.ts index 9161ca0752747..7445d2cdd2363 100644 --- a/packages/gatsby-source-shopify/src/create-schema-customization.ts +++ b/packages/gatsby-source-shopify/src/create-schema-customization.ts @@ -52,15 +52,13 @@ export function createSchemaCustomization( { actions, schema }: CreateSchemaCustomizationArgs, pluginOptions: ShopifyPluginOptions ): void { - const includeCollections = pluginOptions.shopifyConnections?.includes( - `collections` - ) + const includeCollections = + pluginOptions.shopifyConnections?.includes(`collections`) const includeOrders = pluginOptions.shopifyConnections?.includes(`orders`) - const includeLocations = pluginOptions.shopifyConnections?.includes( - `locations` - ) + const includeLocations = + pluginOptions.shopifyConnections?.includes(`locations`) const name = (name: string): string => `${pluginOptions.typePrefix || ``}${name}` diff --git a/packages/gatsby-source-shopify/src/events.ts b/packages/gatsby-source-shopify/src/events.ts index 4e86e8392e244..dac93d4b1a878 100644 --- a/packages/gatsby-source-shopify/src/events.ts +++ b/packages/gatsby-source-shopify/src/events.ts @@ -5,9 +5,7 @@ interface IEvent { subject_type: string } -export function eventsApi( - options: ShopifyPluginOptions -): { +export function eventsApi(options: ShopifyPluginOptions): { fetchDestroyEventsSince: (date: Date) => Promise> } { const shopifyFetch = makeShopifyFetch(options) diff --git a/packages/gatsby-source-shopify/src/gatsby-node.ts b/packages/gatsby-source-shopify/src/gatsby-node.ts index 74170222e7681..ab43dc3db7bc4 100644 --- a/packages/gatsby-source-shopify/src/gatsby-node.ts +++ b/packages/gatsby-source-shopify/src/gatsby-node.ts @@ -195,9 +195,8 @@ export async function sourceNodes( gatsbyApi: SourceNodesArgs, pluginOptions: ShopifyPluginOptions ): Promise { - const pluginStatus = gatsbyApi.store.getState().status.plugins?.[ - `gatsby-source-shopify` - ] + const pluginStatus = + gatsbyApi.store.getState().status.plugins?.[`gatsby-source-shopify`] const lastBuildTime = pluginStatus?.[`lastBuildTime${pluginOptions.typePrefix || ``}`] diff --git a/packages/gatsby-source-shopify/src/query-builders/product-variants-query.ts b/packages/gatsby-source-shopify/src/query-builders/product-variants-query.ts index 48a040c046041..795bef7288408 100644 --- a/packages/gatsby-source-shopify/src/query-builders/product-variants-query.ts +++ b/packages/gatsby-source-shopify/src/query-builders/product-variants-query.ts @@ -12,9 +12,8 @@ export class ProductVariantsQuery extends BulkQuery { filters.push(`created_at:>='${isoDate}' OR updated_at:>='${isoDate}'`) } - const includeLocations = this.pluginOptions.shopifyConnections?.includes( - `locations` - ) + const includeLocations = + this.pluginOptions.shopifyConnections?.includes(`locations`) const ProductVariantSortKey = `POSITION` diff --git a/packages/gatsby-source-wordpress/docs/tutorials/querying-data.md b/packages/gatsby-source-wordpress/docs/tutorials/querying-data.md index 1e601fd8072a5..ab5d2decf3d6c 100644 --- a/packages/gatsby-source-wordpress/docs/tutorials/querying-data.md +++ b/packages/gatsby-source-wordpress/docs/tutorials/querying-data.md @@ -256,7 +256,7 @@ Then, below the component we created, add the following: ```js export const query = graphql` - query($id: String) { + query ($id: String) { wpPost(id: { eq: $id }) { id title @@ -307,7 +307,7 @@ For this, we would want to query for the Post's author, in addition to whatever We might end up with a query like so: ```graphql -query($id: String) { +query ($id: String) { wpPost(id: { eq: $id }) { id title @@ -383,7 +383,7 @@ const WpPost = ({ data }) => { } export const query = graphql` - query($id: String) { + query ($id: String) { wpPost(id: { eq: $id }) { id title diff --git a/packages/gatsby-source-wordpress/src/hooks/node-filters.ts b/packages/gatsby-source-wordpress/src/hooks/node-filters.ts index 4b96ea6da388b..6afe432ce9e58 100644 --- a/packages/gatsby-source-wordpress/src/hooks/node-filters.ts +++ b/packages/gatsby-source-wordpress/src/hooks/node-filters.ts @@ -33,8 +33,8 @@ export const applyNodeFilter = async ({ return data } - const nodeFilters: Array = store.getState().wpHooks - .nodeFilters?.[name] + const nodeFilters: Array = + store.getState().wpHooks.nodeFilters?.[name] if (!nodeFilters || !nodeFilters.length) { return data diff --git a/packages/gatsby-source-wordpress/src/models/gatsby-api.ts b/packages/gatsby-source-wordpress/src/models/gatsby-api.ts index 474a9b55e0566..7dc434d535ad1 100644 --- a/packages/gatsby-source-wordpress/src/models/gatsby-api.ts +++ b/packages/gatsby-source-wordpress/src/models/gatsby-api.ts @@ -338,10 +338,9 @@ const gatsbyApi = { * applied based on a `useIf` function (which returns a boolean) * If it returns true, that preset is used. */ - const optionsPresets = [ - ...defaultPresets, - ...userPresets, - ]?.filter(preset => preset.useIf(payload.helpers, payload.pluginOptions)) + const optionsPresets = [...defaultPresets, ...userPresets]?.filter( + preset => preset.useIf(payload.helpers, payload.pluginOptions) + ) if (optionsPresets?.length) { state.activePluginOptionsPresets = optionsPresets diff --git a/packages/gatsby-source-wordpress/src/models/post-build-warning-logs.ts b/packages/gatsby-source-wordpress/src/models/post-build-warning-logs.ts index 7d8566c79a50d..5215ca837e2b0 100644 --- a/packages/gatsby-source-wordpress/src/models/post-build-warning-logs.ts +++ b/packages/gatsby-source-wordpress/src/models/post-build-warning-logs.ts @@ -8,13 +8,13 @@ interface IPostBuildWarningLogState { [StateKey.maxFileSizeBytesExceeded]: number } -const incrementReducerCreator = (stateKey: StateKey) => ( - state: IPostBuildWarningLogState -): IPostBuildWarningLogState => { - state[stateKey]++ +const incrementReducerCreator = + (stateKey: StateKey) => + (state: IPostBuildWarningLogState): IPostBuildWarningLogState => { + state[stateKey]++ - return state -} + return state + } const postBuildWarningCounts = { state: { diff --git a/packages/gatsby-source-wordpress/src/steps/create-schema-customization/build-types.js b/packages/gatsby-source-wordpress/src/steps/create-schema-customization/build-types.js index 48869eb608079..de91b8b0e32c5 100644 --- a/packages/gatsby-source-wordpress/src/steps/create-schema-customization/build-types.js +++ b/packages/gatsby-source-wordpress/src/steps/create-schema-customization/build-types.js @@ -47,13 +47,8 @@ const unionType = typeBuilderApi => { } const interfaceType = typeBuilderApi => { - const { - type, - schema, - gatsbyNodeTypes, - fieldAliases, - fieldBlacklist, - } = typeBuilderApi + const { type, schema, gatsbyNodeTypes, fieldAliases, fieldBlacklist } = + typeBuilderApi const state = store.getState() const { ingestibles, typeMap } = state.remoteSchema diff --git a/packages/gatsby-source-wordpress/src/steps/create-schema-customization/transform-fields/index.js b/packages/gatsby-source-wordpress/src/steps/create-schema-customization/transform-fields/index.js index 301015e885d02..8809f45c2c1e4 100644 --- a/packages/gatsby-source-wordpress/src/steps/create-schema-customization/transform-fields/index.js +++ b/packages/gatsby-source-wordpress/src/steps/create-schema-customization/transform-fields/index.js @@ -103,9 +103,12 @@ export const transformFields = ({ const parentTypeSettings = getTypeSettingsByType(parentType) - const parentInterfacesImplementingTypeSettings = parentInterfacesImplementingTypes - ? parentInterfacesImplementingTypes.map(type => getTypeSettingsByType(type)) - : null + const parentInterfacesImplementingTypeSettings = + parentInterfacesImplementingTypes + ? parentInterfacesImplementingTypes.map(type => + getTypeSettingsByType(type) + ) + : null const transformedFields = fields.reduce((fieldsObject, field) => { // if there's no field name this field is unusable diff --git a/packages/gatsby-source-wordpress/src/steps/create-schema-customization/transform-fields/transform-object.js b/packages/gatsby-source-wordpress/src/steps/create-schema-customization/transform-fields/transform-object.js index 2fcb59b4b94ec..e700f53c3684a 100644 --- a/packages/gatsby-source-wordpress/src/steps/create-schema-customization/transform-fields/transform-object.js +++ b/packages/gatsby-source-wordpress/src/steps/create-schema-customization/transform-fields/transform-object.js @@ -33,76 +33,77 @@ export const transformListOfGatsbyNodes = ({ field, fieldName }) => { } } -export const buildGatsbyNodeObjectResolver = ({ field, fieldName }) => async ( - source, - _, - context -) => { - const typeName = buildTypeName(field.type.name) - const nodeField = source[fieldName] - - if (!nodeField || (nodeField && !nodeField.id)) { - return null - } - - const existingNode = context.nodeModel.getNodeById({ - id: nodeField.id, - type: typeName, - }) - - const { - schema: { typePrefix: prefix }, - } = getPluginOptions() - - if (existingNode?.__typename && !existingNode.__typename.startsWith(prefix)) { - existingNode.__typename = buildTypeName(existingNode.__typename) - } - - if (existingNode) { - return existingNode - } - - const queryInfo = getQueryInfoByTypeName(field.type.name) - - if (!queryInfo) { - // if we don't have query info for a type - // it probably means this type is excluded in plugin options - return null - } +export const buildGatsbyNodeObjectResolver = + ({ field, fieldName }) => + async (source, _, context) => { + const typeName = buildTypeName(field.type.name) + const nodeField = source[fieldName] + + if (!nodeField || (nodeField && !nodeField.id)) { + return null + } + + const existingNode = context.nodeModel.getNodeById({ + id: nodeField.id, + type: typeName, + }) - const isLazyMediaItem = - queryInfo.typeInfo.nodesTypeName === `MediaItem` && - queryInfo.settings.lazyNodes - - if ( - // only fetch/create nodes in resolvers for media items when they have lazyNodes enabled - !isLazyMediaItem && - // but if we're in preview mode we want to lazy fetch nodes - // because if nodes are limited we still want to lazy fetch connections - !inPreviewMode() - ) { - return null - } + const { + schema: { typePrefix: prefix }, + } = getPluginOptions() + + if ( + existingNode?.__typename && + !existingNode.__typename.startsWith(prefix) + ) { + existingNode.__typename = buildTypeName(existingNode.__typename) + } + + if (existingNode) { + return existingNode + } + + const queryInfo = getQueryInfoByTypeName(field.type.name) + + if (!queryInfo) { + // if we don't have query info for a type + // it probably means this type is excluded in plugin options + return null + } + + const isLazyMediaItem = + queryInfo.typeInfo.nodesTypeName === `MediaItem` && + queryInfo.settings.lazyNodes + + if ( + // only fetch/create nodes in resolvers for media items when they have lazyNodes enabled + !isLazyMediaItem && + // but if we're in preview mode we want to lazy fetch nodes + // because if nodes are limited we still want to lazy fetch connections + !inPreviewMode() + ) { + return null + } + + // if this node doesn't exist, fetch it and create a node + const { node } = await fetchAndCreateSingleNode({ + id: nodeField.id, + actionType: `CREATE`, + singleName: queryInfo.typeInfo.singularName, + }) - // if this node doesn't exist, fetch it and create a node - const { node } = await fetchAndCreateSingleNode({ - id: nodeField.id, - actionType: `CREATE`, - singleName: queryInfo.typeInfo.singularName, - }) + if (source.id && node) { + const { helpers } = getGatsbyApi() - if (source.id && node) { - const { helpers } = getGatsbyApi() + await helpers.actions.createParentChildLink({ + parent: source, + child: node, + }) + } - await helpers.actions.createParentChildLink({ - parent: source, - child: node, - }) + return node || null } - return node || null -} - export const transformGatsbyNodeObject = transformerApi => { const { field } = transformerApi const typeName = buildTypeName(field.type.name) diff --git a/packages/gatsby-source-wordpress/src/steps/ingest-remote-schema/build-queries-from-introspection/generate-queries-from-ingestable-types.js b/packages/gatsby-source-wordpress/src/steps/ingest-remote-schema/build-queries-from-introspection/generate-queries-from-ingestable-types.js index 274d56ee2bdcf..d5f3deffbd3b6 100644 --- a/packages/gatsby-source-wordpress/src/steps/ingest-remote-schema/build-queries-from-introspection/generate-queries-from-ingestable-types.js +++ b/packages/gatsby-source-wordpress/src/steps/ingest-remote-schema/build-queries-from-introspection/generate-queries-from-ingestable-types.js @@ -66,9 +66,8 @@ const recursivelyAliasFragments = field => // if any subfields have conflicting types, alias them if (updatedFragmentField.inlineFragments) { - updatedFragmentField.inlineFragments = recursivelyAliasFragments( - updatedFragmentField - ) + updatedFragmentField.inlineFragments = + recursivelyAliasFragments(updatedFragmentField) } return updatedFragmentField diff --git a/packages/gatsby-source-wordpress/src/steps/ingest-remote-schema/build-queries-from-introspection/recursively-transform-fields.js b/packages/gatsby-source-wordpress/src/steps/ingest-remote-schema/build-queries-from-introspection/recursively-transform-fields.js index e07f0e6665052..68f1cc949972c 100644 --- a/packages/gatsby-source-wordpress/src/steps/ingest-remote-schema/build-queries-from-introspection/recursively-transform-fields.js +++ b/packages/gatsby-source-wordpress/src/steps/ingest-remote-schema/build-queries-from-introspection/recursively-transform-fields.js @@ -599,14 +599,15 @@ const transformFields = ({ }) if (transformedField?.inlineFragments?.length) { - transformedField.inlineFragments = transformedField.inlineFragments.filter( - fieldInlineFragment => - // yes this is a horrible use of .find(). @todo refactor this for better perf - !fragment.inlineFragments.find( - fragmentInlineFragment => - fragmentInlineFragment.name === fieldInlineFragment.name - ) - ) + transformedField.inlineFragments = + transformedField.inlineFragments.filter( + fieldInlineFragment => + // yes this is a horrible use of .find(). @todo refactor this for better perf + !fragment.inlineFragments.find( + fragmentInlineFragment => + fragmentInlineFragment.name === fieldInlineFragment.name + ) + ) } } diff --git a/packages/gatsby-source-wordpress/src/steps/preview/cleanup.ts b/packages/gatsby-source-wordpress/src/steps/preview/cleanup.ts index cd8eb2f1a6ab0..aec508da542af 100644 --- a/packages/gatsby-source-wordpress/src/steps/preview/cleanup.ts +++ b/packages/gatsby-source-wordpress/src/steps/preview/cleanup.ts @@ -7,32 +7,35 @@ import { NodePluginArgs } from "gatsby" * This callback is invoked to send WP the preview status. In this case the status * is that we couldn't find a page for the node being previewed */ -const invokeLeftoverPreviewCallback = ({ - getNode, - status, - context, - error, -}: { - status: PreviewStatusUnion - context?: string - error?: Error - getNode: NodePluginArgs["getNode"] -}) => async ([nodeId, callback]: [string, OnPageCreatedCallback]): Promise< - void -> => { - const passedNode = getNode(nodeId) - - await callback({ - passedNode, - nodeId, - // we pass null as the path because no page was created for this node. - // if it had been, this callback would've been removed earlier in the process - pageNode: { path: null }, +const invokeLeftoverPreviewCallback = + ({ + getNode, status, context, error, - }) -} + }: { + status: PreviewStatusUnion + context?: string + error?: Error + getNode: NodePluginArgs["getNode"] + }) => + async ([nodeId, callback]: [ + string, + OnPageCreatedCallback + ]): Promise => { + const passedNode = getNode(nodeId) + + await callback({ + passedNode, + nodeId, + // we pass null as the path because no page was created for this node. + // if it had been, this callback would've been removed earlier in the process + pageNode: { path: null }, + status, + context, + error, + }) + } export const invokeAndCleanupLeftoverPreviewCallbacks = async ({ status, @@ -72,20 +75,19 @@ export const invokeAndCleanupLeftoverPreviewCallbacks = async ({ * preview callbacks haven't been invoked, and invoke them with a "NO_PAGE_CREATED_FOR_PREVIEWED_NODE" status, which sends that status to WP * After invoking all these leftovers, we clear them out from the store so they aren't called again later. */ -export const onPreExtractQueriesInvokeLeftoverPreviewCallbacks = async (): Promise< - void -> => { - if (!inPreviewMode()) { +export const onPreExtractQueriesInvokeLeftoverPreviewCallbacks = + async (): Promise => { + if (!inPreviewMode()) { + return invokeAndCleanupLeftoverPreviewCallbacks({ + status: `GATSBY_PREVIEW_PROCESS_ERROR`, + context: `Gatsby is not in Preview mode.`, + }) + } + + // check for any onCreatePageCallbacks that weren't called during createPages + // we need to tell WP that a page wasn't created for the preview return invokeAndCleanupLeftoverPreviewCallbacks({ - status: `GATSBY_PREVIEW_PROCESS_ERROR`, - context: `Gatsby is not in Preview mode.`, + status: `NO_PAGE_CREATED_FOR_PREVIEWED_NODE`, + context: `invokeAndCleanupLeftoverPreviewCallbacks`, }) } - - // check for any onCreatePageCallbacks that weren't called during createPages - // we need to tell WP that a page wasn't created for the preview - return invokeAndCleanupLeftoverPreviewCallbacks({ - status: `NO_PAGE_CREATED_FOR_PREVIEWED_NODE`, - context: `invokeAndCleanupLeftoverPreviewCallbacks`, - }) -} diff --git a/packages/gatsby-source-wordpress/src/steps/preview/index.ts b/packages/gatsby-source-wordpress/src/steps/preview/index.ts index 6ca22b558ca5c..c46c0b65dfdb6 100644 --- a/packages/gatsby-source-wordpress/src/steps/preview/index.ts +++ b/packages/gatsby-source-wordpress/src/steps/preview/index.ts @@ -62,9 +62,8 @@ let previewQueue: PQueue const getPreviewQueue = (): PQueue => { if (!previewQueue) { - const { - previewRequestConcurrency, - } = store.getState().gatsbyApi.pluginOptions.schema + const { previewRequestConcurrency } = + store.getState().gatsbyApi.pluginOptions.schema previewQueue = new PQueue({ concurrency: previewRequestConcurrency, @@ -82,8 +81,8 @@ const previewForIdIsAlreadyBeingProcessed = (id: string): boolean => { return false } - const existingCallbacks = store.getState().previewStore - .nodePageCreatedCallbacks + const existingCallbacks = + store.getState().previewStore.nodePageCreatedCallbacks const alreadyProcessingThisPreview = !!existingCallbacks?.[id] @@ -140,73 +139,77 @@ interface IOnPreviewStatusInput { error?: Error } -const createPreviewStatusCallback = ({ - previewData, - reporter, -}: { - previewData: IPreviewData - reporter: Reporter -}) => async ({ - passedNode, - pageNode, - context, - status, - graphqlEndpoint, - error, -}: IOnPreviewStatusInput): Promise => { - if (status === `PREVIEW_SUCCESS`) { - // we might need to write a dummy page-data.json so that - // Gatsby doesn't throw 404 errors when WPGatsby tries to read this file - // that maybe doesn't exist yet - await writeDummyPageDataJsonIfNeeded({ previewData, pageNode }) - } +const createPreviewStatusCallback = + ({ + previewData, + reporter, + }: { + previewData: IPreviewData + reporter: Reporter + }) => + async ({ + passedNode, + pageNode, + context, + status, + graphqlEndpoint, + error, + }: IOnPreviewStatusInput): Promise => { + if (status === `PREVIEW_SUCCESS`) { + // we might need to write a dummy page-data.json so that + // Gatsby doesn't throw 404 errors when WPGatsby tries to read this file + // that maybe doesn't exist yet + await writeDummyPageDataJsonIfNeeded({ previewData, pageNode }) + } - const statusContext = error?.message - ? `${context}\n\n${error.message}` - : context + const statusContext = error?.message + ? `${context}\n\n${error.message}` + : context - const { data } = await fetchGraphql({ - url: graphqlEndpoint, - query: /* GraphQL */ ` - mutation MUTATE_PREVIEW_NODE($input: WpGatsbyRemotePreviewStatusInput!) { - wpGatsbyRemotePreviewStatus(input: $input) { - success + const { data } = await fetchGraphql({ + url: graphqlEndpoint, + query: /* GraphQL */ ` + mutation MUTATE_PREVIEW_NODE( + $input: WpGatsbyRemotePreviewStatusInput! + ) { + wpGatsbyRemotePreviewStatus(input: $input) { + success + } } - } - `, - variables: { - input: { - clientMutationId: `sendPreviewStatus`, - modified: passedNode?.modified, - pagePath: pageNode?.path, - parentDatabaseId: - previewData.parentDatabaseId || previewData.previewDatabaseId, // if the parentDatabaseId is 0 we want to use the previewDatabaseId - status, - statusContext, + `, + variables: { + input: { + clientMutationId: `sendPreviewStatus`, + modified: passedNode?.modified, + pagePath: pageNode?.path, + parentDatabaseId: + previewData.parentDatabaseId || previewData.previewDatabaseId, // if the parentDatabaseId is 0 we want to use the previewDatabaseId + status, + statusContext, + }, }, - }, - errorContext: `Error occurred while mutating WordPress Preview node meta.`, - forceReportCriticalErrors: true, - headers: { - WPGatsbyPreview: previewData.token, - WPGatsbyPreviewUser: previewData.userDatabaseId, - }, - }) + errorContext: `Error occurred while mutating WordPress Preview node meta.`, + forceReportCriticalErrors: true, + headers: { + WPGatsbyPreview: previewData.token, + WPGatsbyPreviewUser: previewData.userDatabaseId, + }, + }) - if (data?.wpGatsbyRemotePreviewStatus?.success) { - reporter.log( - formatLogMessage( - `Successfully sent Preview status back to WordPress post ${previewData.id} during ${context}` + if (data?.wpGatsbyRemotePreviewStatus?.success) { + reporter.log( + formatLogMessage( + `Successfully sent Preview status back to WordPress post ${previewData.id} during ${context}` + ) ) - ) - } else { - reporter.log( - formatLogMessage( - `failed to mutate WordPress post ${previewData.id} during Preview ${context}.\nCheck your WP server logs for more information.` + } else { + reporter.log( + formatLogMessage( + `failed to mutate WordPress post ${previewData.id} during Preview ${context}.\nCheck your WP server logs for more information.` + ) ) - ) + } } -} /** * This is called and passed the result from the ActionMonitor.previewData object along with a JWT token diff --git a/packages/gatsby-source-wordpress/src/steps/preview/on-create-page.ts b/packages/gatsby-source-wordpress/src/steps/preview/on-create-page.ts index 61397fccb8d3d..ed3b5c9021d93 100644 --- a/packages/gatsby-source-wordpress/src/steps/preview/on-create-page.ts +++ b/packages/gatsby-source-wordpress/src/steps/preview/on-create-page.ts @@ -51,10 +51,8 @@ export const onCreatePageRespondToPreviewStatusQuery = async ( return } - const { - nodePageCreatedCallbacks, - pagePathToNodeDependencyId, - } = store.getState().previewStore + const { nodePageCreatedCallbacks, pagePathToNodeDependencyId } = + store.getState().previewStore const { page, getNode } = helpers diff --git a/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/create-local-file-node.js b/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/create-local-file-node.js index 40d7985226559..82ed178119cdc 100644 --- a/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/create-local-file-node.js +++ b/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/create-local-file-node.js @@ -225,10 +225,8 @@ export const createLocalFileNode = async ({ const { wpUrl } = state.remoteSchema mediaItemUrl = ensureSrcHasHostname({ wpUrl, src: mediaItemUrl }) - const { - excludeByMimeTypes, - maxFileSizeBytes, - } = pluginOptions.type?.MediaItem?.localFile + const { excludeByMimeTypes, maxFileSizeBytes } = + pluginOptions.type?.MediaItem?.localFile // if this file is larger than maxFileSizeBytes, don't fetch the remote file if (fileSize > maxFileSizeBytes) { diff --git a/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/create-nodes.js b/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/create-nodes.js index c7a472021bcab..14953e1f37cd4 100644 --- a/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/create-nodes.js +++ b/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/create-nodes.js @@ -17,96 +17,98 @@ const createNodesQueue = new PQueue({ concurrency: 2, }) -export const createNodeWithSideEffects = ({ - node, - state, - wpgqlNodesGroup = null, - referencedMediaItemNodeIds = new Set(), - createdNodeIds = [], - createNodesActivity = null, - totalSideEffectNodes = null, - type = null, -}) => async () => { - const { wpUrl } = state.remoteSchema - const { helpers, pluginOptions } = state.gatsbyApi - - const { actions, createContentDigest } = helpers - - if (node.link) { - // @todo is this still necessary? I don't think it is but double check - // create a pathname for the node using the WP permalink - node.path = urlToPath(node.link) - } - - if (wpgqlNodesGroup?.plural !== `mediaItems`) { - const { processedNode } = await processNode({ - node, - pluginOptions, - referencedMediaItemNodeIds, - wpUrl, - helpers, - }) - - node = processedNode - } - - const builtTypename = buildTypeName(node.__typename) - - let remoteNode = { - ...node, - __typename: builtTypename, - id: node.id, - parent: null, - internal: { - contentDigest: createContentDigest(node), - type: type || builtTypename, - }, - } - - const typeSettings = getTypeSettingsByType({ - name: node.type, - }) +export const createNodeWithSideEffects = + ({ + node, + state, + wpgqlNodesGroup = null, + referencedMediaItemNodeIds = new Set(), + createdNodeIds = [], + createNodesActivity = null, + totalSideEffectNodes = null, + type = null, + }) => + async () => { + const { wpUrl } = state.remoteSchema + const { helpers, pluginOptions } = state.gatsbyApi + + const { actions, createContentDigest } = helpers + + if (node.link) { + // @todo is this still necessary? I don't think it is but double check + // create a pathname for the node using the WP permalink + node.path = urlToPath(node.link) + } - if (typeof typeSettings?.beforeChangeNode === `function`) { - const { additionalNodeIds, remoteNode: changedRemoteNode } = - (await typeSettings.beforeChangeNode({ - actionType: `CREATE_ALL`, - remoteNode, - actions, + if (wpgqlNodesGroup?.plural !== `mediaItems`) { + const { processedNode } = await processNode({ + node, + pluginOptions, + referencedMediaItemNodeIds, + wpUrl, helpers, - type: node.type, - fetchGraphql, - typeSettings, - buildTypeName, - wpStore: store, - })) || {} - - if (changedRemoteNode) { - remoteNode = changedRemoteNode + }) + + node = processedNode } - if (additionalNodeIds?.length && totalSideEffectNodes) { - additionalNodeIds.forEach( - id => createdNodeIds.push(id) && totalSideEffectNodes.push(id) - ) + const builtTypename = buildTypeName(node.__typename) + + let remoteNode = { + ...node, + __typename: builtTypename, + id: node.id, + parent: null, + internal: { + contentDigest: createContentDigest(node), + type: type || builtTypename, + }, } - if ( - totalSideEffectNodes && - typeof totalSideEffectNodes?.length === `number` && - totalSideEffectNodes.length > 0 && - createNodesActivity - ) { - createNodesActivity.setStatus( - `awaiting async side effects - ${totalSideEffectNodes.length} additional nodes fetched` - ) + const typeSettings = getTypeSettingsByType({ + name: node.type, + }) + + if (typeof typeSettings?.beforeChangeNode === `function`) { + const { additionalNodeIds, remoteNode: changedRemoteNode } = + (await typeSettings.beforeChangeNode({ + actionType: `CREATE_ALL`, + remoteNode, + actions, + helpers, + type: node.type, + fetchGraphql, + typeSettings, + buildTypeName, + wpStore: store, + })) || {} + + if (changedRemoteNode) { + remoteNode = changedRemoteNode + } + + if (additionalNodeIds?.length && totalSideEffectNodes) { + additionalNodeIds.forEach( + id => createdNodeIds.push(id) && totalSideEffectNodes.push(id) + ) + } + + if ( + totalSideEffectNodes && + typeof totalSideEffectNodes?.length === `number` && + totalSideEffectNodes.length > 0 && + createNodesActivity + ) { + createNodesActivity.setStatus( + `awaiting async side effects - ${totalSideEffectNodes.length} additional nodes fetched` + ) + } } - } - await actions.createNode(remoteNode) + await actions.createNode(remoteNode) - createdNodeIds.push(node.id) -} + createdNodeIds.push(node.id) + } export const createGatsbyNodesFromWPGQLContentNodes = async ({ wpgqlNodesByContentType, diff --git a/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/process-node.js b/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/process-node.js index b1aa51bd5d5f9..0c492aaa35902 100644 --- a/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/process-node.js +++ b/packages/gatsby-source-wordpress/src/steps/source-nodes/create-nodes/process-node.js @@ -195,11 +195,10 @@ const fetchNodeHtmlImageMediaItemNodes = async ({ }) // build a query to fetch all media items that we don't already have - const mediaItemNodesBySourceUrl = await fetchReferencedMediaItemsAndCreateNodes( - { + const mediaItemNodesBySourceUrl = + await fetchReferencedMediaItemsAndCreateNodes({ mediaItemUrls, - } - ) + }) // images that have been edited from the media library that were previously // uploaded to a post/page will have a different sourceUrl so they can't be fetched by it @@ -292,40 +291,42 @@ const fetchNodeHtmlImageMediaItemNodes = async ({ return htmlMatchesToMediaItemNodesMap } -const getCheerioElementFromMatch = wpUrl => ({ match, tag = `img` }) => { - // unescape quotes - const parsedMatch = JSON.parse(`"${match}"`) - - // load our matching img tag into cheerio - const $ = cheerio.load(parsedMatch, { - xml: { - // make sure it's not wrapped in - withDomLvl1: false, - // no need to normalize whitespace, we're dealing with a single element here - normalizeWhitespace: false, - xmlMode: true, - // entity decoding isn't our job here, that will be the responsibility of WPGQL - // or of the source plugin elsewhere. - decodeEntities: false, - }, - }) +const getCheerioElementFromMatch = + wpUrl => + ({ match, tag = `img` }) => { + // unescape quotes + const parsedMatch = JSON.parse(`"${match}"`) + + // load our matching img tag into cheerio + const $ = cheerio.load(parsedMatch, { + xml: { + // make sure it's not wrapped in + withDomLvl1: false, + // no need to normalize whitespace, we're dealing with a single element here + normalizeWhitespace: false, + xmlMode: true, + // entity decoding isn't our job here, that will be the responsibility of WPGQL + // or of the source plugin elsewhere. + decodeEntities: false, + }, + }) - // there's only ever one element due to our match matching a single tag - // $(tag) isn't an array, it's an object with a key of 0 - const cheerioElement = $(tag)[0] + // there's only ever one element due to our match matching a single tag + // $(tag) isn't an array, it's an object with a key of 0 + const cheerioElement = $(tag)[0] - if (cheerioElement?.attribs?.src?.startsWith(`/wp-content`)) { - cheerioElement.attribs.src = `${wpUrl}${cheerioElement.attribs.src}` - } + if (cheerioElement?.attribs?.src?.startsWith(`/wp-content`)) { + cheerioElement.attribs.src = `${wpUrl}${cheerioElement.attribs.src}` + } - return { - match, - cheerioElement, - // @todo this is from when this function was just used for images - // remove this by refactoring - cheerioImg: cheerioElement, + return { + match, + cheerioElement, + // @todo this is from when this function was just used for images + // remove this by refactoring + cheerioImg: cheerioElement, + } } -} const getCheerioElementsFromMatches = ({ imgTagMatches, wpUrl }) => imgTagMatches @@ -426,23 +427,25 @@ const copyFileToStaticAndReturnUrlPath = async (fileNode, helpers) => { return relativeUrl } -const filterMatches = wpUrl => ({ match }) => { - const { hostname: wpHostname } = url.parse(wpUrl) +const filterMatches = + wpUrl => + ({ match }) => { + const { hostname: wpHostname } = url.parse(wpUrl) - // @todo make it a plugin option to fetch non-wp images - // here we're filtering out image tags that don't contain our site url - const isHostedInWp = - // if it has the full WP url - match.includes(wpHostname) || - // or it's an absolute path - match.includes(`src=\\"/wp-content`) + // @todo make it a plugin option to fetch non-wp images + // here we're filtering out image tags that don't contain our site url + const isHostedInWp = + // if it has the full WP url + match.includes(wpHostname) || + // or it's an absolute path + match.includes(`src=\\"/wp-content`) - // six backslashes means we're looking for three backslashes - // since we're looking for JSON encoded strings inside of our JSON encoded string - const isInJSON = match.includes(`src=\\\\\\"`) + // six backslashes means we're looking for three backslashes + // since we're looking for JSON encoded strings inside of our JSON encoded string + const isInJSON = match.includes(`src=\\\\\\"`) - return isHostedInWp && !isInJSON -} + return isHostedInWp && !isInJSON + } const cacheCreatedFileNodeBySrc = ({ node, src }) => { if (node) { @@ -455,7 +458,8 @@ const cacheCreatedFileNodeBySrc = ({ node, src }) => { } } -const imgSrcRemoteFileRegex = /(?:src=\\")((?:(?:https?|ftp|file):\/\/|www\.|ftp\.|\/)(?:[^'"])*\.(?:jpeg|jpg|png|gif|ico|mpg|ogv|svg|bmp|tif|tiff))(\?[^\\" \.]*|)(?=\\"| |\.)/gim +const imgSrcRemoteFileRegex = + /(?:src=\\")((?:(?:https?|ftp|file):\/\/|www\.|ftp\.|\/)(?:[^'"])*\.(?:jpeg|jpg|png|gif|ico|mpg|ogv|svg|bmp|tif|tiff))(\?[^\\" \.]*|)(?=\\"| |\.)/gim export const getImgSrcRemoteFileMatchesFromNodeString = nodeString => execall(imgSrcRemoteFileRegex, nodeString).filter(({ subMatches }) => { @@ -499,16 +503,15 @@ const replaceNodeHtmlImages = async ({ wpUrl, }) - const htmlMatchesToMediaItemNodesMap = await fetchNodeHtmlImageMediaItemNodes( - { + const htmlMatchesToMediaItemNodesMap = + await fetchNodeHtmlImageMediaItemNodes({ cheerioImages, nodeString, node, helpers, pluginOptions, wpUrl, - } - ) + }) // generate gatsby images for each cheerioImage const htmlMatchesWithImageResizes = await Promise.all( @@ -751,11 +754,10 @@ const replaceFileLinks = async ({ .map(({ url }) => url) .filter(isWebUri) - const mediaItemNodesBySourceUrl = await fetchReferencedMediaItemsAndCreateNodes( - { + const mediaItemNodesBySourceUrl = + await fetchReferencedMediaItemsAndCreateNodes({ mediaItemUrls, - } - ) + }) const findReplaceMaps = [] diff --git a/packages/gatsby-source-wordpress/src/steps/source-nodes/fetch-nodes/fetch-referenced-media-items.js b/packages/gatsby-source-wordpress/src/steps/source-nodes/fetch-nodes/fetch-referenced-media-items.js index e84213199f3c8..5d4135d0aec66 100644 --- a/packages/gatsby-source-wordpress/src/steps/source-nodes/fetch-nodes/fetch-referenced-media-items.js +++ b/packages/gatsby-source-wordpress/src/steps/source-nodes/fetch-nodes/fetch-referenced-media-items.js @@ -282,26 +282,24 @@ const fetchMediaItemsBySourceUrl = async ({ }) => { const processedMediaItemUrls = processAndDedupeImageUrls(mediaItemUrls) - const { - cachedMediaItemNodeIds, - uncachedMediaItemUrls, - } = processedMediaItemUrls.reduce( - (accumulator, url) => { - const { id } = getFileNodeMetaBySourceUrl(url) || {} - - // if we have a cached image and we haven't already recorded this cached image - if (id && !accumulator.cachedMediaItemNodeIds.includes(id)) { - // save it - accumulator.cachedMediaItemNodeIds.push(id) - } else if (!id) { - // otherwise we need to fetch this media item by url - accumulator.uncachedMediaItemUrls.push(url) - } + const { cachedMediaItemNodeIds, uncachedMediaItemUrls } = + processedMediaItemUrls.reduce( + (accumulator, url) => { + const { id } = getFileNodeMetaBySourceUrl(url) || {} + + // if we have a cached image and we haven't already recorded this cached image + if (id && !accumulator.cachedMediaItemNodeIds.includes(id)) { + // save it + accumulator.cachedMediaItemNodeIds.push(id) + } else if (!id) { + // otherwise we need to fetch this media item by url + accumulator.uncachedMediaItemUrls.push(url) + } - return accumulator - }, - { cachedMediaItemNodeIds: [], uncachedMediaItemUrls: [] } - ) + return accumulator + }, + { cachedMediaItemNodeIds: [], uncachedMediaItemUrls: [] } + ) // take our previously cached id's and get nodes for them const previouslyCachedMediaItemNodes = await Promise.all( diff --git a/packages/gatsby-source-wordpress/src/steps/source-nodes/index.ts b/packages/gatsby-source-wordpress/src/steps/source-nodes/index.ts index 743afa7c87cb0..9c2b85e21af23 100644 --- a/packages/gatsby-source-wordpress/src/steps/source-nodes/index.ts +++ b/packages/gatsby-source-wordpress/src/steps/source-nodes/index.ts @@ -35,10 +35,8 @@ const sourceNodes: Step = async helpers => { ? webhookBody.since : await cache.get(LAST_COMPLETED_SOURCE_TIME) - const { - schemaWasChanged, - foundUsableHardCachedData, - } = store.getState().remoteSchema + const { schemaWasChanged, foundUsableHardCachedData } = + store.getState().remoteSchema const fetchEverything = foundUsableHardCachedData || diff --git a/packages/gatsby-source-wordpress/src/steps/source-nodes/update-nodes/wp-actions/update.js b/packages/gatsby-source-wordpress/src/steps/source-nodes/update-nodes/wp-actions/update.js index abe80689aab7c..5d1ac3735a797 100644 --- a/packages/gatsby-source-wordpress/src/steps/source-nodes/update-nodes/wp-actions/update.js +++ b/packages/gatsby-source-wordpress/src/steps/source-nodes/update-nodes/wp-actions/update.js @@ -201,18 +201,17 @@ export const createSingleNode = async ({ additionalNodeIds: receivedAdditionalNodeIds, remoteNode: receivedRemoteNode, cancelUpdate: receivedCancelUpdate, - } = - (await typeSettings.beforeChangeNode({ - actionType: actionType, - remoteNode, - actions, - helpers, - fetchGraphql, - typeSettings, - buildTypeName, - type: typeInfo.nodesTypeName, - wpStore: store, - })) || {} + } = (await typeSettings.beforeChangeNode({ + actionType: actionType, + remoteNode, + actions, + helpers, + fetchGraphql, + typeSettings, + buildTypeName, + type: typeInfo.nodesTypeName, + wpStore: store, + })) || {} additionalNodeIds = [ ...additionalNodeIds, diff --git a/packages/gatsby-source-wordpress/src/utils/fetch-graphql.ts b/packages/gatsby-source-wordpress/src/utils/fetch-graphql.ts index 272dc4f71a335..cf1b4956608c2 100644 --- a/packages/gatsby-source-wordpress/src/utils/fetch-graphql.ts +++ b/packages/gatsby-source-wordpress/src/utils/fetch-graphql.ts @@ -255,11 +255,8 @@ const genericError = ({ url }: { url: string }): string => const slackChannelSupportMessage = `If you're still having issues, please visit https://www.wpgraphql.com/community-and-support/\nand follow the link to join the WPGraphQL Slack.\nThere are a lot of folks there in the #gatsby channel who are happy to help with debugging.` const getLowerRequestConcurrencyOptionMessage = (): string => { - const { - requestConcurrency, - previewRequestConcurrency, - perPage, - } = store.getState().gatsbyApi.pluginOptions.schema + const { requestConcurrency, previewRequestConcurrency, perPage } = + store.getState().gatsbyApi.pluginOptions.schema return `Try reducing the ${bold( `requestConcurrency` @@ -470,9 +467,8 @@ ${slackChannelSupportMessage}` return } - const responseReturnedHtml = !!response?.headers[`content-type`].includes( - `text/html;` - ) + const responseReturnedHtml = + !!response?.headers[`content-type`].includes(`text/html;`) const limit = pluginOptions?.schema?.requestConcurrency if (responseReturnedHtml && isFirstRequest) { diff --git a/packages/gatsby-source-wordpress/src/utils/run-steps.ts b/packages/gatsby-source-wordpress/src/utils/run-steps.ts index 433fa4e1b3ff0..26814fad144a0 100644 --- a/packages/gatsby-source-wordpress/src/utils/run-steps.ts +++ b/packages/gatsby-source-wordpress/src/utils/run-steps.ts @@ -72,10 +72,13 @@ const runSteps = async ( } } -const runApiSteps = (steps: Array, apiName: string) => async ( - helpers: GatsbyNodeApiHelpers, - pluginOptions: IPluginOptions -): Promise => runSteps(steps, helpers, pluginOptions, apiName) +const runApiSteps = + (steps: Array, apiName: string) => + async ( + helpers: GatsbyNodeApiHelpers, + pluginOptions: IPluginOptions + ): Promise => + runSteps(steps, helpers, pluginOptions, apiName) const runApisInSteps = (nodeApis: { [apiName: string]: Array | Step diff --git a/packages/gatsby-telemetry/src/repository-id.ts b/packages/gatsby-telemetry/src/repository-id.ts index 66136d34997dc..9a63457c75413 100644 --- a/packages/gatsby-telemetry/src/repository-id.ts +++ b/packages/gatsby-telemetry/src/repository-id.ts @@ -8,9 +8,10 @@ import gitUp from "git-up" import { getCIName } from "gatsby-core-utils" // there are no types for git-up, so we create our own // based on https://github.com/IonicaBizau/git-up/blob/60e6a4ff93d50360bbb80953bfab2f82d3418900/lib/index.js#L8-L28 -const typedGitUp = gitUp as ( - input: string -) => { resource: string; pathname: string } +const typedGitUp = gitUp as (input: string) => { + resource: string + pathname: string +} interface IRepositoryData { provider: string diff --git a/packages/gatsby-transformer-documentationjs/src/__tests__/gatsby-node.js b/packages/gatsby-transformer-documentationjs/src/__tests__/gatsby-node.js index bca83651c3af7..815c4deab3291 100644 --- a/packages/gatsby-transformer-documentationjs/src/__tests__/gatsby-node.js +++ b/packages/gatsby-transformer-documentationjs/src/__tests__/gatsby-node.js @@ -195,13 +195,10 @@ describe(`gatsby-transformer-documentationjs: onCreateNode`, () => { expect(nestedNode.name).toBe(`nested`) expect(nestedNode.properties___NODE).toBeDefined() expect(nestedNode.properties___NODE.length).toBe(3) - ;[ - nestedFooNode, - nestedOptionalNode, - nestedCallbackNode, - ] = nestedNode.properties___NODE.map(paramID => - createdNodes.find(node => node.id === paramID) - ) + ;[nestedFooNode, nestedOptionalNode, nestedCallbackNode] = + nestedNode.properties___NODE.map(paramID => + createdNodes.find(node => node.id === paramID) + ) }) it(`should strip prefixes from nested nodes`, () => { diff --git a/packages/gatsby-transformer-react-docgen/src/displayname-handler.js b/packages/gatsby-transformer-react-docgen/src/displayname-handler.js index 25b2ed3ff043f..7f2588a8f2453 100644 --- a/packages/gatsby-transformer-react-docgen/src/displayname-handler.js +++ b/packages/gatsby-transformer-react-docgen/src/displayname-handler.js @@ -4,11 +4,8 @@ const path = require(`path`) const { namedTypes: types } = require(`ast-types`) const { utils } = require(`react-docgen`) -const { - getMemberValuePath, - getNameOrValue, - isExportsOrModuleAssignment, -} = utils +const { getMemberValuePath, getNameOrValue, isExportsOrModuleAssignment } = + utils const DEFAULT_NAME = `UnknownComponent` diff --git a/packages/gatsby-transformer-react-docgen/src/parse.js b/packages/gatsby-transformer-react-docgen/src/parse.js index de16b3f6ebf49..c25d8cee1915f 100644 --- a/packages/gatsby-transformer-react-docgen/src/parse.js +++ b/packages/gatsby-transformer-react-docgen/src/parse.js @@ -21,7 +21,11 @@ let fileCount = 0 * Wrap handlers to pass in additional arguments such as the File node */ function makeHandlers(node, handlers) { - handlers = (handlers || []).map(h => (...args) => h(...args, node)) + handlers = (handlers || []).map( + h => + (...args) => + h(...args, node) + ) return [ createDisplayNameHandler( node.absolutePath || `/UnknownComponent${++fileCount}` diff --git a/packages/gatsby-transformer-remark/src/__tests__/extend-node.js b/packages/gatsby-transformer-remark/src/__tests__/extend-node.js index aae314bfdff02..6a6f004a3db89 100644 --- a/packages/gatsby-transformer-remark/src/__tests__/extend-node.js +++ b/packages/gatsby-transformer-remark/src/__tests__/extend-node.js @@ -1233,9 +1233,9 @@ console.log('hello world') `htmlAst`, node => { expect(node).toMatchSnapshot() - expect( - node.htmlAst.children[0].children[0].properties.className - ).toEqual([`language-js`]) + expect(node.htmlAst.children[0].children[0].properties.className).toEqual( + [`language-js`] + ) expect(node.htmlAst.children[0].children[0].properties.dataMeta).toEqual( `foo bar` ) diff --git a/packages/gatsby-worker/src/index.ts b/packages/gatsby-worker/src/index.ts index e672676feaddc..e650f741fba0a 100644 --- a/packages/gatsby-worker/src/index.ts +++ b/packages/gatsby-worker/src/index.ts @@ -124,9 +124,8 @@ export class WorkerPool< private workers: Array> = [] private taskQueue = new TaskQueue>() private idleWorkers: Set> = new Set() - private listeners: Array< - (msg: MessagesFromChild, workerId: number) => void - > = [] + private listeners: Array<(msg: MessagesFromChild, workerId: number) => void> = + [] constructor(private workerPath: string, private options?: IWorkerOptions) { const single: Partial["single"]> = {} @@ -153,12 +152,10 @@ export class WorkerPool< exportName ) as WorkerPool["single"][typeof exportName] - all[exportName] = (this.scheduleWorkAll.bind( + all[exportName] = this.scheduleWorkAll.bind( this, exportName - ) as unknown) as WorkerPool< - WorkerModuleExports - >["all"][typeof exportName] + ) as unknown as WorkerPool["all"][typeof exportName] } } diff --git a/packages/gatsby/cache-dir/__tests__/public-page-renderer-dev.tsx b/packages/gatsby/cache-dir/__tests__/public-page-renderer-dev.tsx index 6df3ff0521645..86d9fcf40939c 100644 --- a/packages/gatsby/cache-dir/__tests__/public-page-renderer-dev.tsx +++ b/packages/gatsby/cache-dir/__tests__/public-page-renderer-dev.tsx @@ -3,12 +3,16 @@ import { render, cleanup } from "@testing-library/react" jest.mock(`../loader`, () => { return { - loadPageSync: jest.fn((path: string): { - loadPageSync: boolean - path: string - } => { - return { loadPageSync: true, path } - }), + loadPageSync: jest.fn( + ( + path: string + ): { + loadPageSync: boolean + path: string + } => { + return { loadPageSync: true, path } + } + ), loadPage: function loadPage( path: string ): Promise<{ loadPage: boolean; path: string }> { diff --git a/packages/gatsby/cache-dir/__tests__/public-page-renderer-prod.tsx b/packages/gatsby/cache-dir/__tests__/public-page-renderer-prod.tsx index 0d9866a81d0f7..9eb49f74300ac 100644 --- a/packages/gatsby/cache-dir/__tests__/public-page-renderer-prod.tsx +++ b/packages/gatsby/cache-dir/__tests__/public-page-renderer-prod.tsx @@ -3,12 +3,16 @@ import { render, cleanup } from "@testing-library/react" jest.mock(`../loader`, () => { return { - loadPageSync: jest.fn((path: string): { - loadPageSync: boolean - path: string - } => { - return { loadPageSync: true, path } - }), + loadPageSync: jest.fn( + ( + path: string + ): { + loadPageSync: boolean + path: string + } => { + return { loadPageSync: true, path } + } + ), loadPage: function loadPage( path: string ): Promise<{ loadPage: boolean; path: string }> { diff --git a/packages/gatsby/cache-dir/__tests__/static-entry.js b/packages/gatsby/cache-dir/__tests__/static-entry.js index 1bac7c3d75232..1230d314885b9 100644 --- a/packages/gatsby/cache-dir/__tests__/static-entry.js +++ b/packages/gatsby/cache-dir/__tests__/static-entry.js @@ -67,10 +67,8 @@ const pageDataMock = { const MOCK_FILE_INFO = { [`${process.cwd()}/public/webpack.stats.json`]: `{}`, [`${process.cwd()}/public/chunk-map.json`]: `{}`, - [join( - process.cwd(), - `/public/page-data/about/page-data.json` - )]: JSON.stringify(pageDataMock), + [join(process.cwd(), `/public/page-data/about/page-data.json`)]: + JSON.stringify(pageDataMock), [join(process.cwd(), `/public/page-data/app-data.json`)]: JSON.stringify({ webpackCompilationHash: `1234567890abcdef1234`, }), diff --git a/packages/gatsby/cache-dir/api-runner-browser.js b/packages/gatsby/cache-dir/api-runner-browser.js index 0adf7772a68cb..c65337c9a37cf 100644 --- a/packages/gatsby/cache-dir/api-runner-browser.js +++ b/packages/gatsby/cache-dir/api-runner-browser.js @@ -1,9 +1,6 @@ const plugins = require(`./api-runner-browser-plugins`) -const { - getResourceURLsForPathname, - loadPage, - loadPageSync, -} = require(`./loader`).publicLoader +const { getResourceURLsForPathname, loadPage, loadPageSync } = + require(`./loader`).publicLoader exports.apiRunner = (api, args = {}, defaultReturn, argTransform) => { // Hooks for gatsby-cypress's API handler diff --git a/packages/gatsby/cache-dir/fast-refresh-overlay/components/graphql-errors.js b/packages/gatsby/cache-dir/fast-refresh-overlay/components/graphql-errors.js index d534de7068549..b748951bd4f04 100644 --- a/packages/gatsby/cache-dir/fast-refresh-overlay/components/graphql-errors.js +++ b/packages/gatsby/cache-dir/fast-refresh-overlay/components/graphql-errors.js @@ -59,9 +59,10 @@ function WrappedAccordionItem({ error, open }) { } export function GraphqlErrors({ errors, dismiss }) { - const deduplicatedErrors = React.useMemo(() => Array.from(new Set(errors)), [ - errors, - ]) + const deduplicatedErrors = React.useMemo( + () => Array.from(new Set(errors)), + [errors] + ) const hasMultipleErrors = deduplicatedErrors.length > 1 return ( diff --git a/packages/gatsby/cache-dir/fast-refresh-overlay/components/runtime-errors.js b/packages/gatsby/cache-dir/fast-refresh-overlay/components/runtime-errors.js index d9e76e97c1091..2732decc9563d 100644 --- a/packages/gatsby/cache-dir/fast-refresh-overlay/components/runtime-errors.js +++ b/packages/gatsby/cache-dir/fast-refresh-overlay/components/runtime-errors.js @@ -53,9 +53,10 @@ function WrappedAccordionItem({ error, open }) { } export function RuntimeErrors({ errors, dismiss }) { - const deduplicatedErrors = React.useMemo(() => Array.from(new Set(errors)), [ - errors, - ]) + const deduplicatedErrors = React.useMemo( + () => Array.from(new Set(errors)), + [errors] + ) const hasMultipleErrors = deduplicatedErrors.length > 1 return ( diff --git a/packages/gatsby/src/bootstrap/create-graphql-runner.ts b/packages/gatsby/src/bootstrap/create-graphql-runner.ts index 60d9de0d646b3..958b1ff170bf4 100644 --- a/packages/gatsby/src/bootstrap/create-graphql-runner.ts +++ b/packages/gatsby/src/bootstrap/create-graphql-runner.ts @@ -88,7 +88,7 @@ export const createGraphQLRunner = ( return null }) - .filter((Boolean as unknown) as (match) => match is IMatch) + .filter(Boolean as unknown as (match) => match is IMatch) if (structuredErrors.length) { // panic on build exits the process diff --git a/packages/gatsby/src/bootstrap/load-plugins/__tests__/validate.ts b/packages/gatsby/src/bootstrap/load-plugins/__tests__/validate.ts index 1777d595640cc..2fd2bed7826b8 100644 --- a/packages/gatsby/src/bootstrap/load-plugins/__tests__/validate.ts +++ b/packages/gatsby/src/bootstrap/load-plugins/__tests__/validate.ts @@ -24,7 +24,7 @@ import { resolveModuleExports } from "../../resolve-module-exports" beforeEach(() => { Object.keys(reporter).forEach(key => (reporter[key] as jest.Mock).mockReset()) - const mocked = (getLatestAPIs as unknown) as jest.MockedFunction< + const mocked = getLatestAPIs as unknown as jest.MockedFunction< typeof getLatestAPIs > mocked.mockClear() @@ -287,9 +287,9 @@ describe(`handleBadExports`, () => { ) expect(reporter.error).toHaveBeenCalledTimes(typoAPIs.length) - const calls = ((reporter.error as unknown) as jest.MockedFunction< - typeof reporter.error - >).mock.calls + const calls = ( + reporter.error as unknown as jest.MockedFunction + ).mock.calls calls.forEach(([call]) => { expect(call).toEqual( @@ -367,9 +367,9 @@ describe(`handleMultipleReplaceRenderers`, () => { describe(`warnOnIncompatiblePeerDependency`, () => { beforeEach(() => { - ;((reporter.warn as unknown) as jest.MockedFunction< - typeof reporter.warn - >).mockClear() + ;( + reporter.warn as unknown as jest.MockedFunction + ).mockClear() }) it(`Does not warn when no peer dependency`, () => { diff --git a/packages/gatsby/src/bootstrap/load-plugins/validate.ts b/packages/gatsby/src/bootstrap/load-plugins/validate.ts index 37e6c05ecca5d..608fe922251b2 100644 --- a/packages/gatsby/src/bootstrap/load-plugins/validate.ts +++ b/packages/gatsby/src/bootstrap/load-plugins/validate.ts @@ -197,10 +197,12 @@ async function validatePluginsOptions( if (!gatsbyNode.pluginOptionsSchema) return plugin - let optionsSchema = (gatsbyNode.pluginOptionsSchema as Exclude< - GatsbyNode["pluginOptionsSchema"], - undefined - >)({ + let optionsSchema = ( + gatsbyNode.pluginOptionsSchema as Exclude< + GatsbyNode["pluginOptionsSchema"], + undefined + > + )({ Joi, }) @@ -228,13 +230,11 @@ async function validatePluginsOptions( ) if (plugin.options?.plugins) { - const { - errors: subErrors, - plugins: subPlugins, - } = await validatePluginsOptions( - plugin.options.plugins as Array, - rootDir - ) + const { errors: subErrors, plugins: subPlugins } = + await validatePluginsOptions( + plugin.options.plugins as Array, + rootDir + ) plugin.options.plugins = subPlugins errors += subErrors } diff --git a/packages/gatsby/src/bootstrap/resolve-module-exports.ts b/packages/gatsby/src/bootstrap/resolve-module-exports.ts index 60919ff50127a..ee81c5128bfab 100644 --- a/packages/gatsby/src/bootstrap/resolve-module-exports.ts +++ b/packages/gatsby/src/bootstrap/resolve-module-exports.ts @@ -30,7 +30,7 @@ const staticallyAnalyzeExports = ( const codeFrame = codeFrameColumns( code, { - start: ((err as unknown) as { loc: SourceLocation["start"] }).loc, + start: (err as unknown as { loc: SourceLocation["start"] }).loc, }, { highlightCode: true, diff --git a/packages/gatsby/src/commands/__tests__/build-utils.ts b/packages/gatsby/src/commands/__tests__/build-utils.ts index 72b9c74579a9c..9fccdde11da4b 100644 --- a/packages/gatsby/src/commands/__tests__/build-utils.ts +++ b/packages/gatsby/src/commands/__tests__/build-utils.ts @@ -240,8 +240,8 @@ describe(`calcDirtyHtmlFiles`, () => { let isolatedCalcDirtyHtmlFiles jest.isolateModules(() => { platformSpy.mockImplementation(() => `linux`) - isolatedCalcDirtyHtmlFiles = require(`../build-utils`) - .calcDirtyHtmlFiles + isolatedCalcDirtyHtmlFiles = + require(`../build-utils`).calcDirtyHtmlFiles }) const state = generateStateToTestHelper({ @@ -268,8 +268,8 @@ describe(`calcDirtyHtmlFiles`, () => { let isolatedCalcDirtyHtmlFiles jest.isolateModules(() => { platformSpy.mockImplementation(() => `win32`) - isolatedCalcDirtyHtmlFiles = require(`../build-utils`) - .calcDirtyHtmlFiles + isolatedCalcDirtyHtmlFiles = + require(`../build-utils`).calcDirtyHtmlFiles }) const state = generateStateToTestHelper({ diff --git a/packages/gatsby/src/commands/build-html.ts b/packages/gatsby/src/commands/build-html.ts index 5cf3b1cdf3114..d3dd804fbe5d9 100644 --- a/packages/gatsby/src/commands/build-html.ts +++ b/packages/gatsby/src/commands/build-html.ts @@ -388,11 +388,8 @@ export async function buildHTMLPagesAndDeleteStaleArtifacts({ }> { buildUtils.markHtmlDirtyIfResultOfUsedStaticQueryChanged() - const { - toRegenerate, - toDelete, - toCleanupFromTrackedState, - } = buildUtils.calcDirtyHtmlFiles(store.getState()) + const { toRegenerate, toDelete, toCleanupFromTrackedState } = + buildUtils.calcDirtyHtmlFiles(store.getState()) store.dispatch({ type: `HTML_TRACKED_PAGES_CLEANUP`, diff --git a/packages/gatsby/src/commands/build-utils.ts b/packages/gatsby/src/commands/build-utils.ts index 9922b67df6472..2b47c3d8bd15c 100644 --- a/packages/gatsby/src/commands/build-utils.ts +++ b/packages/gatsby/src/commands/build-utils.ts @@ -89,9 +89,7 @@ const pageGenerationActionPriority: Record = { delete: 0, } -export function calcDirtyHtmlFiles( - state: IGatsbyState -): { +export function calcDirtyHtmlFiles(state: IGatsbyState): { toRegenerate: Array toDelete: Array toCleanupFromTrackedState: Set diff --git a/packages/gatsby/src/commands/build.ts b/packages/gatsby/src/commands/build.ts index b86fef361838c..a041d03f71bb0 100644 --- a/packages/gatsby/src/commands/build.ts +++ b/packages/gatsby/src/commands/build.ts @@ -224,15 +224,13 @@ module.exports = async function build(program: IBuildArgs): Promise { } await waitForWorkerPoolRestart - const { - toRegenerate, - toDelete, - } = await buildHTMLPagesAndDeleteStaleArtifacts({ - program, - pageRenderer, - workerPool, - buildSpan, - }) + const { toRegenerate, toDelete } = + await buildHTMLPagesAndDeleteStaleArtifacts({ + program, + pageRenderer, + workerPool, + buildSpan, + }) const waitWorkerPoolEnd = Promise.all(workerPool.end()) telemetry.addSiteMeasurement(`BUILD_END`, { diff --git a/packages/gatsby/src/commands/develop-process.ts b/packages/gatsby/src/commands/develop-process.ts index ea523cfb84251..95758861a973c 100644 --- a/packages/gatsby/src/commands/develop-process.ts +++ b/packages/gatsby/src/commands/develop-process.ts @@ -92,17 +92,14 @@ module.exports = async (program: IDevelopArgs): Promise => { // We want to prompt the feedback request when users quit develop // assuming they pass the heuristic check to know they are a user // we want to request feedback from, and we're not annoying them. - process.on( - `SIGINT`, - async (): Promise => { - if (await userGetsSevenDayFeedback()) { - showSevenDayFeedbackRequest() - } else if (await userPassesFeedbackRequestHeuristic()) { - showFeedbackRequest() - } - process.exit(0) + process.on(`SIGINT`, async (): Promise => { + if (await userGetsSevenDayFeedback()) { + showSevenDayFeedbackRequest() + } else if (await userPassesFeedbackRequestHeuristic()) { + showFeedbackRequest() } - ) + process.exit(0) + }) initTracer(program.openTracingConfigFile) markWebpackStatusAsPending() diff --git a/packages/gatsby/src/commands/develop.ts b/packages/gatsby/src/commands/develop.ts index 7fc536a7fcf47..f3672a60757f7 100644 --- a/packages/gatsby/src/commands/develop.ts +++ b/packages/gatsby/src/commands/develop.ts @@ -184,7 +184,8 @@ class ControllableScript { let isRestarting // checks if a string is a valid ip -const REGEX_IP = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/ +const REGEX_IP = + /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/ module.exports = async (program: IProgram): Promise => { // In some cases, port can actually be a string. But our codebase is expecting it to be a number. @@ -222,15 +223,12 @@ module.exports = async (program: IProgram): Promise => { // It is exposed for environments where port access needs to be explicit, such as with Docker. // As the port is meant for internal usage only, any attempt to interface with features // it exposes via third-party software is not supported. - const [ - statusServerPort, - developPort, - telemetryServerPort, - ] = await Promise.all([ - getRandomPort(process.env.INTERNAL_STATUS_PORT), - getRandomPort(), - getRandomPort(), - ]) + const [statusServerPort, developPort, telemetryServerPort] = + await Promise.all([ + getRandomPort(process.env.INTERNAL_STATUS_PORT), + getRandomPort(), + getRandomPort(), + ]) // In order to enable custom ssl, --cert-file --key-file and -https flags must all be // used together diff --git a/packages/gatsby/src/commands/repl.ts b/packages/gatsby/src/commands/repl.ts index af270922e9544..0e8a3cac04d88 100644 --- a/packages/gatsby/src/commands/repl.ts +++ b/packages/gatsby/src/commands/repl.ts @@ -13,14 +13,8 @@ module.exports = async (program: IProgram): Promise => { await bootstrap({ program }) // get all the goodies from the store - const { - schema, - config, - babelrc, - pages, - components, - staticQueryComponents, - } = store.getState() + const { schema, config, babelrc, pages, components, staticQueryComponents } = + store.getState() const nodes = getNodes() diff --git a/packages/gatsby/src/commands/serve.ts b/packages/gatsby/src/commands/serve.ts index 5151acf9e5c20..b665761440078 100644 --- a/packages/gatsby/src/commands/serve.ts +++ b/packages/gatsby/src/commands/serve.ts @@ -63,35 +63,37 @@ const readMatchPaths = async ( return JSON.parse(rawJSON) as Array } -const matchPathRouter = ( - matchPaths: Array, - options: { - root: string - } -) => ( - req: express.Request, - res: express.Response, - next: express.NextFunction -): void => { - const { url } = req - if (req.accepts(`html`)) { - const matchPath = matchPaths.find( - ({ matchPath }) => reachMatch(matchPath, url) !== null - ) - if (matchPath) { - return res.sendFile( - path.join(matchPath.path, `index.html`), - options, - err => { - if (err) { - next() - } - } +const matchPathRouter = + ( + matchPaths: Array, + options: { + root: string + } + ) => + ( + req: express.Request, + res: express.Response, + next: express.NextFunction + ): void => { + const { url } = req + if (req.accepts(`html`)) { + const matchPath = matchPaths.find( + ({ matchPath }) => reachMatch(matchPath, url) !== null ) + if (matchPath) { + return res.sendFile( + path.join(matchPath.path, `index.html`), + options, + err => { + if (err) { + next() + } + } + ) + } } + return next() } - return next() -} module.exports = async (program: IServeProgram): Promise => { telemetry.trackCli(`SERVE_START`) diff --git a/packages/gatsby/src/datastore/common/query.ts b/packages/gatsby/src/datastore/common/query.ts index 9e106712fafa8..143807d744d7b 100644 --- a/packages/gatsby/src/datastore/common/query.ts +++ b/packages/gatsby/src/datastore/common/query.ts @@ -86,34 +86,31 @@ function createDbQueriesFromObjectNested( path: Array = [] ): Array { const keys = Object.getOwnPropertyNames(filter) - return _.flatMap( - keys, - (key: string): Array => { - if (key === `$elemMatch`) { - const queries = createDbQueriesFromObjectNested(filter[key]) - return queries.map(query => { - return { - type: `elemMatch`, - path: path, - nestedQuery: query, - } - }) - } else if (isDbComparator(key)) { - return [ - { - type: `query`, - path, - query: { - comparator: key, - value: filter[key], - }, + return _.flatMap(keys, (key: string): Array => { + if (key === `$elemMatch`) { + const queries = createDbQueriesFromObjectNested(filter[key]) + return queries.map(query => { + return { + type: `elemMatch`, + path: path, + nestedQuery: query, + } + }) + } else if (isDbComparator(key)) { + return [ + { + type: `query`, + path, + query: { + comparator: key, + value: filter[key], }, - ] - } else { - return createDbQueriesFromObjectNested(filter[key], path.concat([key])) - } + }, + ] + } else { + return createDbQueriesFromObjectNested(filter[key], path.concat([key])) } - ) + }) } /** diff --git a/packages/gatsby/src/datastore/in-memory/indexing.ts b/packages/gatsby/src/datastore/in-memory/indexing.ts index 3e838723b586e..7d6acc42c46e5 100644 --- a/packages/gatsby/src/datastore/in-memory/indexing.ts +++ b/packages/gatsby/src/datastore/in-memory/indexing.ts @@ -107,12 +107,10 @@ function postIndexingMetaSetupLtLteGtGte( // These range checks never return `null` or `undefined` so filter those out // By filtering them out early, the sort should be faster. Could be ... - const entries: Array<[ - FilterValue, - Array - ]> = entriesNullable.filter(([v]) => v != null) as Array< - [FilterValue, Array] - > + const entries: Array<[FilterValue, Array]> = + entriesNullable.filter(([v]) => v != null) as Array< + [FilterValue, Array] + > // Sort all arrays by its value, asc. Ignore/allow potential type casting. // Note: while `<` is the inverse of `>=`, the ordering might coerce values. diff --git a/packages/gatsby/src/datastore/in-memory/run-fast-filters.ts b/packages/gatsby/src/datastore/in-memory/run-fast-filters.ts index 48fc1e918151c..53eaeddce63d6 100644 --- a/packages/gatsby/src/datastore/in-memory/run-fast-filters.ts +++ b/packages/gatsby/src/datastore/in-memory/run-fast-filters.ts @@ -101,8 +101,8 @@ export function applyFastFilters( while (nodesPerValueArrs.length > 1) { // TS limitation: cannot guard against .pop(), so we must double cast - const a = (nodesPerValueArrs.pop() as unknown) as Array - const b = (nodesPerValueArrs.pop() as unknown) as Array + const a = nodesPerValueArrs.pop() as unknown as Array + const b = nodesPerValueArrs.pop() as unknown as Array nodesPerValueArrs.push(intersectNodesByCounter(a, b)) } @@ -415,8 +415,10 @@ function sortNodes( return field } }) - const sortFns = sortFields.map(field => (v): ((any) => any) => - getValueAt(v, field) + const sortFns = sortFields.map( + field => + (v): ((any) => any) => + getValueAt(v, field) ) const sortOrder = sort.order.map(order => typeof order === `boolean` ? order : order.toLowerCase() diff --git a/packages/gatsby/src/internal-plugins/functions/gatsby-node.ts b/packages/gatsby/src/internal-plugins/functions/gatsby-node.ts index 9a3b84a3ccb8c..b89d79af4984b 100644 --- a/packages/gatsby/src/internal-plugins/functions/gatsby-node.ts +++ b/packages/gatsby/src/internal-plugins/functions/gatsby-node.ts @@ -153,37 +153,35 @@ const createWebpackConfig = async ({ // Glob and return object with relative/absolute paths + which plugin // they belong to. const allFunctions = await Promise.all( - globs.map( - async (glob): Promise> => { - const knownFunctions: Array = [] - const files = await globAsync(glob.globPattern) - files.map(file => { - const originalAbsoluteFilePath = file - const originalRelativeFilePath = path.relative(glob.rootPath, file) - - const { dir, name } = path.parse(originalRelativeFilePath) - // Ignore the original extension as all compiled functions now end with js. - const compiledFunctionName = path.join(dir, name + `.js`) - const compiledPath = path.join( - compiledFunctionsDir, - compiledFunctionName - ) - const finalName = urlResolve(dir, name === `index` ? `` : name) - - knownFunctions.push({ - functionRoute: finalName, - pluginName: glob.pluginName, - originalAbsoluteFilePath, - originalRelativeFilePath, - relativeCompiledFilePath: compiledFunctionName, - absoluteCompiledFilePath: compiledPath, - matchPath: getMatchPath(finalName), - }) + globs.map(async (glob): Promise> => { + const knownFunctions: Array = [] + const files = await globAsync(glob.globPattern) + files.map(file => { + const originalAbsoluteFilePath = file + const originalRelativeFilePath = path.relative(glob.rootPath, file) + + const { dir, name } = path.parse(originalRelativeFilePath) + // Ignore the original extension as all compiled functions now end with js. + const compiledFunctionName = path.join(dir, name + `.js`) + const compiledPath = path.join( + compiledFunctionsDir, + compiledFunctionName + ) + const finalName = urlResolve(dir, name === `index` ? `` : name) + + knownFunctions.push({ + functionRoute: finalName, + pluginName: glob.pluginName, + originalAbsoluteFilePath, + originalRelativeFilePath, + relativeCompiledFilePath: compiledFunctionName, + absoluteCompiledFilePath: compiledPath, + matchPath: getMatchPath(finalName), }) + }) - return knownFunctions - } - ) + return knownFunctions + }) ) // Combine functions by the route name so that functions in the default @@ -476,9 +474,8 @@ export async function onCreateDevServer({ async (req, res, next) => { const { "0": pathFragment } = req.params - const { - functions, - }: { functions: Array } = store.getState() + const { functions }: { functions: Array } = + store.getState() // Check first for exact matches. let functionObj = functions.find( diff --git a/packages/gatsby/src/query/__tests__/data-tracking.js b/packages/gatsby/src/query/__tests__/data-tracking.js index df56f81a37e2a..92ad2cd01c100 100644 --- a/packages/gatsby/src/query/__tests__/data-tracking.js +++ b/packages/gatsby/src/query/__tests__/data-tracking.js @@ -91,16 +91,15 @@ const setPageQueries = queries => (pageQueries = queries) let staticQueries = {} const setStaticQueries = queries => (staticQueries = queries) -const typedNodeCreator = ( - type, - { createNode, createContentDigest } -) => node => { - node.internal = { - type, - contentDigest: createContentDigest(node), +const typedNodeCreator = + (type, { createNode, createContentDigest }) => + node => { + node.internal = { + type, + contentDigest: createContentDigest(node), + } + return createNode(node) } - return createNode(node) -} const getTypedNodeCreators = ({ actions: { createNode }, @@ -144,9 +143,8 @@ const setup = async ({ restart = isFirstRun, clearCache = false } = {}) => { } jest.doMock(`../query-runner`, () => { - const { queryRunner: actualQueryRunner } = jest.requireActual( - `../query-runner` - ) + const { queryRunner: actualQueryRunner } = + jest.requireActual(`../query-runner`) return { queryRunner: jest.fn(actualQueryRunner), } @@ -339,9 +337,8 @@ describe(`query caching between builds`, () => { beforeAll(() => { setAPIhooks({ sourceNodes: (nodeApiContext, _pluginOptions) => { - const { createSiteNode, createTestNode } = getTypedNodeCreators( - nodeApiContext - ) + const { createSiteNode, createTestNode } = + getTypedNodeCreators(nodeApiContext) createTestNode({ id: `test-1`, @@ -365,11 +362,8 @@ describe(`query caching between builds`, () => { }) it(`first run - should run all queries`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup() + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup() // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -380,11 +374,8 @@ describe(`query caching between builds`, () => { }, 99999) it(`rerunning without data changes and without restart shouldn't run any queries`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup() + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup() // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -395,13 +386,10 @@ describe(`query caching between builds`, () => { }, 99999) it(`rerunning without data changes after restart shouldn't run any queries`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -412,14 +400,11 @@ describe(`query caching between builds`, () => { }, 99999) it(`rerunning after cache clearing - should run all queries`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - clearCache: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + clearCache: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -435,9 +420,8 @@ describe(`query caching between builds`, () => { beforeEach(() => { setAPIhooks({ sourceNodes: (nodeApiContext, _pluginOptions) => { - const { createSiteNode, createTestNode } = getTypedNodeCreators( - nodeApiContext - ) + const { createSiteNode, createTestNode } = + getTypedNodeCreators(nodeApiContext) createTestNode({ id: `test-1`, @@ -465,14 +449,11 @@ describe(`query caching between builds`, () => { }) it(`rerunning after cache clearing - should run all queries`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - clearCache: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + clearCache: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -483,11 +464,8 @@ describe(`query caching between builds`, () => { }, 99999) it(`reruns only static query (no restart)`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup() + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup() // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -498,13 +476,10 @@ describe(`query caching between builds`, () => { }, 999999) it(`reruns only static query (with restart)`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -520,9 +495,8 @@ describe(`query caching between builds`, () => { beforeEach(() => { setAPIhooks({ sourceNodes: (nodeApiContext, _pluginOptions) => { - const { createSiteNode, createTestNode } = getTypedNodeCreators( - nodeApiContext - ) + const { createSiteNode, createTestNode } = + getTypedNodeCreators(nodeApiContext) createTestNode({ id: `test-1`, @@ -550,14 +524,11 @@ describe(`query caching between builds`, () => { }) it(`rerunning after cache clearing - should run all queries`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - clearCache: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + clearCache: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -568,11 +539,8 @@ describe(`query caching between builds`, () => { }, 99999) it(`reruns queries only for listing and detail page that uses that node (no restart)`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup() + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup() // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -583,13 +551,10 @@ describe(`query caching between builds`, () => { }, 999999) it(`reruns queries only for listing and detail page that uses that node (with restart)`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -605,11 +570,8 @@ describe(`query caching between builds`, () => { beforeEach(() => { setAPIhooks({ sourceNodes: (nodeApiContext, _pluginOptions) => { - const { - createSiteNode, - createTestNode, - createNotUsedNode, - } = getTypedNodeCreators(nodeApiContext) + const { createSiteNode, createTestNode, createNotUsedNode } = + getTypedNodeCreators(nodeApiContext) createTestNode({ id: `test-1`, @@ -640,14 +602,11 @@ describe(`query caching between builds`, () => { }) it(`rerunning after cache clearing - should run all queries`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - clearCache: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + clearCache: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -658,11 +617,8 @@ describe(`query caching between builds`, () => { }, 99999) it(`changing node not used by anything doesn't trigger running any queries (no restart)`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup() + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup() // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -673,13 +629,10 @@ describe(`query caching between builds`, () => { }, 999999) it(`changing node not used by anything doesn't trigger running any queries (with restart)`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`, `/bar`, `/foo`]) @@ -759,9 +712,8 @@ describe(`query caching between builds`, () => { beforeAll(() => { setAPIhooks({ sourceNodes: (nodeApiContext, _pluginOptions) => { - const { createTestNode, createTestBNode } = getTypedNodeCreators( - nodeApiContext - ) + const { createTestNode, createTestBNode } = + getTypedNodeCreators(nodeApiContext) createTestNode({ id: `test-1`, @@ -900,9 +852,8 @@ describe(`query caching between builds`, () => { let nodeChangeCounter = 1 setAPIhooks({ sourceNodes: (nodeApiContext, _pluginOptions) => { - const { createTestNode, createSiteNode } = getTypedNodeCreators( - nodeApiContext - ) + const { createTestNode, createSiteNode } = + getTypedNodeCreators(nodeApiContext) createTestNode({ id: `test-1`, @@ -1066,14 +1017,11 @@ describe(`query caching between builds`, () => { const runDataDependencyClearingOnDirtyTest = ({ withRestarts }) => { it(`Initial - adds linked node dependency`, async () => { stage = `initial` - const { - staticQueriesThatRan, - pathsOfPagesWithQueriesThatRan, - pages, - } = await setup({ - restart: true, - clearCache: true, - }) + const { staticQueriesThatRan, pathsOfPagesWithQueriesThatRan, pages } = + await setup({ + restart: true, + clearCache: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`]) @@ -1084,11 +1032,8 @@ describe(`query caching between builds`, () => { it(`Removes linked data - query should be dirty`, async () => { stage = `remove-link` - const { - staticQueriesThatRan, - pathsOfPagesWithQueriesThatRan, - pages, - } = await setup({ restart: withRestarts }) + const { staticQueriesThatRan, pathsOfPagesWithQueriesThatRan, pages } = + await setup({ restart: withRestarts }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`]) @@ -1101,11 +1046,8 @@ describe(`query caching between builds`, () => { it(`No change since last run, should not rerun any queries`, async () => { stage = `unchanged` - const { - staticQueriesThatRan, - pathsOfPagesWithQueriesThatRan, - pages, - } = await setup({ restart: withRestarts }) + const { staticQueriesThatRan, pathsOfPagesWithQueriesThatRan, pages } = + await setup({ restart: withRestarts }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/`]) @@ -1298,14 +1240,11 @@ describe(`query caching between builds`, () => { }) it(`rerunning after cache clearing - should run all queries`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - clearCache: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + clearCache: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/no-dep-page`]) @@ -1316,11 +1255,8 @@ describe(`query caching between builds`, () => { }, 99999) it(`rerunning should not run any queries (no restart)`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup() + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup() // sanity check, to make sure test setup is correct expect(pages).toEqual([`/no-dep-page`]) @@ -1331,13 +1267,10 @@ describe(`query caching between builds`, () => { }, 999999) it(`rerunning should not run any queries (with restart)`, async () => { - const { - pathsOfPagesWithQueriesThatRan, - staticQueriesThatRan, - pages, - } = await setup({ - restart: true, - }) + const { pathsOfPagesWithQueriesThatRan, staticQueriesThatRan, pages } = + await setup({ + restart: true, + }) // sanity check, to make sure test setup is correct expect(pages).toEqual([`/no-dep-page`]) @@ -1403,11 +1336,8 @@ describe(`query caching between builds`, () => { ]) }, sourceNodes: nodeApiContext => { - const { - createTestNode, - createFooNode, - createBarNode, - } = getTypedNodeCreators(nodeApiContext) + const { createTestNode, createFooNode, createBarNode } = + getTypedNodeCreators(nodeApiContext) createTestNode({ id: `test-1`, diff --git a/packages/gatsby/src/query/error-parser.ts b/packages/gatsby/src/query/error-parser.ts index 7170405dcc12b..3b8c3e67a5088 100644 --- a/packages/gatsby/src/query/error-parser.ts +++ b/packages/gatsby/src/query/error-parser.ts @@ -36,7 +36,8 @@ const errorParser = ({ }, }, { - regex: /Variable "(.+)" of type "(.+)" used in position expecting type "(.+)"\./m, + regex: + /Variable "(.+)" of type "(.+)" used in position expecting type "(.+)"\./m, cb: (match): IMatch => { return { id: `85921`, @@ -50,7 +51,8 @@ const errorParser = ({ }, }, { - regex: /Field "(.+)" must not have a selection since type "(.+)" has no subfields\./m, + regex: + /Field "(.+)" must not have a selection since type "(.+)" has no subfields\./m, cb: (match): IMatch => { return { id: `85922`, diff --git a/packages/gatsby/src/query/file-parser.js b/packages/gatsby/src/query/file-parser.js index e459d255a052a..df95dfbb89847 100644 --- a/packages/gatsby/src/query/file-parser.js +++ b/packages/gatsby/src/query/file-parser.js @@ -214,9 +214,12 @@ async function findGraphQLTags( taggedTemplateExpressPath, isHook = false ) => { - const { ast: gqlAst, text, hash, isGlobal } = getGraphQLTag( - taggedTemplateExpressPath - ) + const { + ast: gqlAst, + text, + hash, + isGlobal, + } = getGraphQLTag(taggedTemplateExpressPath) if (!gqlAst) return if (isGlobal) { diff --git a/packages/gatsby/src/query/graphql-errors.js b/packages/gatsby/src/query/graphql-errors.js index e61ed69868da2..eba679375d2d4 100644 --- a/packages/gatsby/src/query/graphql-errors.js +++ b/packages/gatsby/src/query/graphql-errors.js @@ -58,7 +58,8 @@ function formatError(message: string, filePath: string, codeFrame: string) { } function extractError(error: Error): { message: string, docName: string } { - const docRegex = /Error:.(RelayParser|GraphQLParser):(.*)Source: document.`(.*)`.file.*(GraphQL.request.*^\s*$)/gms + const docRegex = + /Error:.(RelayParser|GraphQLParser):(.*)Source: document.`(.*)`.file.*(GraphQL.request.*^\s*$)/gms let matches let message = `` let docName = `` diff --git a/packages/gatsby/src/query/query-compiler.js b/packages/gatsby/src/query/query-compiler.js index 2221e23437219..9598aea6de738 100644 --- a/packages/gatsby/src/query/query-compiler.js +++ b/packages/gatsby/src/query/query-compiler.js @@ -323,14 +323,12 @@ const processDefinitions = ({ continue } - const { - usedFragments, - missingFragments, - } = determineUsedFragmentsForDefinition( - originalDefinition, - definitionsByName, - fragmentsUsedByFragment - ) + const { usedFragments, missingFragments } = + determineUsedFragmentsForDefinition( + originalDefinition, + definitionsByName, + fragmentsUsedByFragment + ) if (missingFragments.length > 0) { for (const { filePath, definition, node } of missingFragments) { diff --git a/packages/gatsby/src/redux/actions/internal.ts b/packages/gatsby/src/redux/actions/internal.ts index 926afd117a25e..ab75a4cbc7d3d 100644 --- a/packages/gatsby/src/redux/actions/internal.ts +++ b/packages/gatsby/src/redux/actions/internal.ts @@ -266,11 +266,12 @@ export const queryStart = ( } } -export const clearDirtyQueriesListToEmitViaWebsocket = (): IQueryClearDirtyQueriesListToEmitViaWebsocket => { - return { - type: `QUERY_CLEAR_DIRTY_QUERIES_LIST_TO_EMIT_VIA_WEBSOCKET`, +export const clearDirtyQueriesListToEmitViaWebsocket = + (): IQueryClearDirtyQueriesListToEmitViaWebsocket => { + return { + type: `QUERY_CLEAR_DIRTY_QUERIES_LIST_TO_EMIT_VIA_WEBSOCKET`, + } } -} /** * Remove jobs which are marked as stale (inputPath doesn't exists) @@ -358,56 +359,53 @@ export const deleteNodeManifests = (): IDeleteNodeManifests => { } } -export const createJobV2FromInternalJob = ( - internalJob: InternalJob -): ICreateJobV2FromInternalAction => ( - dispatch, - getState -): Promise> => { - const jobContentDigest = internalJob.contentDigest - const currentState = getState() - - // Check if we already ran this job before, if yes we return the result - // We have an inflight (in progress) queue inside the jobs manager to make sure - // we don't waste resources twice during the process - if ( - currentState.jobsV2 && - currentState.jobsV2.complete.has(jobContentDigest) - ) { - return Promise.resolve( - currentState.jobsV2.complete.get(jobContentDigest)!.result - ) - } - - const inProgressJobPromise = getInProcessJobPromise(jobContentDigest) - if (inProgressJobPromise) { - return inProgressJobPromise - } +export const createJobV2FromInternalJob = + (internalJob: InternalJob): ICreateJobV2FromInternalAction => + (dispatch, getState): Promise> => { + const jobContentDigest = internalJob.contentDigest + const currentState = getState() + + // Check if we already ran this job before, if yes we return the result + // We have an inflight (in progress) queue inside the jobs manager to make sure + // we don't waste resources twice during the process + if ( + currentState.jobsV2 && + currentState.jobsV2.complete.has(jobContentDigest) + ) { + return Promise.resolve( + currentState.jobsV2.complete.get(jobContentDigest)!.result + ) + } - dispatch({ - type: `CREATE_JOB_V2`, - payload: { - job: internalJob, - }, - plugin: { name: internalJob.plugin.name }, - }) + const inProgressJobPromise = getInProcessJobPromise(jobContentDigest) + if (inProgressJobPromise) { + return inProgressJobPromise + } - const enqueuedJobPromise = enqueueJob(internalJob) - return enqueuedJobPromise.then(result => { - // store the result in redux so we have it for the next run dispatch({ - type: `END_JOB_V2`, - plugin: { name: internalJob.plugin.name }, + type: `CREATE_JOB_V2`, payload: { - jobContentDigest, - result, + job: internalJob, }, + plugin: { name: internalJob.plugin.name }, }) - // remove the job from our inProgressJobQueue as it's available in our done state. - // this is a perf optimisations so we don't grow our memory too much when using gatsby preview - removeInProgressJob(jobContentDigest) + const enqueuedJobPromise = enqueueJob(internalJob) + return enqueuedJobPromise.then(result => { + // store the result in redux so we have it for the next run + dispatch({ + type: `END_JOB_V2`, + plugin: { name: internalJob.plugin.name }, + payload: { + jobContentDigest, + result, + }, + }) - return result - }) -} + // remove the job from our inProgressJobQueue as it's available in our done state. + // this is a perf optimisations so we don't grow our memory too much when using gatsby preview + removeInProgressJob(jobContentDigest) + + return result + }) + } diff --git a/packages/gatsby/src/redux/actions/public.js b/packages/gatsby/src/redux/actions/public.js index a17b73459d885..66c66597624d0 100644 --- a/packages/gatsby/src/redux/actions/public.js +++ b/packages/gatsby/src/redux/actions/public.js @@ -866,27 +866,29 @@ const createNode = ( } } -actions.createNode = (...args) => dispatch => { - const actions = createNode(...args) - - dispatch(actions) - const createNodeAction = (Array.isArray(actions) ? actions : [actions]).find( - action => action.type === `CREATE_NODE` - ) +actions.createNode = + (...args) => + dispatch => { + const actions = createNode(...args) + + dispatch(actions) + const createNodeAction = ( + Array.isArray(actions) ? actions : [actions] + ).find(action => action.type === `CREATE_NODE`) + + if (!createNodeAction) { + return undefined + } - if (!createNodeAction) { - return undefined + const { payload: node, traceId, parentSpan } = createNodeAction + return apiRunnerNode(`onCreateNode`, { + node, + traceId, + parentSpan, + traceTags: { nodeId: node.id, nodeType: node.internal.type }, + }) } - const { payload: node, traceId, parentSpan } = createNodeAction - return apiRunnerNode(`onCreateNode`, { - node, - traceId, - parentSpan, - traceTags: { nodeId: node.id, nodeType: node.internal.type }, - }) -} - const touchNodeDeprecationWarningDisplayedMessages = new Set() /** diff --git a/packages/gatsby/src/redux/actions/restricted.ts b/packages/gatsby/src/redux/actions/restricted.ts index d73742323c73a..533498cd42256 100644 --- a/packages/gatsby/src/redux/actions/restricted.ts +++ b/packages/gatsby/src/redux/actions/restricted.ts @@ -260,40 +260,42 @@ export const actions = { * }) * } */ - createFieldExtension: ( - extension: GraphQLFieldExtensionDefinition, - plugin: IGatsbyPlugin, - traceId?: string - ): ThunkAction< - void, - IGatsbyState, - Record, - ICreateFieldExtension - > => (dispatch, getState): void => { - const { name } = extension || {} - const { fieldExtensions } = getState().schemaCustomization + createFieldExtension: + ( + extension: GraphQLFieldExtensionDefinition, + plugin: IGatsbyPlugin, + traceId?: string + ): ThunkAction< + void, + IGatsbyState, + Record, + ICreateFieldExtension + > => + (dispatch, getState): void => { + const { name } = extension || {} + const { fieldExtensions } = getState().schemaCustomization - if (!name) { - report.error( - `The provided field extension must have a \`name\` property.` - ) - } else if (reservedExtensionNames.includes(name)) { - report.error( - `The field extension name \`${name}\` is reserved for internal use.` - ) - } else if (fieldExtensions[name]) { - report.error( - `A field extension with the name \`${name}\` has already been registered.` - ) - } else { - dispatch({ - type: `CREATE_FIELD_EXTENSION`, - plugin, - traceId, - payload: { name, extension }, - }) - } - }, + if (!name) { + report.error( + `The provided field extension must have a \`name\` property.` + ) + } else if (reservedExtensionNames.includes(name)) { + report.error( + `The field extension name \`${name}\` is reserved for internal use.` + ) + } else if (fieldExtensions[name]) { + report.error( + `A field extension with the name \`${name}\` has already been registered.` + ) + } else { + dispatch({ + type: `CREATE_FIELD_EXTENSION`, + plugin, + traceId, + payload: { name, extension }, + }) + } + }, /** * Write GraphQL schema to file @@ -387,56 +389,56 @@ export const actions = { * })) * } */ - createResolverContext: ( - context: IGatsbyPluginContext, - plugin: IGatsbyPlugin, - traceId?: string - ): ThunkAction< - void, - IGatsbyState, - Record, - ICreateResolverContext - > => (dispatch): void => { - if (!context || typeof context !== `object`) { - report.error( - `Expected context value passed to \`createResolverContext\` to be an object. Received "${context}".` - ) - } else { - const { name } = plugin || {} - const payload = - !name || name === `default-site-plugin` - ? context - : { [camelCase(name.replace(/^gatsby-/, ``))]: context } - dispatch({ - type: `CREATE_RESOLVER_CONTEXT`, - plugin, - traceId, - payload, - }) - } - }, + createResolverContext: + ( + context: IGatsbyPluginContext, + plugin: IGatsbyPlugin, + traceId?: string + ): ThunkAction< + void, + IGatsbyState, + Record, + ICreateResolverContext + > => + (dispatch): void => { + if (!context || typeof context !== `object`) { + report.error( + `Expected context value passed to \`createResolverContext\` to be an object. Received "${context}".` + ) + } else { + const { name } = plugin || {} + const payload = + !name || name === `default-site-plugin` + ? context + : { [camelCase(name.replace(/^gatsby-/, ``))]: context } + dispatch({ + type: `CREATE_RESOLVER_CONTEXT`, + plugin, + traceId, + payload, + }) + } + }, } -const withDeprecationWarning = ( - actionName: RestrictionActionNames, - action: SomeActionCreator, - api: API, - allowedIn: Array -): SomeActionCreator => ( - ...args: Array -): ReturnType> => { - report.warn( - `Calling \`${actionName}\` in the \`${api}\` API is deprecated. ` + - `Please use: ${allowedIn.map(a => `\`${a}\``).join(`, `)}.` - ) - return action(...args) -} +const withDeprecationWarning = + ( + actionName: RestrictionActionNames, + action: SomeActionCreator, + api: API, + allowedIn: Array + ): SomeActionCreator => + (...args: Array): ReturnType> => { + report.warn( + `Calling \`${actionName}\` in the \`${api}\` API is deprecated. ` + + `Please use: ${allowedIn.map(a => `\`${a}\``).join(`, `)}.` + ) + return action(...args) + } -const withErrorMessage = ( - actionName: RestrictionActionNames, - api: API, - allowedIn: Array -) => () => +const withErrorMessage = + (actionName: RestrictionActionNames, api: API, allowedIn: Array) => + () => // return a thunk that does not dispatch anything (): void => { report.error( diff --git a/packages/gatsby/src/redux/index.ts b/packages/gatsby/src/redux/index.ts index cd22eb64e21c8..7a8c9780e6203 100644 --- a/packages/gatsby/src/redux/index.ts +++ b/packages/gatsby/src/redux/index.ts @@ -71,10 +71,11 @@ export interface IMultiDispatch { /** * Redux middleware handling array of actions */ -const multi: Middleware = ({ dispatch }) => next => ( - action: ActionsUnion -): ActionsUnion | Array => - Array.isArray(action) ? action.filter(Boolean).map(dispatch) : next(action) +const multi: Middleware = + ({ dispatch }) => + next => + (action: ActionsUnion): ActionsUnion | Array => + Array.isArray(action) ? action.filter(Boolean).map(dispatch) : next(action) export type GatsbyReduxStore = Store & { dispatch: ThunkDispatch & IMultiDispatch diff --git a/packages/gatsby/src/redux/reducers/html.ts b/packages/gatsby/src/redux/reducers/html.ts index f0e55ce8a70ad..c5d44cec7fa4f 100644 --- a/packages/gatsby/src/redux/reducers/html.ts +++ b/packages/gatsby/src/redux/reducers/html.ts @@ -196,9 +196,8 @@ export function htmlReducer( // mark static queries as not dirty anymore (we flushed their dirtiness into pages) for (const staticQueryHash of action.payload.staticQueryHashes) { - const staticQueryResult = state.trackedStaticQueryResults.get( - staticQueryHash - ) + const staticQueryResult = + state.trackedStaticQueryResults.get(staticQueryHash) if (staticQueryResult) { staticQueryResult.dirty = 0 } diff --git a/packages/gatsby/src/schema/__tests__/node-model.js b/packages/gatsby/src/schema/__tests__/node-model.js index 9fc7a4825cad9..bcec78f2abec2 100644 --- a/packages/gatsby/src/schema/__tests__/node-model.js +++ b/packages/gatsby/src/schema/__tests__/node-model.js @@ -1223,9 +1223,8 @@ describe(`NodeModel`, () => { it(`Doesn't track copied objects`, () => { const node = nodeModel.getNodeById({ id: `id1` }) const copiedInlineObject = { ...node.inlineObject } - const trackedRootNode = nodeModel.findRootNodeAncestor( - copiedInlineObject - ) + const trackedRootNode = + nodeModel.findRootNodeAncestor(copiedInlineObject) expect(trackedRootNode).not.toEqual(node) }) @@ -1249,9 +1248,8 @@ describe(`NodeModel`, () => { it(`Doesn't track copied objects`, () => { const node = nodeModel.getNodesByIds({ ids: [`id1`] })[0] const copiedInlineObject = { ...node.inlineObject } - const trackedRootNode = nodeModel.findRootNodeAncestor( - copiedInlineObject - ) + const trackedRootNode = + nodeModel.findRootNodeAncestor(copiedInlineObject) expect(trackedRootNode).not.toEqual(node) }) @@ -1275,9 +1273,8 @@ describe(`NodeModel`, () => { it(`Doesn't track copied objects`, () => { const node = nodeModel.getAllNodes({ type: `Test` })[0] const copiedInlineObject = { ...node.inlineObject } - const trackedRootNode = nodeModel.findRootNodeAncestor( - copiedInlineObject - ) + const trackedRootNode = + nodeModel.findRootNodeAncestor(copiedInlineObject) expect(trackedRootNode).not.toEqual(node) }) diff --git a/packages/gatsby/src/schema/__tests__/run-query.js b/packages/gatsby/src/schema/__tests__/run-query.js index 3c1b5937be21f..f05d8caa88e13 100644 --- a/packages/gatsby/src/schema/__tests__/run-query.js +++ b/packages/gatsby/src/schema/__tests__/run-query.js @@ -764,15 +764,7 @@ describe(`Filter fields`, () => { // Note: needle property ranges from 1 to 99 or 100. Needles should not exist, otherwise binary search // is skipped entirely. This test is trying to verify the op when the needle misses with ~100 nodes. for (const needle of [ - 0, - 1.5, - 33.5, - 49.5, - 50.5, - 66.5, - 98.5, - 99.5, - 100.5, + 0, 1.5, 33.5, 49.5, 50.5, 66.5, 98.5, 99.5, 100.5, ]) { it(`should pivot upward when needle does not exist, needle=${needle}`, async () => { // This caught a bug in the binary search algo which was incorrectly generating the next pivot index. @@ -865,15 +857,7 @@ describe(`Filter fields`, () => { // Note: needle property ranges from 1 to 99 or 100. Needles should not exist, otherwise binary search // is skipped entirely. This test is trying to verify the op when the needle misses with ~100 nodes. for (const needle of [ - 0, - 1.5, - 33.5, - 49.5, - 50.5, - 66.5, - 98.5, - 99.5, - 100.5, + 0, 1.5, 33.5, 49.5, 50.5, 66.5, 98.5, 99.5, 100.5, ]) { it(`should pivot upward when needle does not exist, needle=${needle}`, async () => { // This caught a bug in the binary search algo which was incorrectly generating the next pivot index. @@ -966,15 +950,7 @@ describe(`Filter fields`, () => { // Note: needle property ranges from 1 to 99 or 100. Needles should not exist, otherwise binary search // is skipped entirely. This test is trying to verify the op when the needle misses with ~100 nodes. for (const needle of [ - 0, - 1.5, - 33.5, - 49.5, - 50.5, - 66.5, - 98.5, - 99.5, - 100.5, + 0, 1.5, 33.5, 49.5, 50.5, 66.5, 98.5, 99.5, 100.5, ]) { it(`should pivot upward when needle does not exist, needle=${needle}`, async () => { // This caught a bug in the binary search algo which was incorrectly generating the next pivot index. @@ -1068,15 +1044,7 @@ describe(`Filter fields`, () => { // Note: needle property ranges from 1 to 99 or 100. Needles should not exist, otherwise binary search // is skipped entirely. This test is trying to verify the op when the needle misses with ~100 nodes. for (const needle of [ - 0, - 1.5, - 33.5, - 49.5, - 50.5, - 66.5, - 98.5, - 99.5, - 100.5, + 0, 1.5, 33.5, 49.5, 50.5, 66.5, 98.5, 99.5, 100.5, ]) { it(`should pivot upward when needle does not exist, needle=${needle}`, async () => { // This caught a bug in the binary search algo which was incorrectly generating the next pivot index. diff --git a/packages/gatsby/src/schema/infer/__tests__/inference-metadata.ts b/packages/gatsby/src/schema/infer/__tests__/inference-metadata.ts index de03708492ece..31c34ad10ea36 100644 --- a/packages/gatsby/src/schema/infer/__tests__/inference-metadata.ts +++ b/packages/gatsby/src/schema/infer/__tests__/inference-metadata.ts @@ -772,7 +772,7 @@ describe(`Get example value for type inference`, () => { }, }, ] - const nodes = (_nodes as unknown) as Array + const nodes = _nodes as unknown as Array it(`updates example value when nodes are added`, () => { let inferenceMetadata = { typeName: `IncrementalExampleValue`, diff --git a/packages/gatsby/src/schema/infer/build-example-data.ts b/packages/gatsby/src/schema/infer/build-example-data.ts index 08dee49810511..22179149d01d6 100644 --- a/packages/gatsby/src/schema/infer/build-example-data.ts +++ b/packages/gatsby/src/schema/infer/build-example-data.ts @@ -205,8 +205,8 @@ const hasOnlyEmptyStrings = (descriptor: IValueDescriptor): boolean => { } const possibleTypes = (descriptor: IValueDescriptor = {}): Array => - Object.keys(descriptor).filter(type => descriptor[type].total > 0) as Array< - ValueType - > + Object.keys(descriptor).filter( + type => descriptor[type].total > 0 + ) as Array export { getExampleObject } diff --git a/packages/gatsby/src/schema/infer/inference-metadata.ts b/packages/gatsby/src/schema/infer/inference-metadata.ts index 7f67cb72593b4..b707c55212067 100644 --- a/packages/gatsby/src/schema/infer/inference-metadata.ts +++ b/packages/gatsby/src/schema/infer/inference-metadata.ts @@ -487,9 +487,9 @@ const addNodes = ( } const possibleTypes = (descriptor: IValueDescriptor = {}): Array => - Object.keys(descriptor).filter(type => descriptor[type].total > 0) as Array< - ValueType - > + Object.keys(descriptor).filter( + type => descriptor[type].total > 0 + ) as Array const isEmpty = ({ fieldMap }): boolean => Object.keys(fieldMap).every( diff --git a/packages/gatsby/src/schema/infer/is-file.ts b/packages/gatsby/src/schema/infer/is-file.ts index 1c9799f6338ed..cee0696a3dafb 100644 --- a/packages/gatsby/src/schema/infer/is-file.ts +++ b/packages/gatsby/src/schema/infer/is-file.ts @@ -18,8 +18,10 @@ const getFirstValueAt = ( return value } -const withBaseDir = (dir: string) => (p: string): string => - path.posix.join(dir, slash(p)) +const withBaseDir = + (dir: string) => + (p: string): string => + path.posix.join(dir, slash(p)) const findAncestorNode = ( childNode: IGatsbyNode, diff --git a/packages/gatsby/src/schema/resolvers.ts b/packages/gatsby/src/schema/resolvers.ts index 55c35e0135ae3..ab2cc4519f1f5 100644 --- a/packages/gatsby/src/schema/resolvers.ts +++ b/packages/gatsby/src/schema/resolvers.ts @@ -598,31 +598,29 @@ function getFieldNodeByNameInSelectionSet( ) } -export const defaultFieldResolver: GatsbyResolver< - any, - any -> = function defaultFieldResolver(source, args, context, info) { - if ( - (typeof source == `object` && source !== null) || - typeof source === `function` - ) { - if (info.from) { - if (info.fromNode) { - const node = context.nodeModel.findRootNodeAncestor(source) - if (!node) return null - return getValueAt(node, info.from) +export const defaultFieldResolver: GatsbyResolver = + function defaultFieldResolver(source, args, context, info) { + if ( + (typeof source == `object` && source !== null) || + typeof source === `function` + ) { + if (info.from) { + if (info.fromNode) { + const node = context.nodeModel.findRootNodeAncestor(source) + if (!node) return null + return getValueAt(node, info.from) + } + return getValueAt(source, info.from) } - return getValueAt(source, info.from) - } - const property = source[info.fieldName] - if (typeof property === `function`) { - return source[info.fieldName](args, context, info) + const property = source[info.fieldName] + if (typeof property === `function`) { + return source[info.fieldName](args, context, info) + } + return property } - return property - } - return null -} + return null + } let WARNED_ABOUT_RESOLVERS = false function badResolverInvocationMessage(missingVar: string, path?: Path): string { diff --git a/packages/gatsby/src/schema/schema-composer.ts b/packages/gatsby/src/schema/schema-composer.ts index e01092e3d02d3..a6b7a0f32ada6 100644 --- a/packages/gatsby/src/schema/schema-composer.ts +++ b/packages/gatsby/src/schema/schema-composer.ts @@ -9,10 +9,8 @@ export const createSchemaComposer = ({ }: GraphQLFieldExtensionDefinition = {}): SchemaComposer< IGatsbyResolverContext > => { - const schemaComposer: SchemaComposer> = new SchemaComposer() + const schemaComposer: SchemaComposer> = + new SchemaComposer() getNodeInterface({ schemaComposer }) schemaComposer.add(GraphQLDate) diff --git a/packages/gatsby/src/schema/types/date.ts b/packages/gatsby/src/schema/types/date.ts index 248ba66527747..603b786bf1015 100644 --- a/packages/gatsby/src/schema/types/date.ts +++ b/packages/gatsby/src/schema/types/date.ts @@ -114,7 +114,8 @@ export const GraphQLDate = new GraphQLScalarType({ }, }) -const momentFormattingTokens = /(\[[^[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g +const momentFormattingTokens = + /(\[[^[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g const momentFormattingRegexes = { YYYY: `\\d{4}`, MM: `\\d{2}`, diff --git a/packages/gatsby/src/schema/types/pagination.ts b/packages/gatsby/src/schema/types/pagination.ts index 9d30d4ff17b30..d393b62ba5fdb 100644 --- a/packages/gatsby/src/schema/types/pagination.ts +++ b/packages/gatsby/src/schema/types/pagination.ts @@ -55,9 +55,8 @@ const createPagination = ({ fields: ObjectTypeComposerFieldConfigMapDefinition typeName: string }): ObjectTypeComposer => { - const paginationTypeComposer: ObjectTypeComposer = schemaComposer.getOrCreateOTC( - typeName, - tc => { + const paginationTypeComposer: ObjectTypeComposer = + schemaComposer.getOrCreateOTC(typeName, tc => { tc.addFields({ totalCount: `Int!`, edges: [getEdge({ schemaComposer, typeComposer }).getTypeNonNull()], @@ -65,8 +64,7 @@ const createPagination = ({ pageInfo: getPageInfo({ schemaComposer }).getTypeNonNull(), ...fields, }) - } - ) + }) paginationTypeComposer.makeFieldNonNull(`edges`) paginationTypeComposer.makeFieldNonNull(`nodes`) addDerivedType({ typeComposer, derivedTypeName: typeName }) @@ -95,7 +93,8 @@ export const getPagination = ({ schemaComposer: SchemaComposer typeComposer: ObjectTypeComposer | InterfaceTypeComposer }): ObjectTypeComposer => { - const inputTypeComposer: InputTypeComposer = typeComposer.getInputTypeComposer() + const inputTypeComposer: InputTypeComposer = + typeComposer.getInputTypeComposer() const typeName = `${typeComposer.getTypeName()}Connection` const fieldsEnumTC = getFieldsEnum({ schemaComposer, diff --git a/packages/gatsby/src/schema/types/sort.ts b/packages/gatsby/src/schema/types/sort.ts index 4a8e29f83103f..f850cb4c18253 100644 --- a/packages/gatsby/src/schema/types/sort.ts +++ b/packages/gatsby/src/schema/types/sort.ts @@ -129,9 +129,8 @@ export const getFieldsEnum = ({ }): EnumTypeComposer => { const typeName = typeComposer.getTypeName() const fieldsEnumTypeName = `${typeName}FieldsEnum` - const fieldsEnumTypeComposer = schemaComposer.getOrCreateETC( - fieldsEnumTypeName - ) + const fieldsEnumTypeComposer = + schemaComposer.getOrCreateETC(fieldsEnumTypeName) addDerivedType({ typeComposer, derivedTypeName: fieldsEnumTypeName }) const fields = convert({ diff --git a/packages/gatsby/src/services/listen-to-webpack.ts b/packages/gatsby/src/services/listen-to-webpack.ts index bfba134880752..c898a8fe8a860 100644 --- a/packages/gatsby/src/services/listen-to-webpack.ts +++ b/packages/gatsby/src/services/listen-to-webpack.ts @@ -2,11 +2,11 @@ import { Compiler } from "webpack" import { InvokeCallback } from "xstate" import reporter from "gatsby-cli/lib/reporter" -export const createWebpackWatcher = (compiler: Compiler): InvokeCallback => ( - callback -): void => { - compiler.hooks.invalid.tap(`file invalidation`, file => { - reporter.verbose(`Webpack file changed: ${file}`) - callback({ type: `SOURCE_FILE_CHANGED`, file }) - }) -} +export const createWebpackWatcher = + (compiler: Compiler): InvokeCallback => + (callback): void => { + compiler.hooks.invalid.tap(`file invalidation`, file => { + reporter.verbose(`Webpack file changed: ${file}`) + callback({ type: `SOURCE_FILE_CHANGED`, file }) + }) + } diff --git a/packages/gatsby/src/services/start-webpack-server.ts b/packages/gatsby/src/services/start-webpack-server.ts index 1d7a728dedd90..647ae186a2245 100644 --- a/packages/gatsby/src/services/start-webpack-server.ts +++ b/packages/gatsby/src/services/start-webpack-server.ts @@ -70,70 +70,70 @@ export async function startWebpackServer({ let isFirstCompile = true return new Promise(resolve => { - compiler.hooks.done.tapAsync(`print gatsby instructions`, async function ( - stats, - done - ) { - if (isFirstCompile) { - webpackWatching.suspend() - } - - if (cancelDevJSNotice) { - cancelDevJSNotice() - } + compiler.hooks.done.tapAsync( + `print gatsby instructions`, + async function (stats, done) { + if (isFirstCompile) { + webpackWatching.suspend() + } - const urls = prepareUrls( - program.https ? `https` : `http`, - program.host, - program.proxyPort - ) - const isSuccessful = !stats.hasErrors() + if (cancelDevJSNotice) { + cancelDevJSNotice() + } - if (isSuccessful && isFirstCompile) { - // Show notices to users about potential experiments/feature flags they could - // try. - showExperimentNotices() - printInstructions( - program.sitePackageJson.name || `(Unnamed package)`, - urls + const urls = prepareUrls( + program.https ? `https` : `http`, + program.host, + program.proxyPort ) - printDeprecationWarnings() - if (program.open) { - try { - await openurl(urls.localUrlForBrowser) - } catch { - console.log( - `${chalk.yellow( - `warn` - )} Browser not opened because no browser was found` - ) + const isSuccessful = !stats.hasErrors() + + if (isSuccessful && isFirstCompile) { + // Show notices to users about potential experiments/feature flags they could + // try. + showExperimentNotices() + printInstructions( + program.sitePackageJson.name || `(Unnamed package)`, + urls + ) + printDeprecationWarnings() + if (program.open) { + try { + await openurl(urls.localUrlForBrowser) + } catch { + console.log( + `${chalk.yellow( + `warn` + )} Browser not opened because no browser was found` + ) + } } } - } - isFirstCompile = false + isFirstCompile = false - if (webpackActivity) { - if (stats.hasWarnings()) { - const rawMessages = stats.toJson({ moduleTrace: false }) - reportWebpackWarnings(rawMessages.warnings, report) - } + if (webpackActivity) { + if (stats.hasWarnings()) { + const rawMessages = stats.toJson({ moduleTrace: false }) + reportWebpackWarnings(rawMessages.warnings, report) + } - if (!isSuccessful) { - const errors = structureWebpackErrors( - Stage.Develop, - stats.compilation.errors - ) - webpackActivity.panicOnBuild(errors) + if (!isSuccessful) { + const errors = structureWebpackErrors( + Stage.Develop, + stats.compilation.errors + ) + webpackActivity.panicOnBuild(errors) + } + webpackActivity.end() + webpackActivity = null } - webpackActivity.end() - webpackActivity = null - } - markWebpackStatusAsDone() - done() - emitter.emit(`COMPILATION_DONE`, stats) - resolve({ compiler, websocketManager, webpackWatching }) - }) + markWebpackStatusAsDone() + done() + emitter.emit(`COMPILATION_DONE`, stats) + resolve({ compiler, websocketManager, webpackWatching }) + } + ) }) } diff --git a/packages/gatsby/src/state-machines/query-running/actions.ts b/packages/gatsby/src/state-machines/query-running/actions.ts index 766900c732223..e05c2b2a2c9e2 100644 --- a/packages/gatsby/src/state-machines/query-running/actions.ts +++ b/packages/gatsby/src/state-machines/query-running/actions.ts @@ -42,11 +42,10 @@ export const trackRequestedQueryRun = assign< }, }) -export const clearCurrentlyHandledPendingQueryRuns = assign< - IQueryRunningContext ->({ - currentlyHandledPendingQueryRuns: undefined, -}) +export const clearCurrentlyHandledPendingQueryRuns = + assign({ + currentlyHandledPendingQueryRuns: undefined, + }) export const queryActions: ActionFunctionMap = { assignDirtyQueries, diff --git a/packages/gatsby/src/utils/__tests__/feedback.ts b/packages/gatsby/src/utils/__tests__/feedback.ts index b59f8d546ccb9..fb096a9cb969e 100644 --- a/packages/gatsby/src/utils/__tests__/feedback.ts +++ b/packages/gatsby/src/utils/__tests__/feedback.ts @@ -17,9 +17,10 @@ jest.mock(`gatsby-core-utils`, () => { } }) -jest.mock(`latest-version`, (): (() => Promise) => (): Promise< - string -> => Promise.resolve(`2.1.1`)) +jest.mock( + `latest-version`, + (): (() => Promise) => (): Promise => Promise.resolve(`2.1.1`) +) const dateFromSixMonthsAgo = new Date() dateFromSixMonthsAgo.setMonth(dateFromSixMonthsAgo.getMonth() - 6) diff --git a/packages/gatsby/src/utils/__tests__/get-page-data.ts b/packages/gatsby/src/utils/__tests__/get-page-data.ts index 70596da95393d..c72efb038a541 100644 --- a/packages/gatsby/src/utils/__tests__/get-page-data.ts +++ b/packages/gatsby/src/utils/__tests__/get-page-data.ts @@ -19,27 +19,21 @@ let MOCK_LMDBCACHE_INFO = {} jest.mock(`fs-extra`, () => { return { - readFile: jest.fn( - async (path: string): Promise => { - if (MOCK_FILE_INFO[path]) { - return MOCK_FILE_INFO[path] - } - throw new Error(`Cannot read file "${path}"`) - } - ), - readJSON: jest.fn( - async (path: string): Promise => { - if (MOCK_FILE_INFO[path]) { - return JSON.parse(MOCK_FILE_INFO[path]) - } - throw new Error(`Cannot read file "${path}"`) + readFile: jest.fn(async (path: string): Promise => { + if (MOCK_FILE_INFO[path]) { + return MOCK_FILE_INFO[path] } - ), - outputFile: jest.fn( - async (path: string, content: string): Promise => { - MOCK_FILE_INFO[path] = content + throw new Error(`Cannot read file "${path}"`) + }), + readJSON: jest.fn(async (path: string): Promise => { + if (MOCK_FILE_INFO[path]) { + return JSON.parse(MOCK_FILE_INFO[path]) } - ), + throw new Error(`Cannot read file "${path}"`) + }), + outputFile: jest.fn(async (path: string, content: string): Promise => { + MOCK_FILE_INFO[path] = content + }), } }) diff --git a/packages/gatsby/src/utils/__tests__/sample-site-for-experiment.ts b/packages/gatsby/src/utils/__tests__/sample-site-for-experiment.ts index e024918e8ebe7..0c261fc3016a4 100644 --- a/packages/gatsby/src/utils/__tests__/sample-site-for-experiment.ts +++ b/packages/gatsby/src/utils/__tests__/sample-site-for-experiment.ts @@ -4,7 +4,7 @@ import { getRepositoryId, IRepositoryId, } from "gatsby-telemetry/lib/repository-id" -;((getRepositoryId as unknown) as jest.Mock).mockReturnValue({ +;(getRepositoryId as unknown as jest.Mock).mockReturnValue({ repositoryId: `mockId`, }) diff --git a/packages/gatsby/src/utils/__tests__/test-require-error.ts b/packages/gatsby/src/utils/__tests__/test-require-error.ts index 9d3eaf42497c8..5414588916c73 100644 --- a/packages/gatsby/src/utils/__tests__/test-require-error.ts +++ b/packages/gatsby/src/utils/__tests__/test-require-error.ts @@ -48,7 +48,8 @@ describe(`test-require-error`, () => { describe(`handles error message thrown by Bazel`, () => { it(`detects require errors`, () => { - const bazelModuleNotFoundError = new Error(`Error: //:build_bin cannot find module './fixtures/module-does-not-exist' required by '/private/var/tmp/_bazel_misiek/eba1803983a26276494495d851e478a5/execroot/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/bazel-out/darwin-fastbuild/bin/build.runfiles/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/node_modules/gatsby/dist/bootstrap/get-config-file.js' + const bazelModuleNotFoundError = + new Error(`Error: //:build_bin cannot find module './fixtures/module-does-not-exist' required by '/private/var/tmp/_bazel_misiek/eba1803983a26276494495d851e478a5/execroot/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/bazel-out/darwin-fastbuild/bin/build.runfiles/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/node_modules/gatsby/dist/bootstrap/get-config-file.js' looked in: built-in, relative, absolute, nested node_modules - Error: Cannot find module './fixtures/module-does-not-exist' runfiles - Error: Cannot find module '/private/var/tmp/_bazel_misiek/eba1803983a26276494495d851e478a5/execroot/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/bazel-out/darwin-fastbuild/bin/build.runfiles/fixtures/module-does-not-exist' @@ -63,7 +64,8 @@ describe(`test-require-error`, () => { }) it(`detects require errors`, () => { - const bazelModuleNotFoundError = new Error(`Error: //:build_bin cannot find module 'cheese' required by '/private/var/tmp/_bazel_misiek/eba1803983a26276494495d851e478a5/execroot/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/bazel-out/darwin-fastbuild/bin/build.runfiles/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/node_modules/gatsby/dist/bootstrap/fixtures/bad-module-require.js' + const bazelModuleNotFoundError = + new Error(`Error: //:build_bin cannot find module 'cheese' required by '/private/var/tmp/_bazel_misiek/eba1803983a26276494495d851e478a5/execroot/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/bazel-out/darwin-fastbuild/bin/build.runfiles/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/node_modules/gatsby/dist/bootstrap/fixtures/bad-module-require.js' looked in: built-in, relative, absolute, nested node_modules - Error: Cannot find module 'cheese' runfiles - Error: Cannot find module '/private/var/tmp/_bazel_misiek/eba1803983a26276494495d851e478a5/execroot/com_github_bweston92_debug_gatsby_bazel_rules_nodejs/bazel-out/darwin-fastbuild/bin/build.runfiles/cheese' diff --git a/packages/gatsby/src/utils/api-runner-node.js b/packages/gatsby/src/utils/api-runner-node.js index 172a4ae538857..b680d3a2556dd 100644 --- a/packages/gatsby/src/utils/api-runner-node.js +++ b/packages/gatsby/src/utils/api-runner-node.js @@ -86,23 +86,25 @@ const initAPICallTracing = parentSpan => { } } -const deferredAction = type => (...args) => { - // Regular createNode returns a Promise, but when deferred we need - // to wrap it in another which we resolve when it's actually called - if (type === `createNode`) { - return new Promise(resolve => { - emitter.emit(`ENQUEUE_NODE_MUTATION`, { - type, - payload: args, - resolve, +const deferredAction = + type => + (...args) => { + // Regular createNode returns a Promise, but when deferred we need + // to wrap it in another which we resolve when it's actually called + if (type === `createNode`) { + return new Promise(resolve => { + emitter.emit(`ENQUEUE_NODE_MUTATION`, { + type, + payload: args, + resolve, + }) }) + } + return emitter.emit(`ENQUEUE_NODE_MUTATION`, { + type, + payload: args, }) } - return emitter.emit(`ENQUEUE_NODE_MUTATION`, { - type, - payload: args, - }) -} const NODE_MUTATION_ACTIONS = [ `createNode`, diff --git a/packages/gatsby/src/utils/cache-lmdb.ts b/packages/gatsby/src/utils/cache-lmdb.ts index ba2f07653034f..08ab4abdd8a34 100644 --- a/packages/gatsby/src/utils/cache-lmdb.ts +++ b/packages/gatsby/src/utils/cache-lmdb.ts @@ -75,6 +75,6 @@ export default class GatsbyCacheLmdb { } async del(key: string): Promise { - return (this.getDb().remove(key) as unknown) as Promise + return this.getDb().remove(key) as unknown as Promise } } diff --git a/packages/gatsby/src/utils/eslint-rules/limited-exports-page-templates.ts b/packages/gatsby/src/utils/eslint-rules/limited-exports-page-templates.ts index 6bfd10af28346..fb17a62a48c0b 100644 --- a/packages/gatsby/src/utils/eslint-rules/limited-exports-page-templates.ts +++ b/packages/gatsby/src/utils/eslint-rules/limited-exports-page-templates.ts @@ -104,38 +104,40 @@ const limitedExports: Rule.RuleModule = { // const { graphql } = require('gatsby') VariableDeclaration: (node): void => { // Check if require('gatsby') - const requiredFromGatsby = (node as VariableDeclaration).declarations.find( - el => { - // Handle require(`gatsby`) - if ( - (el.init as CallExpression)?.arguments?.[0]?.type === - `TemplateLiteral` - ) { - return ( - ((el.init as CallExpression).arguments[0] as TemplateLiteral) - ?.quasis[0].value.raw === `gatsby` - ) - } - + const requiredFromGatsby = ( + node as VariableDeclaration + ).declarations.find(el => { + // Handle require(`gatsby`) + if ( + (el.init as CallExpression)?.arguments?.[0]?.type === + `TemplateLiteral` + ) { return ( - ((el.init as CallExpression)?.arguments?.[0] as Literal) - ?.value === `gatsby` + ((el.init as CallExpression).arguments[0] as TemplateLiteral) + ?.quasis[0].value.raw === `gatsby` ) } - ) + + return ( + ((el.init as CallExpression)?.arguments?.[0] as Literal)?.value === + `gatsby` + ) + }) if (requiredFromGatsby) { // Search for "graphql" in a const { graphql, Link } = require('gatsby') - const graphqlTagSpecifier = ((requiredFromGatsby as VariableDeclarator) - .id as ObjectPattern)?.properties.find( + const graphqlTagSpecifier = ( + (requiredFromGatsby as VariableDeclarator).id as ObjectPattern + )?.properties.find( el => ((el as AssignmentProperty).key as Identifier).name === DEFAULT_GRAPHQL_TAG_NAME ) if (graphqlTagSpecifier) { - graphqlTagName = ((graphqlTagSpecifier as AssignmentProperty) - .value as Identifier).name + graphqlTagName = ( + (graphqlTagSpecifier as AssignmentProperty).value as Identifier + ).name } } @@ -145,22 +147,22 @@ const limitedExports: Rule.RuleModule = { ImportDeclaration: (node): void => { // Make sure that the specifier is imported from "gatsby" if ((node as ImportDeclaration).source.value === `gatsby`) { - const graphqlTagSpecifier = (node as ImportDeclaration).specifiers.find( - el => { - // We only want import { graphql } from "gatsby" - // Not import graphql from "gatsby" - if (el.type === `ImportSpecifier`) { - // Only get the specifier with the original name of "graphql" - return el.imported.name === DEFAULT_GRAPHQL_TAG_NAME - } - // import * as Gatsby from "gatsby" - if (el.type === `ImportNamespaceSpecifier`) { - namespaceSpecifierName = el.local.name - return false - } + const graphqlTagSpecifier = ( + node as ImportDeclaration + ).specifiers.find(el => { + // We only want import { graphql } from "gatsby" + // Not import graphql from "gatsby" + if (el.type === `ImportSpecifier`) { + // Only get the specifier with the original name of "graphql" + return el.imported.name === DEFAULT_GRAPHQL_TAG_NAME + } + // import * as Gatsby from "gatsby" + if (el.type === `ImportNamespaceSpecifier`) { + namespaceSpecifierName = el.local.name return false } - ) + return false + }) if (graphqlTagSpecifier) { // The local.name handles the case for import { graphql as otherName } // For normal import { graphql } the imported & local name are the same diff --git a/packages/gatsby/src/utils/node-manifest.ts b/packages/gatsby/src/utils/node-manifest.ts index 64636636b00b9..d947f17bc07bb 100644 --- a/packages/gatsby/src/utils/node-manifest.ts +++ b/packages/gatsby/src/utils/node-manifest.ts @@ -40,11 +40,7 @@ type FoundPageBy = * When this fn is being used for routing to previews the user wont necessarily have * visited the page in the browser yet. */ -async function findPageOwnedByNodeId({ - nodeId, -}: { - nodeId: string -}): Promise<{ +async function findPageOwnedByNodeId({ nodeId }: { nodeId: string }): Promise<{ page: INodeManifestPage foundPageBy: FoundPageBy }> { @@ -90,11 +86,13 @@ async function findPageOwnedByNodeId({ break } - const path = (usingPagesMap - ? // in development we're using a Map, so the value here is a page object - (pathOrPageObject as IGatsbyPage).path - : // in builds we're using a Set so the page path is the value - pathOrPageObject) as string + const path = ( + usingPagesMap + ? // in development we're using a Map, so the value here is a page object + (pathOrPageObject as IGatsbyPage).path + : // in builds we're using a Set so the page path is the value + pathOrPageObject + ) as string const fullPage: IGatsbyPage | undefined = pages.get(path) @@ -105,8 +103,9 @@ async function findPageOwnedByNodeId({ if (foundOwnerNodeId) { foundPageBy = `ownerNodeId` } else if (foundPageIdInContext && fullPage) { - const pageCreatedByPluginName = nodes.get(fullPage.pluginCreatorId) - ?.name + const pageCreatedByPluginName = nodes.get( + fullPage.pluginCreatorId + )?.name const pageCreatedByFilesystemPlugin = pageCreatedByPluginName === `gatsby-plugin-page-creator` diff --git a/packages/gatsby/src/utils/path.ts b/packages/gatsby/src/utils/path.ts index 69c6545c96748..4d8785990a937 100644 --- a/packages/gatsby/src/utils/path.ts +++ b/packages/gatsby/src/utils/path.ts @@ -1,9 +1,10 @@ import path from "path" import { joinPath, createContentDigest } from "gatsby-core-utils" -export const withBasePath = (basePath: string) => ( - ...paths: Array -): string => joinPath(basePath, ...paths) +export const withBasePath = + (basePath: string) => + (...paths: Array): string => + joinPath(basePath, ...paths) export const withTrailingSlash = (basePath: string): string => `${basePath}/` diff --git a/packages/gatsby/src/utils/start-server.ts b/packages/gatsby/src/utils/start-server.ts index a983af9db3473..c0ce6ecfe2491 100644 --- a/packages/gatsby/src/utils/start-server.ts +++ b/packages/gatsby/src/utils/start-server.ts @@ -213,43 +213,41 @@ module.exports = { app.use( graphqlEndpoint, - graphqlHTTP( - (): OptionsData => { - const { schema, schemaCustomization } = store.getState() + graphqlHTTP((): OptionsData => { + const { schema, schemaCustomization } = store.getState() - if (!schemaCustomization.composer) { - throw new Error( - `A schema composer was not created in time. This is likely a gatsby bug. If you experienced this please create an issue.` - ) - } - return { + if (!schemaCustomization.composer) { + throw new Error( + `A schema composer was not created in time. This is likely a gatsby bug. If you experienced this please create an issue.` + ) + } + return { + schema, + graphiql: false, + extensions(): { [key: string]: unknown } { + return { + enableRefresh: process.env.ENABLE_GATSBY_REFRESH_ENDPOINT, + refreshToken: process.env.GATSBY_REFRESH_TOKEN, + } + }, + context: withResolverContext({ schema, - graphiql: false, - extensions(): { [key: string]: unknown } { - return { - enableRefresh: process.env.ENABLE_GATSBY_REFRESH_ENDPOINT, - refreshToken: process.env.GATSBY_REFRESH_TOKEN, - } - }, - context: withResolverContext({ - schema, - schemaComposer: schemaCustomization.composer, - context: {}, - customContext: schemaCustomization.context, - }), - customFormatErrorFn( - err - ): GraphQLFormattedError<{ stack: Array }> { - return { - ...formatError(err), - extensions: { - stack: err.stack ? err.stack.split(`\n`) : [], - }, - } - }, - } + schemaComposer: schemaCustomization.composer, + context: {}, + customContext: schemaCustomization.context, + }), + customFormatErrorFn( + err + ): GraphQLFormattedError<{ stack: Array }> { + return { + ...formatError(err), + extensions: { + stack: err.stack ? err.stack.split(`\n`) : [], + }, + } + }, } - ) + }) ) /** diff --git a/packages/gatsby/src/utils/webpack-error-utils.ts b/packages/gatsby/src/utils/webpack-error-utils.ts index d35e7d647ac31..ac16ce191921a 100644 --- a/packages/gatsby/src/utils/webpack-error-utils.ts +++ b/packages/gatsby/src/utils/webpack-error-utils.ts @@ -52,7 +52,7 @@ const transformWebpackError = ( stage: StageEnum, webpackError: WebpackError ): ITransformedWebpackError => { - const castedWebpackError = (webpackError as unknown) as IWebpackError + const castedWebpackError = webpackError as unknown as IWebpackError let location if (castedWebpackError.loc && castedWebpackError.loc.start) { @@ -109,9 +109,8 @@ const transformWebpackError = ( // it shows extra information for things that changed with webpack const BreakingChangeRegex = /BREAKING CHANGE[\D\n\d]+$/ if (BreakingChangeRegex.test(castedWebpackError.message)) { - const breakingMatch = castedWebpackError.message.match( - BreakingChangeRegex - ) + const breakingMatch = + castedWebpackError.message.match(BreakingChangeRegex) context.deprecationReason = breakingMatch?.[0] } @@ -150,7 +149,7 @@ export const reportWebpackWarnings = ( ): void => { let warningMessages: Array = [] if (typeof warnings[0] === `string`) { - warningMessages = (warnings as unknown) as Array + warningMessages = warnings as unknown as Array } else if (warnings[0]?.message && warnings[0]?.moduleName) { warningMessages = warnings.map( warning => `${warning.moduleName}\n\n${warning.message}` diff --git a/packages/gatsby/src/utils/webpack-plugins.ts b/packages/gatsby/src/utils/webpack-plugins.ts index c62f06530ac4b..dc40b77965f1b 100644 --- a/packages/gatsby/src/utils/webpack-plugins.ts +++ b/packages/gatsby/src/utils/webpack-plugins.ts @@ -1,20 +1,20 @@ import webpack, { WebpackPluginInstance } from "webpack" -const plugin = ( - name: string, - optimize?: boolean, - deprecationReason?: string -): ((...args: any) => WebpackPluginInstance) => ( - ...args: any -): WebpackPluginInstance => { - if (deprecationReason) { - // TODO add proper deprecation function to reporter - console.warn(`[deprecated]: ${deprecationReason}`) - } +const plugin = + ( + name: string, + optimize?: boolean, + deprecationReason?: string + ): ((...args: any) => WebpackPluginInstance) => + (...args: any): WebpackPluginInstance => { + if (deprecationReason) { + // TODO add proper deprecation function to reporter + console.warn(`[deprecated]: ${deprecationReason}`) + } - const WebpackPlugin = (optimize ? webpack.optimize : webpack)[name] - return new WebpackPlugin(...args) -} + const WebpackPlugin = (optimize ? webpack.optimize : webpack)[name] + return new WebpackPlugin(...args) + } export const builtinPlugins = { normalModuleReplacement: plugin(`NormalModuleReplacementPlugin`), diff --git a/packages/gatsby/src/utils/webpack-utils.ts b/packages/gatsby/src/utils/webpack-utils.ts index 60195246e9f4d..636aad1389ec6 100644 --- a/packages/gatsby/src/utils/webpack-utils.ts +++ b/packages/gatsby/src/utils/webpack-utils.ts @@ -181,21 +181,21 @@ export const createWebpackUtils = ( const isSSR = stage.includes(`html`) const jsxRuntimeExists = reactHasJsxRuntime() - const makeExternalOnly = (original: RuleFactory) => ( - options = {} - ): RuleSetRule => { - const rule = original(options) - rule.include = vendorRegex - return rule - } + const makeExternalOnly = + (original: RuleFactory) => + (options = {}): RuleSetRule => { + const rule = original(options) + rule.include = vendorRegex + return rule + } - const makeInternalOnly = (original: RuleFactory) => ( - options = {} - ): RuleSetRule => { - const rule = original(options) - rule.exclude = vendorRegex - return rule - } + const makeInternalOnly = + (original: RuleFactory) => + (options = {}): RuleSetRule => { + const rule = original(options) + rule.exclude = vendorRegex + return rule + } const loaders: ILoaderUtils = { json: (options = {}) => { @@ -319,9 +319,11 @@ export const createWebpackUtils = ( const autoprefixerPlugin = autoprefixer({ overrideBrowserslist, flexbox: `no-2009`, - ...(((postCSSPlugins.find( - plugin => plugin.postcssPlugin === `autoprefixer` - ) as unknown) as autoprefixer.ExportedAPI)?.options ?? {}), + ...(( + postCSSPlugins.find( + plugin => plugin.postcssPlugin === `autoprefixer` + ) as unknown as autoprefixer.ExportedAPI + )?.options ?? {}), }) postCSSPlugins.unshift(autoprefixerPlugin) @@ -767,8 +769,9 @@ export const createWebpackUtils = ( plugins.extractStats = (): GatsbyWebpackStatsExtractor => new GatsbyWebpackStatsExtractor() - plugins.eslintGraphqlSchemaReload = (): GatsbyWebpackEslintGraphqlSchemaReload => - new GatsbyWebpackEslintGraphqlSchemaReload() + plugins.eslintGraphqlSchemaReload = + (): GatsbyWebpackEslintGraphqlSchemaReload => + new GatsbyWebpackEslintGraphqlSchemaReload() plugins.virtualModules = (): GatsbyWebpackVirtualModules => new GatsbyWebpackVirtualModules() diff --git a/packages/gatsby/src/utils/webpack/static-query-mapper.ts b/packages/gatsby/src/utils/webpack/static-query-mapper.ts index 90c6509f8c37e..23898391ad408 100644 --- a/packages/gatsby/src/utils/webpack/static-query-mapper.ts +++ b/packages/gatsby/src/utils/webpack/static-query-mapper.ts @@ -146,18 +146,18 @@ export class StaticQueryMapper { ChunkGroup >() - const { - webpackModulesByStaticQueryId, - webpackModulesByComponentId, - } = getWebpackModulesByResourcePaths( - compilation.modules, - staticQueryComponents, - components - ) - - const appEntryPoint = (compilation.entrypoints.has(`app`) - ? compilation.entrypoints.get(`app`) - : compilation.entrypoints.get(`commons`)) as EntryPoint + const { webpackModulesByStaticQueryId, webpackModulesByComponentId } = + getWebpackModulesByResourcePaths( + compilation.modules, + staticQueryComponents, + components + ) + + const appEntryPoint = ( + compilation.entrypoints.has(`app`) + ? compilation.entrypoints.get(`app`) + : compilation.entrypoints.get(`commons`) + ) as EntryPoint // group hashes by chunkGroup for ease of use for (const [ @@ -172,9 +172,10 @@ export class StaticQueryMapper { if (chunkGroup === appEntryPoint) { chunkGroupsDerivedFromEntrypoints.push(chunkGroup) } else { - chunkGroupsDerivedFromEntrypoints = chunkGroupsDerivedFromEntrypoints.concat( - getChunkGroupsDerivedFromEntrypoint(chunkGroup, appEntryPoint) - ) + chunkGroupsDerivedFromEntrypoints = + chunkGroupsDerivedFromEntrypoints.concat( + getChunkGroupsDerivedFromEntrypoint(chunkGroup, appEntryPoint) + ) } } } @@ -185,9 +186,11 @@ export class StaticQueryMapper { staticQueriesByChunkGroup.get(chunkGroup) ?? [] staticQueryHashes.push( - (staticQueryComponents.get( - staticQueryId - ) as IGatsbyStaticQueryComponents).hash + ( + staticQueryComponents.get( + staticQueryId + ) as IGatsbyStaticQueryComponents + ).hash ) staticQueriesByChunkGroup.set(chunkGroup, staticQueryHashes) @@ -227,9 +230,9 @@ export class StaticQueryMapper { component.componentPath ) if (chunkGroup && staticQueriesByChunkGroup.has(chunkGroup)) { - ;(staticQueriesByChunkGroup.get(chunkGroup) as Array< - string - >).forEach(staticQuery => { + ;( + staticQueriesByChunkGroup.get(chunkGroup) as Array + ).forEach(staticQuery => { allStaticQueries.add(staticQuery) }) } diff --git a/packages/gatsby/src/utils/websocket-manager.ts b/packages/gatsby/src/utils/websocket-manager.ts index 752b663a9e829..d7bb127d8bec5 100644 --- a/packages/gatsby/src/utils/websocket-manager.ts +++ b/packages/gatsby/src/utils/websocket-manager.ts @@ -124,9 +124,8 @@ export class WebsocketManager { if (process.env.GATSBY_EXPERIMENTAL_QUERY_ON_DEMAND) { // page-data marked stale due to dirty query tracking - const boundEmitStalePageDataPathsFromDirtyQueryTracking = this.emitStalePageDataPathsFromDirtyQueryTracking.bind( - this - ) + const boundEmitStalePageDataPathsFromDirtyQueryTracking = + this.emitStalePageDataPathsFromDirtyQueryTracking.bind(this) emitter.on( `CREATE_PAGE`, boundEmitStalePageDataPathsFromDirtyQueryTracking @@ -214,8 +213,8 @@ export class WebsocketManager { } emitStalePageDataPathsFromDirtyQueryTracking(): void { - const dirtyQueries = store.getState().queries - .dirtyQueriesListToEmitViaWebsocket + const dirtyQueries = + store.getState().queries.dirtyQueriesListToEmitViaWebsocket if (this.emitStalePageDataPaths(dirtyQueries)) { store.dispatch(clearDirtyQueriesListToEmitViaWebsocket()) diff --git a/packages/gatsby/src/utils/worker/__tests__/reporter.ts b/packages/gatsby/src/utils/worker/__tests__/reporter.ts index e94dfd8030f44..0dc8c8ac62782 100644 --- a/packages/gatsby/src/utils/worker/__tests__/reporter.ts +++ b/packages/gatsby/src/utils/worker/__tests__/reporter.ts @@ -2,18 +2,14 @@ import { createTestWorker, GatsbyTestWorkerPool } from "./test-helpers" import * as ActionCreators from "gatsby-cli/lib/reporter/redux/actions" let worker: GatsbyTestWorkerPool | undefined -const spies: Record< - keyof typeof ActionCreators, - jest.SpyInstance -> = (Object.keys(ActionCreators) as Array).reduce( - (acc, key) => { - if (typeof ActionCreators[key] === `function`) { - acc[key] = jest.spyOn(ActionCreators, key) - } - return acc - }, - {} as any -) +const spies: Record = ( + Object.keys(ActionCreators) as Array +).reduce((acc, key) => { + if (typeof ActionCreators[key] === `function`) { + acc[key] = jest.spyOn(ActionCreators, key) + } + return acc +}, {} as any) afterEach(() => { for (const spy of Object.values(spies)) { diff --git a/packages/gatsby/src/utils/worker/__tests__/schema.ts b/packages/gatsby/src/utils/worker/__tests__/schema.ts index 274721db9a68c..6eb132a58d020 100644 --- a/packages/gatsby/src/utils/worker/__tests__/schema.ts +++ b/packages/gatsby/src/utils/worker/__tests__/schema.ts @@ -71,9 +71,11 @@ describeWhenLMDB(`worker (schema)`, () => { }) it(`should have functioning createSchemaCustomization`, async () => { - const typeDefinitions = (stateFromWorker.schemaCustomization.types[0] as { - typeOrTypeDef: DocumentNode - }).typeOrTypeDef.definitions + const typeDefinitions = ( + stateFromWorker.schemaCustomization.types[0] as { + typeOrTypeDef: DocumentNode + } + ).typeOrTypeDef.definitions expect(typeDefinitions).toEqual( expect.arrayContaining([ diff --git a/packages/gatsby/src/utils/worker/child/render-html.ts b/packages/gatsby/src/utils/worker/child/render-html.ts index 6c3a3871d4de2..a971336cb7994 100644 --- a/packages/gatsby/src/utils/worker/child/render-html.ts +++ b/packages/gatsby/src/utils/worker/child/render-html.ts @@ -221,9 +221,8 @@ async function doGetResourcesForTemplate( const staticQueryResultPromises: Array> = [] const staticQueryContext: Record = {} for (const staticQueryHash of pageData.staticQueryHashes) { - const memoizedStaticQueryResult = staticQueryResultCache.get( - staticQueryHash - ) + const memoizedStaticQueryResult = + staticQueryResultCache.get(staticQueryHash) if (memoizedStaticQueryResult) { staticQueryContext[staticQueryHash] = memoizedStaticQueryResult continue @@ -326,14 +325,12 @@ export const renderHTMLProd = async ({ const pageData = await readPageData(publicDir, pagePath) const resourcesForTemplate = await getResourcesForTemplate(pageData) - const { - html, - unsafeBuiltinsUsage, - } = await htmlComponentRenderer.default({ - pagePath, - pageData, - ...resourcesForTemplate, - }) + const { html, unsafeBuiltinsUsage } = + await htmlComponentRenderer.default({ + pagePath, + pageData, + ...resourcesForTemplate, + }) if (unsafeBuiltinsUsage.length > 0) { unsafeBuiltinsUsageByPagePath[pagePath] = unsafeBuiltinsUsage diff --git a/scripts/i18n/create.js b/scripts/i18n/create.js index dc92296c5c5af..6d516c2119667 100644 --- a/scripts/i18n/create.js +++ b/scripts/i18n/create.js @@ -37,7 +37,7 @@ const issueBody = makeProgressIssue() async function getIssue(issueNo) { const { repository } = await graphql( ` - query($issueRepo: String!, $owner: String!, $issueNo: Int!) { + query ($issueRepo: String!, $owner: String!, $issueNo: Int!) { repository(name: $issueRepo, owner: $owner) { issue(number: $issueNo) { id @@ -135,7 +135,7 @@ async function createRepoOnGitHub(repoName, langName) { logger.debug(`getting organization info from github`) const { organization } = await graphql( ` - query($owner: String!) { + query ($owner: String!) { organization(login: $owner) { id } @@ -153,7 +153,7 @@ async function createRepoOnGitHub(repoName, langName) { logger.info(`creating repository ${repoName} on github`) const { createRepository } = await graphql( ` - mutation($input: CreateRepositoryInput!) { + mutation ($input: CreateRepositoryInput!) { createRepository(input: $input) { repository { id @@ -185,7 +185,7 @@ async function createBranchProtections(repo) { logger.info(`creating branch protections for ${repo.name}`) return await graphql( ` - mutation($input: CreateBranchProtectionRuleInput!) { + mutation ($input: CreateBranchProtectionRuleInput!) { createBranchProtectionRule(input: $input) { branchProtectionRule { id @@ -216,7 +216,7 @@ async function createProgressIssue(repo, langName) { createIssue: { issue }, } = await graphql( ` - mutation($input: CreateIssueInput!) { + mutation ($input: CreateIssueInput!) { createIssue(input: $input) { issue { id @@ -238,7 +238,7 @@ async function createProgressIssue(repo, langName) { ) await graphql( ` - mutation($input: PinIssueInput!) { + mutation ($input: PinIssueInput!) { pinIssue(input: $input) { issue { id @@ -286,7 +286,7 @@ Happy translating! logger.info(`responding to original issue`) return await graphql( ` - mutation($input: AddCommentInput!) { + mutation ($input: AddCommentInput!) { addComment(input: $input) { clientMutationId } @@ -308,7 +308,7 @@ async function closeRequestIssue(issueId) { logger.info(`closing original issue`) await graphql( ` - mutation($input: CloseIssueInput!) { + mutation ($input: CloseIssueInput!) { closeIssue(input: $input) { clientMutationId } diff --git a/scripts/i18n/sync.js b/scripts/i18n/sync.js index a59690c70fda6..1451ecd217bc8 100644 --- a/scripts/i18n/sync.js +++ b/scripts/i18n/sync.js @@ -53,7 +53,7 @@ async function graphql(query, params) { async function getRepository(owner, name) { const { repository } = await graphql( ` - query($owner: String!, $name: String!, $syncLabel: String!) { + query ($owner: String!, $name: String!, $syncLabel: String!) { repository(owner: $owner, name: $name) { id syncPullRequests: pullRequests(labels: [$syncLabel], first: 1) { @@ -79,7 +79,7 @@ async function getRepository(owner, name) { async function createLabel(input) { const { createLabel } = await graphql( ` - mutation($input: CreateLabelInput!) { + mutation ($input: CreateLabelInput!) { createLabel(input: $input) { label { id @@ -100,7 +100,7 @@ async function createLabel(input) { async function createPullRequest(input) { const { createPullRequest } = await graphql( ` - mutation($input: CreatePullRequestInput!) { + mutation ($input: CreatePullRequestInput!) { createPullRequest(input: $input) { pullRequest { id @@ -122,7 +122,7 @@ async function createPullRequest(input) { async function addLabelToPullRequest(pullRequest, label) { await graphql( ` - mutation($input: AddLabelsToLabelableInput!) { + mutation ($input: AddLabelsToLabelableInput!) { addLabelsToLabelable(input: $input) { clientMutationId } diff --git a/yarn.lock b/yarn.lock index ef9bb07baa5f6..04aff4ec922dd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11263,10 +11263,10 @@ eslint-plugin-filenames@^1.3.2: lodash.snakecase "4.1.1" lodash.upperfirst "4.3.1" -eslint-plugin-flowtype@^5.7.2, eslint-plugin-flowtype@^5.8.2: - version "5.8.2" - resolved "https://registry.yarnpkg.com/eslint-plugin-flowtype/-/eslint-plugin-flowtype-5.8.2.tgz#e8c4429f2d39d93ccb0732f581b159da16fa0bda" - integrity sha512-/aPTnNKNAYJbEU07HwvohnXp0itBT+P0r+7s80IG5eqfsrx4NLN+0rXNztJBc56u1RJegSn0GMt1cZnGZpCThw== +eslint-plugin-flowtype@^5.8.2, eslint-plugin-flowtype@^5.9.0: + version "5.9.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-flowtype/-/eslint-plugin-flowtype-5.9.0.tgz#8d2d81d3d79bb53470ed62b97409b31684757e30" + integrity sha512-aBUVPA5Wt0XyuV3Wg8flfVqYJR6yR2nRLuyPwoTjCg5VTk4G1X1zQpInr39tUGgRxqrA+d+B9GYK4+/d1i0Rfw== dependencies: lodash "^4.17.15" string-natural-compare "^3.0.1" @@ -11455,7 +11455,7 @@ eslint@^6.8.0: text-table "^0.2.0" v8-compile-cache "^2.0.3" -eslint@^7.28.0, eslint@^7.32.0: +eslint@^7.32.0: version "7.32.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.32.0.tgz#c6d328a14be3fb08c8d1d21e12c02fdb7a2a812d" integrity sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA== @@ -21923,12 +21923,7 @@ prettier-linter-helpers@^1.0.0: dependencies: fast-diff "^1.1.2" -prettier@2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.1.2.tgz#3050700dae2e4c8b67c4c3f666cdb8af405e1ce5" - integrity sha512-16c7K+x4qVlJg9rEbXl7HEGmQyZlG4R9AgP+oHKRMsMsuk8s+ATStlf1NpDqyBI1HpVyfjLOeMhH2LvuNvV5Vg== - -prettier@^2.3.2: +prettier@2.3.2, prettier@^2.3.2: version "2.3.2" resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.3.2.tgz#ef280a05ec253712e486233db5c6f23441e7342d" integrity sha512-lnJzDfJ66zkMy58OL5/NY5zp70S7Nz6KqcKkXYzn2tMVrNxvbqaBpg7H3qHaLxCJ5lNMsGuM8+ohS7cZrthdLQ==