diff --git a/.circleci/config.yml b/.circleci/config.yml index b6037621bc440..0fa0b2f53b4aa 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -179,6 +179,7 @@ jobs: - <<: *install_node_modules - <<: *persist_cache - run: yarn bootstrap -- concurrency=2 + - run: git status yarn.lock -s | grep "M yarn.lock" && echo "yarn.lock is dirty. Please ensure changes have been committed" && exit 1 # Persist the workspace again with all packages already built - persist_to_workspace: root: ./ @@ -221,6 +222,12 @@ jobs: image: "14" <<: *test_template + integration_tests_gatsby_source_wordpress: + executor: node + steps: + - e2e-test: + test_path: integration-tests/gatsby-source-wordpress + integration_tests_long_term_caching: executor: node steps: @@ -258,15 +265,6 @@ jobs: - e2e-test: test_path: integration-tests/artifacts - # temporary - integration_tests_artifacts_conditional_page_builds: - executor: node - steps: - - e2e-test: - test_path: integration-tests/artifacts - environment: - GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES: 1 - integration_tests_ssr: executor: node steps: @@ -334,14 +332,6 @@ jobs: e2e_tests_development_runtime: <<: *e2e_tests_development_runtime_alias - e2e_tests_development_runtime_fast_refresh: - <<: *e2e_tests_development_runtime_alias - environment: - GATSBY_HOT_LOADER: fast-refresh - CYPRESS_HOT_LOADER: fast-refresh - CYPRESS_PROJECT_ID: 917bea - CYPRESS_RECORD_KEY: 4750fb36-4576-4638-a617-d243a381acef - e2e_tests_development_runtime_with_experimental_react: <<: *e2e_tests_development_runtime_alias @@ -596,6 +586,8 @@ workflows: - lint - typecheck - bootstrap + - integration_tests_gatsby_source_wordpress: + <<: *e2e-test-workflow - integration_tests_long_term_caching: <<: *e2e-test-workflow - integration_tests_cache_resilience: @@ -606,8 +598,6 @@ workflows: <<: *e2e-test-workflow - integration_tests_artifacts: <<: *e2e-test-workflow - - integration_tests_artifacts_conditional_page_builds: - <<: *e2e-test-workflow - integration_tests_ssr: <<: *e2e-test-workflow - integration_tests_images: @@ -627,8 +617,6 @@ workflows: <<: *e2e-test-workflow - e2e_tests_development_runtime: <<: *e2e-test-workflow - - e2e_tests_development_runtime_fast_refresh: - <<: *e2e-test-workflow - e2e_tests_production_runtime: <<: *e2e-test-workflow - themes_e2e_tests_production_runtime: diff --git a/.eslintignore b/.eslintignore index 7710f0da72918..1bd8c9b7ab64e 100644 --- a/.eslintignore +++ b/.eslintignore @@ -25,6 +25,7 @@ packages/gatsby-image/withIEPolyfill/index.js packages/gatsby/cache-dir/commonjs/**/* packages/gatsby-admin/public packages/gatsby/gatsby-admin-public +packages/gatsby-codemods/transforms packages/gatsby-source-wordpress/test-site/** !packages/gatsby-source-wordpress/test-site/__tests__ diff --git a/.eslintrc.js b/.eslintrc.js index 601a627b50171..0e801b4351173 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -29,6 +29,11 @@ module.exports = { before: true, after: true, spyOn: true, + // These should be in scope but for some reason eslint can't see them + NodeJS: true, + JSX: true, + NodeRequire: true, + TimerHandler: true, __PATH_PREFIX__: true, __BASE_PATH__: true, __ASSET_PREFIX__: true, @@ -49,6 +54,8 @@ module.exports = { "warn", { varsIgnorePattern: "^_", + argsIgnorePattern: "^_", + ignoreRestSiblings: true, }, ], "consistent-return": ["error"], @@ -93,7 +100,9 @@ module.exports = { ...TSEslint.configs.recommended.rules, // We should absolutely avoid using ts-ignore, but it's not always possible. // particular when a dependencies types are incorrect. - "@typescript-eslint/ban-ts-ignore": "warn", + "@typescript-eslint/ban-ts-comment": { + "ts-ignore": "allow-with-description", + }, // This rule is great. It helps us not throw on types for areas that are // easily inferrable. However we have a desire to have all function inputs // and outputs declaratively typed. So this let's us ignore the parameters @@ -102,16 +111,40 @@ module.exports = { "error", { ignoreParameters: true }, ], - "@typescript-eslint/camelcase": [ + "@typescript-eslint/ban-types": [ "error", { - // This rule tries to ensure we use camelCase for all variables, properties - // functions, etc. However, it is not always possible to ensure properties - // are camelCase. Specifically we have `node.__gatsby_resolve` which breaks - // this rule. This allows properties to be whatever they need to be. - properties: "never", - // Allow unstable api's to use `unstable_`, which is easier to grep - allow: ["^unstable_"], + extendDefaults: true, + types: { + "{}": { + fixWith: "Record", + }, + object: { + fixWith: "Record", + }, + }, + }, + ], + "@typescript-eslint/naming-convention": [ + { + selector: "default", + format: ["camelCase"], + }, + { selector: "variable", format: ["camelCase", "UPPER_CASE"] }, + { + selector: "parameter", + format: ["camelCase"], + leadingUnderscore: "allow", + prefix: ["unstable_", ""], + }, + { + selector: "typeLike", + format: ["PascalCase"], + }, + { + selector: "interface", + format: ["PascalCase"], + prefix: ["I"], }, ], // This rule tries to prevent using `require()`. However in node code, @@ -127,6 +160,7 @@ module.exports = { // - baz: string; // + baz: string // } + "@typescript-eslint/no-extra-semi": false, "@typescript-eslint/member-delimiter-style": [ "error", { @@ -135,13 +169,6 @@ module.exports = { }, }, ], - // This ensures all interfaces are named with an I as a prefix - // e.g., - // interface IFoo {} - "@typescript-eslint/interface-name-prefix": [ - "error", - { prefixWithI: "always" }, - ], "@typescript-eslint/no-empty-function": "off", // This ensures that we always type the return type of functions // a high level focus of our TS setup is typing fn inputs and outputs. diff --git a/docs/contributing/docs-writing-process.md b/docs/contributing/docs-writing-process.md index 08080cc1b5f26..bf03b82dc3ef9 100644 --- a/docs/contributing/docs-writing-process.md +++ b/docs/contributing/docs-writing-process.md @@ -57,7 +57,7 @@ Here are some tips for gathering information on a given topic within Gatsby: 3. You can also search the web for additional examples outside of the Gatsby GitHub org or docs site. Be sure to check Gatsby versions and only reference the most current examples unless for a specific purpose. -4. In the event there is no information available to write a greenfield doc after trying all the above steps, such as for a new integration, try interviewing Gatsby core team members to help to produce an outline and content tips. See [Pair Programming program](/contributing/pair-programming/). +4. In the event there is no information available to write a greenfield doc after trying all the above steps, such as for a new integration, try asking Gatsby core team members to help to produce an outline and content tips. Please open a [documentation issue](https://github.com/gatsbyjs/gatsby/issues/new/choose) for this then. 5. **For Gatsby inkteam members:** You can also search in the Gatsby Slack internally for related information. It’s possible other team members have discussed the issue, or even compiled trouble points into a doc. Look and ask around as part of your discovery work. @@ -90,7 +90,6 @@ Apply feedback from pull request reviews in order for them to be accepted. Furth - [How to File an Issue](/contributing/how-to-file-an-issue/) - [Gatsby Style Guide](/contributing/gatsby-style-guide/) - [Markdown Syntax Doc](/docs/how-to/routing/mdx/markdown-syntax/) -- [Pair Programming](/contributing/pair-programming/) for interviewing the core team only - [Blog Post Guidelines](/contributing/blog-contributions/) - [Docs site setup instructions](/contributing/docs-contributions/#docs-site-setup-instructions) - [How to Open a Pull Request](/contributing/how-to-open-a-pull-request/) diff --git a/docs/contributing/gatsby-governance-model.md b/docs/contributing/gatsby-governance-model.md index c18b3ac55320c..2cd1e61b4d209 100644 --- a/docs/contributing/gatsby-governance-model.md +++ b/docs/contributing/gatsby-governance-model.md @@ -56,7 +56,6 @@ Here are some relevant docs and resources for contributors: - [How to file an issue](/contributing/how-to-file-an-issue/) - [Request-for-comment (RFC) process](/contributing/rfc-process/) - [Community Maintainers Meeting](/contributing/community/#community-maintainers-meeting) -- [Pair programming sessions](/contributing/pair-programming/) ## Engage with the Gatsby team diff --git a/docs/contributing/how-to-contribute.md b/docs/contributing/how-to-contribute.md index 049fa2241829a..c09d7990ac6d8 100644 --- a/docs/contributing/how-to-contribute.md +++ b/docs/contributing/how-to-contribute.md @@ -8,8 +8,4 @@ We want contributing to Gatsby to be fun, enjoyable, and educational for anyone If you are worried or don't know where to start, check out our [where to participate](/contributing/where-to-participate/) page. You can reach out with questions to [@AskGatsbyJS](https://twitter.com/askgatsbyjs) on Twitter, and anyone from the Gatsby team on [Discord](https://gatsby.dev/discord). You can also [submit an issue](/contributing/how-to-file-an-issue/) and a maintainer can give you guidance! -## Pair programming - -Gatsby.js offers free [pair programming sessions](/contributing/pair-programming/) to the community, if there's something you'd like to work on together. Get in touch with us if you have a question about contributing or an idea for something to pair on! - diff --git a/docs/contributing/how-to-write-a-stub.md b/docs/contributing/how-to-write-a-stub.md index ab08fd4920238..d3420d3f9fefd 100644 --- a/docs/contributing/how-to-write-a-stub.md +++ b/docs/contributing/how-to-write-a-stub.md @@ -20,11 +20,6 @@ pull request gets accepted. If you have any questions about titles or other details related to creating stubs, feel free to ask us on a relevant GitHub issue. -## Community Pair Programming Sessions - -If you create a stub or see an existing one on the Gatsby.js site and feel interested in filling out the content, check out the Gatsby.js -[Pair Programming program](/contributing/pair-programming/). We would love to work with you in your open source contributing journey! - ## Converting a Stub to a Doc To change a stub into a living-breathing document, remove the `issue` entry from a stub's frontmatter (a fancy name for Markdown metadata) and replace the boilerplate content with diff --git a/docs/contributing/pair-programming.md b/docs/contributing/pair-programming.md deleted file mode 100644 index d8dfa1dfc765a..0000000000000 --- a/docs/contributing/pair-programming.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Open Community Pair Programming Sessions ---- - -The best part of open source is the community, and every community is stronger when it works together. To help build the strongest community possible, Gatsby is offering free [45 minute pair programming sessions][form] to anyone and everyone in the open source community. - -## How community pair programming sessions work - -1. Select or create [an issue](https://github.com/gatsbyjs/gatsby/issues) you would like to work on and work on it yourself. -2. [Create a pull request](/contributing/how-to-open-a-pull-request/) when you encounter any problem. -3. Fill in your details in [the pair programming request form][form]. -4. You’ll be paired with a Gatsby team member and we'll establish a good time to pair on [Zoom](https://zoom.us). -5. We'll help you with your pull request or issue! -6. The video of your pairing session will be available on our [YouTube channel](https://www.youtube.com/channel/UCjnp770qk7ujOq8Q9wiC82w/videos). - -### What we expect in pair programming sessions - -These sessions are intended for people who would like to contribute to Gatsby. We will pair program together to solve an issue or pull request related to Gatsby. - -If you're interested in support for a commercial Gatsby project, please [get in touch via the contact page](/contact-us/). - -We also expect the following from pair programming participants: - -- These sessions work best when you have a specific goal for the session. You should choose an issue or pull request that you'd like to work on. -- If you're new to building with Gatsby we recommend [working through the tutorial](/docs/tutorial/) before your session. If you get stuck part way through that's a great time to book a pairing session. -- If you're new to contributing to open source we recommend following the ["Setting Up Your Local Dev Environment" guide](/contributing/setting-up-your-local-dev-environment/) before your session. -- All participants are expected to adhere to [Gatsby’s code of conduct](/contributing/code-of-conduct/) -- We will ask if it’s okay to record your session; you are _not_ required to let us record and we will work to find another solution that works for you. However, we think it's really valuable to surface these pairing sessions so more people can learn from them and they have a wider reach. -- Check out our [previous sessions](https://www.youtube.com/playlist?list=PLCU2qJekvcN1f4CRTTMMW6XliGio1NcUD) to see if we've already covered what you're looking to learn! This list will grow over time and we're really excited to have lasting learning artifacts for contributing to Gatsby. Our very first recording was not an actual pairing session but was an [introduction to Gatsby's repository and internals](https://www.youtube.com/watch?v=9wM3pFtyTHw) and is a tremendous resource. - -## How to sign up - -Fill in the [request a pairing session form][form] to reserve your spot. The Gatsby team will be notified. You should get an email shortly with next steps. - -[Reserve your spot today][form] and let’s build something amazing together! - -[form]: https://airtable.com/shrtYlQjqQARrmJH4 diff --git a/docs/contributing/why-contribute-to-gatsby.md b/docs/contributing/why-contribute-to-gatsby.md index 5b6d2fa9b8bd7..cf79c724930a0 100644 --- a/docs/contributing/why-contribute-to-gatsby.md +++ b/docs/contributing/why-contribute-to-gatsby.md @@ -6,7 +6,7 @@ There are many reasons to contribute to Gatsby.js and open source software in ge - **Growing your community.** Working with Gatsby.js in open source can connect you with people working on similar things. You can get help or give help, and you might even make an IRL acquaintance! It has happened. -- **Improving your skills.** When you work on a Gatsby issue or pull request, inevitably you'll learn more about how something works in the project; either by asking questions and gathering info or by digging deeper into the code yourself. Gatsby.js also offers free [pair programming sessions](/contributing/pair-programming/) to the community, if there's something you'd like to work on together. There's a skill-building benefit to contributing to OSS! +- **Improving your skills.** When you work on a Gatsby issue or pull request, inevitably you'll learn more about how something works in the project; either by asking questions and gathering info or by digging deeper into the code yourself. There's a skill-building benefit to contributing to OSS! - **Getting free swag!** By participating in the repo on GitHub, you can become eligible for free swag that the Gatsby team offers as a way to say thank you. With 5 contributions, you can advance to a second level with even more swag options! Learn more about this [sweet swag deal](/contributing/contributor-swag/). diff --git a/docs/docs/caching.md b/docs/docs/caching.md index 58a88d24dd564..dd2d6801501a1 100644 --- a/docs/docs/caching.md +++ b/docs/docs/caching.md @@ -40,7 +40,7 @@ The only exception to this is the file `/sw.js`, which needs to be revalidated u ## Setting up caching on different hosts -How you setup your caching depends on how you host your site. We encourage people to create Gatsby plugins per host to automate the creation of caching headers. +How you set up your caching depends on how you host your site. We encourage people to create Gatsby plugins per host to automate the creation of caching headers. The following plugins have been created: diff --git a/docs/docs/conceptual/choosing-a-cms.md b/docs/docs/conceptual/choosing-a-cms.md index 5143f5e0d7613..51764bbbe26c6 100644 --- a/docs/docs/conceptual/choosing-a-cms.md +++ b/docs/docs/conceptual/choosing-a-cms.md @@ -18,7 +18,7 @@ In terms of popularity, you can see [top integrations listed by monthly download - **five general-purpose headless CMSs:** Contentful, DatoCMS, Prismic, Sanity and Strapi -- **two general-purpose full-stack CMSs** running in "headless" mode: Drupal and Wordpress +- **two general-purpose full-stack CMSs** running in "headless" mode: Drupal and WordPress - **one specialized CMS**: Shopify @@ -28,7 +28,7 @@ In terms of popularity, you can see [top integrations listed by monthly download - If you're working on a personal project or prototype, a few of these have a generous free tier (Contentful, DatoCMS, Prismic, Sanity, Strapi). -- If you're looking more at "Team", "Pro", or "Business" price points (eg $29, $99, or \$299 per month), the above CMSs are all good options, plus Drupal and Wordpress. +- If you're looking more at "Team", "Pro", or "Business" price points (eg $29, $99, or \$299 per month), the above CMSs are all good options, plus Drupal and WordPress. - If you're looking more at an "enterprise" project in the four digits per month and up, your main options are Contentful, Contentstack, Sanity, and Strapi. @@ -45,7 +45,7 @@ Users choosing other CMSs typically have a specific reason for their choice. Som - **Drupal** if open-source, configurability, or custom code are important. - **Prismic** if they like the content editing UI - **Sanity** or **Strapi** for the developer-friendliness or if they need something on-premise. In addition, Sanity tends to have significantly better build times, which can be a key usability consideration, especially for larger sites (we [benchmark build times by CMS here](https://willit.build/)). -- **Wordpress** when the client or content team is already familiar with the Wordpress UI +- **WordPress** when the client or content team is already familiar with the WordPress UI ## Using multiple CMS systems together @@ -65,13 +65,13 @@ Typically, teams that use multiple CMSs use a specialized CMS for part of the we ### Considerations when using multiple CMSs -One of the key considerations when using content in multiple systems is that - at some point - one content system often needs to "know about" another system. For example, a landing page with content in Contentful may need to embed information about a specific product SKU from Shopify or blog post in Wordpress. +One of the key considerations when using content in multiple systems is that - at some point - one content system often needs to "know about" another system. For example, a landing page with content in Contentful may need to embed information about a specific product SKU from Shopify or blog post in WordPress. The easiest way to create relationship references across CMSs is through one CMS storing unique IDs of content living in another CMS. -In this case, you'd store an array of Wordpress blog post IDs as a field of the relevant model in Contentful, then pull in the correct data via the appropriate queries in `gatsby-node.js.` +In this case, you'd store an array of WordPress blog post IDs as a field of the relevant model in Contentful, then pull in the correct data via the appropriate queries in `gatsby-node.js.` -To make that a bit more concrete, here's a screenshot of what this looks like currently (January 2020) in the Gatsbyjs.com Contentful setup for the [e-commerce use case page](https://www.gatsbyjs.com/use-cases/e-commerce); the model is called `Use Case Landing Page`, the field is called `Blog Posts`, and the items in the array are unique blog post IDs from Wordpress: +To make that a bit more concrete, here's a screenshot of what this looks like currently (January 2020) in the Gatsbyjs.com Contentful setup for the [e-commerce use case page](https://www.gatsbyjs.com/use-cases/e-commerce); the model is called `Use Case Landing Page`, the field is called `Blog Posts`, and the items in the array are unique blog post IDs from WordPress: ![Screenshot of Gatsbyjs.com Contentful setup](../images/use-case-landing-page-screenshot.jpg) diff --git a/docs/docs/conceptual/gatsby-core-philosophy.md b/docs/docs/conceptual/gatsby-core-philosophy.md index 35b6fd762506d..3119969b1617c 100644 --- a/docs/docs/conceptual/gatsby-core-philosophy.md +++ b/docs/docs/conceptual/gatsby-core-philosophy.md @@ -161,7 +161,6 @@ Some things we do in order to create an inclusive, welcoming community include: - Friendlier robots - Implicit trust - Active gratitude -- [Active mentorship](/contributing/pair-programming/) We’ve built an active community with thousands of contributors, and we want to live the example of what a great open source community can be. diff --git a/docs/docs/conceptual/gatsby-for-ecommerce.md b/docs/docs/conceptual/gatsby-for-ecommerce.md index 03ba5772cd3e9..769a896d4321f 100644 --- a/docs/docs/conceptual/gatsby-for-ecommerce.md +++ b/docs/docs/conceptual/gatsby-for-ecommerce.md @@ -18,7 +18,7 @@ In this case, your options are likely between a technologically forward e-commer ### Choosing additional content systems -Once an organization selects a main e-commerce platform, it may also want or need other content stores that will get pulled into the website. They might choose a CMS like Contentful for complex content modelling, or Wordpress for blog content authoring. They might choose Yotpo for customer reviews or Salsify for product information management. +Once an organization selects a main e-commerce platform, it may also want or need other content stores that will get pulled into the website. They might choose a CMS like Contentful for complex content modelling, or WordPress for blog content authoring. They might choose Yotpo for customer reviews or Salsify for product information management. ### Why organizations build e-commerce sites with Gatsby @@ -26,13 +26,13 @@ Organizations looking for a JAMStack e-commerce site that go with Gatsby typical From a conversion perspective, Gatsby’s lightning-fast performance is a huge win: Gatsby automates code splitting, image optimization, inlining critical styles, lazy-loading, prefetching resources, and more to ensure your site is fully optimized. -And with Gatsby’s pre-built integrations, it can pull data in from all of these sources (Shopify, plus Wordpress, Contentful, Yotpo, etc) and make it available for the React components. +And with Gatsby’s pre-built integrations, it can pull data in from all of these sources (Shopify, plus WordPress, Contentful, Yotpo, etc) and make it available for the React components. ### Specific e-commerce development considerations E-commerce tends to have a number of specific requirements. When building a Gatsby site (or other decoupled/JAMStack site, for that matter) sourced from an ecommerce backend like Shopify, developers will typically have to think through a few additional touchpoints between the systems: -- **Persisting a cart across site pages and between sessions** (ie, if the user closes their browser and reopens it tomorrow, the items should still be there). This can handled either through local-storage or through the shopify-buy JS library. +- **Persisting a cart across site pages and between sessions** (ie, if the user closes their browser and reopens it tomorrow, the items should still be there). This can be handled either through local-storage or through the shopify-buy JS library. - **Product search** can be done client-side if the SKU count is small enough to store all products in a global state. Alternatively, it can be handled through the e-commerce provider’s search features, or if those aren’t robust enough, a third-party search provider like Algolia. - **Surfacing price adjustments** like tax, shipping, discounts/promos to the user while browsing the site. Different e-commerce solutions provide different levels of API access to these objects. - **Handling checkout.** In order to comply with PCI regulations around storing credit card information, e-commerce providers typically exert strong control over the "buy" or "checkout" experience. Shopify requires all checkout flows using their platform to use their hosted checkout pages, though it's common to wrap them in a subdomain of the main site (eg the Gatsby/Shopify site [strivectin.com](strivectin.com] wraps a `myshopify.com` URL under a `shop.strivectin.com` URL for checkout). @@ -42,6 +42,6 @@ Additional resources: - [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://github.com/AlexanderProd/gatsby-shopify-starter) -- 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/) +- 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/) - [Gatsby Use Cases: E-commerce](https://www.gatsbyjs.com/use-cases/e-commerce) - [Best e-commerce solutions for Jamstack websites](https://bejamas.io/blog/jamstack-ecommerce/) from the Bejamas blog. diff --git a/docs/docs/conceptual/gatsby-lifecycle-apis.md b/docs/docs/conceptual/gatsby-lifecycle-apis.md index 3e0709d58ad4d..ce9580365e1ad 100644 --- a/docs/docs/conceptual/gatsby-lifecycle-apis.md +++ b/docs/docs/conceptual/gatsby-lifecycle-apis.md @@ -44,7 +44,7 @@ During the main bootstrap sequence, Gatsby (in this order): - writes page redirects (if any) to `.cache/redirects.json` - the [onPostBootstrap](/docs/reference/config-files/gatsby-node/#onPostBootstrap) lifecycle is executed -In development this is a running process powered by [webpack](https://github.com/gatsbyjs/gatsby/blob/dd91b8dceb3b8a20820b15acae36529799217ae4/packages/gatsby/package.json#L128) and [`react-hot-loader`](https://github.com/gatsbyjs/gatsby/blob/dd91b8dceb3b8a20820b15acae36529799217ae4/packages/gatsby/package.json#L104), so changes to any files get re-run through the sequence again, with [smart cache invalidation](https://github.com/gatsbyjs/gatsby/blob/ffd8b2d691c995c760fe380769852bcdb26a2278/packages/gatsby/src/bootstrap/index.js#L141). For example, `gatsby-source-filesystem` watches files for changes, and each change triggers re-running queries. Other plugins may also perform this service. Queries are also watched, so if you modify a query, your development app is hot reloaded. +In development this is a running process powered by [webpack](https://github.com/gatsbyjs/gatsby/blob/dd91b8dceb3b8a20820b15acae36529799217ae4/packages/gatsby/package.json#L128) and [`react-refresh`](https://github.com/gatsbyjs/gatsby/blob/4dff7550a29f4635bf47a068a05f634470eb9ef1/packages/gatsby/package.json#L134)), so changes to any files get re-run through the sequence again, with [smart cache invalidation](https://github.com/gatsbyjs/gatsby/blob/ffd8b2d691c995c760fe380769852bcdb26a2278/packages/gatsby/src/bootstrap/index.js#L141). For example, `gatsby-source-filesystem` watches files for changes, and each change triggers re-running queries. Other plugins may also perform this service. Queries are also watched, so if you modify a query, your development app is hot reloaded. The core of the bootstrap process is the "api-runner", which helps to execute APIs in sequence, with state managed in Redux. Gatsby exposes a number of lifecycle APIs which can either be implemented by you (or any of your configured plugins) in `gatsby-node.js`, `gatsby-browser.js` or `gatsby-ssr.js`. diff --git a/docs/docs/conceptual/overview-of-the-gatsby-build-process.md b/docs/docs/conceptual/overview-of-the-gatsby-build-process.md index 6d648abc51cbf..f235d9141ab74 100644 --- a/docs/docs/conceptual/overview-of-the-gatsby-build-process.md +++ b/docs/docs/conceptual/overview-of-the-gatsby-build-process.md @@ -304,7 +304,7 @@ Page queries that were queued up earlier from query extraction are run so the da With everything ready for the HTML pages in place, HTML is compiled and written out to files so it can be served up statically. Since HTML is being produced in a Node.js server context, [references to browser APIs like `window` can break the build](/docs/debugging-html-builds/) and must be conditionally applied. -By default, Gatsby rebuilds static HTML for all pages on each build. There is an experimental feature flag `GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES` which enables [conditional page builds](/docs/conditional-page-builds/). +Gatsby will smartly rebuild only needed HTML files. This can result in no HTML files being generated if nothing used for HTML files changed. The opposite can also be true and lead to a full site rebuild when data is used on all pages or when a code change happens. ## What do you get from a successful build? diff --git a/docs/docs/conceptual/using-gatsby-image.md b/docs/docs/conceptual/using-gatsby-image.md index d3bb46cbf42ff..d49a4036a32dd 100644 --- a/docs/docs/conceptual/using-gatsby-image.md +++ b/docs/docs/conceptual/using-gatsby-image.md @@ -22,7 +22,7 @@ We provide a [detailed guide on using Gatsby Image](docs/how-to/images-and-media ### Avoid hydration lag for React apps -When you're building a website with React you face a bit of a catch-22 for optimizing image loads. If you send over React JavaScript files to be evaluated by the browser (client-side rendering), you can't start loading images until the browser evaluates all of the Javascript to figure out what images you want to load. On the other hand, if you evaluate the Javascript on the server and then send over the HTML (server-side rendering), then the initial request will take longer to load while it waits for this server-side evaluation. +When you're building a website with React you face a bit of a catch-22 for optimizing image loads. If you send over React JavaScript files to be evaluated by the browser (client-side rendering), you can't start loading images until the browser evaluates all of the JavaScript to figure out what images you want to load. On the other hand, if you evaluate the JavaScript on the server and then send over the HTML (server-side rendering), then the initial request will take longer to load while it waits for this server-side evaluation. Because Gatsby does server rendering during the build process _(rather than when a user is loading the page)_ a Gatsby site will return HTML immediately without waiting for server rendering, and then the client's browser can start loading images as soon as it receives the HTML. Depending on the size of the app, this could save anything from a few hundred milliseconds to a few seconds. diff --git a/docs/docs/conditional-page-builds.md b/docs/docs/conditional-page-builds.md deleted file mode 100644 index ccc19a03f405a..0000000000000 --- a/docs/docs/conditional-page-builds.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: Conditional Page Builds ---- - -If you have a large site, you may be able to improve build times for data updates by enabling an experimental feature called "conditional page builds". While this is not as fast as true [Incremental Builds](https://support.gatsbyjs.com/hc/en-us/articles/360053099253-Distributed-Builds-and-Incremental-Builds) available in Gatsby Cloud, it can save time on the HTML-generation step by not re-rendering HTML for pages with unchanged data. This feature is experimental, but _may_ improve build times for sites with a large number of complex pages. Test it thoroughly with your site before deploying to production. - -For more info on the standard build process, please see the [overview of the Gatsby build process](/docs/conceptual/overview-of-the-gatsby-build-process/). - -## How to use - -To enable conditional page builds, use the environment variable `GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES=true` in your `gatsby build` command, for example: - -`GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES=true gatsby build --log-pages` - -This will run the Gatsby build process, but only build pages that have data changes since your last build. If there are any changes to code (JS, CSS) the bundling process returns a new webpack compilation hash which causes all pages to be rebuilt. - -### Reporting what has been built - -You may want to retrieve a list of the pages that were built. For example, if you want to perform a sync action in your CI/CD pipeline. - -To list the paths in the build assets (`public`) folder, you can use one (or both) of the following arguments in your `build` command. - -- `--log-pages` parameter will output all the file paths that were updated or deleted at the end of the build stage. - -```shell -success Building production JavaScript and CSS bundles - 82.198s -success run queries - 82.762s - 4/4 0.05/s -success Building static HTML for pages - 19.386s - 2/2 0.10/s -+ success Delete previous page data - 1.512s -info Done building in 152.084 sec -+ info Built pages: -+ Updated page: /about -+ Updated page: /accounts/example -+ info Deleted pages: -+ Deleted page: /test - -Done in 154.501 sec -``` - -- `--write-to-file` creates two files in the `.cache` folder, with lists of the changed paths in the build assets (`public`) folder. - - - `newPages.txt` will contain a list of new or changed paths - - `deletedPages.txt` will contain a list of deleted paths - -## More information - -- This feature works by comparing the page data from the previous build to the new page data. This creates a list of page directories that are passed to the static build process. - -- To enable this build option you will need to set an environment variable, which requires access to do so in your build environment. - -- You should not try to use this flag alongside Incremental Builds in Gatsby Cloud, as it uses a different process and may conflict with it. - -- You will need to persist the `.cache` and `public` directories between builds. This allows for comparisons and reuse of previously built files. If `.cache` directory was not persisted then a full build will be triggered. If `public` directory was not persisted then you might experience failing builds or builds that are missing certain assets. - -- Any code changes (templates, components, source handling, new plugins etc) will prompt the creation of a new webpack compilation hash and trigger a full build. diff --git a/docs/docs/debugging-html-builds.md b/docs/docs/debugging-html-builds.md index fd4a48a6bbefc..ae1d496ead899 100644 --- a/docs/docs/debugging-html-builds.md +++ b/docs/docs/debugging-html-builds.md @@ -63,7 +63,7 @@ rendering. ```js:title=gatsby-node.js exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => { - if (stage === "build-html") { + if (stage === "build-html" || stage === "develop-html") { actions.setWebpackConfig({ module: { rules: [ diff --git a/docs/docs/graphql-reference.md b/docs/docs/graphql-reference.md index 2b55d72fe6657..5ecae3f41e95a 100644 --- a/docs/docs/graphql-reference.md +++ b/docs/docs/graphql-reference.md @@ -117,7 +117,7 @@ _In the playground below the list, there is an example query with a description - `eq`: short for **equal**, must match the given data exactly - `ne`: short for **not equal**, must be different from the given data -- `regex`: short for **regular expression**, must match the given pattern. Note that backslashes need to be escaped _twice_, so `/\w+/` needs to be written as `"/\\\\w+/"`. +- `regex`: short for **regular expression**, must match the given pattern - `glob`: short for **global**, allows to use wildcard `*` which acts as a placeholder for any non-empty string - `in`: short for **in array**, must be an element of the array - `nin`: short for **not in array**, must NOT be an element of the array diff --git a/docs/docs/how-to/images-and-media/using-cloudinary-image-service.md b/docs/docs/how-to/images-and-media/using-cloudinary-image-service.md index dabcb04adf53f..5ab438e70ee8c 100644 --- a/docs/docs/how-to/images-and-media/using-cloudinary-image-service.md +++ b/docs/docs/how-to/images-and-media/using-cloudinary-image-service.md @@ -77,7 +77,7 @@ module.exports = { Note that `gatsby-source-cloudinary` takes the following options: -- **`cloudName`** , **`apiKey`** , and **`apiSecret`** **:** These are credentials from your Cloudinary console, stored as three separate environment variables for security. +- **`cloudName`**, **`apiKey`**, and **`apiSecret`** **:** These are credentials from your Cloudinary console, stored as three separate environment variables for security. - **`resourceType`** **:** This is the resource type of the media assets - either an image or a video. - **`prefix`** **:** This is the folder (in your Cloudinary account) in which the files reside. In the example above, the folder is called `gatsby-source-cloudinary`. Assign a name of your choice. Other optional options are `type`, `tags`, and `maxResult`. diff --git a/docs/docs/how-to/performance/improving-site-performance.md b/docs/docs/how-to/performance/improving-site-performance.md new file mode 100644 index 0000000000000..7674bd66cdfed --- /dev/null +++ b/docs/docs/how-to/performance/improving-site-performance.md @@ -0,0 +1,213 @@ +--- +title: Improving Site Performance +--- + +To paraphrase Tolstoy, all fast websites are alike, but all slow websites are slow in different ways. + +This document is a brief guide to improve your Gatsby site's performance. + +## Part 1: Creating a process for performance improvements + +Because websites are hard to make fast and easy to make slow, performance improvement isn't just something that takes place at one point in time. Instead, performance is a system that you put in place to maintain and extend performance gains over time. + +### Step 1: Choose a testing tool + +In order to get a baseline, you need to decide what you consider the "source of truth". + +Lighthouse / PageSpeed Insights and Webpagetest are the most common website performance testing tools in the Gatsby community. Lighthouse tends to be seen as more "canonical". Webpagetest tends to be seen as more precise. + +These tools measure what are known as "Core Web Vitals", which measure both time to page load and time to page interactivity. [Google's official page](https://web.dev/vitals/) has more detail on what these metrics are. + +### Step 2: Set up performance monitoring  + +Site performance monitoring becomes increasingly important the more long-lasting your project is. You can put a lot of effort into performance work -- but then ship a performance regression that wipes out all your hard work! + +There are two options for this: + +- Gatsby Cloud has Lighthouse performance reports built into its CI/CD. Every time someone opens a pull request or merges into master, a Lighthouse report will be run and the performance score displayed. + +- Use a third-party service that offers performance monitoring. Different services offer different options -- schedule runs on a daily basis or CI/CD integration through Github (or your source control service). + +For additional precision, run Lighthouse multiple times and take the median result. + +### Step 3: Quantify the impact of each change you make  + +While you're doing performance-improvement work, it's important to understand the impact of each change or set of changes. You may find that one change gives you a 2-point Lighthouse improvement and another gives you a 20-point improvement. + +There's an easy way to measure this: + +1. Write a pull request with each change or set of changes, using a service like Gatsby Cloud or Netlify that generates deploy previews per-PR. +2. Run Lighthouse tests against the deploy preview for that branch and the deploy preview for master. Do not compare the live site to a deploy preview since the CDN setup may differ. +3. Calculate the difference in Lighthouse scores. +4. If you don't see a significant difference from a change, consider batching similar changes together until the difference is noticeable and thinking about the changes as a group. + +Performance work can be surprisingly nonlinear in impact. + +## Part 2: Implement Improvements. + +When you run a test in your testing tool of choice, it will give you a number of recommendations. While this can feel like a laundry list of issues, it can be helpful to understand the five core categories that these issues are bucketed into. + +- Blocking calls & third-party scripts. +- Javascript bundle size. +- Stylesheets and font files. +- Images and other media. +- Resource requests & CDN caching configuration. + +Every site is different, and the recommendations will give some guidance as to where the highest effort to impact ratio is on your site. + +### Address third-party-script impact + +Various types of calls made in your HTML, like calls to external font files, will block page load or page interactivity in different ways. In addition, third-party scripts can execute "eagerly", often delaying page load while they do so. + +#### Step 1: Remove unneeded and high-cost, low-value scripts + +For each script, it can be helpful to understand the business purpose, relative importance, and who's using the data. This will allow you to identify and remove any unused scripts. + +There may also be relatively unimportant scripts that have a high performance costs; these are also good candidates for removal. + +#### Step 2: lazy load or inline scripts + +One of the lowest-hanging fruits is to set your scripts to load lazily rather than "eagerly" (the default). Any `

Hello world

"`; +exports[`SSR is run for a page when it is requested 1`] = `"

Hello world

"`; exports[`SSR it generates an error page correctly 1`] = ` " diff --git a/integration-tests/ssr/__tests__/ssr.js b/integration-tests/ssr/__tests__/ssr.js index 25b0cccd0d95e..b08b293208ac4 100644 --- a/integration-tests/ssr/__tests__/ssr.js +++ b/integration-tests/ssr/__tests__/ssr.js @@ -3,6 +3,20 @@ const execa = require(`execa`) const fs = require(`fs-extra`) const path = require(`path`) +function fetchUntil(url, filter, timeout = 1000) { + return new Promise(resolve => { + fetch(url).then(res => { + if (filter(res)) { + resolve(res) + } else { + setTimeout(() => { + resolve(fetchUntil(url, filter, timeout)) + }, timeout) + } + }) + }) +} + describe(`SSR`, () => { test(`is run for a page when it is requested`, async () => { const html = await fetch(`http://localhost:8000/`).then(res => res.text()) @@ -22,36 +36,15 @@ describe(`SSR`, () => { fs.copySync(src, dest) const pageUrl = `http://localhost:8000/bad-page/` - await new Promise(resolve => { - // Poll until the new page is bundled (so starts returning a non-404 status). - const testInterval = setInterval(() => { - fetch(pageUrl).then(res => { - if (res.status !== 404) { - clearInterval(testInterval) - resolve() - } - }) - }, 1000) - }) - - const rawDevHtml = await fetch( - `http://localhost:8000/bad-page/` + // Poll until the new page is bundled (so starts returning a non-404 status). + const rawDevHtml = await fetchUntil( + pageUrl, + res => res.status === 500 ).then(res => res.text()) expect(rawDevHtml).toMatchSnapshot() - fs.remove(dest) + await fs.remove(dest) // After the page is gone, it'll 404. - await new Promise(resolve => { - setTimeout(() => { - const testInterval = setInterval(() => { - fetch(pageUrl).then(res => { - if (res.status === 404) { - clearInterval(testInterval) - resolve() - } - }) - }, 400) - }, 400) - }) + await fetchUntil(pageUrl, res => res.status === 404) }, 15000) }) diff --git a/package.json b/package.json index 0a97c408b6e37..d69cea3cf8ce7 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,6 @@ "@types/bluebird": "^3.5.33", "@types/cache-manager": "^2.10.3", "@types/common-tags": "^1.8.0", - "@types/eslint": "^6.8.1", "@types/express": "^4.17.3", "@types/fs-extra": "^8.1.1", "@types/got": "^9.6.11", @@ -25,10 +24,9 @@ "@types/semver": "^7.3.4", "@types/signal-exit": "^3.0.0", "@types/stack-trace": "^0.0.29", - "@types/webpack": "^4.41.24", "@types/webpack-merge": "^4.1.5", - "@typescript-eslint/eslint-plugin": "^2.34.0", - "@typescript-eslint/parser": "^2.34.0", + "@typescript-eslint/eslint-plugin": "^4.14.2", + "@typescript-eslint/parser": "^4.14.2", "babel-eslint": "^10.1.0", "babel-jest": "^24.9.0", "chalk": "^4.1.0", @@ -75,6 +73,7 @@ "remark-preset-lint-markdown-style-guide": "^3.0.1", "remark-preset-lint-recommended": "^4.0.1", "remark-retext": "^4.0.0", + "retext": "^7.0.1", "retext-diacritics": "^3.0.0", "retext-emoji": "^7.0.2", "retext-english": "^3.0.4", @@ -84,11 +83,10 @@ "retext-spell": "^4.0.0", "retext-syntax-mentions": "^2.1.1", "retext-syntax-urls": "^2.0.0", - "retext": "^7.0.1", "rimraf": "^3.0.2", "svgo": "1.3.2", "ts-jest": "^22", - "typescript": "^3.9.7", + "typescript": "^4.1.5", "unified": "^9.2.0", "yargs": "^15.4.1" }, @@ -106,7 +104,7 @@ ], "private": true, "lint-staged": { - "*.{js,jsx,ts,tsx}": "eslint --cache --ext .js,.jsx,.ts,.tsx --fix", + "*.{js,jsx,ts,tsx}": "eslint --ext .js,.jsx,.ts,.tsx --fix", "*.{md,css,scss,yaml,yml}": "prettier --write", "*.svg": "svgo --pretty --indent=2 --config=svgo.yml --multipass" }, @@ -131,7 +129,7 @@ "lerna": "lerna", "lerna-prepare": "lerna run prepare", "lint": "npm-run-all --continue-on-error -p lint:code lint:docs lint:other", - "lint:code": "eslint --cache --ext .js,.jsx,.ts,.tsx .", + "lint:code": "eslint --ext .js,.jsx,.ts,.tsx .", "lint:docs": "remark docs/{contributing,docs,tutorial}", "lint:scripts": "sh scripts/lint-shell-scripts.sh", "lint:other": "npm run prettier -- --check", diff --git a/packages/babel-plugin-remove-graphql-queries/CHANGELOG.md b/packages/babel-plugin-remove-graphql-queries/CHANGELOG.md index 776c04c7957a6..a6b9493989469 100644 --- a/packages/babel-plugin-remove-graphql-queries/CHANGELOG.md +++ b/packages/babel-plugin-remove-graphql-queries/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/babel-plugin-remove-graphql-queries@3.0.0-next.1...babel-plugin-remove-graphql-queries@3.0.0-next.2) (2021-02-22) + +**Note:** Version bump only for package babel-plugin-remove-graphql-queries + +# [3.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/babel-plugin-remove-graphql-queries@3.0.0-next.0...babel-plugin-remove-graphql-queries@3.0.0-next.1) (2021-02-17) + +### Features + +- **gatsby:** Remove possibility to use global graphql tag for queries ([#29291](https://github.com/gatsbyjs/gatsby/issues/29291)) ([d933462](https://github.com/gatsbyjs/gatsby/commit/d933462d64f004e1a9db2d3407797d45ff8b4762)) + # [3.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/babel-plugin-remove-graphql-queries@2.17.0-next.0...babel-plugin-remove-graphql-queries@3.0.0-next.0) (2021-02-05) **Note:** Version bump only for package babel-plugin-remove-graphql-queries diff --git a/packages/babel-plugin-remove-graphql-queries/package.json b/packages/babel-plugin-remove-graphql-queries/package.json index da97e1b8293c2..6a9b5f7d3739c 100644 --- a/packages/babel-plugin-remove-graphql-queries/package.json +++ b/packages/babel-plugin-remove-graphql-queries/package.json @@ -1,6 +1,6 @@ { "name": "babel-plugin-remove-graphql-queries", - "version": "3.0.0-next.0", + "version": "3.0.0-next.2", "author": "Jason Quense ", "repository": { "type": "git", @@ -13,7 +13,7 @@ "@babel/core": "^7.12.3", "babel-preset-gatsby-package": "^1.0.0-next.0", "cross-env": "^7.0.3", - "gatsby-core-utils": "^2.0.0-next.0" + "gatsby-core-utils": "^2.0.0-next.1" }, "peerDependencies": { "@babel/core": "^7.0.0", diff --git a/packages/babel-preset-gatsby/CHANGELOG.md b/packages/babel-preset-gatsby/CHANGELOG.md index cd4221f6bdd9b..0ec03686a7fb8 100644 --- a/packages/babel-preset-gatsby/CHANGELOG.md +++ b/packages/babel-preset-gatsby/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.0.0-next.3](https://github.com/gatsbyjs/gatsby/compare/babel-preset-gatsby@1.0.0-next.2...babel-preset-gatsby@1.0.0-next.3) (2021-02-22) + +**Note:** Version bump only for package babel-preset-gatsby + # [1.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/babel-preset-gatsby@1.0.0-next.1...babel-preset-gatsby@1.0.0-next.2) (2021-02-11) **Note:** Version bump only for package babel-preset-gatsby diff --git a/packages/babel-preset-gatsby/package.json b/packages/babel-preset-gatsby/package.json index 1d40deda08db4..95b144819b981 100644 --- a/packages/babel-preset-gatsby/package.json +++ b/packages/babel-preset-gatsby/package.json @@ -1,6 +1,6 @@ { "name": "babel-preset-gatsby", - "version": "1.0.0-next.2", + "version": "1.0.0-next.3", "author": "Philipp Spiess ", "repository": { "type": "git", @@ -22,7 +22,7 @@ "babel-plugin-dynamic-import-node": "^2.3.3", "babel-plugin-macros": "^2.8.0", "babel-plugin-transform-react-remove-prop-types": "^0.4.24", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "gatsby-legacy-polyfills": "^1.0.0-next.0" }, "peerDependencies": { diff --git a/packages/create-gatsby/package.json b/packages/create-gatsby/package.json index 344dbea06f5c9..146a89661922e 100644 --- a/packages/create-gatsby/package.json +++ b/packages/create-gatsby/package.json @@ -29,13 +29,13 @@ "fs-extra": "^9.0.1", "gatsby-plugin-utils": "^1.0.0-next.0", "joi": "^17.2.1", - "microbundle": "^0.12.4", + "microbundle": "^0.13.0", "node-fetch": "^2.6.1", "prettier": "^2.1.2", "string-length": "^4.0.1", "terminal-link": "^2.1.1", "tiny-spin": "^1.0.2", - "typescript": "^4.0.5", + "typescript": "^4.1.5", "uuid": "3.4.0" }, "repository": { diff --git a/packages/create-gatsby/src/index.ts b/packages/create-gatsby/src/index.ts index 7f7ede1b248f0..a970a623426cf 100644 --- a/packages/create-gatsby/src/index.ts +++ b/packages/create-gatsby/src/index.ts @@ -307,7 +307,7 @@ ${center(c.blueBright.bold.underline(`Welcome to Gatsby!`))} trackCli(`CREATE_GATSBY_SET_PLUGINS_START`) - const enquirer = new Enquirer>() + const enquirer = new Enquirer>>() enquirer.use(plugin) pluginConfig = { ...pluginConfig, ...(await enquirer.prompt(config)) } diff --git a/packages/create-gatsby/src/utils.ts b/packages/create-gatsby/src/utils.ts index bcf66234d56b9..26165037004b0 100644 --- a/packages/create-gatsby/src/utils.ts +++ b/packages/create-gatsby/src/utils.ts @@ -1,6 +1,6 @@ const ESC = `\u001b` -export const clearLine = (count = 1): Promise => +export const clearLine = (count = 1): Promise => new Promise(resolve => { // First move the cursor up one line... process.stderr.moveCursor(0, -count, () => { diff --git a/packages/create-gatsby/tsconfig.json b/packages/create-gatsby/tsconfig.json index dec522cda6d45..711af0cabea91 100644 --- a/packages/create-gatsby/tsconfig.json +++ b/packages/create-gatsby/tsconfig.json @@ -7,6 +7,7 @@ "allowJs": true /* Allow javascript files to be compiled. */, // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // If you're getting a warning about declarationDir, it's probably this https://github.com/developit/microbundle/issues/771 "declaration": false /* Generates corresponding '.d.ts' file. */, // "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ diff --git a/packages/gatsby-admin/CHANGELOG.md b/packages/gatsby-admin/CHANGELOG.md index 8c56b899094f2..4126582e123cb 100644 --- a/packages/gatsby-admin/CHANGELOG.md +++ b/packages/gatsby-admin/CHANGELOG.md @@ -3,6 +3,24 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [0.10.0-next.8](https://github.com/gatsbyjs/gatsby/compare/gatsby-admin@0.10.0-next.7...gatsby-admin@0.10.0-next.8) (2021-02-22) + +**Note:** Version bump only for package gatsby-admin + +# [0.10.0-next.7](https://github.com/gatsbyjs/gatsby/compare/gatsby-admin@0.10.0-next.6...gatsby-admin@0.10.0-next.7) (2021-02-19) + +**Note:** Version bump only for package gatsby-admin + +# [0.10.0-next.6](https://github.com/gatsbyjs/gatsby/compare/gatsby-admin@0.10.0-next.5...gatsby-admin@0.10.0-next.6) (2021-02-18) + +**Note:** Version bump only for package gatsby-admin + +# [0.10.0-next.5](https://github.com/gatsbyjs/gatsby/compare/gatsby-admin@0.10.0-next.4...gatsby-admin@0.10.0-next.5) (2021-02-17) + +### Features + +- **gatsby:** upgrade webpack to version 5 ([#29145](https://github.com/gatsbyjs/gatsby/issues/29145)) ([a7a3991](https://github.com/gatsbyjs/gatsby/commit/a7a3991ca2ad450abaacdc168e9900dad995b584)) + # [0.10.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby-admin@0.10.0-next.3...gatsby-admin@0.10.0-next.4) (2021-02-15) **Note:** Version bump only for package gatsby-admin diff --git a/packages/gatsby-admin/gatsby-node.js b/packages/gatsby-admin/gatsby-node.js index a82ea6cf8c268..f8701b58a67a8 100644 --- a/packages/gatsby-admin/gatsby-node.js +++ b/packages/gatsby-admin/gatsby-node.js @@ -1,7 +1,9 @@ exports.onCreateWebpackConfig = ({ actions }) => { actions.setWebpackConfig({ - node: { - fs: 'empty' + resolve: { + alias: { + path: require.resolve("path-browserify") + } } }) - } \ No newline at end of file + } diff --git a/packages/gatsby-admin/package.json b/packages/gatsby-admin/package.json index 1c6036afd1dd0..89d82ee2fedf6 100644 --- a/packages/gatsby-admin/package.json +++ b/packages/gatsby-admin/package.json @@ -1,6 +1,6 @@ { "name": "gatsby-admin", - "version": "0.10.0-next.4", + "version": "0.10.0-next.8", "main": "index.js", "author": "Max Stoiber", "license": "MIT", @@ -16,19 +16,20 @@ "@feedback-fish/react": "^1.2.1", "@types/react-instantsearch-dom": "^5.2.6", "@types/socket.io-client": "^1.4.35", - "@typescript-eslint/eslint-plugin": "^2.34.0", - "@typescript-eslint/parser": "^2.34.0", + "@typescript-eslint/eslint-plugin": "^4.14.2", + "@typescript-eslint/parser": "^4.14.2", "csstype": "^2.6.14", "formik": "^2.2.6", - "gatsby": "^3.0.0-next.4", + "gatsby": "^3.0.0-next.8", "gatsby-interface": "^0.0.244", - "gatsby-plugin-typescript": "^3.0.0-next.0", + "gatsby-plugin-typescript": "^3.0.0-next.2", "gatsby-plugin-webfonts": "^1.1.4", "gatsby-source-graphql": "^3.0.0-next.1", "lodash-es": "^4.17.20", "ncp": "^2.0.0", "nodemon": "^2.0.7", "normalize.css": "^8.0.1", + "path-browserify": "^1.0.1", "prism-react-renderer": "^1.1.1", "query-string": "^6.13.8", "react": "^16.12.0", @@ -44,7 +45,7 @@ "strict-ui": "^0.2.0-0", "subscriptions-transport-ws": "^0.9.18", "theme-ui": "^0.4.0-rc.14", - "typescript": "^3.9.7", + "typescript": "^4.1.5", "urql": "^1.11.6", "yup": "^0.32.8" }, diff --git a/packages/gatsby-admin/src/components/instantsearch-provider.tsx b/packages/gatsby-admin/src/components/instantsearch-provider.tsx index 4571748531cc9..6b10a88ba6d5c 100644 --- a/packages/gatsby-admin/src/components/instantsearch-provider.tsx +++ b/packages/gatsby-admin/src/components/instantsearch-provider.tsx @@ -7,12 +7,13 @@ import { ToggleRefinement, } from "react-instantsearch-dom" import algoliaConfig from "../utils/algolia-config" +import { ReactNode } from "react" export default function InstantSearchProvider({ children, searchState, }: { - children: React.ReactNode + children: ReactNode searchState?: string }): JSX.Element { return ( diff --git a/packages/gatsby-admin/src/components/layout.tsx b/packages/gatsby-admin/src/components/layout.tsx index f1ccf229d9eff..b1a75cbaec325 100644 --- a/packages/gatsby-admin/src/components/layout.tsx +++ b/packages/gatsby-admin/src/components/layout.tsx @@ -5,8 +5,9 @@ import { Helmet } from "react-helmet" import Providers from "./providers" import Navbar from "./navbar" import { PageviewTracker } from "./pageview-tracker" +import { ReactNode } from "react" -function Layout({ children }: { children: React.ReactNode }): JSX.Element { +function Layout({ children }: { children: ReactNode }): JSX.Element { return ( diff --git a/packages/gatsby-admin/src/components/plugin-search.tsx b/packages/gatsby-admin/src/components/plugin-search.tsx index 28109baa9e780..008b049629c0f 100644 --- a/packages/gatsby-admin/src/components/plugin-search.tsx +++ b/packages/gatsby-admin/src/components/plugin-search.tsx @@ -1,5 +1,6 @@ /* @jsx jsx */ import { jsx } from "strict-ui" +import React from "react" import { connectAutoComplete } from "react-instantsearch-dom" import { Combobox, @@ -36,7 +37,7 @@ const SearchCombobox: React.FC<{ )) // the search bar holds the Search component in the InstantSearch widget -const PluginSearchInput: React.FC<{}> = () => ( +const PluginSearchInput: React.FC> = () => (
= ({ children }) => { +const GraphQLProvider: React.FC> = ({ children }) => { const services = useServices() const [client, setClient] = React.useState(() => services @@ -158,7 +158,7 @@ const GraphQLProvider: React.FC<{}> = ({ children }) => { return {children} } -const Providers: React.FC<{}> = ({ children }) => ( +const Providers: React.FC> = ({ children }) => ( {/* NOTE(@mxstbr): The GraphQLProvider needs to be in the ServicesProvider */} diff --git a/packages/gatsby-admin/src/pages/plugins.tsx b/packages/gatsby-admin/src/pages/plugins.tsx index b37b8e84afbc6..251fdcdaefa46 100644 --- a/packages/gatsby-admin/src/pages/plugins.tsx +++ b/packages/gatsby-admin/src/pages/plugins.tsx @@ -5,7 +5,7 @@ import { useQuery } from "urql" import { Spinner } from "theme-ui" import { Global } from "@emotion/react" import { useMutation } from "urql" -import { useState, Fragment, useEffect } from "react" +import { useState, Fragment, useEffect, FormEvent } from "react" import { AnchorButton, Button, @@ -70,8 +70,10 @@ const markdownRenderers = { style={style} > {tokens.map((line, i) => ( + // eslint-disable-next-line react/jsx-key
{line.map((token, key) => ( + // eslint-disable-next-line react/jsx-key ))}
@@ -319,7 +321,7 @@ export default function PluginView( { + onSubmit={(evt: FormEvent): void => { evt.preventDefault() setValidationError(null) let json diff --git a/packages/gatsby-admin/src/utils/use-npm-data.tsx b/packages/gatsby-admin/src/utils/use-npm-data.tsx index 747a974ed4a44..fa1bc26a4aea8 100644 --- a/packages/gatsby-admin/src/utils/use-npm-data.tsx +++ b/packages/gatsby-admin/src/utils/use-npm-data.tsx @@ -19,7 +19,7 @@ export default function useNpmPackageData( ): IUseNpmPackageDataResult { const [fetching, setFetching] = React.useState(true) const [error, setError] = React.useState(null) - const [data, setData] = React.useState<{} | null>(null) + const [data, setData] = React.useState | null>(null) React.useEffect(() => { setFetching(true) diff --git a/packages/gatsby-cli/CHANGELOG.md b/packages/gatsby-cli/CHANGELOG.md index c2586d11aa378..f9985997df0ff 100644 --- a/packages/gatsby-cli/CHANGELOG.md +++ b/packages/gatsby-cli/CHANGELOG.md @@ -3,6 +3,20 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.6](https://github.com/gatsbyjs/gatsby/compare/gatsby-cli@3.0.0-next.5...gatsby-cli@3.0.0-next.6) (2021-02-22) + +**Note:** Version bump only for package gatsby-cli + +# [3.0.0-next.5](https://github.com/gatsbyjs/gatsby/compare/gatsby-cli@3.0.0-next.4...gatsby-cli@3.0.0-next.5) (2021-02-18) + +### Features + +- **conditional-page-builds:** make it default ([#29548](https://github.com/gatsbyjs/gatsby/issues/29548)) ([348a5bf](https://github.com/gatsbyjs/gatsby/commit/348a5bf989a955345d1b958e25978ed90864cd72)) + +# [3.0.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby-cli@3.0.0-next.3...gatsby-cli@3.0.0-next.4) (2021-02-17) + +**Note:** Version bump only for package gatsby-cli + # [3.0.0-next.3](https://github.com/gatsbyjs/gatsby/compare/gatsby-cli@3.0.0-next.2...gatsby-cli@3.0.0-next.3) (2021-02-15) **Note:** Version bump only for package gatsby-cli diff --git a/packages/gatsby-cli/package.json b/packages/gatsby-cli/package.json index d158a4402b1d7..5f9889733b114 100644 --- a/packages/gatsby-cli/package.json +++ b/packages/gatsby-cli/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-cli", "description": "Gatsby command-line interface for creating new sites and running Gatsby commands", - "version": "3.0.0-next.3", + "version": "3.0.0-next.6", "author": "Kyle Mathews ", "bin": { "gatsby": "cli.js" @@ -24,9 +24,9 @@ "execa": "^3.4.0", "fs-exists-cached": "^1.0.0", "fs-extra": "^8.1.0", - "gatsby-core-utils": "^2.0.0-next.0", - "gatsby-recipes": "^0.11.0-next.2", - "gatsby-telemetry": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", + "gatsby-recipes": "^0.11.0-next.4", + "gatsby-telemetry": "^2.0.0-next.1", "hosted-git-info": "^3.0.6", "is-valid-path": "^0.1.1", "lodash": "^4.17.20", @@ -69,7 +69,7 @@ "rollup": "^2.34.2", "rollup-plugin-auto-external": "^2.0.0", "rollup-plugin-internal": "^1.0.0", - "typescript": "^3.9.7" + "typescript": "^4.1.5" }, "files": [ "lib/", diff --git a/packages/gatsby-cli/src/create-cli.ts b/packages/gatsby-cli/src/create-cli.ts index bccffe11ee8ea..dcee342521f69 100644 --- a/packages/gatsby-cli/src/create-cli.ts +++ b/packages/gatsby-cli/src/create-cli.ts @@ -24,8 +24,10 @@ import { getPackageManager, setPackageManager } from "./util/package-manager" import reporter from "./reporter" import pluginHandler from "./handlers/plugin" -const handlerP = (fn: Function) => (...args: Array): void => { - Promise.resolve(fn(...args)).then( +const handlerP = (fn: (args: yargs.Arguments) => void) => ( + args: yargs.Arguments +): void => { + Promise.resolve(fn(args)).then( () => process.exit(0), err => report.panic(err) ) @@ -65,7 +67,9 @@ function buildLocalCommands(cli: yargs.Argv, isLocalSite: boolean): void { return undefined } - function resolveLocalCommand(command: string): Function | never { + function resolveLocalCommand( + command: string + ): ((...args: Array) => void) | never { if (!isLocalSite) { cli.showHelp() report.verbose(`current directory: ${directory}`) @@ -107,8 +111,11 @@ function buildLocalCommands(cli: yargs.Argv, isLocalSite: boolean): void { function getCommandHandler( command: string, - handler?: (args: yargs.Arguments, cmd: Function) => void - ) { + handler?: ( + args: yargs.Arguments, + cmd: (args: yargs.Arguments) => void + ) => void + ): (argv: yargs.Arguments) => void { return (argv: yargs.Arguments): void => { report.setVerbose(!!argv.verbose) @@ -193,23 +200,26 @@ function buildLocalCommands(cli: yargs.Argv, isLocalSite: boolean): void { describe: `Opens a port for debugging. Will block until debugger is attached. See https://www.gatsbyjs.com/docs/debugging-the-build-process/`, }), handler: handlerP( - getCommandHandler(`develop`, (args: yargs.Arguments, cmd: Function) => { - process.env.NODE_ENV = process.env.NODE_ENV || `development` - startGraphQLServer(siteInfo.directory, true) + getCommandHandler( + `develop`, + (args: yargs.Arguments, cmd: (args: yargs.Arguments) => unknown) => { + process.env.NODE_ENV = process.env.NODE_ENV || `development` + startGraphQLServer(siteInfo.directory, true) + + if (args.hasOwnProperty(`inspect`)) { + args.inspect = args.inspect || 9229 + } + if (args.hasOwnProperty(`inspect-brk`)) { + args.inspect = args.inspect || 9229 + } - if (args.hasOwnProperty(`inspect`)) { - args.inspect = args.inspect || 9229 - } - if (args.hasOwnProperty(`inspect-brk`)) { - args.inspect = args.inspect || 9229 + cmd(args) + // Return an empty promise to prevent handlerP from exiting early. + // The development server shouldn't ever exit until the user directly + // kills it so this is fine. + return new Promise(() => {}) } - - cmd(args) - // Return an empty promise to prevent handlerP from exiting early. - // The development server shouldn't ever exit until the user directly - // kills it so this is fine. - return new Promise(() => {}) - }) + ) ), }) @@ -243,25 +253,30 @@ function buildLocalCommands(cli: yargs.Argv, isLocalSite: boolean): void { type: `string`, describe: `Tracer configuration file (OpenTracing compatible). See https://gatsby.dev/tracing`, }) - // log-pages and write-to-file are specific to experimental GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES feature - // because of that they are hidden from `--help` but still defined so `yargs` know about them + // log-pages and write-to-file were added specifically to experimental GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES feature + // in gatsby@2. They are useful, but not very applicable (specifically `--write-to-file`) as generic approach, as it only + // list pages without other artifacts, so it's useful in very narrow scope. Because we don't have alternative right now + // those toggles are kept for users that rely on them, but we won't promote them and will keep them "hidden". .option(`log-pages`, { type: `boolean`, default: false, - describe: `Log the pages that changes since last build (only available when using GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES).`, + describe: `Log the pages that changes since last build.`, hidden: true, }) .option(`write-to-file`, { type: `boolean`, default: false, - describe: `Save the log of changed pages for future comparison (only available when using GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES).`, + describe: `Save the log of changed pages for future comparison.`, hidden: true, }), handler: handlerP( - getCommandHandler(`build`, (args: yargs.Arguments, cmd: Function) => { - process.env.NODE_ENV = `production` - return cmd(args) - }) + getCommandHandler( + `build`, + (args: yargs.Arguments, cmd: (args: yargs.Arguments) => void) => { + process.env.NODE_ENV = `production` + return cmd(args) + } + ) ), }) @@ -362,7 +377,7 @@ function buildLocalCommands(cli: yargs.Argv, isLocalSite: boolean): void { describe: `Get a node repl with context of Gatsby environment, see (https://www.gatsbyjs.com/docs/gatsby-repl/)`, handler: getCommandHandler( `repl`, - (args: yargs.Arguments, cmd: Function) => { + (args: yargs.Arguments, cmd: (args: yargs.Arguments) => void) => { process.env.NODE_ENV = process.env.NODE_ENV || `development` return cmd(args) } @@ -384,19 +399,14 @@ function buildLocalCommands(cli: yargs.Argv, isLocalSite: boolean): void { default: false, describe: `Install recipe (defaults to plan mode)`, }), - handler: handlerP( - async ({ - recipe, - develop, - install, - }: yargs.Arguments<{ - recipe: string | undefined - develop: boolean - install: boolean - }>) => { - await recipesHandler(siteInfo.directory, recipe, develop, install) - } - ), + handler: handlerP(async ({ recipe, develop, install }: yargs.Arguments) => { + await recipesHandler( + siteInfo.directory, + recipe as string, + develop as boolean, + install as boolean + ) + }), }) cli.command({ diff --git a/packages/gatsby-cli/src/reporter/errors.ts b/packages/gatsby-cli/src/reporter/errors.ts index 2bebaabed4418..5f10a3a251d6d 100644 --- a/packages/gatsby-cli/src/reporter/errors.ts +++ b/packages/gatsby-cli/src/reporter/errors.ts @@ -106,7 +106,7 @@ export function getErrorFormatter(): PrettyError { export async function createErrorFromString( errorStr: string = ``, sourceMapFile: string -): Promise { +): Promise { let [message, ...rest] = errorStr.split(/\r\n|[\n\r]/g) // pull the message from the first line then remove the `Error:` prefix // FIXME: when https://github.com/AriaMinaei/pretty-error/pull/49 is merged diff --git a/packages/gatsby-cli/src/reporter/prepare-stack-trace.ts b/packages/gatsby-cli/src/reporter/prepare-stack-trace.ts index 08de28315d899..21a8b46fde302 100644 --- a/packages/gatsby-cli/src/reporter/prepare-stack-trace.ts +++ b/packages/gatsby-cli/src/reporter/prepare-stack-trace.ts @@ -13,7 +13,7 @@ import { } from "source-map" export class ErrorWithCodeFrame extends Error { - codeFrame = `` + codeFrame?: string = `` constructor(error: Error) { super(error.message) diff --git a/packages/gatsby-cli/src/reporter/reporter.ts b/packages/gatsby-cli/src/reporter/reporter.ts index dfdbc866399a2..cf1439ba521fc 100644 --- a/packages/gatsby-cli/src/reporter/reporter.ts +++ b/packages/gatsby-cli/src/reporter/reporter.ts @@ -109,7 +109,7 @@ class Reporter { ): IStructuredError | Array => { let details: { error?: Error - context: {} + context: Record } = { context: {}, } diff --git a/packages/gatsby-cli/src/structured-errors/error-map.ts b/packages/gatsby-cli/src/structured-errors/error-map.ts index a25efb6bad705..b5248b3148b0b 100644 --- a/packages/gatsby-cli/src/structured-errors/error-map.ts +++ b/packages/gatsby-cli/src/structured-errors/error-map.ts @@ -49,8 +49,15 @@ const errors = { level: Level.ERROR, }, "98124": { - text: (context): string => - `${context.stageLabel} failed\n\n${context.sourceMessage}\n\nIf you're trying to use a package make sure that '${context.packageName}' is installed. If you're trying to use a local file make sure that the path is correct.`, + text: (context): string => { + let message = `${context.stageLabel} failed\n\n${context.sourceMessage}\n\nIf you're trying to use a package make sure that '${context.packageName}' is installed. If you're trying to use a local file make sure that the path is correct.` + + if (context.deprecationReason) { + message += `\n\n${context.deprecationReason}` + } + + return message + }, type: Type.WEBPACK, level: Level.ERROR, category: ErrorCategory.USER, diff --git a/packages/gatsby-codemods/CHANGELOG.md b/packages/gatsby-codemods/CHANGELOG.md index c093168d43cc2..f3edc064e34f7 100644 --- a/packages/gatsby-codemods/CHANGELOG.md +++ b/packages/gatsby-codemods/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [2.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-codemods@2.0.0-next.1...gatsby-codemods@2.0.0-next.2) (2021-02-22) + +### Bug Fixes + +- **deps:** update minor and patch for gatsby-codemods ([#29513](https://github.com/gatsbyjs/gatsby/issues/29513)) ([e65d60c](https://github.com/gatsbyjs/gatsby/commit/e65d60c154b3523fbefa9a9fb7a4bc8dddef32f6)) + # [2.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-codemods@2.0.0-next.0...gatsby-codemods@2.0.0-next.1) (2021-02-11) **Note:** Version bump only for package gatsby-codemods diff --git a/packages/gatsby-codemods/package.json b/packages/gatsby-codemods/package.json index 65fd37fc955f3..6fe27db850018 100644 --- a/packages/gatsby-codemods/package.json +++ b/packages/gatsby-codemods/package.json @@ -1,6 +1,6 @@ { "name": "gatsby-codemods", - "version": "2.0.0-next.1", + "version": "2.0.0-next.2", "description": "A collection of codemod scripts for use with JSCodeshift that help migrate to newer versions of Gatsby.", "main": "index.js", "scripts": { @@ -30,7 +30,7 @@ "@babel/plugin-syntax-typescript": "^7.12.1", "@babel/runtime": "^7.12.5", "execa": "^5.0.0", - "graphql": "^15.4.0", + "graphql": "^15.5.0", "jscodeshift": "^0.11.0", "recast": "^0.20.4" }, diff --git a/packages/gatsby-core-utils/CHANGELOG.md b/packages/gatsby-core-utils/CHANGELOG.md index 798e2fd24d9bb..0149a04b3962f 100644 --- a/packages/gatsby-core-utils/CHANGELOG.md +++ b/packages/gatsby-core-utils/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [2.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-core-utils@2.0.0-next.0...gatsby-core-utils@2.0.0-next.1) (2021-02-22) + +### Features + +- **gatsby-core-utils:** Add file download functions ([#29531](https://github.com/gatsbyjs/gatsby/issues/29531)) ([1a9469d](https://github.com/gatsbyjs/gatsby/commit/1a9469d67a19007faebebfb8ce876970c5e0ffaf)) + # [2.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-core-utils@1.11.0-next.0...gatsby-core-utils@2.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-core-utils diff --git a/packages/gatsby-core-utils/package.json b/packages/gatsby-core-utils/package.json index 8215a4fa57493..839bd4d97defb 100644 --- a/packages/gatsby-core-utils/package.json +++ b/packages/gatsby-core-utils/package.json @@ -1,6 +1,6 @@ { "name": "gatsby-core-utils", - "version": "2.0.0-next.0", + "version": "2.0.0-next.1", "description": "A collection of gatsby utils used in different gatsby packages", "keywords": [ "gatsby", @@ -31,6 +31,7 @@ "dependencies": { "ci-info": "2.0.0", "configstore": "^5.0.1", + "file-type": "^16.2.0", "fs-extra": "^8.1.0", "node-object-hash": "^2.0.0", "proper-lockfile": "^4.1.1", @@ -43,7 +44,7 @@ "@types/ci-info": "2.0.0", "babel-preset-gatsby-package": "^1.0.0-next.0", "cross-env": "^7.0.3", - "typescript": "^3.9.7" + "typescript": "^4.1.5" }, "engines": { "node": ">=12.13.0" diff --git a/packages/gatsby-core-utils/src/__tests__/create-remote-file-node-integration.js b/packages/gatsby-core-utils/src/__tests__/create-remote-file-node-integration.js new file mode 100644 index 0000000000000..70cb94d036268 --- /dev/null +++ b/packages/gatsby-core-utils/src/__tests__/create-remote-file-node-integration.js @@ -0,0 +1,238 @@ +// @ts-check +import path from "path" +import zlib from "zlib" +import os from "os" +import { rest } from "msw" +import { setupServer } from "msw/node" +import { Writable } from "stream" +import got from "got" +import { fetchRemoteFile } from "../fetch-remote-file" + +const fs = jest.requireActual(`fs-extra`) + +const gotStream = jest.spyOn(got, `stream`) +const urlCount = new Map() + +async function getFileSize(file) { + const stat = await fs.stat(file) + + return stat.size +} + +/** + * A utility to help create file responses + * - Url with attempts will use maxBytes for x amount of time until it delivers the full response + * - MaxBytes indicates how much bytes we'll be sending + * + * @param {string} file File path on disk + * @param {Object} req Is the request object from msw + * @param {{ compress?: boolean}} options Options for the getFilecontent (use gzip or not) + */ +async function getFileContent(file, req, options = {}) { + const cacheKey = req.url.origin + req.url.pathname + const maxRetry = req.url.searchParams.get(`attempts`) + const maxBytes = req.url.searchParams.get(`maxBytes`) + const currentRetryCount = urlCount.get(cacheKey) || 0 + urlCount.set(cacheKey, currentRetryCount + 1) + + let fileContentBuffer = await fs.readFile(file) + if (options.compress) { + fileContentBuffer = zlib.deflateSync(fileContentBuffer) + } + + const content = await new Promise(resolve => { + const fileStream = fs.createReadStream(file, { + end: + currentRetryCount < Number(maxRetry) + ? Number(maxBytes) + : Number.MAX_SAFE_INTEGER, + }) + + const writableStream = new Writable() + const result = [] + writableStream._write = (chunk, encoding, next) => { + result.push(chunk) + + next() + } + + writableStream.on(`finish`, () => { + resolve(Buffer.concat(result)) + }) + + // eslint-disable-next-line no-unused-vars + let stream = fileStream + if (options.compress) { + stream = stream.pipe(zlib.createDeflate()) + } + + stream.pipe(writableStream) + }) + + return { + content, + contentLength: + req.url.searchParams.get(`contentLength`) === `false` + ? undefined + : fileContentBuffer.length, + } +} + +const server = setupServer( + rest.get(`http://external.com/logo.svg`, async (req, res, ctx) => { + const { content, contentLength } = await getFileContent( + path.join(__dirname, `./fixtures/gatsby-logo.svg`), + req + ) + + return res( + ctx.set(`Content-Type`, `image/svg+xml`), + ctx.set(`Content-Length`, contentLength), + ctx.status(200), + ctx.body(content) + ) + }), + rest.get(`http://external.com/logo-gzip.svg`, async (req, res, ctx) => { + const { content, contentLength } = await getFileContent( + path.join(__dirname, `./fixtures/gatsby-logo.svg`), + req, + { + compress: true, + } + ) + + return res( + ctx.set(`Content-Type`, `image/svg+xml`), + ctx.set(`content-encoding`, `gzip`), + ctx.set(`Content-Length`, contentLength), + ctx.status(200), + ctx.body(content) + ) + }), + rest.get(`http://external.com/dog.jpg`, async (req, res, ctx) => { + const { content, contentLength } = await getFileContent( + path.join(__dirname, `./fixtures/dog-thumbnail.jpg`), + req + ) + + return res( + ctx.set(`Content-Type`, `image/svg+xml`), + ctx.set(`Content-Length`, contentLength), + ctx.status(200), + ctx.body(content) + ) + }) +) + +function createMockCache() { + const tmpDir = fs.mkdtempSync( + path.join(os.tmpdir(), `gatsby-source-filesystem-`) + ) + + return { + get: jest.fn(), + set: jest.fn(), + directory: tmpDir, + } +} + +describe(`create-remote-file-node`, () => { + let cache + + beforeAll(() => { + cache = createMockCache() + // Establish requests interception layer before all tests. + server.listen() + }) + afterAll(() => { + if (cache) { + fs.removeSync(cache.directory) + } + + // Clean up after all tests are done, preventing this + // interception layer from affecting irrelevant tests. + server.close() + }) + + beforeEach(() => { + gotStream.mockClear() + urlCount.clear() + }) + + it(`downloads and create a file`, async () => { + const filePath = await fetchRemoteFile({ + url: `http://external.com/logo.svg`, + cache, + }) + + expect(path.basename(filePath)).toBe(`logo.svg`) + expect(gotStream).toBeCalledTimes(1) + }) + + it(`downloads and create a gzip file`, async () => { + const filePath = await fetchRemoteFile({ + url: `http://external.com/logo-gzip.svg`, + cache, + }) + + expect(path.basename(filePath)).toBe(`logo-gzip.svg`) + expect(getFileSize(filePath)).resolves.toBe( + await getFileSize(path.join(__dirname, `./fixtures/gatsby-logo.svg`)) + ) + expect(gotStream).toBeCalledTimes(1) + }) + + it(`downloads and create a file`, async () => { + const filePath = await fetchRemoteFile({ + url: `http://external.com/dog.jpg`, + cache, + }) + + expect(path.basename(filePath)).toBe(`dog.jpg`) + expect(getFileSize(filePath)).resolves.toBe( + await getFileSize(path.join(__dirname, `./fixtures/dog-thumbnail.jpg`)) + ) + expect(gotStream).toBeCalledTimes(1) + }) + + it(`doesn't retry when no content-length is given`, async () => { + const filePath = await fetchRemoteFile({ + url: `http://external.com/logo-gzip.svg?attempts=1&maxBytes=300&contentLength=false`, + cache, + }) + + expect(path.basename(filePath)).toBe(`logo-gzip.svg`) + expect(getFileSize(filePath)).resolves.not.toBe( + await getFileSize(path.join(__dirname, `./fixtures/gatsby-logo.svg`)) + ) + expect(gotStream).toBeCalledTimes(1) + }) + + describe(`retries the download`, () => { + it(`Retries when gzip compression file is incomplete`, async () => { + const filePath = await fetchRemoteFile({ + url: `http://external.com/logo-gzip.svg?attempts=1&maxBytes=300`, + cache, + }) + + expect(path.basename(filePath)).toBe(`logo-gzip.svg`) + expect(getFileSize(filePath)).resolves.toBe( + await getFileSize(path.join(__dirname, `./fixtures/gatsby-logo.svg`)) + ) + expect(gotStream).toBeCalledTimes(2) + }) + + it(`Retries when binary file is incomplete`, async () => { + const filePath = await fetchRemoteFile({ + url: `http://external.com/dog.jpg?attempts=1&maxBytes=300`, + cache, + }) + + expect(path.basename(filePath)).toBe(`dog.jpg`) + expect(getFileSize(filePath)).resolves.toBe( + await getFileSize(path.join(__dirname, `./fixtures/dog-thumbnail.jpg`)) + ) + expect(gotStream).toBeCalledTimes(2) + }) + }) +}) diff --git a/packages/gatsby-core-utils/src/__tests__/fixtures/dog-thumbnail.jpg b/packages/gatsby-core-utils/src/__tests__/fixtures/dog-thumbnail.jpg new file mode 100644 index 0000000000000..331026eae75de Binary files /dev/null and b/packages/gatsby-core-utils/src/__tests__/fixtures/dog-thumbnail.jpg differ diff --git a/packages/gatsby-core-utils/src/__tests__/fixtures/file.json b/packages/gatsby-core-utils/src/__tests__/fixtures/file.json new file mode 100644 index 0000000000000..fdd7b2b78c340 --- /dev/null +++ b/packages/gatsby-core-utils/src/__tests__/fixtures/file.json @@ -0,0 +1 @@ +{"yo": "dog"} diff --git a/packages/gatsby-core-utils/src/__tests__/fixtures/gatsby-logo.svg b/packages/gatsby-core-utils/src/__tests__/fixtures/gatsby-logo.svg new file mode 100644 index 0000000000000..0c233ea41d1e1 --- /dev/null +++ b/packages/gatsby-core-utils/src/__tests__/fixtures/gatsby-logo.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/packages/gatsby-telemetry/src/__tests__/is-truthy.ts b/packages/gatsby-core-utils/src/__tests__/is-truthy.ts similarity index 100% rename from packages/gatsby-telemetry/src/__tests__/is-truthy.ts rename to packages/gatsby-core-utils/src/__tests__/is-truthy.ts diff --git a/packages/gatsby-core-utils/src/fetch-remote-file.ts b/packages/gatsby-core-utils/src/fetch-remote-file.ts new file mode 100644 index 0000000000000..79ac09790061d --- /dev/null +++ b/packages/gatsby-core-utils/src/fetch-remote-file.ts @@ -0,0 +1,231 @@ +import got from "got" +import fileType from "file-type" +import path from "path" +import { IncomingMessage, OutgoingHttpHeaders } from "http" +import fs from "fs-extra" +import { createContentDigest } from "." +import { + getRemoteFileName, + getRemoteFileExtension, + createFilePath, +} from "./filename-utils" + +import { GatsbyCache } from "gatsby" + +export interface IFetchRemoteFileOptions { + url: string + cache: GatsbyCache + auth?: { + htaccess_pass?: string + htaccess_user?: string + } + httpHeaders?: OutgoingHttpHeaders + ext?: string + name?: string +} + +const cacheIdForHeaders = (url: string): string => + `create-remote-file-node-headers-${url}` +const cacheIdForExtensions = (url: string): string => + `create-remote-file-node-extension-${url}` + +const STALL_RETRY_LIMIT = process.env.GATSBY_STALL_RETRY_LIMIT + ? parseInt(process.env.GATSBY_STALL_RETRY_LIMIT, 10) + : 3 +const STALL_TIMEOUT = process.env.GATSBY_STALL_TIMEOUT + ? parseInt(process.env.GATSBY_STALL_TIMEOUT, 10) + : 30000 + +const CONNECTION_TIMEOUT = process.env.GATSBY_CONNECTION_TIMEOUT + ? parseInt(process.env.GATSBY_CONNECTION_TIMEOUT, 10) + : 30000 + +const INCOMPLETE_RETRY_LIMIT = process.env.GATSBY_INCOMPLETE_RETRY_LIMIT + ? parseInt(process.env.GATSBY_INCOMPLETE_RETRY_LIMIT, 10) + : 3 + +/** + * requestRemoteNode + * -- + * Download the requested file + * + * @param {String} url + * @param {Headers} headers + * @param {String} tmpFilename + * @param {Object} httpOpts + * @param {number} attempt + * @return {Promise} Resolves with the [http Result Object]{@link https://nodejs.org/api/http.html#http_class_http_serverresponse} + */ +const requestRemoteNode = ( + url: got.GotUrl, + headers: OutgoingHttpHeaders, + tmpFilename: string, + httpOpts: got.GotOptions | undefined, + attempt: number = 1 +): Promise => + new Promise((resolve, reject) => { + let timeout: NodeJS.Timeout + const fsWriteStream = fs.createWriteStream(tmpFilename) + + // Called if we stall for 30s without receiving any data + const handleTimeout = async (): Promise => { + fsWriteStream.close() + fs.removeSync(tmpFilename) + if (attempt < STALL_RETRY_LIMIT) { + // Retry by calling ourself recursively + resolve( + requestRemoteNode(url, headers, tmpFilename, httpOpts, attempt + 1) + ) + } else { + reject(`Failed to download ${url} after ${STALL_RETRY_LIMIT} attempts`) + } + } + + const resetTimeout = (): void => { + if (timeout) { + clearTimeout(timeout) + } + timeout = setTimeout(handleTimeout, STALL_TIMEOUT) + } + const responseStream = got.stream(url, { + headers, + timeout: { + send: CONNECTION_TIMEOUT, // https://github.com/sindresorhus/got#timeout + }, + ...httpOpts, + }) + + let haveAllBytesBeenWritten = false + responseStream.on(`downloadProgress`, progress => { + if (progress.transferred === progress.total || progress.total === null) { + haveAllBytesBeenWritten = true + } + }) + + responseStream.pipe(fsWriteStream) + + // If there's a 400/500 response or other error. + responseStream.on(`error`, error => { + if (timeout) { + clearTimeout(timeout) + } + fs.removeSync(tmpFilename) + reject(error) + }) + + fsWriteStream.on(`error`, (error: any) => { + if (timeout) { + clearTimeout(timeout) + } + reject(error) + }) + + responseStream.on(`response`, response => { + resetTimeout() + + fsWriteStream.on(`finish`, () => { + fsWriteStream.close() + + // We have an incomplete download + if (!haveAllBytesBeenWritten) { + fs.removeSync(tmpFilename) + + if (attempt < INCOMPLETE_RETRY_LIMIT) { + resolve( + requestRemoteNode( + url, + headers, + tmpFilename, + httpOpts, + attempt + 1 + ) + ) + } else { + reject( + `Failed to download ${url} after ${INCOMPLETE_RETRY_LIMIT} attempts` + ) + } + } + + if (timeout) { + clearTimeout(timeout) + } + resolve(response) + }) + }) + }) + +export async function fetchRemoteFile({ + url, + cache, + auth = {}, + httpHeaders = {}, + ext, + name, +}: IFetchRemoteFileOptions): Promise { + const pluginCacheDir = cache.directory + // See if there's response headers for this url + // from a previous request. + const cachedHeaders = await cache.get(cacheIdForHeaders(url)) + + const headers = { ...httpHeaders } + if (cachedHeaders && cachedHeaders.etag) { + headers[`If-None-Match`] = cachedHeaders.etag + } + + // Add htaccess authentication if passed in. This isn't particularly + // extensible. We should define a proper API that we validate. + const httpOpts: got.GotOptions = {} + if (auth && (auth.htaccess_pass || auth.htaccess_user)) { + httpOpts.auth = `${auth.htaccess_user}:${auth.htaccess_pass}` + } + + // Create the temp and permanent file names for the url. + const digest = createContentDigest(url) + if (!name) { + name = getRemoteFileName(url) + } + if (!ext) { + ext = getRemoteFileExtension(url) + } + + const tmpFilename = createFilePath(pluginCacheDir, `tmp-${digest}`, ext) + + // Fetch the file. + const response = await requestRemoteNode(url, headers, tmpFilename, httpOpts) + + if (response.statusCode === 200) { + // Save the response headers for future requests. + await cache.set(cacheIdForHeaders(url), response.headers) + } + + // If the user did not provide an extension and we couldn't get one from remote file, try and guess one + if (ext === ``) { + if (response.statusCode === 200) { + // if this is fresh response - try to guess extension and cache result for future + const filetype = await fileType.fromFile(tmpFilename) + if (filetype) { + ext = `.${filetype.ext}` + await cache.set(cacheIdForExtensions(url), ext) + } + } else if (response.statusCode === 304) { + // if file on server didn't change - grab cached extension + ext = await cache.get(cacheIdForExtensions(url)) + } + } + + const filename = createFilePath( + path.join(pluginCacheDir, digest), + name, + ext as string + ) + // If the status code is 200, move the piped temp file to the real name. + if (response.statusCode === 200) { + await fs.move(tmpFilename, filename, { overwrite: true }) + // Else if 304, remove the empty response. + } else { + await fs.remove(tmpFilename) + } + + return filename +} diff --git a/packages/gatsby-core-utils/src/filename-utils.ts b/packages/gatsby-core-utils/src/filename-utils.ts new file mode 100644 index 0000000000000..3039de4b011fd --- /dev/null +++ b/packages/gatsby-core-utils/src/filename-utils.ts @@ -0,0 +1,44 @@ +import path from "path" +import Url from "url" + +/** + * getParsedPath + * -- + * Parses remote url to a path object + * + */ +function getParsedPath(url: string): path.ParsedPath { + return path.parse(Url.parse(url).pathname || ``) +} + +/** + * getRemoteFileExtension + * -- + * Parses remote url to retrieve remote file extension + * + */ +export function getRemoteFileExtension(url: string): string { + return getParsedPath(url).ext +} + +/** + * getRemoteFileName + * -- + * Parses remote url to retrieve remote file name + * + */ +export function getRemoteFileName(url: string): string { + return getParsedPath(url).name +} + +/** + * createFilePath + * -- + */ +export function createFilePath( + directory: string, + filename: string, + ext: string +): string { + return path.join(directory, `${filename}${ext}`) +} diff --git a/packages/gatsby-core-utils/src/index.ts b/packages/gatsby-core-utils/src/index.ts index 860766ce160f7..390d7c0d6d42e 100644 --- a/packages/gatsby-core-utils/src/index.ts +++ b/packages/gatsby-core-utils/src/index.ts @@ -7,5 +7,7 @@ export { createRequireFromPath } from "./create-require-from-path" export { getConfigStore } from "./get-config-store" export { getGatsbyVersion } from "./get-gatsby-version" export { getTermProgram } from "./get-term-program" +export { fetchRemoteFile, IFetchRemoteFileOptions } from "./fetch-remote-file" +export { isTruthy } from "./is-truthy" export * from "./service-lock" export * from "./site-metadata" diff --git a/packages/gatsby-telemetry/src/is-truthy.ts b/packages/gatsby-core-utils/src/is-truthy.ts similarity index 100% rename from packages/gatsby-telemetry/src/is-truthy.ts rename to packages/gatsby-core-utils/src/is-truthy.ts diff --git a/packages/gatsby-design-tokens/package.json b/packages/gatsby-design-tokens/package.json index ef80549409a5a..a716bfb4b58d6 100644 --- a/packages/gatsby-design-tokens/package.json +++ b/packages/gatsby-design-tokens/package.json @@ -31,7 +31,7 @@ "devDependencies": { "agadoo": "^1.1.0", "cross-env": "^7.0.3", - "microbundle": "^0.12.4", + "microbundle": "^0.13.0", "preval.macro": "^3.0.0" }, "engines": { diff --git a/packages/gatsby-image/README.md b/packages/gatsby-image/README.md index 380c56d8bd3f2..f1108f0263ec7 100644 --- a/packages/gatsby-image/README.md +++ b/packages/gatsby-image/README.md @@ -1,3 +1,7 @@ +## :warning: This package is now deprecated + +The `gatsby-image` package is now deprecated. The new [Gatsby image plugin](https://www.gatsbyjs.com/plugins/gatsby-plugin-image) has better performance, cool new features and a simpler API. See [the migration guide](https://www.gatsbyjs.com/docs/reference/release-notes/image-migration-guide/) to learn how to upgrade. + # gatsby-image Speedy, optimized images without the work. diff --git a/packages/gatsby-legacy-polyfills/package.json b/packages/gatsby-legacy-polyfills/package.json index 07a54a610c0cf..68fcc9c1222d4 100644 --- a/packages/gatsby-legacy-polyfills/package.json +++ b/packages/gatsby-legacy-polyfills/package.json @@ -37,7 +37,7 @@ "cross-env": "^7.0.3", "execa": "^4.1.0", "fs-extra": "^9.0.1", - "microbundle": "^0.12.4", + "microbundle": "^0.13.0", "npm-run-all": "^4.1.5", "object-assign": "^4.1.1", "source-map": "^0.7.3", diff --git a/packages/gatsby-page-utils/CHANGELOG.md b/packages/gatsby-page-utils/CHANGELOG.md index 3c74a1633f857..06d52e9e1442c 100644 --- a/packages/gatsby-page-utils/CHANGELOG.md +++ b/packages/gatsby-page-utils/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-page-utils@1.0.0-next.0...gatsby-page-utils@1.0.0-next.1) (2021-02-22) + +**Note:** Version bump only for package gatsby-page-utils + # [1.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-page-utils@0.10.0-next.0...gatsby-page-utils@1.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-page-utils diff --git a/packages/gatsby-page-utils/package.json b/packages/gatsby-page-utils/package.json index e137f80af6b8a..7a8c631508e47 100644 --- a/packages/gatsby-page-utils/package.json +++ b/packages/gatsby-page-utils/package.json @@ -1,6 +1,6 @@ { "name": "gatsby-page-utils", - "version": "1.0.0-next.0", + "version": "1.0.0-next.1", "description": "Gatsby library that helps creating pages", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -26,7 +26,7 @@ "bluebird": "^3.7.2", "chokidar": "^3.5.1", "fs-exists-cached": "^1.0.0", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "glob": "^7.1.6", "lodash": "^4.17.20", "micromatch": "^4.0.2" @@ -38,7 +38,7 @@ "babel-preset-gatsby-package": "^1.0.0-next.0", "cross-env": "^7.0.3", "rimraf": "^3.0.2", - "typescript": "^3.9.7" + "typescript": "^4.1.5" }, "files": [ "dist/" diff --git a/packages/gatsby-plugin-canonical-urls/src/gatsby-node.js b/packages/gatsby-plugin-canonical-urls/src/gatsby-node.js new file mode 100644 index 0000000000000..7fcf0309ad814 --- /dev/null +++ b/packages/gatsby-plugin-canonical-urls/src/gatsby-node.js @@ -0,0 +1,9 @@ +exports.pluginOptionsSchema = ({ Joi }) => + Joi.object({ + siteUrl: Joi.string() + .required() + .description(`The full URL for the site e.g. https://www.example.com`), + stripQueryString: Joi.boolean().description( + `Enables stripQueryString to strip query strings from paths e.g. /blog?tag=foobar becomes /blog.` + ), + }) diff --git a/packages/gatsby-plugin-gatsby-cloud/.babelrc b/packages/gatsby-plugin-gatsby-cloud/.babelrc new file mode 100644 index 0000000000000..ac0ad292bb087 --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": [["babel-preset-gatsby-package"]] +} diff --git a/packages/gatsby-plugin-gatsby-cloud/.gitignore b/packages/gatsby-plugin-gatsby-cloud/.gitignore new file mode 100644 index 0000000000000..ce91172efccec --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/.gitignore @@ -0,0 +1,2 @@ +yarn.lock +/*.js diff --git a/packages/gatsby-plugin-gatsby-cloud/.npmignore b/packages/gatsby-plugin-gatsby-cloud/.npmignore new file mode 100644 index 0000000000000..e771d2c9fa299 --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/.npmignore @@ -0,0 +1,34 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git +node_modules +*.un~ +yarn.lock +src +flow-typed +coverage +decls +examples diff --git a/packages/gatsby-plugin-gatsby-cloud/CHANGELOG.md b/packages/gatsby-plugin-gatsby-cloud/CHANGELOG.md new file mode 100644 index 0000000000000..3b156d570a5ad --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/CHANGELOG.md @@ -0,0 +1,8 @@ +# Change Log + +All notable changes to this project will be documented in this file. +See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. + +# 1.1.0-next.2 (2021-02-19) + +**Note:** Version bump only for package gatsby-plugin-gatsby-cloud diff --git a/packages/gatsby-plugin-gatsby-cloud/README.md b/packages/gatsby-plugin-gatsby-cloud/README.md new file mode 100644 index 0000000000000..06005903e9b77 --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/README.md @@ -0,0 +1,142 @@ +# gatsby-plugin-gatsby-cloud + +Automatically generates a `_headers.json` file and a `_redirects.json` file at the root of the public folder to configure +Headers and Redirects on Gatsby Cloud + +By default, the plugin will add some basic security headers. You can easily add or replace headers through the plugin config. + +## Install + +`npm install --save gatsby-plugin-gatsby-cloud` + +## How to use + +```javascript +// In your gatsby-config.js +plugins: [`gatsby-plugin-gatsby-cloud`] +``` + +## Configuration + +If you just need the critical assets, you don't need to add any additional +config. However, if you want to add headers, remove default headers, or +transform the given headers, you can use the following configuration options. + +```javascript +plugins: [ + { + resolve: `gatsby-plugin-gatsby-cloud`, + options: { + headers: {}, // option to add more headers. `Link` headers are transformed by the below criteria + allPageHeaders: [], // option to add headers for all pages. `Link` headers are transformed by the below criteria + mergeSecurityHeaders: true, // boolean to turn off the default security headers + mergeLinkHeaders: true, // boolean to turn off the default gatsby js headers + mergeCachingHeaders: true, // boolean to turn off the default caching headers + transformHeaders: (headers, path) => headers, // optional transform for manipulating headers under each path (e.g.sorting), etc. + generateMatchPathRewrites: true, // boolean to turn off automatic creation of redirect rules for client only paths + }, + }, +] +``` + +### Headers + +You should pass in an object with string keys (representing the paths) and an +array of strings for each header. + +An example: + +```javascript +{ + options: { + headers: { + "/*": [ + "Basic-Auth: someuser:somepassword anotheruser:anotherpassword", + ], + "/my-page": [ + // matching headers (by type) are replaced by Gatsby Cloud with more specific routes + "Basic-Auth: differentuser:differentpassword", + ], + }, + } +} +``` + +Link paths are specially handled by this plugin. Since most files are processed +and cache-busted through Gatsby (with a file hash), the plugin will transform +any base file names to the hashed variants. If the file is not hashed, it will +ensure the path is valid relative to the output `public` folder. You should be +able to reference assets imported through javascript in the `static` folder. + +Do not specify the public path in the config, as the plugin will provide it for +you. + +The `_headers.json` file does not inherit headers, and it will replace any +matching headers it finds in more specific routes. For example, if you add a +link to the root wildcard path (`/*`), it will be replaced by any more +specific path. If you want a resource to put linked across the site, you will +have to add to every path. To make this easier, the plugin provides the +`allPageHeaders` option to inject the same headers on every path. + +```javascript +{ + options: { + allPageHeaders: [ + "Link: ; rel=preload; as=image", + ], + headers: { + "/*": [ + "Basic-Auth: someuser:somepassword anotheruser:anotherpassword", + ], + }, + } +} +``` + +### Redirects + +You can create redirects using the [`createRedirect`](https://www.gatsbyjs.org/docs/actions/#createRedirect) action. + +In addition to the options provided by the Gatsby API, you can pass these options specific to this plugin: + +| Attribute | Description | +| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `statusCode` | Overrides the HTTP status code which is set to `302` by default or `301` when [`isPermanent`](https://www.gatsbyjs.org/docs/actions/#createRedirect) is `true`. You can set one here. For example, `200` for rewrites, or `404` for a custom error page. | + +An example: + +```javascript +createRedirect({ fromPath: "/old-url", toPath: "/new-url", isPermanent: true }) +createRedirect({ fromPath: "/url", toPath: "/zn-CH/url", Language: "zn" }) +createRedirect({ + fromPath: "/url_that_is/not_pretty", + toPath: "/pretty/url", + statusCode: 200, +}) +createRedirect({ + fromPath: "/packages/*", + toPath: "/plugins/*", +}) +``` + +Redirect rules are automatically added for [client only paths](https://www.gatsbyjs.org/docs/client-only-routes-and-user-authentication). The plugin uses the [matchPath](https://www.gatsbyjs.org/docs/gatsby-internals-terminology/#matchpath) syntax to match all possible requests in the range of your client-side routes and serves the HTML file for the client-side route. Without it, only the exact route of the client-side route works. + +If those rules are conflicting with custom rules or if you want to have more control over them you can disable them in [configuration](#configuration) by setting `generateMatchPathRewrites` to `false`. + +An asterix, `*`, will match anything that follows. i.e. `/packages/gatsby-plugin-gatsby-cloud/` will be redirected to `/plugins/gatsby-plugin-gatsby-cloud/`. + +### HTTP Strict Transport Security + +[HSTS Cheatsheet](https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html) + +Since this header is an opt-in security enhancement with permanent consequences we don't include it as a default feature but use can use the `allPagesHeaders` to include it. + +```javascript +{ + options: { + allPageHeaders: [ + "Strict-Transport-Security: max-age=31536000; includeSubDomains; preload", + ], + } +} +``` diff --git a/packages/gatsby-plugin-gatsby-cloud/package.json b/packages/gatsby-plugin-gatsby-cloud/package.json new file mode 100644 index 0000000000000..863844c04a073 --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/package.json @@ -0,0 +1,47 @@ +{ + "name": "gatsby-plugin-gatsby-cloud", + "description": "A Gatsby plugin which optimizes working with Gatsby Cloud", + "version": "1.1.0-next.2", + "author": "Kyle Mathews ", + "bugs": { + "url": "https://github.com/gatsbyjs/gatsby/issues" + }, + "dependencies": { + "@babel/runtime": "^7.12.5", + "fs-extra": "^8.1.0", + "kebab-hash": "^0.1.2", + "lodash": "^4.17.20", + "webpack-assets-manifest": "^5.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.12.1", + "@babel/core": "^7.12.3", + "babel-preset-gatsby-package": "^1.0.0-next.0", + "cross-env": "^7.0.3" + }, + "homepage": "https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-gatsby-cloud#readme", + "keywords": [ + "gatsby", + "gatsby-plugin", + "http/2-server-push", + "gatsby-cloud" + ], + "license": "MIT", + "main": "index.js", + "peerDependencies": { + "gatsby": "^3.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/gatsbyjs/gatsby.git", + "directory": "packages/gatsby-plugin-gatsby-cloud" + }, + "scripts": { + "build": "babel src --out-dir . --ignore \"**/__tests__\"", + "prepare": "cross-env NODE_ENV=production npm run build", + "watch": "babel -w src --out-dir . --ignore \"**/__tests__\"" + }, + "engines": { + "node": ">=12.13.0" + } +} diff --git a/packages/gatsby-plugin-gatsby-cloud/src/__tests__/__snapshots__/build-headers-program.js.snap b/packages/gatsby-plugin-gatsby-cloud/src/__tests__/__snapshots__/build-headers-program.js.snap new file mode 100644 index 0000000000000..147dd943233b9 --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/src/__tests__/__snapshots__/build-headers-program.js.snap @@ -0,0 +1,9 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`build-headers-program with caching headers 1`] = `"{\\"/*\\":[\\"X-Frame-Options: DENY\\",\\"X-XSS-Protection: 1; mode=block\\",\\"X-Content-Type-Options: nosniff\\",\\"Referrer-Policy: same-origin\\"],\\"/component---node-modules-gatsby-plugin-offline-app-shell-js-78f9e4dea04737fa062d.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/0-0180cd94ef2497ac7db8.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/component---src-templates-blog-post-js-517987eae96e75cddbe7.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/component---src-pages-404-js-53e6c51a5a7e73090f50.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/component---src-pages-index-js-0bdd01c77ee09ef0224c.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/webpack-runtime-acaa8994f1f704475e21.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/styles.1025963f4f2ec7abbad4.css\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/styles-565f081c8374bbda155f.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/app-f33c13590352da20930f.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/static/*\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/sw.js\\":[\\"Cache-Control: public, max-age=0, must-revalidate\\"],\\"/offline-plugin-app-shell-fallback/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/hi-folks/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/my-second-post/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/hello-world/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/404/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/404.html\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"]}"`; + +exports[`build-headers-program with manifest['pages-manifest'] 1`] = `"{\\"/*\\":[\\"X-Frame-Options: DENY\\",\\"X-XSS-Protection: 1; mode=block\\",\\"X-Content-Type-Options: nosniff\\",\\"Referrer-Policy: same-origin\\"],\\"/component---node-modules-gatsby-plugin-offline-app-shell-js-78f9e4dea04737fa062d.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/0-0180cd94ef2497ac7db8.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/component---src-templates-blog-post-js-517987eae96e75cddbe7.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/component---src-pages-404-js-53e6c51a5a7e73090f50.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/component---src-pages-index-js-0bdd01c77ee09ef0224c.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/pages-manifest-ab11f09e0ca7ecd3b43e.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/webpack-runtime-acaa8994f1f704475e21.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/styles.1025963f4f2ec7abbad4.css\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/styles-565f081c8374bbda155f.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/app-f33c13590352da20930f.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/static/*\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/sw.js\\":[\\"Cache-Control: public, max-age=0, must-revalidate\\"],\\"/offline-plugin-app-shell-fallback/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\"],\\"/hi-folks/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\"],\\"/my-second-post/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\"],\\"/hello-world/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\"],\\"/404/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\"],\\"/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\"],\\"/404.html\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\"]}"`; + +exports[`build-headers-program with security headers 1`] = `"{\\"/*\\":[\\"X-Frame-Options: ALLOW-FROM https://app.storyblok.com/\\",\\"X-XSS-Protection: 1; mode=block\\",\\"X-Content-Type-Options: nosniff\\",\\"Referrer-Policy: same-origin\\",\\"Content-Security-Policy: frame-ancestors 'self' https://*.storyblok.com/\\"],\\"/hello\\":[\\"X-Frame-Options: SAMEORIGIN\\"],\\"/component---node-modules-gatsby-plugin-offline-app-shell-js-78f9e4dea04737fa062d.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/0-0180cd94ef2497ac7db8.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/component---src-templates-blog-post-js-517987eae96e75cddbe7.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/component---src-pages-404-js-53e6c51a5a7e73090f50.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/component---src-pages-index-js-0bdd01c77ee09ef0224c.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/webpack-runtime-acaa8994f1f704475e21.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/styles.1025963f4f2ec7abbad4.css\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/styles-565f081c8374bbda155f.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/app-f33c13590352da20930f.js\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/static/*\\":[\\"Cache-Control: public, max-age=31536000, immutable\\"],\\"/sw.js\\":[\\"Cache-Control: public, max-age=0, must-revalidate\\"],\\"/offline-plugin-app-shell-fallback/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/hi-folks/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/my-second-post/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/hello-world/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/404/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/404.html\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"]}"`; + +exports[`build-headers-program without caching headers 1`] = `"{\\"/*\\":[\\"X-Frame-Options: DENY\\",\\"X-XSS-Protection: 1; mode=block\\",\\"X-Content-Type-Options: nosniff\\",\\"Referrer-Policy: same-origin\\"],\\"/offline-plugin-app-shell-fallback/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/hi-folks/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/my-second-post/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/hello-world/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/404/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"],\\"/404.html\\":[\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=script; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\",\\"Link: ; rel=preload; as=fetch; crossorigin; nopush\\"]}"`; diff --git a/packages/gatsby-plugin-gatsby-cloud/src/__tests__/__snapshots__/create-redirects.js.snap b/packages/gatsby-plugin-gatsby-cloud/src/__tests__/__snapshots__/create-redirects.js.snap new file mode 100644 index 0000000000000..9202cd7c0838e --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/src/__tests__/__snapshots__/create-redirects.js.snap @@ -0,0 +1,3 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`create-redirects should assemble a redirects file 1`] = `"{\\"redirects\\":[{\\"fromPath\\":\\"/old-url\\",\\"toPath\\":\\"/new-url\\",\\"isPermanent\\":true},{\\"fromPath\\":\\"/url_that_is/not_pretty\\",\\"toPath\\":\\"/pretty/url\\",\\"statusCode\\":201}],\\"rewrites\\":[{\\"fromPath\\":\\"/url_that_is/ugly\\",\\"toPath\\":\\"/not_ugly/url\\"},{\\"fromPath\\":\\"/path2/*splatparam\\",\\"toPath\\":\\"/path2/[...splatparam]/\\"},{\\"fromPath\\":\\"/path/*\\",\\"toPath\\":\\"/path/[...]/\\"},{\\"fromPath\\":\\"/path3/:level1/:level2\\",\\"toPath\\":\\"/path3/[level1]/[level2]/\\"},{\\"fromPath\\":\\"/path4/:param1\\",\\"toPath\\":\\"/path4/[param1]/\\"}]}"`; diff --git a/packages/gatsby-plugin-gatsby-cloud/src/__tests__/build-headers-program.js b/packages/gatsby-plugin-gatsby-cloud/src/__tests__/build-headers-program.js new file mode 100644 index 0000000000000..c9ec4c6e6d146 --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/src/__tests__/build-headers-program.js @@ -0,0 +1,292 @@ +import buildHeadersProgram from "../build-headers-program" +import * as path from "path" +import * as os from "os" +import * as fs from "fs-extra" +import { DEFAULT_OPTIONS, HEADERS_FILENAME } from "../constants" + +jest.mock(`fs-extra`, () => { + return { + ...jest.requireActual(`fs-extra`), + existsSync: jest.fn(), + } +}) + +describe(`build-headers-program`, () => { + let reporter + + beforeEach(() => { + reporter = { + warn: jest.fn(), + } + fs.existsSync.mockClear() + fs.existsSync.mockReturnValue(true) + }) + + const createPluginData = async () => { + const tmpDir = await fs.mkdtemp( + path.join(os.tmpdir(), `abhi-plugin-fastly-`) + ) + + return { + pages: new Map([ + [ + `/offline-plugin-app-shell-fallback/`, + { + jsonName: `offline-plugin-app-shell-fallback-a30`, + internalComponentName: `ComponentOfflinePluginAppShellFallback`, + path: `/offline-plugin-app-shell-fallback/`, + matchPath: undefined, + componentChunkName: `component---node-modules-gatsby-plugin-offline-app-shell-js`, + isCreatedByStatefulCreatePages: false, + context: {}, + updatedAt: 1557740602268, + pluginCreator___NODE: `63e5f7ff-e5f1-58f7-8e2c-55872ac42281`, + pluginCreatorId: `63e5f7ff-e5f1-58f7-8e2c-55872ac42281`, + }, + ], + [ + `/hi-folks/`, + { + jsonName: `hi-folks-a2b`, + internalComponentName: `ComponentHiFolks`, + path: `/hi-folks/`, + matchPath: undefined, + componentChunkName: `component---src-templates-blog-post-js`, + isCreatedByStatefulCreatePages: false, + context: {}, + updatedAt: 1557740602330, + pluginCreator___NODE: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + pluginCreatorId: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + }, + ], + [ + `/my-second-post/`, + { + jsonName: `my-second-post-2aa`, + internalComponentName: `ComponentMySecondPost`, + path: `/my-second-post/`, + matchPath: undefined, + componentChunkName: `component---src-templates-blog-post-js`, + isCreatedByStatefulCreatePages: false, + context: {}, + updatedAt: 1557740602333, + pluginCreator___NODE: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + pluginCreatorId: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + }, + ], + [ + `/hello-world/`, + { + jsonName: `hello-world-8bc`, + internalComponentName: `ComponentHelloWorld`, + path: `/hello-world/`, + matchPath: undefined, + componentChunkName: `component---src-templates-blog-post-js`, + isCreatedByStatefulCreatePages: false, + context: {}, + updatedAt: 1557740602335, + pluginCreator___NODE: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + pluginCreatorId: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + }, + ], + [ + `/404/`, + { + jsonName: `404-22d`, + internalComponentName: `Component404`, + path: `/404/`, + matchPath: undefined, + componentChunkName: `component---src-pages-404-js`, + isCreatedByStatefulCreatePages: true, + context: {}, + updatedAt: 1557740602358, + pluginCreator___NODE: `049c1cfd-95f7-5555-a4ac-9b396d098b26`, + pluginCreatorId: `049c1cfd-95f7-5555-a4ac-9b396d098b26`, + }, + ], + [ + `/`, + { + jsonName: `index`, + internalComponentName: `ComponentIndex`, + path: `/`, + matchPath: undefined, + componentChunkName: `component---src-pages-index-js`, + isCreatedByStatefulCreatePages: true, + context: {}, + updatedAt: 1557740602361, + pluginCreator___NODE: `049c1cfd-95f7-5555-a4ac-9b396d098b26`, + pluginCreatorId: `049c1cfd-95f7-5555-a4ac-9b396d098b26`, + }, + ], + [ + `/404.html`, + { + jsonName: `404-html-516`, + internalComponentName: `Component404Html`, + path: `/404.html`, + matchPath: undefined, + componentChunkName: `component---src-pages-404-js`, + isCreatedByStatefulCreatePages: true, + context: {}, + updatedAt: 1557740602382, + pluginCreator___NODE: `f795702c-a3b8-5a88-88ee-5d06019d44fa`, + pluginCreatorId: `f795702c-a3b8-5a88-88ee-5d06019d44fa`, + }, + ], + ]), + manifest: { + "main.js": `render-page.js`, + "main.js.map": `render-page.js.map`, + app: [ + `webpack-runtime-acaa8994f1f704475e21.js`, + `styles.1025963f4f2ec7abbad4.css`, + `styles-565f081c8374bbda155f.js`, + `app-f33c13590352da20930f.js`, + ], + "component---node-modules-gatsby-plugin-offline-app-shell-js": [ + `component---node-modules-gatsby-plugin-offline-app-shell-js-78f9e4dea04737fa062d.js`, + ], + "component---src-templates-blog-post-js": [ + `0-0180cd94ef2497ac7db8.js`, + `component---src-templates-blog-post-js-517987eae96e75cddbe7.js`, + ], + "component---src-pages-404-js": [ + `0-0180cd94ef2497ac7db8.js`, + `component---src-pages-404-js-53e6c51a5a7e73090f50.js`, + ], + "component---src-pages-index-js": [ + `0-0180cd94ef2497ac7db8.js`, + `component---src-pages-index-js-0bdd01c77ee09ef0224c.js`, + ], + }, + pathPrefix: ``, + publicFolder: (...files) => path.join(tmpDir, ...files), + } + } + + it(`with caching headers`, async () => { + const pluginData = await createPluginData() + + const pluginOptions = { + ...DEFAULT_OPTIONS, + mergeCachingHeaders: true, + } + + await buildHeadersProgram(pluginData, pluginOptions, reporter) + + expect(reporter.warn).not.toHaveBeenCalled() + const output = await fs.readFile( + pluginData.publicFolder(HEADERS_FILENAME), + `utf8` + ) + expect(output).toMatchSnapshot() + expect(output).toMatch(/app-data\.json/) + expect(output).toMatch(/page-data\.json/) + // we should only check page-data & app-data once which leads to 2 times + expect(fs.existsSync).toBeCalledTimes(2) + }) + + it(`with manifest['pages-manifest']`, async () => { + const pluginData = await createPluginData() + + fs.existsSync.mockImplementation(path => { + if (path.includes(`page-data.json`) || path.includes(`app-data.json`)) { + return false + } + + return true + }) + + // gatsby < 2.9 uses page-manifest + pluginData.manifest[`pages-manifest`] = [ + `pages-manifest-ab11f09e0ca7ecd3b43e.js`, + ] + + const pluginOptions = { + ...DEFAULT_OPTIONS, + mergeCachingHeaders: true, + } + + await buildHeadersProgram(pluginData, pluginOptions, reporter) + + expect(reporter.warn).not.toHaveBeenCalled() + const output = await fs.readFile( + pluginData.publicFolder(HEADERS_FILENAME), + `utf8` + ) + expect(output).toMatchSnapshot() + expect(output).toMatch(/\/pages-manifest-ab11f09e0ca7ecd3b43e\.js/g) + expect(output).not.toMatch(/\/app-data\.json/g) + expect(output).not.toMatch(/\/page-data\.json/g) + expect(output).not.toMatch(/\/undefined/g) + }) + + it(`without app-data file`, async () => { + const pluginData = await createPluginData() + + // gatsby 2.17.0+ adds an app-data file + delete pluginData.manifest[`pages-manifest`] + + const pluginOptions = { + ...DEFAULT_OPTIONS, + mergeCachingHeaders: true, + } + fs.existsSync.mockImplementation(path => { + if (path.includes(`app-data.json`)) { + return false + } + + return true + }) + + await buildHeadersProgram(pluginData, pluginOptions, reporter) + + expect(reporter.warn).not.toHaveBeenCalled() + const output = await fs.readFile( + pluginData.publicFolder(HEADERS_FILENAME), + `utf8` + ) + expect(output).not.toMatch(/app-data\.json/g) + expect(output).not.toMatch(/\/undefined/g) + }) + + it(`without caching headers`, async () => { + const pluginData = await createPluginData() + + const pluginOptions = { + ...DEFAULT_OPTIONS, + mergeCachingHeaders: false, + } + + await buildHeadersProgram(pluginData, pluginOptions, reporter) + + expect(reporter.warn).not.toHaveBeenCalled() + expect( + await fs.readFile(pluginData.publicFolder(HEADERS_FILENAME), `utf8`) + ).toMatchSnapshot() + }) + + it(`with security headers`, async () => { + const pluginData = await createPluginData() + + const pluginOptions = { + ...DEFAULT_OPTIONS, + mergeSecurityHeaders: true, + headers: { + "/*": [ + `Content-Security-Policy: frame-ancestors 'self' https://*.storyblok.com/`, + `X-Frame-Options: ALLOW-FROM https://app.storyblok.com/`, + ], + "/hello": [`X-Frame-Options: SAMEORIGIN`], + }, + } + + await buildHeadersProgram(pluginData, pluginOptions, reporter) + + expect(reporter.warn).not.toHaveBeenCalled() + expect( + await fs.readFile(pluginData.publicFolder(HEADERS_FILENAME), `utf8`) + ).toMatchSnapshot() + }) +}) diff --git a/packages/gatsby-plugin-gatsby-cloud/src/__tests__/create-redirects.js b/packages/gatsby-plugin-gatsby-cloud/src/__tests__/create-redirects.js new file mode 100644 index 0000000000000..1bbcb6e3c9fe3 --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/src/__tests__/create-redirects.js @@ -0,0 +1,215 @@ +import createRedirects from "../create-redirects" +import * as path from "path" +import * as os from "os" +import * as fs from "fs-extra" +import { REDIRECTS_FILENAME } from "../constants" + +jest.mock(`fs-extra`, () => { + return { + ...jest.requireActual(`fs-extra`), + existsSync: jest.fn(), + } +}) + +describe(`create-redirects`, () => { + let reporter + + beforeEach(() => { + reporter = { + warn: jest.fn(), + } + fs.existsSync.mockClear() + fs.existsSync.mockReturnValue(true) + }) + + const createPluginData = async () => { + const tmpDir = await fs.mkdtemp( + path.join(os.tmpdir(), `gatsby-plugin-gatsby-cloud-`) + ) + + return { + pages: new Map([ + [ + `/offline-plugin-app-shell-fallback/`, + { + jsonName: `offline-plugin-app-shell-fallback-a30`, + internalComponentName: `ComponentOfflinePluginAppShellFallback`, + path: `/offline-plugin-app-shell-fallback/`, + matchPath: undefined, + componentChunkName: `component---node-modules-gatsby-plugin-offline-app-shell-js`, + isCreatedByStatefulCreatePages: false, + context: {}, + updatedAt: 1557740602268, + pluginCreator___NODE: `63e5f7ff-e5f1-58f7-8e2c-55872ac42281`, + pluginCreatorId: `63e5f7ff-e5f1-58f7-8e2c-55872ac42281`, + }, + ], + [ + `/hi-folks/`, + { + jsonName: `hi-folks-a2b`, + internalComponentName: `ComponentHiFolks`, + path: `/hi-folks/`, + matchPath: undefined, + componentChunkName: `component---src-templates-blog-post-js`, + isCreatedByStatefulCreatePages: false, + context: {}, + updatedAt: 1557740602330, + pluginCreator___NODE: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + pluginCreatorId: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + }, + ], + [ + `/my-second-post/`, + { + jsonName: `my-second-post-2aa`, + internalComponentName: `ComponentMySecondPost`, + path: `/my-second-post/`, + matchPath: undefined, + componentChunkName: `component---src-templates-blog-post-js`, + isCreatedByStatefulCreatePages: false, + context: {}, + updatedAt: 1557740602333, + pluginCreator___NODE: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + pluginCreatorId: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + }, + ], + [ + `/hello-world/`, + { + jsonName: `hello-world-8bc`, + internalComponentName: `ComponentHelloWorld`, + path: `/hello-world/`, + matchPath: undefined, + componentChunkName: `component---src-templates-blog-post-js`, + isCreatedByStatefulCreatePages: false, + context: {}, + updatedAt: 1557740602335, + pluginCreator___NODE: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + pluginCreatorId: `7374ebf2-d961-52ee-92a2-c25e7cb387a9`, + }, + ], + [ + `/404/`, + { + jsonName: `404-22d`, + internalComponentName: `Component404`, + path: `/404/`, + matchPath: undefined, + componentChunkName: `component---src-pages-404-js`, + isCreatedByStatefulCreatePages: true, + context: {}, + updatedAt: 1557740602358, + pluginCreator___NODE: `049c1cfd-95f7-5555-a4ac-9b396d098b26`, + pluginCreatorId: `049c1cfd-95f7-5555-a4ac-9b396d098b26`, + }, + ], + [ + `/`, + { + jsonName: `index`, + internalComponentName: `ComponentIndex`, + path: `/`, + matchPath: undefined, + componentChunkName: `component---src-pages-index-js`, + isCreatedByStatefulCreatePages: true, + context: {}, + updatedAt: 1557740602361, + pluginCreator___NODE: `049c1cfd-95f7-5555-a4ac-9b396d098b26`, + pluginCreatorId: `049c1cfd-95f7-5555-a4ac-9b396d098b26`, + }, + ], + [ + `/404.html`, + { + jsonName: `404-html-516`, + internalComponentName: `Component404Html`, + path: `/404.html`, + matchPath: undefined, + componentChunkName: `component---src-pages-404-js`, + isCreatedByStatefulCreatePages: true, + context: {}, + updatedAt: 1557740602382, + pluginCreator___NODE: `f795702c-a3b8-5a88-88ee-5d06019d44fa`, + pluginCreatorId: `f795702c-a3b8-5a88-88ee-5d06019d44fa`, + }, + ], + ]), + manifest: { + "main.js": `render-page.js`, + "main.js.map": `render-page.js.map`, + app: [ + `webpack-runtime-acaa8994f1f704475e21.js`, + `styles.1025963f4f2ec7abbad4.css`, + `styles-565f081c8374bbda155f.js`, + `app-f33c13590352da20930f.js`, + ], + "component---node-modules-gatsby-plugin-offline-app-shell-js": [ + `component---node-modules-gatsby-plugin-offline-app-shell-js-78f9e4dea04737fa062d.js`, + ], + "component---src-templates-blog-post-js": [ + `0-0180cd94ef2497ac7db8.js`, + `component---src-templates-blog-post-js-517987eae96e75cddbe7.js`, + ], + "component---src-pages-404-js": [ + `0-0180cd94ef2497ac7db8.js`, + `component---src-pages-404-js-53e6c51a5a7e73090f50.js`, + ], + "component---src-pages-index-js": [ + `0-0180cd94ef2497ac7db8.js`, + `component---src-pages-index-js-0bdd01c77ee09ef0224c.js`, + ], + }, + pathPrefix: ``, + publicFolder: (...files) => path.join(tmpDir, ...files), + } + } + + it(`should assemble a redirects file`, async () => { + const pluginData = await createPluginData() + + await createRedirects( + pluginData, + [ + { + fromPath: `/old-url`, + toPath: `/new-url`, + isPermanent: true, + }, + { + fromPath: `/url_that_is/not_pretty`, + toPath: `/pretty/url`, + statusCode: 201, + }, + ], + [ + { + fromPath: `/url_that_is/ugly`, + toPath: `/not_ugly/url`, + }, + { + fromPath: `/path2/*splatparam`, + toPath: `/path2/[...splatparam]/`, + }, + { + fromPath: `/path/*`, + toPath: `/path/[...]/`, + }, + { + fromPath: `/path3/:level1/:level2`, + toPath: `/path3/[level1]/[level2]/`, + }, + { + fromPath: `/path4/:param1`, + toPath: `/path4/[param1]/`, + }, + ] + ) + + const output = await fs.readFile( + pluginData.publicFolder(REDIRECTS_FILENAME), + `utf8` + ) + expect(output).toMatchSnapshot() + }) +}) diff --git a/packages/gatsby-plugin-gatsby-cloud/src/build-headers-program.js b/packages/gatsby-plugin-gatsby-cloud/src/build-headers-program.js new file mode 100644 index 0000000000000..1c7b584e05593 --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/src/build-headers-program.js @@ -0,0 +1,315 @@ +import _ from "lodash" +import { writeFile, existsSync } from "fs-extra" +import { parse, posix } from "path" +import kebabHash from "kebab-hash" +import { IMMUTABLE_CACHING_HEADER } from "./constants" + +import { + COMMON_BUNDLES, + SECURITY_HEADERS, + CACHING_HEADERS, + LINK_REGEX, + HEADERS_FILENAME, + PAGE_DATA_DIR, +} from "./constants" + +function getHeaderName(header) { + const matches = header.match(/^([^:]+):/) + return matches && matches[1] +} + +function validHeaders(headers, reporter) { + if (!headers || !_.isObject(headers)) { + return false + } + + return _.every( + headers, + (headersList, path) => + _.isArray(headersList) && + _.every(headersList, header => { + if (_.isString(header)) { + if (!getHeaderName(header)) { + // TODO panic on builds on v3 + reporter.warn( + `[gatsby-plugin-gatsby-cloud] ${path} contains an invalid header (${header}). Please check your plugin configuration` + ) + } + + return true + } + + return false + }) + ) +} + +function linkTemplate(assetPath, type = `script`) { + return `Link: <${assetPath}>; rel=preload; as=${type}${ + type === `fetch` ? `; crossorigin` : `` + }; nopush` +} + +function pathChunkName(path) { + const name = path === `/` ? `index` : kebabHash(path) + return `path---${name}` +} + +function getPageDataPath(path) { + const fixedPagePath = path === `/` ? `index` : path + return posix.join(`page-data`, fixedPagePath, `page-data.json`) +} + +function getScriptPath(file, manifest) { + const chunk = manifest[file] + + if (!chunk) { + return [] + } + + // convert to array if it's not already + const chunks = _.isArray(chunk) ? chunk : [chunk] + + return chunks.filter(script => { + const parsed = parse(script) + // handle only .js, .css content is inlined already + // and doesn't need to be pushed + return parsed.ext === `.js` + }) +} + +function linkHeaders(files, pathPrefix) { + const linkHeaders = [] + for (const resourceType in files) { + files[resourceType].forEach(file => { + linkHeaders.push(linkTemplate(`${pathPrefix}/${file}`, resourceType)) + }) + } + + return linkHeaders +} + +function headersPath(pathPrefix, path) { + return `${pathPrefix}${path}` +} + +function preloadHeadersByPage({ pages, manifest, pathPrefix, publicFolder }) { + let linksByPage = {} + + const appDataPath = publicFolder(PAGE_DATA_DIR, `app-data.json`) + const hasAppData = existsSync(appDataPath) + + let hasPageData = false + if (pages.size) { + // test if 1 page-data file exists, if it does we know we're on a gatsby version that supports page-data + const pageDataPath = publicFolder( + getPageDataPath(pages.get(pages.keys().next().value).path) + ) + hasPageData = existsSync(pageDataPath) + } + + pages.forEach(page => { + const scripts = _.flatMap(COMMON_BUNDLES, file => + getScriptPath(file, manifest) + ) + scripts.push(...getScriptPath(pathChunkName(page.path), manifest)) + scripts.push(...getScriptPath(page.componentChunkName, manifest)) + + const json = [] + if (hasAppData) { + json.push(posix.join(PAGE_DATA_DIR, `app-data.json`)) + } + + if (hasPageData) { + json.push(getPageDataPath(page.path)) + } + + const filesByResourceType = { + script: scripts.filter(Boolean), + fetch: json, + } + + const pathKey = headersPath(pathPrefix, page.path) + linksByPage[pathKey] = linkHeaders(filesByResourceType, pathPrefix) + }) + + return linksByPage +} + +function defaultMerge(...headers) { + function unionMerge(objValue, srcValue) { + if (_.isArray(objValue)) { + return _.union(objValue, srcValue) + } else { + return undefined // opt into default merge behavior + } + } + + return _.mergeWith({}, ...headers, unionMerge) +} + +function headersMerge(userHeaders, defaultHeaders) { + const merged = {} + Object.keys(defaultHeaders).forEach(path => { + if (!userHeaders[path]) { + merged[path] = defaultHeaders[path] + return + } + const headersMap = {} + defaultHeaders[path].forEach(header => { + headersMap[getHeaderName(header)] = header + }) + userHeaders[path].forEach(header => { + headersMap[getHeaderName(header)] = header // override if exists + }) + merged[path] = Object.values(headersMap) + }) + Object.keys(userHeaders).forEach(path => { + if (!merged[path]) { + merged[path] = userHeaders[path] + } + }) + return merged +} + +function transformLink(manifest, publicFolder, pathPrefix) { + return header => + header.replace(LINK_REGEX, (__, prefix, file, suffix) => { + const hashed = manifest[file] + if (hashed) { + return `${prefix}${pathPrefix}${hashed}${suffix}` + } else if (existsSync(publicFolder(file))) { + return `${prefix}${pathPrefix}${file}${suffix}` + } else { + throw new Error( + `Could not find the file specified in the Link header \`${header}\`.` + + `The gatsby-plugin-gatsby-cloud is looking for a matching file (with or without a ` + + `webpack hash). Check the public folder and your gatsby-config.js to ensure you are ` + + `pointing to a public file.` + ) + } + }) +} + +function stringifyHeaders(headers) { + return _.reduce( + headers, + (text, headerList, path) => { + const headersString = _.reduce( + headerList, + (accum, header) => `${accum} ${header}\n`, + `` + ) + return `${text}${path}\n${headersString}` + }, + `` + ) +} + +// 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 { pages, manifest, publicFolder, pathPrefix } = pluginData + + const headersList = _.map( + allPageHeaders, + transformLink(manifest, publicFolder, pathPrefix) + ) + + const duplicateHeadersByPage = {} + pages.forEach(page => { + const pathKey = headersPath(pathPrefix, page.path) + duplicateHeadersByPage[pathKey] = headersList + }) + + return defaultMerge(headers, duplicateHeadersByPage) +} + +const applyLinkHeaders = (pluginData, { mergeLinkHeaders }) => headers => { + if (!mergeLinkHeaders) { + return headers + } + + const { pages, manifest, pathPrefix, publicFolder } = pluginData + const perPageHeaders = preloadHeadersByPage({ + pages, + manifest, + pathPrefix, + publicFolder, + }) + + return defaultMerge(headers, perPageHeaders) +} + +const applySecurityHeaders = ({ mergeSecurityHeaders }) => headers => { + if (!mergeSecurityHeaders) { + return headers + } + + return headersMerge(headers, SECURITY_HEADERS) +} + +const applyCachingHeaders = ( + pluginData, + { mergeCachingHeaders } +) => headers => { + if (!mergeCachingHeaders) { + return headers + } + + const chunks = Array.from(pluginData.pages.values()).map( + page => page.componentChunkName + ) + + chunks.push(`pages-manifest`, `app`) + + const files = [].concat(...chunks.map(chunk => pluginData.manifest[chunk])) + + const cachingHeaders = {} + + 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 writeHeadersFile = ({ publicFolder }) => contents => + writeFile(publicFolder(HEADERS_FILENAME), JSON.stringify(contents)) + +export default function buildHeadersProgram( + pluginData, + pluginOptions, + reporter +) { + return _.flow( + mapUserLinkHeaders(pluginData), + applySecurityHeaders(pluginOptions), + applyCachingHeaders(pluginData, pluginOptions), + mapUserLinkAllPageHeaders(pluginData, pluginOptions), + applyLinkHeaders(pluginData, pluginOptions), + applyTransfromHeaders(pluginOptions), + writeHeadersFile(pluginData) + )(pluginOptions.headers) +} diff --git a/packages/gatsby-plugin-gatsby-cloud/src/constants.js b/packages/gatsby-plugin-gatsby-cloud/src/constants.js new file mode 100644 index 0000000000000..7ab32a3e7745a --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/src/constants.js @@ -0,0 +1,41 @@ +import _ from "lodash" + +// Gatsby values +export const BUILD_HTML_STAGE = `build-html` +export const BUILD_CSS_STAGE = `build-css` + +// Plugin values +export const HEADERS_FILENAME = `_headers.json` +export const REDIRECTS_FILENAME = `_redirects.json` + +export const DEFAULT_OPTIONS = { + headers: {}, + mergeSecurityHeaders: true, + mergeLinkHeaders: true, + mergeCachingHeaders: true, + transformHeaders: _.identity, // optional transform for manipulating headers for sorting, etc + generateMatchPathRewrites: true, // generate rewrites for client only paths +} + +export const SECURITY_HEADERS = { + "/*": [ + `X-Frame-Options: DENY`, + `X-XSS-Protection: 1; mode=block`, + `X-Content-Type-Options: nosniff`, + `Referrer-Policy: same-origin`, + ], +} + +export const IMMUTABLE_CACHING_HEADER = `Cache-Control: public, max-age=31536000, immutable` +export const NEVER_CACHE_HEADER = `Cache-Control: public, max-age=0, must-revalidate` + +export const CACHING_HEADERS = { + "/static/*": [IMMUTABLE_CACHING_HEADER], + "/sw.js": [NEVER_CACHE_HEADER], +} + +export const LINK_REGEX = /^(Link: <\/)(.+)(>;.+)/ + +export const COMMON_BUNDLES = [`commons`, `app`] + +export const PAGE_DATA_DIR = `page-data/` diff --git a/packages/gatsby-plugin-gatsby-cloud/src/create-redirects.js b/packages/gatsby-plugin-gatsby-cloud/src/create-redirects.js new file mode 100644 index 0000000000000..c930dc3408c66 --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/src/create-redirects.js @@ -0,0 +1,17 @@ +import { writeFile } from "fs-extra" +import { REDIRECTS_FILENAME } from "./constants" + +export default async function writeRedirectsFile( + pluginData, + redirects, + rewrites +) { + const { publicFolder } = pluginData + + if (!redirects.length && !rewrites.length) return null + + // Is it ok to pass through the data or should we format it so that we don't have dependencies + // between the redirects and rewrites formats? What are the chances those will change? + const FILE_PATH = publicFolder(REDIRECTS_FILENAME) + return writeFile(FILE_PATH, JSON.stringify({ redirects, rewrites })) +} diff --git a/packages/gatsby-plugin-gatsby-cloud/src/gatsby-node.js b/packages/gatsby-plugin-gatsby-cloud/src/gatsby-node.js new file mode 100644 index 0000000000000..c5a083a7b6dcf --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/src/gatsby-node.js @@ -0,0 +1,92 @@ +import WebpackAssetsManifest from "webpack-assets-manifest" + +import makePluginData from "./plugin-data" +import buildHeadersProgram from "./build-headers-program" +import createRedirects from "./create-redirects" +import { readJSON } from "fs-extra" +import { joinPath } from "gatsby-core-utils" +import { DEFAULT_OPTIONS, BUILD_HTML_STAGE, BUILD_CSS_STAGE } from "./constants" + +let assetsManifest = {} + +// Inject a webpack plugin to get the file manifests so we can translate all link headers +exports.onCreateWebpackConfig = ({ actions, stage }) => { + if (stage !== BUILD_HTML_STAGE && stage !== BUILD_CSS_STAGE) { + return + } + + actions.setWebpackConfig({ + plugins: [ + new WebpackAssetsManifest({ + assets: assetsManifest, // mutates object with entries + merge: true, + }), + ], + }) +} + +exports.onPostBuild = async ( + { store, pathPrefix, reporter }, + userPluginOptions +) => { + const pluginData = makePluginData(store, assetsManifest, pathPrefix) + const pluginOptions = { ...DEFAULT_OPTIONS, ...userPluginOptions } + + const { redirects } = store.getState() + + let rewrites = [] + if (pluginOptions.generateMatchPathRewrites) { + const matchPathsFile = joinPath( + pluginData.program.directory, + `.cache`, + `match-paths.json` + ) + + const matchPaths = await readJSON(matchPathsFile) + + rewrites = matchPaths.map(({ matchPath, path }) => { + return { + fromPath: matchPath, + toPath: path, + } + }) + } + + await Promise.all([ + buildHeadersProgram(pluginData, pluginOptions, reporter), + createRedirects(pluginData, redirects, rewrites), + ]) +} + +const MATCH_ALL_KEYS = /^/ +const pluginOptionsSchema = function ({ Joi }) { + const headersSchema = Joi.object() + .pattern(MATCH_ALL_KEYS, Joi.array().items(Joi.string())) + .description(`Add more headers to specific pages`) + + return Joi.object({ + headers: headersSchema, + allPageHeaders: Joi.array() + .items(Joi.string()) + .description(`Add more headers to all the pages`), + mergeSecurityHeaders: Joi.boolean().description( + `When set to false, turns off the default security headers` + ), + mergeLinkHeaders: Joi.boolean().description( + `When set to false, turns off the default gatsby js headers` + ), + mergeCachingHeaders: Joi.boolean().description( + `When set to false, turns off the default caching headers` + ), + transformHeaders: Joi.function() + .maxArity(2) + .description( + `Transform function for manipulating headers under each path (e.g.sorting), etc. This should return an object of type: { key: Array }` + ), + generateMatchPathRewrites: Joi.boolean().description( + `When set to false, turns off automatic creation of redirect rules for client only paths` + ), + }) +} + +exports.pluginOptionsSchema = pluginOptionsSchema diff --git a/packages/gatsby-plugin-gatsby-cloud/src/plugin-data.js b/packages/gatsby-plugin-gatsby-cloud/src/plugin-data.js new file mode 100644 index 0000000000000..1ffd8c1cf7d8b --- /dev/null +++ b/packages/gatsby-plugin-gatsby-cloud/src/plugin-data.js @@ -0,0 +1,28 @@ +import path from "path" + +export function buildPrefixer(prefix, ...paths) { + return (...subpaths) => path.join(prefix, ...paths, ...subpaths) +} + +// This function assembles data across the manifests and store to match a similar +// shape of `static-entry.js`. With it, we can build headers that point to the correct +// hashed filenames and ensure we pull in the componentChunkName. +export default function makePluginData(store, assetsManifest, pathPrefix) { + const { program, pages: storePages } = store.getState() + const publicFolder = buildPrefixer(program.directory, `public`) + const stats = require(publicFolder(`webpack.stats.json`)) + // Get all the files, not just the first + const chunkManifest = stats.assetsByChunkName + const pages = storePages + + // We combine the manifest of JS and the manifest of assets to make a lookup table. + const manifest = { ...assetsManifest, ...chunkManifest } + + return { + pages, + manifest, + program, + pathPrefix, + publicFolder, + } +} diff --git a/packages/gatsby-plugin-image/CHANGELOG.md b/packages/gatsby-plugin-image/CHANGELOG.md index 00401f43290df..aa6e3a035340d 100644 --- a/packages/gatsby-plugin-image/CHANGELOG.md +++ b/packages/gatsby-plugin-image/CHANGELOG.md @@ -3,6 +3,38 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.0.0-next.8](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-image@1.0.0-next.7...gatsby-plugin-image@1.0.0-next.8) (2021-02-22) + +**Note:** Version bump only for package gatsby-plugin-image + +# [1.0.0-next.7](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-image@1.0.0-next.6...gatsby-plugin-image@1.0.0-next.7) (2021-02-19) + +### Bug Fixes + +- **gatsby-plugin-image:** Correct default enum value ([#29607](https://github.com/gatsbyjs/gatsby/issues/29607)) ([7e8b91c](https://github.com/gatsbyjs/gatsby/commit/7e8b91c5a0d7f171a72c7088ace8d5fa3fdc39a8)) + +# [1.0.0-next.6](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-image@1.0.0-next.5...gatsby-plugin-image@1.0.0-next.6) (2021-02-19) + +### Bug Fixes + +- **gatsby-plugin-image:** Apply inline styles and img size ([3f7f06c](https://github.com/gatsbyjs/gatsby/commit/3f7f06cb6f0c7be2ddde709283b7d116fa88cd6a)) +- **gatsby-plugin-image:** Apply inline styles and img size ([#29603](https://github.com/gatsbyjs/gatsby/issues/29603)) ([9db36db](https://github.com/gatsbyjs/gatsby/commit/9db36dbe165c35105cef4ad95f4802061ff5fcc5)) +- **gatsby-source-contentful:** Correct supported image formats ([#29562](https://github.com/gatsbyjs/gatsby/issues/29562)) ([3b4d32f](https://github.com/gatsbyjs/gatsby/commit/3b4d32f0b2d6aef3193213252c3eb813cc2cbea9)) + +### Reverts + +- Revert "fix(gatsby-plugin-image): Apply inline styles and img size" (#29602) ([8d0f48f](https://github.com/gatsbyjs/gatsby/commit/8d0f48f02ec0b631320dcb980f69944804f72803)), closes [#29602](https://github.com/gatsbyjs/gatsby/issues/29602) + +# [1.0.0-next.5](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-image@1.0.0-next.4...gatsby-plugin-image@1.0.0-next.5) (2021-02-18) + +### Features + +- **gatsby-plugin-image:** Add getLowResolutionImageURL plugin helper ([#29518](https://github.com/gatsbyjs/gatsby/issues/29518)) ([4b7fe37](https://github.com/gatsbyjs/gatsby/commit/4b7fe37ac39897ab76090ef76cff19d98fa5924b)) + +# [1.0.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-image@1.0.0-next.3...gatsby-plugin-image@1.0.0-next.4) (2021-02-17) + +**Note:** Version bump only for package gatsby-plugin-image + # [1.0.0-next.3](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-image@1.0.0-next.2...gatsby-plugin-image@1.0.0-next.3) (2021-02-12) ### Bug Fixes diff --git a/packages/gatsby-plugin-image/README.md b/packages/gatsby-plugin-image/README.md index 601646fb5a518..33666d542df25 100644 --- a/packages/gatsby-plugin-image/README.md +++ b/packages/gatsby-plugin-image/README.md @@ -1,6 +1,4 @@ -# gatsby-plugin-image (beta) - -_The new Gatsby Image plugin is currently in beta, but you can try it out now_ +# gatsby-plugin-image Adding responsive images to your site while maintaining high performance scores can be difficult to do manually. The Gatsby Image plugin handles the hard parts of producing images in multiple sizes and formats for you! diff --git a/packages/gatsby-plugin-image/package.json b/packages/gatsby-plugin-image/package.json index 5cd473664b765..86a6edd41ba46 100644 --- a/packages/gatsby-plugin-image/package.json +++ b/packages/gatsby-plugin-image/package.json @@ -1,6 +1,6 @@ { "name": "gatsby-plugin-image", - "version": "1.0.0-next.3", + "version": "1.0.0-next.8", "scripts": { "build": "npm-run-all -s clean -p build:*", "build:gatsby-node": "tsc --jsx react --downlevelIteration true --skipLibCheck true --esModuleInterop true --outDir dist/ src/gatsby-node.ts src/babel-plugin-parse-static-images.ts src/resolver-utils.ts src/types.d.ts -d --declarationDir dist/src", @@ -57,11 +57,11 @@ "cssnano": "^4.1.10", "del-cli": "^3.0.1", "do-sync": "^2.2.0", - "microbundle": "^0.12.4", + "microbundle": "^0.13.0", "npm-run-all": "^4.1.5", "postcss": "^8.2.4", "terser": "^5.3.8", - "typescript": "^3.9.7" + "typescript": "^4.1.5" }, "peerDependencies": { "gatsby": "^3.0.0-next.0", @@ -75,12 +75,12 @@ "@babel/parser": "^7.12.5", "@babel/traverse": "^7.12.5", "babel-jsx-utils": "^1.0.1", - "babel-plugin-remove-graphql-queries": "^3.0.0-next.0", + "babel-plugin-remove-graphql-queries": "^3.0.0-next.2", "camelcase": "^5.3.1", "chokidar": "^3.5.1", "common-tags": "^1.8.0", "fs-extra": "^8.1.0", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "objectFitPolyfill": "^2.3.0", "prop-types": "^15.7.2" }, diff --git a/packages/gatsby-plugin-image/src/__tests__/image-utils.ts b/packages/gatsby-plugin-image/src/__tests__/image-utils.ts index 42551c5bcd452..fbbafac1172c9 100644 --- a/packages/gatsby-plugin-image/src/__tests__/image-utils.ts +++ b/packages/gatsby-plugin-image/src/__tests__/image-utils.ts @@ -3,6 +3,7 @@ import { generateImageData, IGatsbyImageHelperArgs, IImage, + getLowResolutionImageURL, } from "../image-utils" const generateImageSource = ( @@ -35,7 +36,7 @@ const args: IGatsbyImageHelperArgs = { }, } -const fluidArgs: IGatsbyImageHelperArgs = { +const fullWidthArgs: IGatsbyImageHelperArgs = { ...args, sourceMetadata: { width: 2000, @@ -159,7 +160,7 @@ describe(`the image data helper`, () => { }) it(`calculates sizes for fullWidth`, () => { - const data = generateImageData(fluidArgs) + const data = generateImageData(fullWidthArgs) expect(data.images.fallback?.sizes).toEqual(`100vw`) }) @@ -182,7 +183,7 @@ describe(`the image data helper`, () => { }) it(`returns URLs for fullWidth`, () => { - const data = generateImageData(fluidArgs) + const data = generateImageData(fullWidthArgs) expect(data?.images?.fallback?.src).toEqual( `https://example.com/afile.jpg/750/563/image.jpg` ) @@ -294,4 +295,17 @@ describe(`the helper utils`, () => { expect(ext).toBe(expected[idx]) } }) + + it(`gets a low-resolution image URL`, () => { + const url = getLowResolutionImageURL(args) + expect(url).toEqual(`https://example.com/afile.jpg/20/15/image.jpg`) + }) + + it(`gets a low-resolution image URL with correct aspect ratio`, () => { + const url = getLowResolutionImageURL({ + ...fullWidthArgs, + aspectRatio: 2 / 1, + }) + expect(url).toEqual(`https://example.com/afile.jpg/20/10/image.jpg`) + }) }) diff --git a/packages/gatsby-plugin-image/src/components/__tests__/hooks.ts b/packages/gatsby-plugin-image/src/components/__tests__/hooks.ts new file mode 100644 index 0000000000000..054ea0a4f6c7f --- /dev/null +++ b/packages/gatsby-plugin-image/src/components/__tests__/hooks.ts @@ -0,0 +1,113 @@ +import { Node } from "gatsby" +import { getSrc, getSrcSet, getImage, IGatsbyImageData } from "../../" + +const imageData: IGatsbyImageData = { + images: { + fallback: { + src: `imagesrc.jpg`, + srcSet: `imagesrcset.jpg 1x`, + }, + }, + layout: `constrained`, + width: 1, + height: 2, +} + +const node: Node = { + id: ``, + parent: ``, + children: [], + internal: { + type: ``, + contentDigest: ``, + owner: ``, + }, +} + +const dataParent = { + ...node, + gatsbyImageData: imageData, +} + +const fileNode = { + ...node, + childImageSharp: dataParent, +} + +describe(`The image helper functions`, () => { + describe(`getImage`, () => { + it(`returns the same data if passed gatsbyImageData`, () => { + expect(getImage(imageData)).toEqual(imageData) + }) + + it(`gets an image from a FileNode`, () => { + expect(getImage(fileNode)?.images.fallback?.src).toEqual(`imagesrc.jpg`) + }) + + it(`gets an image from an IGatsbyImageDataParent`, () => { + expect(getImage(dataParent)?.images.fallback?.src).toEqual(`imagesrc.jpg`) + }) + it(`returns undefined from an invalid object`, () => { + expect(getImage(node)).toBeUndefined() + }) + + it(`returns undefined when passed a number`, () => { + expect(getImage((1 as any) as Node)).toBeUndefined() + }) + + it(`returns undefined when passed undefined`, () => { + expect(getImage((undefined as any) as Node)).toBeUndefined() + }) + }) + + describe(`getSrc`, () => { + it(`gets src from an image data object`, () => { + expect(getSrc(imageData)).toEqual(`imagesrc.jpg`) + }) + + it(`gets src from a FileNode`, () => { + expect(getSrc(fileNode)).toEqual(`imagesrc.jpg`) + }) + + it(`gets src from an IGatsbyImageDataParent`, () => { + expect(getSrc(dataParent)).toEqual(`imagesrc.jpg`) + }) + + it(`returns undefined from an invalid object`, () => { + expect(getSrc(node)).toBeUndefined() + }) + it(`returns undefined when passed undefined`, () => { + expect(getSrc((undefined as any) as Node)).toBeUndefined() + }) + + it(`returns undefined when passed a number`, () => { + expect(getSrc((1 as any) as Node)).toBeUndefined() + }) + }) + + describe(`getSrcSet`, () => { + it(`gets srcSet from am image data object`, () => { + expect(getSrcSet(imageData)).toEqual(`imagesrcset.jpg 1x`) + }) + + it(`gets srcSet from a FileNode`, () => { + expect(getSrcSet(fileNode)).toEqual(`imagesrcset.jpg 1x`) + }) + + it(`gets srcSet from an IGatsbyImageDataParent`, () => { + expect(getSrcSet(dataParent)).toEqual(`imagesrcset.jpg 1x`) + }) + + it(`returns undefined from an invalid object`, () => { + expect(getSrcSet(node)).toBeUndefined() + }) + + it(`returns undefined when passed undefined`, () => { + expect(getSrcSet((undefined as any) as Node)).toBeUndefined() + }) + + it(`returns undefined when passed a number`, () => { + expect(getSrcSet((1 as any) as Node)).toBeUndefined() + }) + }) +}) diff --git a/packages/gatsby-plugin-image/src/components/hooks.ts b/packages/gatsby-plugin-image/src/components/hooks.ts index 810f939471d8e..20118805ffdc4 100644 --- a/packages/gatsby-plugin-image/src/components/hooks.ts +++ b/packages/gatsby-plugin-image/src/components/hooks.ts @@ -38,18 +38,41 @@ export function storeImageloaded(cacheKey?: string): void { export function hasImageLoaded(cacheKey: string): boolean { return imageCache.has(cacheKey) } - +export type IGatsbyImageDataParent = T & { + gatsbyImageData: IGatsbyImageData +} export type FileNode = Node & { - childImageSharp?: Node & { - gatsbyImageData?: IGatsbyImageData + childImageSharp?: IGatsbyImageDataParent +} + +const isGatsbyImageData = ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + node: IGatsbyImageData | any +): node is IGatsbyImageData => + // 🦆 check for a deep prop to be sure this is a valid gatsbyImageData object + Boolean(node?.images?.fallback?.src) + +const isGatsbyImageDataParent = ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + node: IGatsbyImageDataParent | any +): node is IGatsbyImageDataParent => Boolean(node?.gatsbyImageData) + +type ImageDataLike = FileNode | IGatsbyImageDataParent | IGatsbyImageData +export const getImage = (node: ImageDataLike): IGatsbyImageData | undefined => { + if (isGatsbyImageData(node)) { + return node } + if (isGatsbyImageDataParent(node)) { + return node.gatsbyImageData + } + return node?.childImageSharp?.gatsbyImageData } -export const getImage = (file: FileNode): IGatsbyImageData | undefined => - file?.childImageSharp?.gatsbyImageData +export const getSrc = (node: ImageDataLike): string | undefined => + getImage(node)?.images?.fallback?.src -export const getSrc = (file: FileNode): string | undefined => - file?.childImageSharp?.gatsbyImageData?.images?.fallback?.src +export const getSrcSet = (node: ImageDataLike): string | undefined => + getImage(node)?.images?.fallback?.srcSet export function getWrapperProps( width: number, @@ -62,6 +85,12 @@ export function getWrapperProps( let className = `gatsby-image-wrapper` + // If the plugin isn't installed we need to apply the styles inline + if (!global.GATSBY___IMAGE) { + wrapperStyle.position = `relative` + wrapperStyle.overflow = `hidden` + } + if (layout === `fixed`) { wrapperStyle.width = width wrapperStyle.height = height @@ -97,7 +126,7 @@ export interface IUrlBuilderArgs { format: ImageFormat options: OptionsType } -export interface IGetImageDataArgs { +export interface IGetImageDataArgs> { baseUrl: string /** * For constrained and fixed images, the size of the image element diff --git a/packages/gatsby-plugin-image/src/components/later-hydrator.tsx b/packages/gatsby-plugin-image/src/components/later-hydrator.tsx index cc1c136cabcfa..85b70825ad4ea 100644 --- a/packages/gatsby-plugin-image/src/components/later-hydrator.tsx +++ b/packages/gatsby-plugin-image/src/components/later-hydrator.tsx @@ -1,8 +1,9 @@ import * as React from "react" export function LaterHydrator({ children, -}: React.PropsWithChildren<{}>): React.ReactNode { +}: React.PropsWithChildren>): React.ReactNode { React.useEffect(() => { + // eslint-disable-next-line no-unused-expressions import(`./lazy-hydrate`) }, []) diff --git a/packages/gatsby-plugin-image/src/components/layout-wrapper.tsx b/packages/gatsby-plugin-image/src/components/layout-wrapper.tsx index 09ae80690c389..755d5a7c9808f 100644 --- a/packages/gatsby-plugin-image/src/components/layout-wrapper.tsx +++ b/packages/gatsby-plugin-image/src/components/layout-wrapper.tsx @@ -1,7 +1,7 @@ // eslint-disable-next-line @typescript-eslint/triple-slash-reference /// -import React, { Fragment, FunctionComponent } from "react" +import React, { Fragment, FunctionComponent, ReactElement } from "react" import terserMacro from "../../macros/terser.macro" import { Layout } from "../image-utils" @@ -62,7 +62,7 @@ export const LayoutWrapper: FunctionComponent = function La height, children, }) { - let sizer: JSX.Element | null = null + let sizer: ReactElement | null = null if (layout === `fullWidth`) { sizer = (
diff --git a/packages/gatsby-plugin-image/src/components/lazy-hydrate.tsx b/packages/gatsby-plugin-image/src/components/lazy-hydrate.tsx index 3cff538bc7c88..65e232291e8f7 100644 --- a/packages/gatsby-plugin-image/src/components/lazy-hydrate.tsx +++ b/packages/gatsby-plugin-image/src/components/lazy-hydrate.tsx @@ -84,6 +84,8 @@ export function lazyHydrate( )} )} + width={width} + height={height} className={imgClassName} {...getMainProps( isLoading, diff --git a/packages/gatsby-plugin-image/src/components/placeholder.tsx b/packages/gatsby-plugin-image/src/components/placeholder.tsx index d54b37e288c9c..667f3b57ed980 100644 --- a/packages/gatsby-plugin-image/src/components/placeholder.tsx +++ b/packages/gatsby-plugin-image/src/components/placeholder.tsx @@ -2,7 +2,7 @@ import React, { FunctionComponent, ImgHTMLAttributes } from "react" import * as PropTypes from "prop-types" import { Picture, SourceProps } from "./picture" -export type PlaceholderProps = ImgHTMLAttributes<{}> & { +export type PlaceholderProps = ImgHTMLAttributes & { fallback?: string sources?: Array } 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 483cf55dba18b..75f86147bd012 100644 --- a/packages/gatsby-plugin-image/src/components/static-image.server.tsx +++ b/packages/gatsby-plugin-image/src/components/static-image.server.tsx @@ -1,4 +1,4 @@ -import React, { FunctionComponent } from "react" +import React, { FunctionComponent, ReactElement } from "react" import { GatsbyImage as GatsbyImageServer } from "./gatsby-image.server" import { GatsbyImageProps, IGatsbyImageData } from "./gatsby-image.browser" import PropTypes from "prop-types" @@ -40,7 +40,7 @@ export function _getStaticImage( blurredOptions, /* eslint-enable @typescript-eslint/no-unused-vars */ ...props - }): JSX.Element { + }): ReactElement { if (__error) { console.warn(__error) } diff --git a/packages/gatsby-plugin-image/src/components/static-image.tsx b/packages/gatsby-plugin-image/src/components/static-image.tsx index b8433e5c7295f..b2305d83a1d7f 100644 --- a/packages/gatsby-plugin-image/src/components/static-image.tsx +++ b/packages/gatsby-plugin-image/src/components/static-image.tsx @@ -2,6 +2,7 @@ import { GatsbyImage as GatsbyImageBrowser, IGatsbyImageData, } from "./gatsby-image.browser" +import React from "react" import { _getStaticImage, propTypes, diff --git a/packages/gatsby-plugin-image/src/image-utils.ts b/packages/gatsby-plugin-image/src/image-utils.ts index 9c7db11837caa..477d9e02f543c 100644 --- a/packages/gatsby-plugin-image/src/image-utils.ts +++ b/packages/gatsby-plugin-image/src/image-utils.ts @@ -170,7 +170,7 @@ export function setDefaultDimensions( layout = camelCase(layout) as Layout if (width && height) { - return args + return { ...args, formats, layout } } if (sourceMetadata.width && sourceMetadata.height && !aspectRatio) { aspectRatio = sourceMetadata.width / sourceMetadata.height @@ -194,11 +194,33 @@ export function setDefaultDimensions( if (aspectRatio && !height) { height = Math.round(width / aspectRatio) + } else if (!aspectRatio) { + aspectRatio = width / height } } return { ...args, width, height, aspectRatio, layout, formats } } +/** + * Use this for getting an image for the blurred placeholder. This ensures the + * aspect ratio and crop match the main image + */ +export function getLowResolutionImageURL( + args: IGatsbyImageHelperArgs, + width = 20 +): string { + args = setDefaultDimensions(args) + const { generateImageSource, filename, aspectRatio } = args + return generateImageSource( + filename, + width, + Math.round(width / aspectRatio), + args.sourceMetadata.format || `jpg`, + args.fit, + args.options + )?.src +} + export function generateImageData( args: IGatsbyImageHelperArgs ): IGatsbyImageData { diff --git a/packages/gatsby-plugin-image/src/index.browser.ts b/packages/gatsby-plugin-image/src/index.browser.ts index 992793af4491c..f804c2a7e74db 100644 --- a/packages/gatsby-plugin-image/src/index.browser.ts +++ b/packages/gatsby-plugin-image/src/index.browser.ts @@ -10,6 +10,7 @@ export { LaterHydrator } from "./components/later-hydrator" export { getImage, getSrc, + getSrcSet, getImageData, withArtDirection, IArtDirectedImage, @@ -18,6 +19,7 @@ export { } from "./components/hooks" export { generateImageData, + getLowResolutionImageURL, IGatsbyImageHelperArgs, IImage, ImageFormat, diff --git a/packages/gatsby-plugin-image/src/index.ts b/packages/gatsby-plugin-image/src/index.ts index 1723b79de5780..eb6ee653dd5e2 100644 --- a/packages/gatsby-plugin-image/src/index.ts +++ b/packages/gatsby-plugin-image/src/index.ts @@ -9,6 +9,7 @@ export { StaticImage } from "./components/static-image.server" export { getImage, getSrc, + getSrcSet, getImageData, withArtDirection, IArtDirectedImage, @@ -17,6 +18,7 @@ export { } from "./components/hooks" export { generateImageData, + getLowResolutionImageURL, IGatsbyImageHelperArgs, ISharpGatsbyImageArgs, IImage, diff --git a/packages/gatsby-plugin-image/src/resolver-utils.ts b/packages/gatsby-plugin-image/src/resolver-utils.ts index 0f471d4c8b8dd..ad900ae8e5560 100644 --- a/packages/gatsby-plugin-image/src/resolver-utils.ts +++ b/packages/gatsby-plugin-image/src/resolver-utils.ts @@ -168,7 +168,7 @@ export function getGatsbyImageFieldConfig( BLURRED: a blurred, low resolution image, encoded as a base64 data URI (default) DOMINANT_COLOR: a solid color, calculated from the dominant color of the image. TRACED_SVG: a low-resolution traced SVG of the image. - NONE: no placeholder. Set "background" to use a fixed background color.`, + NONE: no placeholder. Set the argument "backgroundColor" to use a fixed background color.`, }, formats: { type: GraphQLList(ImageFormatType), @@ -176,9 +176,9 @@ export function getGatsbyImageFieldConfig( The image formats to generate. Valid values are AUTO (meaning the same format as the source image), JPG, PNG, WEBP and AVIF. The default value is [AUTO, WEBP], and you should rarely need to change this. Take care if you specify JPG or PNG when you do not know the formats of the source images, as this could lead to unwanted results such as converting JPEGs to PNGs. Specifying - both PNG and JPG is not supported and will be ignored. AVIF support is currently experimental. + both PNG and JPG is not supported and will be ignored. `, - defaultValue: [`auto`, `webp`], + defaultValue: [``, `webp`], }, outputPixelDensities: { type: GraphQLList(GraphQLFloat), diff --git a/packages/gatsby-plugin-less/CHANGELOG.md b/packages/gatsby-plugin-less/CHANGELOG.md index 34d2d8b7c4f99..557ec448c9ddf 100644 --- a/packages/gatsby-plugin-less/CHANGELOG.md +++ b/packages/gatsby-plugin-less/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [5.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-less@5.0.0-next.0...gatsby-plugin-less@5.0.0-next.1) (2021-02-19) + +### Bug Fixes + +- make minicss-extract-plugin compatible with plugins ([#29599](https://github.com/gatsbyjs/gatsby/issues/29599)) ([c0ab195](https://github.com/gatsbyjs/gatsby/commit/c0ab19598708750ce98b39448469a39126f55571)) + # [5.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-less@4.8.0-next.0...gatsby-plugin-less@5.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-less diff --git a/packages/gatsby-plugin-less/package.json b/packages/gatsby-plugin-less/package.json index 2b95aab4f764f..4fec671499517 100644 --- a/packages/gatsby-plugin-less/package.json +++ b/packages/gatsby-plugin-less/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-plugin-less", "description": "Gatsby plugin to add support for using Less", - "version": "5.0.0-next.0", + "version": "5.0.0-next.1", "author": "monastic.panic@gmail.com", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" diff --git a/packages/gatsby-plugin-less/src/__tests__/__snapshots__/gatsby-node.js.snap b/packages/gatsby-plugin-less/src/__tests__/__snapshots__/gatsby-node.js.snap index e8e3aab66132b..0dca9da84c798 100644 --- a/packages/gatsby-plugin-less/src/__tests__/__snapshots__/gatsby-node.js.snap +++ b/packages/gatsby-plugin-less/src/__tests__/__snapshots__/gatsby-node.js.snap @@ -12,6 +12,7 @@ exports[`gatsby-plugin-less Stage: build-html / Less options #1 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { @@ -23,7 +24,6 @@ exports[`gatsby-plugin-less Stage: build-html / Less options #1 1`] = ` }, "strictMath": true, }, - "sourceMap": false, }, }, ], @@ -62,6 +62,7 @@ exports[`gatsby-plugin-less Stage: build-html / Less options #2 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { @@ -72,7 +73,6 @@ exports[`gatsby-plugin-less Stage: build-html / Less options #2 1`] = ` "text-color": "#fff", }, }, - "sourceMap": false, }, }, ], @@ -111,6 +111,7 @@ exports[`gatsby-plugin-less Stage: build-html / Loader options #1 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { @@ -118,7 +119,6 @@ exports[`gatsby-plugin-less Stage: build-html / Loader options #1 1`] = ` "options": Object { "appendData": "@env: test;", "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -157,13 +157,13 @@ exports[`gatsby-plugin-less Stage: build-html / No options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -202,13 +202,13 @@ exports[`gatsby-plugin-less Stage: build-html / PostCss plugins 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -247,13 +247,13 @@ exports[`gatsby-plugin-less Stage: build-html / css-loader options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"camelCase\\":false,\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -304,7 +304,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / Less options #1 1`] = ` }, "strictMath": true, }, - "sourceMap": false, }, }, ], @@ -324,7 +323,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / Less options #1 1`] = ` }, "strictMath": true, }, - "sourceMap": false, }, }, ], @@ -368,7 +366,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / Less options #2 1`] = ` "text-color": "#fff", }, }, - "sourceMap": false, }, }, ], @@ -387,7 +384,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / Less options #2 1`] = ` "text-color": "#fff", }, }, - "sourceMap": false, }, }, ], @@ -428,7 +424,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / Loader options #1 1`] = ` "options": Object { "appendData": "@env: test;", "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -444,7 +439,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / Loader options #1 1`] = ` "options": Object { "appendData": "@env: test;", "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -484,7 +478,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / No options 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -499,7 +492,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / No options 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -539,7 +531,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / PostCss plugins 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -554,7 +545,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / PostCss plugins 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -594,7 +584,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / css-loader options 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -609,7 +598,6 @@ exports[`gatsby-plugin-less Stage: build-javascript / css-loader options 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -654,7 +642,6 @@ exports[`gatsby-plugin-less Stage: develop / Less options #1 1`] = ` }, "strictMath": true, }, - "sourceMap": true, }, }, ], @@ -674,7 +661,6 @@ exports[`gatsby-plugin-less Stage: develop / Less options #1 1`] = ` }, "strictMath": true, }, - "sourceMap": true, }, }, ], @@ -718,7 +704,6 @@ exports[`gatsby-plugin-less Stage: develop / Less options #2 1`] = ` "text-color": "#fff", }, }, - "sourceMap": true, }, }, ], @@ -737,7 +722,6 @@ exports[`gatsby-plugin-less Stage: develop / Less options #2 1`] = ` "text-color": "#fff", }, }, - "sourceMap": true, }, }, ], @@ -778,7 +762,6 @@ exports[`gatsby-plugin-less Stage: develop / Loader options #1 1`] = ` "options": Object { "appendData": "@env: test;", "lessOptions": Object {}, - "sourceMap": true, }, }, ], @@ -794,7 +777,6 @@ exports[`gatsby-plugin-less Stage: develop / Loader options #1 1`] = ` "options": Object { "appendData": "@env: test;", "lessOptions": Object {}, - "sourceMap": true, }, }, ], @@ -834,7 +816,6 @@ exports[`gatsby-plugin-less Stage: develop / No options 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": true, }, }, ], @@ -849,7 +830,6 @@ exports[`gatsby-plugin-less Stage: develop / No options 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": true, }, }, ], @@ -889,7 +869,6 @@ exports[`gatsby-plugin-less Stage: develop / PostCss plugins 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": true, }, }, ], @@ -904,7 +883,6 @@ exports[`gatsby-plugin-less Stage: develop / PostCss plugins 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": true, }, }, ], @@ -944,7 +922,6 @@ exports[`gatsby-plugin-less Stage: develop / css-loader options 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": true, }, }, ], @@ -959,7 +936,6 @@ exports[`gatsby-plugin-less Stage: develop / css-loader options 1`] = ` "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": true, }, }, ], @@ -992,6 +968,7 @@ exports[`gatsby-plugin-less Stage: develop-html / Less options #1 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { @@ -1003,7 +980,6 @@ exports[`gatsby-plugin-less Stage: develop-html / Less options #1 1`] = ` }, "strictMath": true, }, - "sourceMap": false, }, }, ], @@ -1042,6 +1018,7 @@ exports[`gatsby-plugin-less Stage: develop-html / Less options #2 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { @@ -1052,7 +1029,6 @@ exports[`gatsby-plugin-less Stage: develop-html / Less options #2 1`] = ` "text-color": "#fff", }, }, - "sourceMap": false, }, }, ], @@ -1091,6 +1067,7 @@ exports[`gatsby-plugin-less Stage: develop-html / Loader options #1 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { @@ -1098,7 +1075,6 @@ exports[`gatsby-plugin-less Stage: develop-html / Loader options #1 1`] = ` "options": Object { "appendData": "@env: test;", "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -1137,13 +1113,13 @@ exports[`gatsby-plugin-less Stage: develop-html / No options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -1182,13 +1158,13 @@ exports[`gatsby-plugin-less Stage: develop-html / PostCss plugins 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"modules\\":true,\\"importLoaders\\":2})", "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], @@ -1227,13 +1203,13 @@ exports[`gatsby-plugin-less Stage: develop-html / css-loader options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.less\\$/, "use": Array [ + "miniCssExtract", "css({\\"camelCase\\":false,\\"modules\\":true,\\"importLoaders\\":2})", "postcss({})", Object { "loader": "/resolved/path/less-loader", "options": Object { "lessOptions": Object {}, - "sourceMap": false, }, }, ], diff --git a/packages/gatsby-plugin-less/src/gatsby-node.js b/packages/gatsby-plugin-less/src/gatsby-node.js index 70215c7a64bf7..a50e765691e76 100644 --- a/packages/gatsby-plugin-less/src/gatsby-node.js +++ b/packages/gatsby-plugin-less/src/gatsby-node.js @@ -1,17 +1,15 @@ import resolve from "./resolve" exports.onCreateWebpackConfig = ( - { actions, stage, rules, plugins, loaders }, + { actions, stage, loaders }, { cssLoaderOptions = {}, postCssPlugins, loaderOptions, lessOptions } ) => { + const isSSR = [`develop-html`, `build-html`].includes(stage) const { setWebpackConfig } = actions - const PRODUCTION = stage !== `develop` - const isSSR = stage.includes(`html`) const lessLoader = { loader: resolve(`less-loader`), options: { - sourceMap: !PRODUCTION, lessOptions: { ...lessOptions, }, @@ -33,27 +31,18 @@ exports.onCreateWebpackConfig = ( const lessRuleModules = { test: /\.module\.less$/, use: [ - !isSSR && loaders.miniCssExtract({ hmr: false }), + loaders.miniCssExtract({ modules: true }), loaders.css({ ...cssLoaderOptions, modules: true, importLoaders: 2 }), loaders.postcss({ plugins: postCssPlugins }), lessLoader, - ].filter(Boolean), + ], } - let configRules = [] - - switch (stage) { - case `develop`: - case `build-javascript`: - case `build-html`: - case `develop-html`: - configRules = configRules.concat([ - { - oneOf: [lessRuleModules, lessRule], - }, - ]) - break - } + const configRules = [ + { + oneOf: [lessRuleModules, lessRule], + }, + ] setWebpackConfig({ module: { diff --git a/packages/gatsby-plugin-manifest/CHANGELOG.md b/packages/gatsby-plugin-manifest/CHANGELOG.md index 6278891c6e3bf..4bd8136e4f6f9 100644 --- a/packages/gatsby-plugin-manifest/CHANGELOG.md +++ b/packages/gatsby-plugin-manifest/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-manifest@3.0.0-next.0...gatsby-plugin-manifest@3.0.0-next.1) (2021-02-22) + +**Note:** Version bump only for package gatsby-plugin-manifest + # [3.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-manifest@2.13.0-next.1...gatsby-plugin-manifest@3.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-manifest diff --git a/packages/gatsby-plugin-manifest/package.json b/packages/gatsby-plugin-manifest/package.json index dbbc099207db2..850ba0df7a863 100644 --- a/packages/gatsby-plugin-manifest/package.json +++ b/packages/gatsby-plugin-manifest/package.json @@ -1,14 +1,14 @@ { "name": "gatsby-plugin-manifest", "description": "Gatsby plugin which adds a manifest.webmanifest to make sites progressive web apps", - "version": "3.0.0-next.0", + "version": "3.0.0-next.1", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" }, "dependencies": { "@babel/runtime": "^7.12.5", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "gatsby-plugin-utils": "^1.0.0-next.0", "semver": "^7.3.2", "sharp": "^0.27.0" diff --git a/packages/gatsby-plugin-mdx/CHANGELOG.md b/packages/gatsby-plugin-mdx/CHANGELOG.md index 406a1f19ae11e..51aa220500ebb 100644 --- a/packages/gatsby-plugin-mdx/CHANGELOG.md +++ b/packages/gatsby-plugin-mdx/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [2.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-mdx@2.0.0-next.1...gatsby-plugin-mdx@2.0.0-next.2) (2021-02-22) + +**Note:** Version bump only for package gatsby-plugin-mdx + # [2.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-mdx@2.0.0-next.0...gatsby-plugin-mdx@2.0.0-next.1) (2021-02-12) **Note:** Version bump only for package gatsby-plugin-mdx diff --git a/packages/gatsby-plugin-mdx/package.json b/packages/gatsby-plugin-mdx/package.json index b2f08c2474164..7ab60e79333e9 100644 --- a/packages/gatsby-plugin-mdx/package.json +++ b/packages/gatsby-plugin-mdx/package.json @@ -1,6 +1,6 @@ { "name": "gatsby-plugin-mdx", - "version": "2.0.0-next.1", + "version": "2.0.0-next.2", "description": "MDX integration for Gatsby", "main": "index.js", "license": "MIT", @@ -35,7 +35,7 @@ "escape-string-regexp": "^1.0.5", "eval": "^0.1.4", "fs-extra": "^8.1.0", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "gray-matter": "^4.0.2", "json5": "^2.1.3", "loader-utils": "^1.4.0", diff --git a/packages/gatsby-plugin-netlify-cms/CHANGELOG.md b/packages/gatsby-plugin-netlify-cms/CHANGELOG.md index 11cdeff229d9e..0c7f31dd0177a 100644 --- a/packages/gatsby-plugin-netlify-cms/CHANGELOG.md +++ b/packages/gatsby-plugin-netlify-cms/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [5.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-netlify-cms@5.0.0-next.0...gatsby-plugin-netlify-cms@5.0.0-next.1) (2021-02-19) + +### Bug Fixes + +- make minicss-extract-plugin compatible with plugins ([#29599](https://github.com/gatsbyjs/gatsby/issues/29599)) ([c0ab195](https://github.com/gatsbyjs/gatsby/commit/c0ab19598708750ce98b39448469a39126f55571)) + # [5.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-netlify-cms@4.11.0-next.0...gatsby-plugin-netlify-cms@5.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-netlify-cms diff --git a/packages/gatsby-plugin-netlify-cms/package.json b/packages/gatsby-plugin-netlify-cms/package.json index a503dff0c239e..48ccdfb68b049 100644 --- a/packages/gatsby-plugin-netlify-cms/package.json +++ b/packages/gatsby-plugin-netlify-cms/package.json @@ -1,25 +1,24 @@ { "name": "gatsby-plugin-netlify-cms", "description": "A Gatsby plugin which generates the Netlify CMS single page app", - "version": "5.0.0-next.0", + "version": "5.0.0-next.1", "author": "Shawn Erquhart ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" }, "dependencies": { "@pieh/friendly-errors-webpack-plugin": "1.7.0-chalk-2", - "copy-webpack-plugin": "^5.1.2", - "html-webpack-exclude-assets-plugin": "^0.0.7", - "html-webpack-plugin": "^3.2.0", - "html-webpack-tags-plugin": "^2.0.17", - "lodash": "^4.17.20", - "mini-css-extract-plugin": "^0.12.0", + "copy-webpack-plugin": "^7.0.0", + "html-webpack-plugin": "^5.2.0", + "html-webpack-tags-plugin": "^3.0.0", + "lodash": "^4.17.21", + "mini-css-extract-plugin": "^1.3.8", "netlify-identity-widget": "^1.9.1", - "webpack": "^4.46.0" + "webpack": "^5.23.00" }, "devDependencies": { - "@babel/cli": "^7.12.1", - "@babel/core": "^7.12.3", + "@babel/cli": "^7.12.17", + "@babel/core": "^7.12.17", "babel-preset-gatsby-package": "^1.0.0-next.0", "cross-env": "^7.0.3", "react": "^16.12.0", diff --git a/packages/gatsby-plugin-netlify-cms/src/gatsby-node.js b/packages/gatsby-plugin-netlify-cms/src/gatsby-node.js index 04730ccd31864..15c5a7097f534 100644 --- a/packages/gatsby-plugin-netlify-cms/src/gatsby-node.js +++ b/packages/gatsby-plugin-netlify-cms/src/gatsby-node.js @@ -2,7 +2,6 @@ import path from "path" import { mapValues, isPlainObject, trim } from "lodash" import webpack from "webpack" import HtmlWebpackPlugin from "html-webpack-plugin" -import HtmlWebpackExcludeAssetsPlugin from "html-webpack-exclude-assets-plugin" import MiniCssExtractPlugin from "mini-css-extract-plugin" // TODO: swap back when https://github.com/geowarin/friendly-errors-webpack-plugin/pull/86 lands import FriendlyErrorsPlugin from "@pieh/friendly-errors-webpack-plugin" @@ -31,10 +30,6 @@ function deepMap(obj, fn) { const cssTests = [] -function isCssRule({ test }) { - return test instanceof RegExp && cssTests.includes(test.toString()) -} - function replaceRule(value, stage) { // If `value` does not have a `test` property, it isn't a rule object. if (!value || !value.test) { @@ -55,35 +50,6 @@ function replaceRule(value, stage) { return null } - // use MiniCssExtractPlugin.loader in development - if (stage === `develop` && value.test && isCssRule(value)) { - function replaceStyleLoader(rule) { - if (rule.loader.includes(`style-loader`)) { - return { - ...rule, - loader: MiniCssExtractPlugin.loader, - options: { - hmr: true, - }, - } - } - - return rule - } - - if (value.use) { - return { - ...value, - use: value.use.map(replaceStyleLoader), - } - } else if (value.loader) { - return { - ...value, - loader: replaceStyleLoader(value), - } - } - } - return value } @@ -243,8 +209,9 @@ exports.onCreateWebpackConfig = ( // Exclude CSS from index.html, as any imported styles are assumed to be // targeting the editor preview pane. Uses `excludeAssets` option from - // `HtmlWebpackPlugin` config. - new HtmlWebpackExcludeAssetsPlugin(), + // `HtmlWebpackPlugin` config + // not compatible with webpack 5 + // new HtmlWebpackExcludeAssetsPlugin(), // Pass in needed Gatsby config values. new webpack.DefinePlugin({ @@ -252,10 +219,9 @@ exports.onCreateWebpackConfig = ( CMS_PUBLIC_PATH: JSON.stringify(publicPath), }), - new CopyPlugin( - [].concat.apply( - [], - externals.map(({ name, assetName, sourceMap, assetDir }) => + new CopyPlugin({ + patterns: externals.flatMap( + ({ name, assetName, sourceMap, assetDir }) => [ { from: require.resolve(path.join(name, assetDir, assetName)), @@ -265,10 +231,9 @@ exports.onCreateWebpackConfig = ( from: require.resolve(path.join(name, assetDir, sourceMap)), to: sourceMap, }, - ].filter(item => item) - ) - ) - ), + ].filter(Boolean) + ), + }), new HtmlWebpackTagsPlugin({ tags: externals.map(({ assetName }) => assetName), diff --git a/packages/gatsby-plugin-offline/CHANGELOG.md b/packages/gatsby-plugin-offline/CHANGELOG.md index f5cd7b1cbab5a..a52d4cdc62dcc 100644 --- a/packages/gatsby-plugin-offline/CHANGELOG.md +++ b/packages/gatsby-plugin-offline/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [4.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-offline@4.0.0-next.1...gatsby-plugin-offline@4.0.0-next.2) (2021-02-22) + +**Note:** Version bump only for package gatsby-plugin-offline + # [4.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-offline@4.0.0-next.0...gatsby-plugin-offline@4.0.0-next.1) (2021-02-11) ### Bug Fixes diff --git a/packages/gatsby-plugin-offline/package.json b/packages/gatsby-plugin-offline/package.json index 7d1931703b0f2..d341b515f496c 100644 --- a/packages/gatsby-plugin-offline/package.json +++ b/packages/gatsby-plugin-offline/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-plugin-offline", "description": "Gatsby plugin which sets up a site to be able to run offline", - "version": "4.0.0-next.1", + "version": "4.0.0-next.2", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -9,7 +9,7 @@ "dependencies": { "@babel/runtime": "^7.12.5", "cheerio": "^1.0.0-rc.3", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "glob": "^7.1.6", "idb-keyval": "^3.2.0", "lodash": "^4.17.20", diff --git a/packages/gatsby-plugin-page-creator/CHANGELOG.md b/packages/gatsby-plugin-page-creator/CHANGELOG.md index e79e5994e7979..e1dde1357c441 100644 --- a/packages/gatsby-plugin-page-creator/CHANGELOG.md +++ b/packages/gatsby-plugin-page-creator/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-page-creator@3.0.0-next.0...gatsby-plugin-page-creator@3.0.0-next.1) (2021-02-22) + +**Note:** Version bump only for package gatsby-plugin-page-creator + # [3.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-page-creator@2.11.0-next.0...gatsby-plugin-page-creator@3.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-page-creator diff --git a/packages/gatsby-plugin-page-creator/package.json b/packages/gatsby-plugin-page-creator/package.json index 65c5d2cc5e63d..76d0090f89d31 100644 --- a/packages/gatsby-plugin-page-creator/package.json +++ b/packages/gatsby-plugin-page-creator/package.json @@ -1,6 +1,6 @@ { "name": "gatsby-plugin-page-creator", - "version": "3.0.0-next.0", + "version": "3.0.0-next.1", "description": "Gatsby plugin that automatically creates pages from React components in specified directories", "main": "index.js", "scripts": { @@ -28,8 +28,8 @@ "@sindresorhus/slugify": "^1.1.0", "chokidar": "^3.5.1", "fs-exists-cached": "^1.0.0", - "gatsby-page-utils": "^1.0.0-next.0", - "gatsby-telemetry": "^2.0.0-next.0", + "gatsby-page-utils": "^1.0.0-next.1", + "gatsby-telemetry": "^2.0.0-next.1", "globby": "^11.0.2", "lodash": "^4.17.20" }, diff --git a/packages/gatsby-plugin-page-creator/src/__tests__/collection-extract-query-string.ts b/packages/gatsby-plugin-page-creator/src/__tests__/collection-extract-query-string.ts index 300d199f8265c..c0e13cb3e9833 100644 --- a/packages/gatsby-plugin-page-creator/src/__tests__/collection-extract-query-string.ts +++ b/packages/gatsby-plugin-page-creator/src/__tests__/collection-extract-query-string.ts @@ -1,9 +1,13 @@ import sysPath from "path" import fs from "fs-extra" import { collectionExtractQueryString } from "../collection-extract-query-string" -import reporter from "gatsby-cli/lib/reporter" +import reporter from "gatsby/reporter" -jest.mock(`gatsby-cli/lib/reporter`) +jest.mock(`gatsby/reporter`, () => { + return { + panicOnBuild: jest.fn(), + } +}) // This makes the tests work on windows properly const createPath = (path: string): string => path.replace(/\//g, sysPath.sep) diff --git a/packages/gatsby-plugin-page-creator/src/__tests__/derive-path.ts b/packages/gatsby-plugin-page-creator/src/__tests__/derive-path.ts index 3f857a2a47ef8..bd87e466779da 100644 --- a/packages/gatsby-plugin-page-creator/src/__tests__/derive-path.ts +++ b/packages/gatsby-plugin-page-creator/src/__tests__/derive-path.ts @@ -1,5 +1,5 @@ import { derivePath } from "../derive-path" -import reporter from "gatsby-cli/lib/reporter" +import reporter from "gatsby/reporter" describe(`derive-path`, () => { it(`has basic support`, () => { diff --git a/packages/gatsby-plugin-page-creator/src/__tests__/is-valid-collection-path-implementation.ts b/packages/gatsby-plugin-page-creator/src/__tests__/is-valid-collection-path-implementation.ts index 208a9a1104c84..c306c39eba09c 100644 --- a/packages/gatsby-plugin-page-creator/src/__tests__/is-valid-collection-path-implementation.ts +++ b/packages/gatsby-plugin-page-creator/src/__tests__/is-valid-collection-path-implementation.ts @@ -1,8 +1,12 @@ import { isValidCollectionPathImplementation } from "../is-valid-collection-path-implementation" -import reporter from "gatsby-cli/lib/reporter" +import reporter from "gatsby/reporter" import syspath from "path" -jest.mock(`gatsby-cli/lib/reporter`) +jest.mock(`gatsby/reporter`, () => { + return { + panicOnBuild: jest.fn(), + } +}) // windows and mac have different seperators, all code is written with unix-like // file systems, but the underlying code uses `path.sep`. So when running tests diff --git a/packages/gatsby-plugin-page-creator/src/collection-extract-query-string.ts b/packages/gatsby-plugin-page-creator/src/collection-extract-query-string.ts index a56ff521c38fb..093dec6e9f5f3 100644 --- a/packages/gatsby-plugin-page-creator/src/collection-extract-query-string.ts +++ b/packages/gatsby-plugin-page-creator/src/collection-extract-query-string.ts @@ -1,6 +1,6 @@ import { generateQueryFromString } from "./extract-query" import fs from "fs-extra" -import { Reporter } from "gatsby" +import { Reporter } from "gatsby/reporter" import { extractModel } from "./path-utils" import { CODES, prefixId } from "./error-utils" diff --git a/packages/gatsby-plugin-page-creator/src/create-page-wrapper.ts b/packages/gatsby-plugin-page-creator/src/create-page-wrapper.ts index 7bf3186a64d7d..d5ec631fdb644 100644 --- a/packages/gatsby-plugin-page-creator/src/create-page-wrapper.ts +++ b/packages/gatsby-plugin-page-creator/src/create-page-wrapper.ts @@ -10,7 +10,7 @@ import { createClientOnlyPage } from "./create-client-only-page" import { createPagesFromCollectionBuilder } from "./create-pages-from-collection-builder" import systemPath from "path" import { trackFeatureIsUsed } from "gatsby-telemetry" -import { Reporter } from "gatsby" +import { Reporter } from "gatsby/reporter" function pathIsCollectionBuilder(path: string): boolean { return path.includes(`{`) 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 1fe40032b1a91..a11a1de01bfdd 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 @@ -1,7 +1,7 @@ // Move this to gatsby-core-utils? import { Actions, CreatePagesArgs } from "gatsby" import { createPath } from "gatsby-page-utils" -import { Reporter } from "gatsby" +import { Reporter } from "gatsby/reporter" import { Options as ISlugifyOptions } from "@sindresorhus/slugify" import { reverseLookupParams } from "./extract-query" import { getMatchPath } from "./get-match-path" @@ -92,7 +92,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< - Record + Record> > if (nodes) { @@ -107,7 +107,7 @@ ${errors.map(error => error.message).join(`\n`)}`.trim(), // 3. Loop through each node and create the page, also save the path it creates to pass to the watcher // the watcher will use this data to delete the pages if the query changes significantly. - const paths = nodes.map((node: Record) => { + const paths = nodes.map((node: Record>) => { // URL path for the component and node const { derivedPath, errors } = derivePath( filePath, diff --git a/packages/gatsby-plugin-page-creator/src/derive-path.ts b/packages/gatsby-plugin-page-creator/src/derive-path.ts index 1ee0b13a3b7b6..5487b1e5f04e9 100644 --- a/packages/gatsby-plugin-page-creator/src/derive-path.ts +++ b/packages/gatsby-plugin-page-creator/src/derive-path.ts @@ -1,6 +1,6 @@ import _ from "lodash" import slugify, { Options as ISlugifyOptions } from "@sindresorhus/slugify" -import { Reporter } from "gatsby" +import { Reporter } from "gatsby/reporter" import { extractFieldWithoutUnion, extractAllCollectionSegments, diff --git a/packages/gatsby-plugin-page-creator/src/error-utils.ts b/packages/gatsby-plugin-page-creator/src/error-utils.ts index ef267522aa6e7..c6f48e2951f97 100644 --- a/packages/gatsby-plugin-page-creator/src/error-utils.ts +++ b/packages/gatsby-plugin-page-creator/src/error-utils.ts @@ -1,4 +1,4 @@ -import { Reporter } from "gatsby" +import { Reporter } from "gatsby/reporter" export const CODES = { Generic: `12101`, diff --git a/packages/gatsby-plugin-page-creator/src/extract-query.ts b/packages/gatsby-plugin-page-creator/src/extract-query.ts index 9e4aef4919d7f..6b9823d48076a 100644 --- a/packages/gatsby-plugin-page-creator/src/extract-query.ts +++ b/packages/gatsby-plugin-page-creator/src/extract-query.ts @@ -26,7 +26,7 @@ export function generateQueryFromString( // translates the object into `{ fields__value: 'foo' }`. This is necassary to pass the value // into a query function for each individual page. export function reverseLookupParams( - queryResults: Record, + queryResults: Record | string>, absolutePath: string ): Record { const reversedParams = { diff --git a/packages/gatsby-plugin-page-creator/src/gatsby-node.ts b/packages/gatsby-plugin-page-creator/src/gatsby-node.ts index c44bdfb7a207a..e0bc8f42fc678 100644 --- a/packages/gatsby-plugin-page-creator/src/gatsby-node.ts +++ b/packages/gatsby-plugin-page-creator/src/gatsby-node.ts @@ -166,7 +166,7 @@ Please pick a path to an existing directory.`, export function setFieldsOnGraphQLNodeType( { getNode, type, store, reporter }: SetFieldsOnGraphQLNodeTypeArgs, { slugify: slugifyOptions }: PluginOptions & { slugify: ISlugifyOptions } -): object { +): Record { try { const extensions = store.getState().program.extensions const collectionQuery = _.camelCase(`all ${type.name}`) @@ -180,7 +180,7 @@ export function setFieldsOnGraphQLNodeType( }, }, resolve: ( - source: object, + source: Record, { filePath }: { filePath: string } ): string => { // This is a quick hack for attaching parents to the node. diff --git a/packages/gatsby-plugin-page-creator/src/is-valid-collection-path-implementation.ts b/packages/gatsby-plugin-page-creator/src/is-valid-collection-path-implementation.ts index bbd9c44dc4db1..8cac58a49c003 100644 --- a/packages/gatsby-plugin-page-creator/src/is-valid-collection-path-implementation.ts +++ b/packages/gatsby-plugin-page-creator/src/is-valid-collection-path-implementation.ts @@ -1,7 +1,6 @@ import sysPath from "path" -import { Reporter } from "gatsby" +import { Reporter } from "gatsby/reporter" import { CODES, prefixId } from "./error-utils" -import { matchAllPolyfill } from "./path-utils" // This file is a helper for consumers. It's going to log an error to them if they // in any way have an incorrect filepath setup for us to predictably use collection @@ -19,9 +18,8 @@ export function isValidCollectionPathImplementation( parts.forEach(part => { if (!part.includes(`{`) && !part.includes(`}`)) return - const model = matchAllPolyfill(/\{([a-zA-Z_]\w*)./g, part) // Search for word before first dot, e.g. Model - const field = matchAllPolyfill(/.*?((?<=\w\.)[^}]*)}/g, part) // Search for everything after the first dot, e.g. foo__bar (or in invalid case: foo.bar) - + const model = Array.from(part.matchAll(/\{([a-zA-Z_]\w*)./g)) // Search for word before first dot, e.g. Model + const field = Array.from(part.matchAll(/.*?((?<=\w\.)[^}]*)}/g)) // Search for everything after the first dot, e.g. foo__bar (or in invalid case: foo.bar) try { if ( model.length === 0 || diff --git a/packages/gatsby-plugin-page-creator/src/path-utils.ts b/packages/gatsby-plugin-page-creator/src/path-utils.ts index 664ba5ed3a4ad..8d1099d88f67a 100644 --- a/packages/gatsby-plugin-page-creator/src/path-utils.ts +++ b/packages/gatsby-plugin-page-creator/src/path-utils.ts @@ -121,24 +121,3 @@ export function compose( return (filePart: string): string => functions.reduce((value, fn) => fn(value), filePart) } - -/** - * Since String.prototype.matchAll() is only supported by Node v12+ and we still support Node 10, this is how we need to workaround this - * @param regexPattern - Should include the /g flag! - * @param sourceString - Input string to match against - * @returns An array of RegExpExecArray similar to the shape of .matchAll() - */ -export function matchAllPolyfill( - regexPattern, - sourceString -): Array { - const output: Array = [] - let match: RegExpExecArray | null - while ((match = regexPattern.exec(sourceString))) { - // get rid of the string copy - delete match.input - // store the match data - output.push(match) - } - return output -} diff --git a/packages/gatsby-plugin-postcss/CHANGELOG.md b/packages/gatsby-plugin-postcss/CHANGELOG.md index fc5e503d04caf..e9652bd26f2ca 100644 --- a/packages/gatsby-plugin-postcss/CHANGELOG.md +++ b/packages/gatsby-plugin-postcss/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [4.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-postcss@4.0.0-next.0...gatsby-plugin-postcss@4.0.0-next.1) (2021-02-19) + +### Bug Fixes + +- make minicss-extract-plugin compatible with plugins ([#29599](https://github.com/gatsbyjs/gatsby/issues/29599)) ([c0ab195](https://github.com/gatsbyjs/gatsby/commit/c0ab19598708750ce98b39448469a39126f55571)) + # [4.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-postcss@3.8.0-next.0...gatsby-plugin-postcss@4.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-postcss diff --git a/packages/gatsby-plugin-postcss/package.json b/packages/gatsby-plugin-postcss/package.json index 52aeb9d3ae1ad..aeee116c35435 100644 --- a/packages/gatsby-plugin-postcss/package.json +++ b/packages/gatsby-plugin-postcss/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-plugin-postcss", "description": "Gatsby plugin to handle PostCSS", - "version": "4.0.0-next.0", + "version": "4.0.0-next.1", "author": "Marat Dreizin ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" diff --git a/packages/gatsby-plugin-postcss/src/__tests__/__snapshots__/gatsby-node.test.js.snap b/packages/gatsby-plugin-postcss/src/__tests__/__snapshots__/gatsby-node.test.js.snap index a2803bd43a604..25c9d4a1d2314 100644 --- a/packages/gatsby-plugin-postcss/src/__tests__/__snapshots__/gatsby-node.test.js.snap +++ b/packages/gatsby-plugin-postcss/src/__tests__/__snapshots__/gatsby-node.test.js.snap @@ -12,12 +12,12 @@ exports[`gatsby-plugin-postcss Stage: build-html / Css options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": Array [ + "miniCssExtract", "css-loader({\\"camelCase\\":true,\\"importLoaders\\":1,\\"modules\\":true})", Object { "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -31,12 +31,12 @@ exports[`gatsby-plugin-postcss Stage: build-html / Css options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": Array [ + "miniCssExtract", "css-loader({\\"camelCase\\":true,\\"importLoaders\\":1,\\"modules\\":true})", Object { "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -56,7 +56,6 @@ exports[`gatsby-plugin-postcss Stage: build-html / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -70,7 +69,6 @@ exports[`gatsby-plugin-postcss Stage: build-html / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -84,7 +82,6 @@ exports[`gatsby-plugin-postcss Stage: build-html / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -98,7 +95,6 @@ exports[`gatsby-plugin-postcss Stage: build-html / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -149,12 +145,12 @@ exports[`gatsby-plugin-postcss Stage: build-html / No options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": Array [ + "miniCssExtract", "css-loader({\\"importLoaders\\":1,\\"modules\\":true})", Object { "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -193,6 +189,7 @@ exports[`gatsby-plugin-postcss Stage: build-html / PostCss options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": Array [ + "miniCssExtract", "css-loader({\\"importLoaders\\":1,\\"modules\\":true})", Object { "loader": "/resolved/path/postcss-loader", @@ -216,6 +213,7 @@ exports[`gatsby-plugin-postcss Stage: build-html / PostCss options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": Array [ + "miniCssExtract", "css-loader({\\"importLoaders\\":1,\\"modules\\":true})", Object { "loader": "/resolved/path/postcss-loader", @@ -360,7 +358,6 @@ exports[`gatsby-plugin-postcss Stage: build-javascript / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -374,7 +371,6 @@ exports[`gatsby-plugin-postcss Stage: build-javascript / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -388,7 +384,6 @@ exports[`gatsby-plugin-postcss Stage: build-javascript / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -402,7 +397,6 @@ exports[`gatsby-plugin-postcss Stage: build-javascript / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -459,7 +453,6 @@ exports[`gatsby-plugin-postcss Stage: build-javascript / No options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -473,7 +466,6 @@ exports[`gatsby-plugin-postcss Stage: build-javascript / No options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -627,7 +619,6 @@ exports[`gatsby-plugin-postcss Stage: develop / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -641,7 +632,6 @@ exports[`gatsby-plugin-postcss Stage: develop / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -698,7 +688,6 @@ exports[`gatsby-plugin-postcss Stage: develop / No options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -712,7 +701,6 @@ exports[`gatsby-plugin-postcss Stage: develop / No options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -824,12 +812,12 @@ exports[`gatsby-plugin-postcss Stage: develop-html / Css options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": Array [ + "miniCssExtract", "css-loader({\\"camelCase\\":true,\\"importLoaders\\":1,\\"modules\\":true})", Object { "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -849,7 +837,6 @@ exports[`gatsby-plugin-postcss Stage: develop-html / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -863,7 +850,6 @@ exports[`gatsby-plugin-postcss Stage: develop-html / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": false, }, }, ], @@ -877,7 +863,6 @@ exports[`gatsby-plugin-postcss Stage: develop-html / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -891,7 +876,6 @@ exports[`gatsby-plugin-postcss Stage: develop-html / Css options 1`] = ` "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -942,12 +926,12 @@ exports[`gatsby-plugin-postcss Stage: develop-html / No options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": Array [ + "miniCssExtract", "css-loader({\\"importLoaders\\":1,\\"modules\\":true})", Object { "loader": "/resolved/path/postcss-loader", "options": Object { "postcssOptions": Object {}, - "sourceMap": true, }, }, ], @@ -986,6 +970,7 @@ exports[`gatsby-plugin-postcss Stage: develop-html / PostCss options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": Array [ + "miniCssExtract", "css-loader({\\"importLoaders\\":1,\\"modules\\":true})", Object { "loader": "/resolved/path/postcss-loader", diff --git a/packages/gatsby-plugin-postcss/src/gatsby-node.js b/packages/gatsby-plugin-postcss/src/gatsby-node.js index 1305bb43955cc..17a31dc19f5c1 100644 --- a/packages/gatsby-plugin-postcss/src/gatsby-node.js +++ b/packages/gatsby-plugin-postcss/src/gatsby-node.js @@ -15,15 +15,13 @@ const findCssRules = config => exports.onCreateWebpackConfig = ( { actions, stage, loaders, getConfig }, - { cssLoaderOptions = {}, postCssPlugins, ...postcssLoaderOptions } + // eslint-disable-next-line no-unused-vars + { cssLoaderOptions = {}, postCssPlugins, plugins, ...postcssLoaderOptions } ) => { - const isProduction = !stage.includes(`develop`) - const isSSR = stage.includes(`html`) + const isSSR = [`develop-html`, `build-html`].includes(stage) const config = getConfig() const cssRules = findCssRules(config) - delete postcssLoaderOptions.plugins - if (!postcssLoaderOptions.postcssOptions) { postcssLoaderOptions.postcssOptions = {} } @@ -34,37 +32,28 @@ exports.onCreateWebpackConfig = ( const postcssLoader = { loader: resolve(`postcss-loader`), - options: { sourceMap: !isProduction, ...postcssLoaderOptions }, + options: postcssLoaderOptions, } const postcssRule = { test: CSS_PATTERN, use: isSSR ? [loaders.null()] - : [loaders.css({ ...cssLoaderOptions, importLoaders: 1 }), postcssLoader], + : [ + loaders.miniCssExtract(), + loaders.css({ ...cssLoaderOptions, importLoaders: 1 }), + postcssLoader, + ], } const postcssRuleModules = { test: MODULE_CSS_PATTERN, use: [ + loaders.miniCssExtract({ modules: true }), loaders.css({ ...cssLoaderOptions, importLoaders: 1, modules: true }), postcssLoader, ], } - if (!isSSR) { - postcssRule.use.unshift(loaders.miniCssExtract()) - postcssRuleModules.use.unshift(loaders.miniCssExtract({ hmr: false })) - } - - const postcssRules = { oneOf: [] } - - switch (stage) { - case `develop`: - case `build-javascript`: - case `build-html`: - case `develop-html`: - postcssRules.oneOf.push(...[postcssRuleModules, postcssRule]) - break - } + const postcssRules = { oneOf: [postcssRuleModules, postcssRule] } if (cssRules) { cssRules.oneOf.unshift(...postcssRules.oneOf) diff --git a/packages/gatsby-plugin-preact/CHANGELOG.md b/packages/gatsby-plugin-preact/CHANGELOG.md index 1f2f8acd68dd9..2daa9a6b997bc 100644 --- a/packages/gatsby-plugin-preact/CHANGELOG.md +++ b/packages/gatsby-plugin-preact/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [5.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-preact@5.0.0-next.0...gatsby-plugin-preact@5.0.0-next.1) (2021-02-19) + +### Features + +- remove react-hot-loader ([#29540](https://github.com/gatsbyjs/gatsby/issues/29540)) ([a5210b2](https://github.com/gatsbyjs/gatsby/commit/a5210b2550b9646656aae28c28cb5be580cd5677)) + # [5.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-preact@4.8.0-next.0...gatsby-plugin-preact@5.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-preact diff --git a/packages/gatsby-plugin-preact/package.json b/packages/gatsby-plugin-preact/package.json index 60b5936cf5bb6..c12ebfa933662 100644 --- a/packages/gatsby-plugin-preact/package.json +++ b/packages/gatsby-plugin-preact/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-plugin-preact", "description": "A Gatsby plugin which replaces React with Preact", - "version": "5.0.0-next.0", + "version": "5.0.0-next.1", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" diff --git a/packages/gatsby-plugin-preact/src/__tests__/gatsby-node.js b/packages/gatsby-plugin-preact/src/__tests__/gatsby-node.js index a9c357d58cec2..92a70305767c4 100644 --- a/packages/gatsby-plugin-preact/src/__tests__/gatsby-node.js +++ b/packages/gatsby-plugin-preact/src/__tests__/gatsby-node.js @@ -31,7 +31,7 @@ describe(`gatsby-plugin-preact`, () => { }, }) - expect(getConfig).toHaveBeenCalledTimes(1) + expect(getConfig).toHaveBeenCalledTimes(2) expect(actions.setBabelPlugin).toHaveBeenCalledTimes(1) expect(actions.setBabelPlugin).toHaveBeenCalledWith({ name: `@prefresh/babel-plugin`, diff --git a/packages/gatsby-plugin-preact/src/gatsby-node.js b/packages/gatsby-plugin-preact/src/gatsby-node.js index 5e25c8e97c70d..1418deb964d3a 100644 --- a/packages/gatsby-plugin-preact/src/gatsby-node.js +++ b/packages/gatsby-plugin-preact/src/gatsby-node.js @@ -1,10 +1,5 @@ const PreactRefreshPlugin = require(`@prefresh/webpack`) -exports.onPreInit = () => { - // force fast-refresh in gatsby - process.env.GATSBY_HOT_LOADER = `fast-refresh` -} - exports.onCreateBabelConfig = ({ actions, stage }) => { if (stage === `develop`) { // enable react-refresh babel plugin to enable hooks @@ -30,7 +25,7 @@ exports.onCreateWebpackConfig = ({ stage, actions, getConfig }) => { } // add preact to the framework bundle - if (stage === `build-javascript`) { + if (stage === `build-javascript` || stage === `develop`) { const webpackConfig = getConfig() if ( webpackConfig?.optimization?.splitChunks?.cacheGroups?.framework?.test diff --git a/packages/gatsby-plugin-preload-fonts/CHANGELOG.md b/packages/gatsby-plugin-preload-fonts/CHANGELOG.md index e15be5e715aa6..7ac64f544c095 100644 --- a/packages/gatsby-plugin-preload-fonts/CHANGELOG.md +++ b/packages/gatsby-plugin-preload-fonts/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [2.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-preload-fonts@2.0.0-next.0...gatsby-plugin-preload-fonts@2.0.0-next.1) (2021-02-22) + +**Note:** Version bump only for package gatsby-plugin-preload-fonts + # [2.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-preload-fonts@1.10.0-next.0...gatsby-plugin-preload-fonts@2.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-preload-fonts diff --git a/packages/gatsby-plugin-preload-fonts/package.json b/packages/gatsby-plugin-preload-fonts/package.json index 68f12623141d3..dd30ddd070e4e 100644 --- a/packages/gatsby-plugin-preload-fonts/package.json +++ b/packages/gatsby-plugin-preload-fonts/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-plugin-preload-fonts", "description": "Gatsby plugin for preloading fonts per page", - "version": "2.0.0-next.0", + "version": "2.0.0-next.1", "author": "Aaron Ross ", "main": "index.js", "bin": { @@ -14,7 +14,7 @@ "chalk": "^4.1.0", "date-fns": "^2.16.1", "fs-extra": "^8.1.0", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "graphql-request": "^1.8.2", "progress": "^2.0.3", "puppeteer": "^3.3.0" diff --git a/packages/gatsby-plugin-sass/CHANGELOG.md b/packages/gatsby-plugin-sass/CHANGELOG.md index b541288de593e..655d036ad7a15 100644 --- a/packages/gatsby-plugin-sass/CHANGELOG.md +++ b/packages/gatsby-plugin-sass/CHANGELOG.md @@ -3,6 +3,18 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [4.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-sass@4.0.0-next.1...gatsby-plugin-sass@4.0.0-next.2) (2021-02-22) + +### Bug Fixes + +- **deps:** update minor and patch for gatsby-plugin-sass ([#29182](https://github.com/gatsbyjs/gatsby/issues/29182)) ([1038069](https://github.com/gatsbyjs/gatsby/commit/10380695cf7016c019d9bee443948ad394a32e66)) + +# [4.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-sass@4.0.0-next.0...gatsby-plugin-sass@4.0.0-next.1) (2021-02-19) + +### Bug Fixes + +- make minicss-extract-plugin compatible with plugins ([#29599](https://github.com/gatsbyjs/gatsby/issues/29599)) ([c0ab195](https://github.com/gatsbyjs/gatsby/commit/c0ab19598708750ce98b39448469a39126f55571)) + # [4.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-sass@3.3.0-next.0...gatsby-plugin-sass@4.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-sass diff --git a/packages/gatsby-plugin-sass/package.json b/packages/gatsby-plugin-sass/package.json index efdd06f049281..b8d0151436c6a 100644 --- a/packages/gatsby-plugin-sass/package.json +++ b/packages/gatsby-plugin-sass/package.json @@ -1,14 +1,15 @@ { "name": "gatsby-plugin-sass", "description": "Gatsby plugin to handle SCSS/Sass files", - "version": "4.0.0-next.0", + "version": "4.0.0-next.2", "author": "Daniel Farrell ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" }, "dependencies": { "@babel/runtime": "^7.12.5", - "sass-loader": "^10.1.0" + "resolve-url-loader": "^3.1.2", + "sass-loader": "^10.1.1" }, "devDependencies": { "@babel/cli": "^7.12.1", diff --git a/packages/gatsby-plugin-sass/src/__tests__/__snapshots__/gatsby-node.js.snap b/packages/gatsby-plugin-sass/src/__tests__/__snapshots__/gatsby-node.js.snap index 9d8fff779989b..45489f3dcef6e 100644 --- a/packages/gatsby-plugin-sass/src/__tests__/__snapshots__/gatsby-node.js.snap +++ b/packages/gatsby-plugin-sass/src/__tests__/__snapshots__/gatsby-node.js.snap @@ -12,13 +12,14 @@ exports[`gatsby-plugin-sass Stage: build-html / No options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -27,6 +28,13 @@ exports[`gatsby-plugin-sass Stage: build-html / No options 1`] = ` "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], @@ -57,13 +65,14 @@ exports[`gatsby-plugin-sass Stage: build-html / PostCss plugins 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -72,6 +81,13 @@ exports[`gatsby-plugin-sass Stage: build-html / PostCss plugins 1`] = ` "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], @@ -102,6 +118,7 @@ exports[`gatsby-plugin-sass Stage: build-html / Sass options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({})", Object { @@ -113,7 +130,7 @@ exports[`gatsby-plugin-sass Stage: build-html / Sass options 1`] = ` "absolute/path/b", ], }, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -122,6 +139,18 @@ exports[`gatsby-plugin-sass Stage: build-html / Sass options 1`] = ` "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object { + "includePaths": Array [ + "absolute/path/a", + "absolute/path/b", + ], + }, + "sourceMap": undefined, + }, + }, ], }, ], @@ -152,13 +181,14 @@ exports[`gatsby-plugin-sass Stage: build-html / css-loader options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"camelCase\\":false,\\"modules\\":true})", "postcss({})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -167,6 +197,13 @@ exports[`gatsby-plugin-sass Stage: build-html / css-loader options 1`] = ` "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], @@ -197,13 +234,14 @@ exports[`gatsby-plugin-sass Stage: build-html / sass rule modules test options 1 Object { "test": /\\\\\\.global\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -212,6 +250,13 @@ exports[`gatsby-plugin-sass Stage: build-html / sass rule modules test options 1 "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], @@ -242,13 +287,14 @@ exports[`gatsby-plugin-sass Stage: build-html / sass rule test options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -257,6 +303,13 @@ exports[`gatsby-plugin-sass Stage: build-html / sass rule test options 1`] = ` "test": /\\\\\\.global\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], @@ -294,7 +347,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / No options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -309,7 +362,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / No options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -349,7 +402,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / PostCss plugins 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -364,7 +417,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / PostCss plugins 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -409,7 +462,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / Sass options 1`] = ` "absolute/path/b", ], }, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -429,7 +482,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / Sass options 1`] = ` "absolute/path/b", ], }, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -469,7 +522,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / css-loader options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -484,7 +537,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / css-loader options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -524,7 +577,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / sass rule modules test opt "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -539,7 +592,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / sass rule modules test opt "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -579,7 +632,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / sass rule test options 1`] "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -594,7 +647,7 @@ exports[`gatsby-plugin-sass Stage: build-javascript / sass rule test options 1`] "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -634,7 +687,7 @@ exports[`gatsby-plugin-sass Stage: develop / No options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -649,7 +702,7 @@ exports[`gatsby-plugin-sass Stage: develop / No options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -689,7 +742,7 @@ exports[`gatsby-plugin-sass Stage: develop / PostCss plugins 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -704,7 +757,7 @@ exports[`gatsby-plugin-sass Stage: develop / PostCss plugins 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -749,7 +802,7 @@ exports[`gatsby-plugin-sass Stage: develop / Sass options 1`] = ` "absolute/path/b", ], }, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -769,7 +822,7 @@ exports[`gatsby-plugin-sass Stage: develop / Sass options 1`] = ` "absolute/path/b", ], }, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -809,7 +862,7 @@ exports[`gatsby-plugin-sass Stage: develop / css-loader options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -824,7 +877,7 @@ exports[`gatsby-plugin-sass Stage: develop / css-loader options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -864,7 +917,7 @@ exports[`gatsby-plugin-sass Stage: develop / sass rule modules test options 1`] "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -879,7 +932,7 @@ exports[`gatsby-plugin-sass Stage: develop / sass rule modules test options 1`] "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -919,7 +972,7 @@ exports[`gatsby-plugin-sass Stage: develop / sass rule test options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -934,7 +987,7 @@ exports[`gatsby-plugin-sass Stage: develop / sass rule test options 1`] = ` "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": true, + "sourceMap": undefined, }, }, ], @@ -967,13 +1020,14 @@ exports[`gatsby-plugin-sass Stage: develop-html / No options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -982,6 +1036,13 @@ exports[`gatsby-plugin-sass Stage: develop-html / No options 1`] = ` "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], @@ -1012,13 +1073,14 @@ exports[`gatsby-plugin-sass Stage: develop-html / PostCss plugins 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -1027,6 +1089,13 @@ exports[`gatsby-plugin-sass Stage: develop-html / PostCss plugins 1`] = ` "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], @@ -1057,6 +1126,7 @@ exports[`gatsby-plugin-sass Stage: develop-html / Sass options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({})", Object { @@ -1068,7 +1138,7 @@ exports[`gatsby-plugin-sass Stage: develop-html / Sass options 1`] = ` "absolute/path/b", ], }, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -1077,6 +1147,18 @@ exports[`gatsby-plugin-sass Stage: develop-html / Sass options 1`] = ` "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object { + "includePaths": Array [ + "absolute/path/a", + "absolute/path/b", + ], + }, + "sourceMap": undefined, + }, + }, ], }, ], @@ -1107,13 +1189,14 @@ exports[`gatsby-plugin-sass Stage: develop-html / css-loader options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"camelCase\\":false,\\"modules\\":true})", "postcss({})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -1122,6 +1205,13 @@ exports[`gatsby-plugin-sass Stage: develop-html / css-loader options 1`] = ` "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], @@ -1152,13 +1242,14 @@ exports[`gatsby-plugin-sass Stage: develop-html / sass rule modules test options Object { "test": /\\\\\\.global\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -1167,6 +1258,13 @@ exports[`gatsby-plugin-sass Stage: develop-html / sass rule modules test options "test": /\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], @@ -1197,13 +1295,14 @@ exports[`gatsby-plugin-sass Stage: develop-html / sass rule test options 1`] = ` Object { "test": /\\\\\\.module\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ + "miniCssExtract", "css({\\"importLoaders\\":2,\\"modules\\":true})", "postcss({})", Object { "loader": "/node_modules/sass-loader/dist/cjs.js", "options": Object { "sassOptions": Object {}, - "sourceMap": false, + "sourceMap": undefined, }, }, ], @@ -1212,6 +1311,13 @@ exports[`gatsby-plugin-sass Stage: develop-html / sass rule test options 1`] = ` "test": /\\\\\\.global\\\\\\.s\\(a\\|c\\)ss\\$/, "use": Array [ "null", + Object { + "loader": "/node_modules/sass-loader/dist/cjs.js", + "options": Object { + "sassOptions": Object {}, + "sourceMap": undefined, + }, + }, ], }, ], diff --git a/packages/gatsby-plugin-sass/src/gatsby-node.js b/packages/gatsby-plugin-sass/src/gatsby-node.js index 1d859abe542fa..7a6f6852e2f81 100644 --- a/packages/gatsby-plugin-sass/src/gatsby-node.js +++ b/packages/gatsby-plugin-sass/src/gatsby-node.js @@ -1,7 +1,7 @@ import resolve from "./resolve" exports.onCreateWebpackConfig = ( - { actions, stage, rules, plugins, loaders }, + { actions, stage, loaders }, { cssLoaderOptions = {}, postCssPlugins, @@ -9,19 +9,18 @@ exports.onCreateWebpackConfig = ( sassRuleTest, sassRuleModulesTest, sassOptions = {}, + // eslint-disable-next-line no-unused-vars + plugins, ...sassLoaderOptions } ) => { const { setWebpackConfig } = actions - const PRODUCTION = stage !== `develop` - const isSSR = stage.includes(`html`) - - delete sassLoaderOptions.plugins + const isSSR = [`develop-html`, `build-html`].includes(stage) const sassLoader = { loader: resolve(`sass-loader`), options: { - sourceMap: useResolveUrlLoader ? true : !PRODUCTION, + sourceMap: useResolveUrlLoader ? true : undefined, sassOptions, ...sassLoaderOptions, }, @@ -35,43 +34,36 @@ exports.onCreateWebpackConfig = ( loaders.miniCssExtract(), loaders.css({ importLoaders: 2, ...cssLoaderOptions }), loaders.postcss({ plugins: postCssPlugins }), - sassLoader, ], } const sassRuleModules = { test: sassRuleModulesTest || /\.module\.s(a|c)ss$/, use: [ - !isSSR && loaders.miniCssExtract({ hmr: false }), + loaders.miniCssExtract({ modules: true }), loaders.css({ importLoaders: 2, ...cssLoaderOptions, modules: true }), loaders.postcss({ plugins: postCssPlugins }), - sassLoader, - ].filter(Boolean), + ], } if (useResolveUrlLoader && !isSSR) { - sassRule.use.splice(-1, 0, { + sassRule.use.push({ loader: `resolve-url-loader`, options: useResolveUrlLoader.options ? useResolveUrlLoader.options : {}, }) - sassRuleModules.use.splice(-1, 0, { + sassRuleModules.use.push({ loader: `resolve-url-loader`, options: useResolveUrlLoader.options ? useResolveUrlLoader.options : {}, }) } - let configRules = [] + // add sass loaders + sassRule.use.push(sassLoader) + sassRuleModules.use.push(sassLoader) - switch (stage) { - case `develop`: - case `build-javascript`: - case `build-html`: - case `develop-html`: - configRules = configRules.concat([ - { - oneOf: [sassRuleModules, sassRule], - }, - ]) - break - } + const configRules = [ + { + oneOf: [sassRuleModules, sassRule], + }, + ] setWebpackConfig({ module: { diff --git a/packages/gatsby-plugin-sharp/CHANGELOG.md b/packages/gatsby-plugin-sharp/CHANGELOG.md index 2bb0995d4d1e3..6e66977f0fb5b 100644 --- a/packages/gatsby-plugin-sharp/CHANGELOG.md +++ b/packages/gatsby-plugin-sharp/CHANGELOG.md @@ -3,6 +3,28 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.8](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-sharp@3.0.0-next.7...gatsby-plugin-sharp@3.0.0-next.8) (2021-02-22) + +**Note:** Version bump only for package gatsby-plugin-sharp + +# [3.0.0-next.7](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-sharp@3.0.0-next.6...gatsby-plugin-sharp@3.0.0-next.7) (2021-02-19) + +**Note:** Version bump only for package gatsby-plugin-sharp + +# [3.0.0-next.6](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-sharp@3.0.0-next.5...gatsby-plugin-sharp@3.0.0-next.6) (2021-02-19) + +### Bug Fixes + +- **gatsby-plugin-sharp:** Fix defaults handling ([#29564](https://github.com/gatsbyjs/gatsby/issues/29564)) ([107926a](https://github.com/gatsbyjs/gatsby/commit/107926a7d23901fa3e645a966bd6aa793fb0ddd3)) + +# [3.0.0-next.5](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-sharp@3.0.0-next.4...gatsby-plugin-sharp@3.0.0-next.5) (2021-02-18) + +**Note:** Version bump only for package gatsby-plugin-sharp + +# [3.0.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-sharp@3.0.0-next.3...gatsby-plugin-sharp@3.0.0-next.4) (2021-02-17) + +**Note:** Version bump only for package gatsby-plugin-sharp + # [3.0.0-next.3](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-sharp@3.0.0-next.2...gatsby-plugin-sharp@3.0.0-next.3) (2021-02-12) **Note:** Version bump only for package gatsby-plugin-sharp diff --git a/packages/gatsby-plugin-sharp/README.md b/packages/gatsby-plugin-sharp/README.md index 71c2ee80513fe..e6aa34190e659 100644 --- a/packages/gatsby-plugin-sharp/README.md +++ b/packages/gatsby-plugin-sharp/README.md @@ -30,18 +30,30 @@ plugins: [ { resolve: `gatsby-plugin-sharp`, options: { - // Available options and their defaults: + // Defaults used for gatsbyImageData and StaticImage + defaults: {}, + // Set to false to allow builds to continue on image errors + failOnError: true, + // deprecated options and their defaults: base64Width: 20, forceBase64Format: ``, // valid formats: png,jpg,webp useMozJpeg: process.env.GATSBY_JPEG_ENCODER === `MOZJPEG`, stripMetadata: true, defaultQuality: 50, - failOnError: true, }, }, ] ``` +## Options + +- `defaults`: default values used for `gatsbyImageData` and `StaticImage` from [gatsby-plugin-image](https://www.gatsbyjs.com/plugins/gatsby-plugin-image). + Available options are: `formats`,`placeholder`,`quality`,`breakpoints`,`backgroundColor`,`tracedSVGOptions`,`blurredOptions`,`jpgOptions`,`pngOptions`,`webpOptions`,`avifOptions`. + For details of these, see [the reference guide](https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-plugin-image). +- `failOnError`: default = `true`. By default builds will fail if there is a corrupted image. Set to false to continue the build on error. The image will return `undefined`. + +Other options are deprecated, and should only be used for the legacy `fixed` and `fluid` functions. + ## Methods ### resize @@ -155,7 +167,7 @@ Convert the source image to one of the following available options: `NO_CHANGE`, #### toFormatBase64 -base64 image uses the image format from the source , or the value of `toFormat`. This setting allows a different image format instead, available options are: `JPG`, `PNG`, `WEBP`. +base64 image uses the image format from the source, or the value of `toFormat`. This setting allows a different image format instead, available options are: `JPG`, `PNG`, `WEBP`. `WEBP` allows for a smaller data size, allowing you to reduce your HTML size when transferring over the network, or to use a larger base64 placeholder width default for improved image placeholder quality. diff --git a/packages/gatsby-plugin-sharp/package.json b/packages/gatsby-plugin-sharp/package.json index 80b6d17cd8105..5f701bdb268fc 100644 --- a/packages/gatsby-plugin-sharp/package.json +++ b/packages/gatsby-plugin-sharp/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-plugin-sharp", "description": "Wrapper of the Sharp image manipulation library for Gatsby plugins", - "version": "3.0.0-next.3", + "version": "3.0.0-next.8", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -12,8 +12,8 @@ "bluebird": "^3.7.2", "filenamify": "^4.2.0", "fs-extra": "^9.1.0", - "gatsby-core-utils": "^2.0.0-next.0", - "gatsby-telemetry": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", + "gatsby-telemetry": "^2.0.0-next.1", "got": "^10.7.0", "imagemin": "^7.0.1", "imagemin-mozjpeg": "^9.0.0", @@ -34,7 +34,7 @@ "@types/sharp": "^0.27.1", "babel-preset-gatsby-package": "^1.0.0-next.0", "cross-env": "^7.0.3", - "gatsby-plugin-image": "^1.0.0-next.3", + "gatsby-plugin-image": "^1.0.0-next.8", "gatsby-plugin-utils": "^1.0.0-next.0" }, "homepage": "https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-sharp#readme", diff --git a/packages/gatsby-plugin-sharp/src/__tests__/index.js b/packages/gatsby-plugin-sharp/src/__tests__/index.js index 98e67a3f24f62..56c7504d3c0fe 100644 --- a/packages/gatsby-plugin-sharp/src/__tests__/index.js +++ b/packages/gatsby-plugin-sharp/src/__tests__/index.js @@ -38,7 +38,7 @@ const { setPluginOptions, } = require(`../plugin-options`) -jest.mock(`gatsby-cli/lib/reporter`, () => { +jest.mock(`gatsby/reporter`, () => { return { log: jest.fn(), info: jest.fn(), diff --git a/packages/gatsby-plugin-sharp/src/__tests__/plugin-options.ts b/packages/gatsby-plugin-sharp/src/__tests__/plugin-options.ts index 39826017dec26..e9d74afa5fcf5 100644 --- a/packages/gatsby-plugin-sharp/src/__tests__/plugin-options.ts +++ b/packages/gatsby-plugin-sharp/src/__tests__/plugin-options.ts @@ -1,5 +1,20 @@ import { testPluginOptionsSchema } from "gatsby-plugin-utils" import { pluginOptionsSchema } from "../../gatsby-node" +import { doMergeDefaults } from "../plugin-options" + +const defaults = { + formats: [`auto`, `webp`], + placeholder: `dominantColor`, + quality: 50, + breakpoints: [100, 200], + backgroundColor: `rebeccapurple`, + tracedSVGOptions: {}, + blurredOptions: { quality: 20 }, + jpgOptions: { quality: 20 }, + pngOptions: { quality: 20 }, + webpOptions: { quality: 20 }, + avifOptions: { quality: 20 }, +} describe(`pluginOptionsSchema`, () => { it(`should reject incorrect options`, async () => { @@ -40,21 +55,7 @@ describe(`pluginOptionsSchema`, () => { }) it(`should accept correct options`, async () => { - const options = { - defaults: { - formats: [`auto`, `webp`], - placeholder: `dominantColor`, - quality: 50, - breakpoints: [100, 200], - backgroundColor: `rebeccapurple`, - tracedSVGOptions: {}, - blurredOptions: { quality: 20 }, - jpgOptions: { quality: 20 }, - pngOptions: { quality: 20 }, - webpOptions: { quality: 20 }, - avifOptions: { quality: 20 }, - }, - } + const options = { defaults } const { isValid } = await testPluginOptionsSchema( pluginOptionsSchema, options @@ -62,3 +63,62 @@ describe(`pluginOptionsSchema`, () => { expect(isValid).toBe(true) }) }) + +describe(`plugin defaults`, () => { + it(`uses defaults`, () => { + const output = doMergeDefaults({}, defaults) + expect(output).toMatchInlineSnapshot(` + Object { + "avifOptions": Object { + "quality": 20, + }, + "backgroundColor": "rebeccapurple", + "blurredOptions": Object { + "quality": 20, + }, + "breakpoints": Array [ + 100, + 200, + ], + "formats": Array [ + "auto", + "webp", + ], + "jpgOptions": Object { + "quality": 20, + }, + "placeholder": "dominantColor", + "pngOptions": Object { + "quality": 20, + }, + "quality": 50, + "tracedSVGOptions": Object {}, + "webpOptions": Object { + "quality": 20, + }, + } + `) + }) + + it(`allows overrides`, () => { + const output = doMergeDefaults({ backgroundColor: `papayawhip` }, defaults) + expect(output.backgroundColor).toEqual(`papayawhip`) + expect(output.quality).toEqual(50) + }) + + it(`allows overrides of arrays`, () => { + const output = doMergeDefaults({ formats: [`auto`, `avif`] }, defaults) + expect(output.formats).toEqual([`auto`, `avif`]) + expect(output.breakpoints).toEqual([100, 200]) + }) + + it(`allows override of deep objects`, () => { + const output = doMergeDefaults({ avifOptions: { quality: 50 } }, defaults) + expect(output.avifOptions).toEqual({ quality: 50 }) + }) + + it(`allows extra keys in objects`, () => { + const output = doMergeDefaults({ avifOptions: { speed: 50 } }, defaults) + expect(output.avifOptions).toEqual({ quality: 20, speed: 50 }) + }) +}) diff --git a/packages/gatsby-plugin-sharp/src/__tests__/utils.js b/packages/gatsby-plugin-sharp/src/__tests__/utils.js index c6ac9832d7116..82b92839a8c39 100644 --- a/packages/gatsby-plugin-sharp/src/__tests__/utils.js +++ b/packages/gatsby-plugin-sharp/src/__tests__/utils.js @@ -1,8 +1,7 @@ -jest.mock(`gatsby-cli/lib/reporter`) +jest.mock(`gatsby/reporter`) jest.mock(`progress`) const { calculateImageSizes } = require(`../utils`) -const reporter = require(`gatsby-cli/lib/reporter`) -const progress = require(`progress`) +const reporter = require(`gatsby/reporter`) const sharp = require(`sharp`) const file = { diff --git a/packages/gatsby-plugin-sharp/src/image-data.ts b/packages/gatsby-plugin-sharp/src/image-data.ts index 7c46add364945..1187dbd93e226 100644 --- a/packages/gatsby-plugin-sharp/src/image-data.ts +++ b/packages/gatsby-plugin-sharp/src/image-data.ts @@ -1,7 +1,7 @@ /* eslint-disable no-unused-expressions */ import { IGatsbyImageData, ISharpGatsbyImageArgs } from "gatsby-plugin-image" import { GatsbyCache, Node } from "gatsby" -import { Reporter } from "gatsby-cli/lib/reporter/reporter" +import { Reporter } from "gatsby/reporter" import { rgbToHex, calculateImageSizes, getSrcSet, getSizes } from "./utils" import { traceSVG, getImageSizeAsync, base64, batchQueueImageResizing } from "." import sharp from "./safe-sharp" diff --git a/packages/gatsby-plugin-sharp/src/plugin-options.js b/packages/gatsby-plugin-sharp/src/plugin-options.js index 92195c779d8a4..7e4c6c8f36db2 100644 --- a/packages/gatsby-plugin-sharp/src/plugin-options.js +++ b/packages/gatsby-plugin-sharp/src/plugin-options.js @@ -74,14 +74,20 @@ exports.createTransformObject = args => { /** * Used for gatsbyImageData and StaticImage only */ -exports.mergeDefaults = args => { - const { defaults } = pluginOptions +exports.mergeDefaults = args => doMergeDefaults(args, pluginOptions.defaults) + +const customizer = (objValue, srcValue) => + Array.isArray(objValue) ? srcValue : undefined + +function doMergeDefaults(args, defaults) { if (!defaults) { return args } - return _.defaultsDeep(args, defaults) + return _.mergeWith({}, defaults, args, customizer) } +exports.doMergeDefaults = doMergeDefaults + exports.healOptions = ( { defaultQuality: quality, base64Width }, args, diff --git a/packages/gatsby-plugin-styled-components/CHANGELOG.md b/packages/gatsby-plugin-styled-components/CHANGELOG.md index f49c82cd7a1d6..e4cd0743a773e 100644 --- a/packages/gatsby-plugin-styled-components/CHANGELOG.md +++ b/packages/gatsby-plugin-styled-components/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [4.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-styled-components@4.0.0-next.1...gatsby-plugin-styled-components@4.0.0-next.2) (2021-02-17) + +### Bug Fixes + +- **gatsby-plugin-styled-components:** Support `topLevelImportPaths` option ([#29544](https://github.com/gatsbyjs/gatsby/issues/29544)) ([a6be92e](https://github.com/gatsbyjs/gatsby/commit/a6be92eb80bb98c308310a0fb3c340dab8e104aa)) + # [4.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-styled-components@4.0.0-next.0...gatsby-plugin-styled-components@4.0.0-next.1) (2021-02-15) **Note:** Version bump only for package gatsby-plugin-styled-components diff --git a/packages/gatsby-plugin-styled-components/package.json b/packages/gatsby-plugin-styled-components/package.json index 77e135cf609fc..373ee52a19d18 100644 --- a/packages/gatsby-plugin-styled-components/package.json +++ b/packages/gatsby-plugin-styled-components/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-plugin-styled-components", "description": "Gatsby plugin to add support for styled components", - "version": "4.0.0-next.1", + "version": "4.0.0-next.2", "author": "Guten Ye ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" diff --git a/packages/gatsby-plugin-styled-components/src/gatsby-node.js b/packages/gatsby-plugin-styled-components/src/gatsby-node.js index 2f6815d1f9303..bfc75ecc23a5d 100644 --- a/packages/gatsby-plugin-styled-components/src/gatsby-node.js +++ b/packages/gatsby-plugin-styled-components/src/gatsby-node.js @@ -28,6 +28,10 @@ exports.pluginOptionsSchema = ({ Joi }) => transpileTemplateLiterals: Joi.boolean() .default(true) .description(`Transpile tagged template literals into optimized code.`), + topLevelImportPaths: Joi.array() + .default([]) + .items(Joi.string()) + .description(`Top level import paths allowed to identify library`), pure: Joi.boolean() .default(false) .description( diff --git a/packages/gatsby-plugin-stylus/CHANGELOG.md b/packages/gatsby-plugin-stylus/CHANGELOG.md index a7df35271b2d0..8f5c03df5241c 100644 --- a/packages/gatsby-plugin-stylus/CHANGELOG.md +++ b/packages/gatsby-plugin-stylus/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-stylus@3.0.0-next.0...gatsby-plugin-stylus@3.0.0-next.1) (2021-02-19) + +### Bug Fixes + +- make minicss-extract-plugin compatible with plugins ([#29599](https://github.com/gatsbyjs/gatsby/issues/29599)) ([c0ab195](https://github.com/gatsbyjs/gatsby/commit/c0ab19598708750ce98b39448469a39126f55571)) + # [3.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-stylus@2.11.0-next.0...gatsby-plugin-stylus@3.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-stylus diff --git a/packages/gatsby-plugin-stylus/package.json b/packages/gatsby-plugin-stylus/package.json index 82338183854af..d6dd898e5a3d2 100644 --- a/packages/gatsby-plugin-stylus/package.json +++ b/packages/gatsby-plugin-stylus/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-plugin-stylus", "description": "Gatsby support for Stylus", - "version": "3.0.0-next.0", + "version": "3.0.0-next.1", "author": "Ian Sinnott ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" diff --git a/packages/gatsby-plugin-stylus/src/__tests__/__snapshots__/gatsby-node.js.snap b/packages/gatsby-plugin-stylus/src/__tests__/__snapshots__/gatsby-node.js.snap index 9077c69439512..2e3983eec3429 100644 --- a/packages/gatsby-plugin-stylus/src/__tests__/__snapshots__/gatsby-node.js.snap +++ b/packages/gatsby-plugin-stylus/src/__tests__/__snapshots__/gatsby-node.js.snap @@ -17,9 +17,7 @@ exports[`gatsby-plugin-stylus Stage: build-html / No options 1`] = ` "postcss({})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -31,9 +29,7 @@ exports[`gatsby-plugin-stylus Stage: build-html / No options 1`] = ` "postcss({})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -70,9 +66,7 @@ exports[`gatsby-plugin-stylus Stage: build-html / PostCss plugins 1`] = ` "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -84,9 +78,7 @@ exports[`gatsby-plugin-stylus Stage: build-html / PostCss plugins 1`] = ` "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -124,7 +116,6 @@ exports[`gatsby-plugin-stylus Stage: build-html / Stylus options #1 1`] = ` Object { "loader": "/resolved/path/stylus-loader", "options": Object { - "sourceMap": true, "use": Array [ "foo", ], @@ -141,7 +132,6 @@ exports[`gatsby-plugin-stylus Stage: build-html / Stylus options #1 1`] = ` Object { "loader": "/resolved/path/stylus-loader", "options": Object { - "sourceMap": true, "use": Array [ "foo", ], @@ -187,7 +177,6 @@ exports[`gatsby-plugin-stylus Stage: build-html / Stylus options #2 1`] = ` "file.js", "file2.js", ], - "sourceMap": true, "use": Array [ "foo", ], @@ -208,7 +197,6 @@ exports[`gatsby-plugin-stylus Stage: build-html / Stylus options #2 1`] = ` "file.js", "file2.js", ], - "sourceMap": true, "use": Array [ "foo", ], @@ -249,9 +237,7 @@ exports[`gatsby-plugin-stylus Stage: build-javascript / No options 1`] = ` "postcss({})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -263,9 +249,7 @@ exports[`gatsby-plugin-stylus Stage: build-javascript / No options 1`] = ` "postcss({})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -302,9 +286,7 @@ exports[`gatsby-plugin-stylus Stage: build-javascript / PostCss plugins 1`] = ` "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -316,9 +298,7 @@ exports[`gatsby-plugin-stylus Stage: build-javascript / PostCss plugins 1`] = ` "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -356,7 +336,6 @@ exports[`gatsby-plugin-stylus Stage: build-javascript / Stylus options #1 1`] = Object { "loader": "/resolved/path/stylus-loader", "options": Object { - "sourceMap": true, "use": Array [ "foo", ], @@ -373,7 +352,6 @@ exports[`gatsby-plugin-stylus Stage: build-javascript / Stylus options #1 1`] = Object { "loader": "/resolved/path/stylus-loader", "options": Object { - "sourceMap": true, "use": Array [ "foo", ], @@ -419,7 +397,6 @@ exports[`gatsby-plugin-stylus Stage: build-javascript / Stylus options #2 1`] = "file.js", "file2.js", ], - "sourceMap": true, "use": Array [ "foo", ], @@ -440,7 +417,6 @@ exports[`gatsby-plugin-stylus Stage: build-javascript / Stylus options #2 1`] = "file.js", "file2.js", ], - "sourceMap": true, "use": Array [ "foo", ], @@ -481,9 +457,7 @@ exports[`gatsby-plugin-stylus Stage: develop / No options 1`] = ` "postcss({})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -495,9 +469,7 @@ exports[`gatsby-plugin-stylus Stage: develop / No options 1`] = ` "postcss({})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -534,9 +506,7 @@ exports[`gatsby-plugin-stylus Stage: develop / PostCss plugins 1`] = ` "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -548,9 +518,7 @@ exports[`gatsby-plugin-stylus Stage: develop / PostCss plugins 1`] = ` "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -588,7 +556,6 @@ exports[`gatsby-plugin-stylus Stage: develop / Stylus options #1 1`] = ` Object { "loader": "/resolved/path/stylus-loader", "options": Object { - "sourceMap": true, "use": Array [ "foo", ], @@ -605,7 +572,6 @@ exports[`gatsby-plugin-stylus Stage: develop / Stylus options #1 1`] = ` Object { "loader": "/resolved/path/stylus-loader", "options": Object { - "sourceMap": true, "use": Array [ "foo", ], @@ -651,7 +617,6 @@ exports[`gatsby-plugin-stylus Stage: develop / Stylus options #2 1`] = ` "file.js", "file2.js", ], - "sourceMap": true, "use": Array [ "foo", ], @@ -672,7 +637,6 @@ exports[`gatsby-plugin-stylus Stage: develop / Stylus options #2 1`] = ` "file.js", "file2.js", ], - "sourceMap": true, "use": Array [ "foo", ], @@ -713,9 +677,7 @@ exports[`gatsby-plugin-stylus Stage: develop-html / No options 1`] = ` "postcss({})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -727,9 +689,7 @@ exports[`gatsby-plugin-stylus Stage: develop-html / No options 1`] = ` "postcss({})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -766,9 +726,7 @@ exports[`gatsby-plugin-stylus Stage: develop-html / PostCss plugins 1`] = ` "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -780,9 +738,7 @@ exports[`gatsby-plugin-stylus Stage: develop-html / PostCss plugins 1`] = ` "postcss({\\"plugins\\":[\\"test1\\"]})", Object { "loader": "/resolved/path/stylus-loader", - "options": Object { - "sourceMap": true, - }, + "options": Object {}, }, ], }, @@ -820,7 +776,6 @@ exports[`gatsby-plugin-stylus Stage: develop-html / Stylus options #1 1`] = ` Object { "loader": "/resolved/path/stylus-loader", "options": Object { - "sourceMap": true, "use": Array [ "foo", ], @@ -837,7 +792,6 @@ exports[`gatsby-plugin-stylus Stage: develop-html / Stylus options #1 1`] = ` Object { "loader": "/resolved/path/stylus-loader", "options": Object { - "sourceMap": true, "use": Array [ "foo", ], @@ -883,7 +837,6 @@ exports[`gatsby-plugin-stylus Stage: develop-html / Stylus options #2 1`] = ` "file.js", "file2.js", ], - "sourceMap": true, "use": Array [ "foo", ], @@ -904,7 +857,6 @@ exports[`gatsby-plugin-stylus Stage: develop-html / Stylus options #2 1`] = ` "file.js", "file2.js", ], - "sourceMap": true, "use": Array [ "foo", ], diff --git a/packages/gatsby-plugin-stylus/src/gatsby-node.js b/packages/gatsby-plugin-stylus/src/gatsby-node.js index e0476957fe63b..34ca66662f01b 100644 --- a/packages/gatsby-plugin-stylus/src/gatsby-node.js +++ b/packages/gatsby-plugin-stylus/src/gatsby-node.js @@ -23,17 +23,15 @@ const resolve = require(`./resolve`) exports.onCreateWebpackConfig = ( - { actions, stage, rules, plugins, loaders }, + { actions, stage, loaders }, { postCssPlugins, ...stylusOptions } ) => { + const isSSR = [`develop-html`, `build-html`].includes(stage) const { setWebpackConfig } = actions - const PRODUCTION = stage !== `develop` - const isSSR = stage.includes(`html`) const stylusLoader = { loader: resolve(`stylus-loader`), options: { - sourceMap: !PRODUCTION, ...stylusOptions, }, } @@ -53,27 +51,18 @@ exports.onCreateWebpackConfig = ( const stylusRuleModules = { test: /\.module\.styl$/, use: [ - !isSSR && loaders.miniCssExtract({ hmr: false }), + loaders.miniCssExtract({ modules: true }), loaders.css({ modules: true, importLoaders: 2 }), loaders.postcss({ plugins: postCssPlugins }), stylusLoader, - ].filter(Boolean), + ], } - let configRules = [] - - switch (stage) { - case `develop`: - case `build-javascript`: - case `build-html`: - case `develop-html`: - configRules = configRules.concat([ - { - oneOf: [stylusRuleModules, stylusRule], - }, - ]) - break - } + const configRules = [ + { + oneOf: [stylusRuleModules, stylusRule], + }, + ] setWebpackConfig({ module: { diff --git a/packages/gatsby-plugin-typescript/CHANGELOG.md b/packages/gatsby-plugin-typescript/CHANGELOG.md index 6847919a29fa2..7590563889077 100644 --- a/packages/gatsby-plugin-typescript/CHANGELOG.md +++ b/packages/gatsby-plugin-typescript/CHANGELOG.md @@ -3,6 +3,14 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-typescript@3.0.0-next.1...gatsby-plugin-typescript@3.0.0-next.2) (2021-02-22) + +**Note:** Version bump only for package gatsby-plugin-typescript + +# [3.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-typescript@3.0.0-next.0...gatsby-plugin-typescript@3.0.0-next.1) (2021-02-17) + +**Note:** Version bump only for package gatsby-plugin-typescript + # [3.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-plugin-typescript@2.13.0-next.0...gatsby-plugin-typescript@3.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-plugin-typescript diff --git a/packages/gatsby-plugin-typescript/package.json b/packages/gatsby-plugin-typescript/package.json index 48f44a7f58695..aa2b850231790 100644 --- a/packages/gatsby-plugin-typescript/package.json +++ b/packages/gatsby-plugin-typescript/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-plugin-typescript", "description": "Adds TypeScript support to Gatsby", - "version": "3.0.0-next.0", + "version": "3.0.0-next.2", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -16,7 +16,7 @@ "@babel/plugin-proposal-optional-chaining": "^7.12.1", "@babel/preset-typescript": "^7.12.1", "@babel/runtime": "^7.12.5", - "babel-plugin-remove-graphql-queries": "^3.0.0-next.0" + "babel-plugin-remove-graphql-queries": "^3.0.0-next.2" }, "devDependencies": { "@babel/cli": "^7.12.1", diff --git a/packages/gatsby-plugin-utils/package.json b/packages/gatsby-plugin-utils/package.json index 0499d36405e2b..894b7bef50f3e 100644 --- a/packages/gatsby-plugin-utils/package.json +++ b/packages/gatsby-plugin-utils/package.json @@ -29,7 +29,7 @@ "babel-preset-gatsby-package": "^1.0.0-next.0", "cross-env": "^7.0.3", "rimraf": "^3.0.2", - "typescript": "^3.9.7" + "typescript": "^4.1.5" }, "peerDependencies": { "gatsby": "^3.0.0-next.0" diff --git a/packages/gatsby-react-router-scroll/src/use-scroll-restoration.ts b/packages/gatsby-react-router-scroll/src/use-scroll-restoration.ts index c7e2fb67eb696..58b40686e55b2 100644 --- a/packages/gatsby-react-router-scroll/src/use-scroll-restoration.ts +++ b/packages/gatsby-react-router-scroll/src/use-scroll-restoration.ts @@ -1,9 +1,9 @@ import { ScrollContext } from "./scroll-handler" -import { useRef, useContext, useLayoutEffect } from "react" +import { useRef, useContext, useLayoutEffect, MutableRefObject } from "react" import { useLocation } from "@reach/router" interface IScrollRestorationProps { - ref: React.MutableRefObject + ref: MutableRefObject onScroll(): void } diff --git a/packages/gatsby-recipes/CHANGELOG.md b/packages/gatsby-recipes/CHANGELOG.md index 8a17bb6401e9d..532ed509c849f 100644 --- a/packages/gatsby-recipes/CHANGELOG.md +++ b/packages/gatsby-recipes/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [0.11.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby-recipes@0.11.0-next.3...gatsby-recipes@0.11.0-next.4) (2021-02-22) + +### Bug Fixes + +- **gatsby-recipes:** change 'Typescript' to 'TypeScript' ([#29587](https://github.com/gatsbyjs/gatsby/issues/29587)) ([d7c4459](https://github.com/gatsbyjs/gatsby/commit/d7c4459cf1d26944ac1804d21f17ef161b32e267)) + +# [0.11.0-next.3](https://github.com/gatsbyjs/gatsby/compare/gatsby-recipes@0.11.0-next.2...gatsby-recipes@0.11.0-next.3) (2021-02-17) + +**Note:** Version bump only for package gatsby-recipes + # [0.11.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-recipes@0.11.0-next.1...gatsby-recipes@0.11.0-next.2) (2021-02-15) ### Bug Fixes diff --git a/packages/gatsby-recipes/package.json b/packages/gatsby-recipes/package.json index 1dc0e03ff1fcd..dd9fee7865cbd 100644 --- a/packages/gatsby-recipes/package.json +++ b/packages/gatsby-recipes/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-recipes", "description": "Core functionality for Gatsby Recipes", - "version": "0.11.0-next.2", + "version": "0.11.0-next.4", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -30,8 +30,8 @@ "express": "^4.17.1", "express-graphql": "^0.9.0", "fs-extra": "^8.1.0", - "gatsby-core-utils": "^2.0.0-next.0", - "gatsby-telemetry": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", + "gatsby-telemetry": "^2.0.0-next.1", "glob": "^7.1.6", "graphql": "^15.4.0", "graphql-compose": "~7.25.0", diff --git a/packages/gatsby-recipes/src/recipes-list.js b/packages/gatsby-recipes/src/recipes-list.js index 9e38d544a5d8e..d0fc01ec55381 100644 --- a/packages/gatsby-recipes/src/recipes-list.js +++ b/packages/gatsby-recipes/src/recipes-list.js @@ -66,7 +66,7 @@ export default [ value: `sass`, }, { - label: `Add Typescript`, + label: `Add TypeScript`, value: `typescript`, }, { diff --git a/packages/gatsby-remark-code-repls/src/__tests__/gatsby-node.js b/packages/gatsby-remark-code-repls/src/__tests__/gatsby-node.js index 16a5e0e7b3809..dbfeab2cd35ca 100644 --- a/packages/gatsby-remark-code-repls/src/__tests__/gatsby-node.js +++ b/packages/gatsby-remark-code-repls/src/__tests__/gatsby-node.js @@ -5,7 +5,7 @@ jest.mock(`fs`, () => { } }) jest.mock(`recursive-readdir`, () => jest.fn()) -jest.mock(`gatsby-cli/lib/reporter`, () => { +jest.mock(`gatsby/reporter`, () => { return { panic: jest.fn(), } @@ -15,7 +15,7 @@ const fs = require(`fs`) const nodePath = require(`path`) const readdir = require(`recursive-readdir`) -const reporter = require(`gatsby-cli/lib/reporter`) +const reporter = require(`gatsby/reporter`) const { OPTION_DEFAULT_REPL_DIRECTORY, diff --git a/packages/gatsby-remark-embed-snippet/CHANGELOG.md b/packages/gatsby-remark-embed-snippet/CHANGELOG.md index 3cb362f6d0ee4..96b20584b647b 100644 --- a/packages/gatsby-remark-embed-snippet/CHANGELOG.md +++ b/packages/gatsby-remark-embed-snippet/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [5.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-remark-embed-snippet@5.0.0-next.0...gatsby-remark-embed-snippet@5.0.0-next.1) (2021-02-19) + +**Note:** Version bump only for package gatsby-remark-embed-snippet + # [5.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-remark-embed-snippet@4.11.0-next.0...gatsby-remark-embed-snippet@5.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-remark-embed-snippet diff --git a/packages/gatsby-remark-embed-snippet/README.md b/packages/gatsby-remark-embed-snippet/README.md index 584aa510f5557..248f9c7ff23b7 100644 --- a/packages/gatsby-remark-embed-snippet/README.md +++ b/packages/gatsby-remark-embed-snippet/README.md @@ -396,7 +396,7 @@ As an alternative to selecting a range of lines from a file, you can add `start- You can specify that you want to only include a named snippet from the embed by using the syntax `{snippet: "snippet-name"}`. -**Javascript example**: +**JavaScript example**: ```markdown The function to use is: diff --git a/packages/gatsby-remark-embed-snippet/package.json b/packages/gatsby-remark-embed-snippet/package.json index 7b4459c2427ce..a02c948938517 100644 --- a/packages/gatsby-remark-embed-snippet/package.json +++ b/packages/gatsby-remark-embed-snippet/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-remark-embed-snippet", "description": "Gatsby plugin to embed formatted code snippets within markdown", - "version": "5.0.0-next.0", + "version": "5.0.0-next.1", "author": "Brian Vaughn ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" diff --git a/packages/gatsby-remark-images/CHANGELOG.md b/packages/gatsby-remark-images/CHANGELOG.md index 1e57dcdc0158b..7f3044b64d2aa 100644 --- a/packages/gatsby-remark-images/CHANGELOG.md +++ b/packages/gatsby-remark-images/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [4.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-remark-images@4.0.0-next.0...gatsby-remark-images@4.0.0-next.1) (2021-02-22) + +**Note:** Version bump only for package gatsby-remark-images + # [4.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-remark-images@3.12.0-next.0...gatsby-remark-images@4.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-remark-images diff --git a/packages/gatsby-remark-images/package.json b/packages/gatsby-remark-images/package.json index 287e702723d90..3d005c5b04dcd 100644 --- a/packages/gatsby-remark-images/package.json +++ b/packages/gatsby-remark-images/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-remark-images", "description": "Processes images in markdown so they can be used in the production build.", - "version": "4.0.0-next.0", + "version": "4.0.0-next.1", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -10,7 +10,7 @@ "@babel/runtime": "^7.12.5", "chalk": "^4.1.0", "cheerio": "^1.0.0-rc.3", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "is-relative-url": "^3.0.0", "lodash": "^4.17.20", "mdast-util-definitions": "^1.2.5", diff --git a/packages/gatsby-remark-smartypants/README.md b/packages/gatsby-remark-smartypants/README.md index 214776c2dbcf6..970ddc617f1e5 100644 --- a/packages/gatsby-remark-smartypants/README.md +++ b/packages/gatsby-remark-smartypants/README.md @@ -25,7 +25,7 @@ plugins: [ Valid `remark-smartypants` options may passed to the plugin. For more on valid options refer to the -[retext-smartypants API](https://github.com/retextjs/retext-smartypants#api) . +[retext-smartypants API](https://github.com/retextjs/retext-smartypants#api). ```javascript // In your gatsby-config.js diff --git a/packages/gatsby-source-contentful/CHANGELOG.md b/packages/gatsby-source-contentful/CHANGELOG.md index 88a1366dd820c..089fd820f317f 100644 --- a/packages/gatsby-source-contentful/CHANGELOG.md +++ b/packages/gatsby-source-contentful/CHANGELOG.md @@ -3,6 +3,30 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [5.0.0-next.9](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-contentful@5.0.0-next.8...gatsby-source-contentful@5.0.0-next.9) (2021-02-22) + +**Note:** Version bump only for package gatsby-source-contentful + +# [5.0.0-next.8](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-contentful@5.0.0-next.7...gatsby-source-contentful@5.0.0-next.8) (2021-02-19) + +**Note:** Version bump only for package gatsby-source-contentful + +# [5.0.0-next.7](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-contentful@5.0.0-next.6...gatsby-source-contentful@5.0.0-next.7) (2021-02-19) + +### Bug Fixes + +- **gatsby-source-contentful:** Correct supported image formats ([#29562](https://github.com/gatsbyjs/gatsby/issues/29562)) ([3b4d32f](https://github.com/gatsbyjs/gatsby/commit/3b4d32f0b2d6aef3193213252c3eb813cc2cbea9)) + +# [5.0.0-next.6](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-contentful@5.0.0-next.5...gatsby-source-contentful@5.0.0-next.6) (2021-02-18) + +### Bug Fixes + +- **contentful:** fix import ([#29522](https://github.com/gatsbyjs/gatsby/issues/29522)) ([a639e9d](https://github.com/gatsbyjs/gatsby/commit/a639e9dcc30ee26f826f5ff2e63c0261a29837af)) + +# [5.0.0-next.5](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-contentful@5.0.0-next.4...gatsby-source-contentful@5.0.0-next.5) (2021-02-17) + +**Note:** Version bump only for package gatsby-source-contentful + # [5.0.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-contentful@5.0.0-next.3...gatsby-source-contentful@5.0.0-next.4) (2021-02-15) **Note:** Version bump only for package gatsby-source-contentful @@ -199,13 +223,15 @@ export const pageQuery = graphql` raw references { ... on ContentfulPage { - # contentful_id is required to resolve the references + # __typename and contentful_id are required to resolve the references + __typename contentful_id title slug } ... on ContentfulAsset { - # contentful_id is required to resolve the references + # __typename and contentful_id are required to resolve the references + __typename contentful_id fluid(maxWidth: 600) { ...GatsbyContentfulFluid_withWebp diff --git a/packages/gatsby-source-contentful/package.json b/packages/gatsby-source-contentful/package.json index 632886edeb7c5..71ca3fe4d176e 100644 --- a/packages/gatsby-source-contentful/package.json +++ b/packages/gatsby-source-contentful/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-source-contentful", "description": "Gatsby source plugin for building websites using the Contentful CMS as a data source", - "version": "5.0.0-next.4", + "version": "5.0.0-next.9", "author": "Marcus Ericsson (mericsson.com)", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -11,15 +11,16 @@ "@contentful/rich-text-react-renderer": "^14.1.2", "@contentful/rich-text-types": "^14.1.2", "@hapi/joi": "^15.1.1", + "@vercel/fetch-retry": "^5.0.3", "axios": "^0.21.1", "chalk": "^4.1.0", "common-tags": "^1.8.0", "contentful": "^7.15.2", "fs-extra": "^9.1.0", - "gatsby-core-utils": "^2.0.0-next.0", - "gatsby-plugin-image": "^1.0.0-next.3", + "gatsby-core-utils": "^2.0.0-next.1", + "gatsby-plugin-image": "^1.0.0-next.8", "gatsby-plugin-utils": "^1.0.0-next.0", - "gatsby-source-filesystem": "^3.0.0-next.2", + "gatsby-source-filesystem": "^3.0.0-next.3", "is-online": "^8.5.1", "json-stringify-safe": "^5.0.1", "lodash": "^4.17.20", diff --git a/packages/gatsby-source-contentful/src/cache-image.js b/packages/gatsby-source-contentful/src/cache-image.js index a2c3ad3bb12a6..8997006bc6f95 100644 --- a/packages/gatsby-source-contentful/src/cache-image.js +++ b/packages/gatsby-source-contentful/src/cache-image.js @@ -3,7 +3,7 @@ const { resolve, parse } = require(`path`) const { pathExists, createWriteStream } = require(`fs-extra`) -const downloadWithRetry = require(`./download-with-retry`) +const downloadWithRetry = require(`./download-with-retry`).default const inFlightImageCache = new Map() diff --git a/packages/gatsby-source-contentful/src/extend-node-type.js b/packages/gatsby-source-contentful/src/extend-node-type.js index b178e48f992c2..4cc752b5422f2 100644 --- a/packages/gatsby-source-contentful/src/extend-node-type.js +++ b/packages/gatsby-source-contentful/src/extend-node-type.js @@ -12,6 +12,7 @@ const { GraphQLFloat, GraphQLNonNull, GraphQLJSON, + GraphQLList, } = require(`gatsby/graphql`) const qs = require(`qs`) const { generateImageData } = require(`gatsby-plugin-image`) @@ -21,7 +22,7 @@ const { const { stripIndent } = require(`common-tags`) const cacheImage = require(`./cache-image`) -const downloadWithRetry = require(`./download-with-retry`) +const downloadWithRetry = require(`./download-with-retry`).default const { ImageFormatType, ImageResizingBehavior, @@ -33,6 +34,8 @@ const { // cache is more likely to go stale than the images (which never go stale) // Note that the same image might be requested multiple times in the same run +const validImageFormats = new Set([`jpg`, `png`, `webp`]) + if (process.env.GATSBY_REMOTE_CACHE) { console.warn( `Note: \`GATSBY_REMOTE_CACHE\` will be removed soon because it has been renamed to \`GATSBY_CONTENTFUL_EXPERIMENTAL_REMOTE_CACHE\`` @@ -200,6 +203,13 @@ const generateImageSource = ( height = CONTENTFUL_IMAGE_MAX_SIZE } + if (!validImageFormats.has(toFormat)) { + console.warn( + `[gatsby-source-contentful] Invalid image format "${toFormat}". Supported types are jpg, png and webp"` + ) + return undefined + } + const src = createUrl(filename, { width, height, @@ -781,6 +791,16 @@ exports.extendNodeType = ({ type, store, reporter }) => { type: GraphQLInt, defaultValue: 50, }, + formats: { + type: GraphQLList(ImageFormatType), + description: stripIndent` + The image formats to generate. Valid values are AUTO (meaning the same format as the source image), JPG, PNG, and WEBP. + The default value is [AUTO, WEBP], and you should rarely need to change this. Take care if you specify JPG or PNG when you do + not know the formats of the source images, as this could lead to unwanted results such as converting JPEGs to PNGs. Specifying + both PNG and JPG is not supported and will be ignored. + `, + defaultValue: [``, `webp`], + }, }) fieldConfig.type = GraphQLJSON diff --git a/packages/gatsby-source-contentful/src/gatsby-node.js b/packages/gatsby-source-contentful/src/gatsby-node.js index 6a173d2a57952..1fbc0c8b0a4e0 100644 --- a/packages/gatsby-source-contentful/src/gatsby-node.js +++ b/packages/gatsby-source-contentful/src/gatsby-node.js @@ -4,7 +4,7 @@ const _ = require(`lodash`) const fs = require(`fs-extra`) const { createClient } = require(`contentful`) const v8 = require(`v8`) -const fetch = require(`node-fetch`) +const fetch = require(`@vercel/fetch-retry`)(require(`node-fetch`)) const { CODES } = require(`./report`) const normalize = require(`./normalize`) diff --git a/packages/gatsby-source-contentful/src/schemes.js b/packages/gatsby-source-contentful/src/schemes.js index 3b01e7fa26508..beabb967fa1a5 100644 --- a/packages/gatsby-source-contentful/src/schemes.js +++ b/packages/gatsby-source-contentful/src/schemes.js @@ -4,6 +4,7 @@ const ImageFormatType = new GraphQLEnumType({ name: `ContentfulImageFormat`, values: { NO_CHANGE: { value: `` }, + AUTO: { value: `` }, JPG: { value: `jpg` }, PNG: { value: `png` }, WEBP: { value: `webp` }, diff --git a/packages/gatsby-source-drupal/CHANGELOG.md b/packages/gatsby-source-drupal/CHANGELOG.md index a445b035dc3fb..beeb72d34c013 100644 --- a/packages/gatsby-source-drupal/CHANGELOG.md +++ b/packages/gatsby-source-drupal/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [4.0.0-next.3](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-drupal@4.0.0-next.2...gatsby-source-drupal@4.0.0-next.3) (2021-02-22) + +**Note:** Version bump only for package gatsby-source-drupal + # [4.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-drupal@4.0.0-next.1...gatsby-source-drupal@4.0.0-next.2) (2021-02-15) **Note:** Version bump only for package gatsby-source-drupal diff --git a/packages/gatsby-source-drupal/package.json b/packages/gatsby-source-drupal/package.json index b4161010bf00f..0b6a1111cdcff 100644 --- a/packages/gatsby-source-drupal/package.json +++ b/packages/gatsby-source-drupal/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-source-drupal", "description": "Gatsby source plugin for building websites using the Drupal CMS as a data source", - "version": "4.0.0-next.2", + "version": "4.0.0-next.3", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -11,7 +11,7 @@ "axios": "^0.21.1", "bluebird": "^3.7.2", "body-parser": "^1.19.0", - "gatsby-source-filesystem": "^3.0.0-next.2", + "gatsby-source-filesystem": "^3.0.0-next.3", "lodash": "^4.17.20", "tiny-async-pool": "^1.1.0" }, diff --git a/packages/gatsby-source-filesystem/CHANGELOG.md b/packages/gatsby-source-filesystem/CHANGELOG.md index 25ff38ff7c4b6..5488dd5522b8a 100644 --- a/packages/gatsby-source-filesystem/CHANGELOG.md +++ b/packages/gatsby-source-filesystem/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.3](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-filesystem@3.0.0-next.2...gatsby-source-filesystem@3.0.0-next.3) (2021-02-22) + +### Features + +- **gatsby-core-utils:** Add file download functions ([#29531](https://github.com/gatsbyjs/gatsby/issues/29531)) ([1a9469d](https://github.com/gatsbyjs/gatsby/commit/1a9469d67a19007faebebfb8ce876970c5e0ffaf)) + # [3.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-filesystem@3.0.0-next.1...gatsby-source-filesystem@3.0.0-next.2) (2021-02-15) **Note:** Version bump only for package gatsby-source-filesystem diff --git a/packages/gatsby-source-filesystem/package.json b/packages/gatsby-source-filesystem/package.json index 7c8b8224c3e85..5687ea8e52925 100644 --- a/packages/gatsby-source-filesystem/package.json +++ b/packages/gatsby-source-filesystem/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-source-filesystem", "description": "Gatsby source plugin for building websites from local data. Markdown, JSON, images, YAML, CSV, and dozens of other data types supported.", - "version": "3.0.0-next.2", + "version": "3.0.0-next.3", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -12,7 +12,7 @@ "chokidar": "^3.4.3", "file-type": "^16.0.0", "fs-extra": "^8.1.0", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "got": "^9.6.0", "md5-file": "^5.0.0", "mime": "^2.4.6", diff --git a/packages/gatsby-source-filesystem/src/__tests__/create-remote-file-node.js b/packages/gatsby-source-filesystem/src/__tests__/create-remote-file-node.js index e473dc20dbda4..3b79ee5a00881 100644 --- a/packages/gatsby-source-filesystem/src/__tests__/create-remote-file-node.js +++ b/packages/gatsby-source-filesystem/src/__tests__/create-remote-file-node.js @@ -27,7 +27,7 @@ jest.mock(`../create-file-node`, () => { createFileNode: jest.fn(), } }) -const reporter = require(`gatsby-cli/lib/reporter`) +const reporter = require(`gatsby/reporter`) const got = require(`got`) const createRemoteFileNode = require(`../create-remote-file-node`) diff --git a/packages/gatsby-source-filesystem/src/__tests__/utils.js b/packages/gatsby-source-filesystem/src/__tests__/utils.js index debb834d5b0e7..9a8ac914f991a 100644 --- a/packages/gatsby-source-filesystem/src/__tests__/utils.js +++ b/packages/gatsby-source-filesystem/src/__tests__/utils.js @@ -1,5 +1,3 @@ -jest.mock(`gatsby-cli/lib/reporter`) -jest.mock(`progress`) const { getRemoteFileExtension, getRemoteFileName } = require(`../utils`) describe(`create remote file node`, () => { diff --git a/packages/gatsby-source-filesystem/src/create-remote-file-node.js b/packages/gatsby-source-filesystem/src/create-remote-file-node.js index beab39d3da846..aca385ae98c05 100644 --- a/packages/gatsby-source-filesystem/src/create-remote-file-node.js +++ b/packages/gatsby-source-filesystem/src/create-remote-file-node.js @@ -1,19 +1,11 @@ const fs = require(`fs-extra`) -const got = require(`got`) const { createContentDigest } = require(`gatsby-core-utils`) const path = require(`path`) const { isWebUri } = require(`valid-url`) const Queue = require(`better-queue`) -const fileType = require(`file-type`) - +const { fetchRemoteFile } = require(`gatsby-core-utils`) const { createFileNode } = require(`./create-file-node`) -const { - getRemoteFileExtension, - getRemoteFileName, - createFilePath, -} = require(`./utils`) -const cacheIdForHeaders = url => `create-remote-file-node-headers-${url}` -const cacheIdForExtensions = url => `create-remote-file-node-extension-${url}` +const { getRemoteFileExtension, createFilePath } = require(`./utils`) let showFlagWarning = !!process.env.GATSBY_EXPERIMENTAL_REMOTE_FILE_PLACEHOLDER @@ -51,13 +43,6 @@ let showFlagWarning = !!process.env.GATSBY_EXPERIMENTAL_REMOTE_FILE_PLACEHOLDER * @param {Reporter} [options.reporter] */ -const STALL_RETRY_LIMIT = process.env.GATSBY_STALL_RETRY_LIMIT || 3 -const STALL_TIMEOUT = process.env.GATSBY_STALL_TIMEOUT || 30000 - -const CONNECTION_TIMEOUT = process.env.GATSBY_CONNECTION_TIMEOUT || 30000 - -const INCOMPLETE_RETRY_LIMIT = process.env.GATSBY_INCOMPLETE_RETRY_LIMIT || 3 - /******************** * Queue Management * ********************/ @@ -103,111 +88,6 @@ async function pushToQueue(task, cb) { * Core Functions * ******************/ -/** - * requestRemoteNode - * -- - * Download the requested file - * - * @param {String} url - * @param {Headers} headers - * @param {String} tmpFilename - * @param {Object} httpOpts - * @param {number} attempt - * @return {Promise} Resolves with the [http Result Object]{@link https://nodejs.org/api/http.html#http_class_http_serverresponse} - */ -const requestRemoteNode = (url, headers, tmpFilename, httpOpts, attempt = 1) => - new Promise((resolve, reject) => { - let timeout - - // Called if we stall for 30s without receiving any data - const handleTimeout = async () => { - fsWriteStream.close() - fs.removeSync(tmpFilename) - if (attempt < STALL_RETRY_LIMIT) { - // Retry by calling ourself recursively - resolve( - requestRemoteNode(url, headers, tmpFilename, httpOpts, attempt + 1) - ) - } else { - reject(`Failed to download ${url} after ${STALL_RETRY_LIMIT} attempts`) - } - } - - const resetTimeout = () => { - if (timeout) { - clearTimeout(timeout) - } - timeout = setTimeout(handleTimeout, STALL_TIMEOUT) - } - const responseStream = got.stream(url, { - headers, - timeout: { - send: CONNECTION_TIMEOUT, // https://github.com/sindresorhus/got#timeout - }, - ...httpOpts, - }) - - let haveAllBytesBeenWritten = false - responseStream.on(`downloadProgress`, progress => { - if (progress.transferred === progress.total || progress.total === null) { - haveAllBytesBeenWritten = true - } - }) - - const fsWriteStream = fs.createWriteStream(tmpFilename) - responseStream.pipe(fsWriteStream) - - // If there's a 400/500 response or other error. - responseStream.on(`error`, error => { - if (timeout) { - clearTimeout(timeout) - } - fs.removeSync(tmpFilename) - reject(error) - }) - - fsWriteStream.on(`error`, error => { - if (timeout) { - clearTimeout(timeout) - } - reject(error) - }) - - responseStream.on(`response`, response => { - resetTimeout() - - fsWriteStream.on(`finish`, () => { - fsWriteStream.close() - - // We have an incomplete download - if (!haveAllBytesBeenWritten) { - fs.removeSync(tmpFilename) - - if (attempt < INCOMPLETE_RETRY_LIMIT) { - resolve( - requestRemoteNode( - url, - headers, - tmpFilename, - httpOpts, - attempt + 1 - ) - ) - } else { - reject( - `Failed to download ${url} after ${INCOMPLETE_RETRY_LIMIT} attempts` - ) - } - } - - if (timeout) { - clearTimeout(timeout) - } - resolve(response) - }) - }) - }) - /** * processRemoteNode * -- @@ -237,7 +117,7 @@ async function processRemoteNode({ name, }) } else { - filename = await fetchRemoteNode({ + filename = await fetchRemoteFile({ url, cache, auth, @@ -261,77 +141,6 @@ async function processRemoteNode({ return fileNode } -async function fetchRemoteNode({ - url, - cache, - auth = {}, - httpHeaders = {}, - ext, - name, -}) { - const pluginCacheDir = cache.directory - // See if there's response headers for this url - // from a previous request. - const cachedHeaders = await cache.get(cacheIdForHeaders(url)) - - const headers = { ...httpHeaders } - if (cachedHeaders && cachedHeaders.etag) { - headers[`If-None-Match`] = cachedHeaders.etag - } - - // Add htaccess authentication if passed in. This isn't particularly - // extensible. We should define a proper API that we validate. - const httpOpts = {} - if (auth && (auth.htaccess_pass || auth.htaccess_user)) { - httpOpts.auth = `${auth.htaccess_user}:${auth.htaccess_pass}` - } - - // Create the temp and permanent file names for the url. - const digest = createContentDigest(url) - if (!name) { - name = getRemoteFileName(url) - } - if (!ext) { - ext = getRemoteFileExtension(url) - } - - const tmpFilename = createFilePath(pluginCacheDir, `tmp-${digest}`, ext) - - // Fetch the file. - const response = await requestRemoteNode(url, headers, tmpFilename, httpOpts) - - if (response.statusCode === 200) { - // Save the response headers for future requests. - await cache.set(cacheIdForHeaders(url), response.headers) - } - - // If the user did not provide an extension and we couldn't get one from remote file, try and guess one - if (ext === ``) { - if (response.statusCode === 200) { - // if this is fresh response - try to guess extension and cache result for future - const filetype = await fileType.fromFile(tmpFilename) - if (filetype) { - ext = `.${filetype.ext}` - await cache.set(cacheIdForExtensions(url), ext) - } - } else if (response.statusCode === 304) { - // if file on server didn't change - grab cached extension - ext = await cache.get(cacheIdForExtensions(url)) - } - } - - const filename = createFilePath(path.join(pluginCacheDir, digest), name, ext) - // If the status code is 200, move the piped temp file to the real name. - if (response.statusCode === 200) { - await fs.move(tmpFilename, filename, { overwrite: true }) - // Else if 304, remove the empty response. - } else { - await fs.remove(tmpFilename) - } - - return filename -} - async function fetchPlaceholder({ fromPath, url, cache, ext, name }) { const pluginCacheDir = cache.directory const digest = createContentDigest(url) @@ -396,7 +205,6 @@ module.exports = function createRemoteFileNode({ createNodeId, ext = null, name = null, - reporter, }) { if (showFlagWarning) { showFlagWarning = false diff --git a/packages/gatsby-source-filesystem/src/utils.js b/packages/gatsby-source-filesystem/src/utils.js index 5e04cc0ceb5fd..ff26698ad1e7c 100644 --- a/packages/gatsby-source-filesystem/src/utils.js +++ b/packages/gatsby-source-filesystem/src/utils.js @@ -1,6 +1,5 @@ const path = require(`path`) const Url = require(`url`) -const ProgressBar = require(`progress`) /** * getParsedPath diff --git a/packages/gatsby-source-npm-package-search/CHANGELOG.md b/packages/gatsby-source-npm-package-search/CHANGELOG.md index e9d2b7a463e54..a0942c37ec228 100644 --- a/packages/gatsby-source-npm-package-search/CHANGELOG.md +++ b/packages/gatsby-source-npm-package-search/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-npm-package-search@3.0.0-next.1...gatsby-source-npm-package-search@3.0.0-next.2) (2021-02-22) + +### Bug Fixes + +- **npm-package-search:** declare mimeType so markdown trasformer children are added ([#29615](https://github.com/gatsbyjs/gatsby/issues/29615)) ([cbcd996](https://github.com/gatsbyjs/gatsby/commit/cbcd9962de044a746e5336dfe2db58d202950e73)) + # [3.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-npm-package-search@3.0.0-next.0...gatsby-source-npm-package-search@3.0.0-next.1) (2021-02-11) ### Features diff --git a/packages/gatsby-source-npm-package-search/package.json b/packages/gatsby-source-npm-package-search/package.json index a422169ca7639..306d0b5cbf12c 100644 --- a/packages/gatsby-source-npm-package-search/package.json +++ b/packages/gatsby-source-npm-package-search/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-source-npm-package-search", "description": "Search NPM packages and pull NPM & GitHub metadata from Algolia's NPM index", - "version": "3.0.0-next.1", + "version": "3.0.0-next.2", "author": "james.a.stack@gmail.com", "repository": { "type": "git", diff --git a/packages/gatsby-source-npm-package-search/src/gatsby-node.js b/packages/gatsby-source-npm-package-search/src/gatsby-node.js index 6a238d0102af1..cbd9219491b98 100644 --- a/packages/gatsby-source-npm-package-search/src/gatsby-node.js +++ b/packages/gatsby-source-npm-package-search/src/gatsby-node.js @@ -37,7 +37,7 @@ exports.createSchemaCustomization = ({ actions }) => { lastPublisher: NPMPackageOwner _searchInternal: NPMPackage_searchInternal } - type NPMPackageReadme implements Node @dontInfer { + type NPMPackageReadme implements Node @dontInfer @mimeTypes(types: ["text/markdown"]) { slug: String! } type NPMPackageRepository { diff --git a/packages/gatsby-source-shopify/CHANGELOG.md b/packages/gatsby-source-shopify/CHANGELOG.md index 4827b95917639..de6c017467ff9 100644 --- a/packages/gatsby-source-shopify/CHANGELOG.md +++ b/packages/gatsby-source-shopify/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [4.0.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-shopify@4.0.0-next.3...gatsby-source-shopify@4.0.0-next.4) (2021-02-22) + +**Note:** Version bump only for package gatsby-source-shopify + +# [4.0.0-next.3](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-shopify@4.0.0-next.2...gatsby-source-shopify@4.0.0-next.3) (2021-02-18) + +### Bug Fixes + +- **gatsby-source-shopify:** Don't remove version string from Shopify image URLs ([#29458](https://github.com/gatsbyjs/gatsby/issues/29458)) ([f25ea67](https://github.com/gatsbyjs/gatsby/commit/f25ea673384eca87ed288dcc8c6160d7dd2d0df3)) + # [4.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-shopify@4.0.0-next.1...gatsby-source-shopify@4.0.0-next.2) (2021-02-15) **Note:** Version bump only for package gatsby-source-shopify diff --git a/packages/gatsby-source-shopify/package.json b/packages/gatsby-source-shopify/package.json index 8e888dd44b406..bcaf24527e6c2 100644 --- a/packages/gatsby-source-shopify/package.json +++ b/packages/gatsby-source-shopify/package.json @@ -1,6 +1,6 @@ { "name": "gatsby-source-shopify", - "version": "4.0.0-next.2", + "version": "4.0.0-next.4", "description": "Gatsby source plugin for building websites using Shopify as a data source.", "scripts": { "build": "babel src --out-dir . --ignore \"**/__tests__\"", @@ -36,7 +36,7 @@ "babel-preset-gatsby-package": "^1.0.0-next.0", "chalk": "^4.1.0", "gatsby-node-helpers": "^0.3.0", - "gatsby-source-filesystem": "^3.0.0-next.2", + "gatsby-source-filesystem": "^3.0.0-next.3", "graphql-request": "^1.8.2", "lodash": "^4.17.20", "p-iteration": "^1.1.8", diff --git a/packages/gatsby-source-shopify/src/nodes.js b/packages/gatsby-source-shopify/src/nodes.js index 3f612b7280a46..e57f998dfded3 100644 --- a/packages/gatsby-source-shopify/src/nodes.js +++ b/packages/gatsby-source-shopify/src/nodes.js @@ -99,7 +99,7 @@ export const CollectionNode = imageArgs => node.image.localFile___NODE = await downloadImageAndCreateFileNode( { id: node.image.id, - url: node.image.src && node.image.src.split(`?`)[0], + url: node.image.src, nodeId: node.id, }, imageArgs @@ -142,7 +142,7 @@ export const ProductNode = imageArgs => edge.node.localFile___NODE = await downloadImageAndCreateFileNode( { id: edge.node.id, - url: edge.node.originalSrc && edge.node.originalSrc.split(`?`)[0], + url: edge.node.originalSrc, }, imageArgs ) @@ -172,7 +172,7 @@ export const ProductVariantNode = (imageArgs, productNode) => node.image.localFile___NODE = await downloadImageAndCreateFileNode( { id: node.image.id, - url: node.image.originalSrc && node.image.originalSrc.split(`?`)[0], + url: node.image.originalSrc, }, imageArgs ) diff --git a/packages/gatsby-source-wordpress/CHANGELOG.md b/packages/gatsby-source-wordpress/CHANGELOG.md index 2625c76717319..abf714483481b 100644 --- a/packages/gatsby-source-wordpress/CHANGELOG.md +++ b/packages/gatsby-source-wordpress/CHANGELOG.md @@ -3,6 +3,22 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [5.0.0-next.8](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-wordpress@5.0.0-next.7...gatsby-source-wordpress@5.0.0-next.8) (2021-02-22) + +**Note:** Version bump only for package gatsby-source-wordpress + +# [5.0.0-next.7](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-wordpress@5.0.0-next.6...gatsby-source-wordpress@5.0.0-next.7) (2021-02-19) + +**Note:** Version bump only for package gatsby-source-wordpress + +# [5.0.0-next.6](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-wordpress@5.0.0-next.5...gatsby-source-wordpress@5.0.0-next.6) (2021-02-18) + +**Note:** Version bump only for package gatsby-source-wordpress + +# [5.0.0-next.5](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-wordpress@5.0.0-next.4...gatsby-source-wordpress@5.0.0-next.5) (2021-02-17) + +**Note:** Version bump only for package gatsby-source-wordpress + # [5.0.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby-source-wordpress@5.0.0-next.3...gatsby-source-wordpress@5.0.0-next.4) (2021-02-15) **Note:** Version bump only for package gatsby-source-wordpress diff --git a/packages/gatsby-source-wordpress/__tests__/plugin-options-schema.test.js b/packages/gatsby-source-wordpress/__tests__/plugin-options-schema.test.js new file mode 100644 index 0000000000000..6335466205e09 --- /dev/null +++ b/packages/gatsby-source-wordpress/__tests__/plugin-options-schema.test.js @@ -0,0 +1,112 @@ +import { testPluginOptionsSchema } from "gatsby-plugin-utils/dist/test-plugin-options-schema" +import { pluginOptionsSchema } from "gatsby-source-wordpress/dist/steps/declare-plugin-options-schema" + +describe(`pluginOptionsSchema`, () => { + it(`should validate a minimal, valid config`, async () => { + const { isValid } = await testPluginOptionsSchema(pluginOptionsSchema, { + url: `http://localhost:8000/graphql`, + }) + + expect(isValid).toEqual(true) + }) + + it(`should invalidate a config missing required vars`, async () => { + const { isValid, errors } = await testPluginOptionsSchema( + pluginOptionsSchema, + {} + ) + + expect(isValid).toEqual(false) + expect(errors).toMatchInlineSnapshot(` + Array [ + "\\"url\\" is required", + ] + `) + }) + + it(`should validate a fully custom config`, async () => { + const { isValid, errors } = await testPluginOptionsSchema( + pluginOptionsSchema, + { + url: `https://fakeurl.com/graphql`, + verbose: false, + debug: { + throwRefetchErrors: true, + graphql: { + showQueryOnError: false, + showQueryVarsOnError: false, + copyQueryOnError: false, + panicOnError: false, + onlyReportCriticalErrors: true, + copyNodeSourcingQueryAndExit: false, + writeQueriesToDisk: false, + }, + timeBuildSteps: false, + disableCompatibilityCheck: false, + }, + develop: { + nodeUpdateInterval: 300, + hardCacheMediaFiles: false, + hardCacheData: false, + }, + production: { + hardCacheMediaFiles: false, + }, + auth: { + htaccess: { + username: `test`, + password: `test`, + }, + }, + schema: { + queryDepth: 15, + circularQueryLimit: 5, + typePrefix: `Wp`, + timeout: 30 * 1000, // 30 seconds + perPage: 100, + }, + excludeFieldNames: [], + html: { + useGatsbyImage: true, + imageMaxWidth: null, + fallbackImageMaxWidth: 100, + imageQuality: 90, + createStaticFiles: true, + }, + type: { + __all: { + excludeFieldNames: [`viewer`], + }, + RootQuery: { + excludeFieldNames: [`schemaMd5`], + }, + MediaItem: { + lazyNodes: true, + localFile: { + excludeByMimeTypes: [`video/mp4`], + maxFileSizeBytes: 1400000, + }, + }, + ContentNode: { + nodeInterface: true, + }, + Menu: { + beforeChangeNode: () => {}, + }, + MenuItem: { + beforeChangeNode: null, + }, + EnqueuedScript: { + exclude: true, + }, + EnqueuedThing: { + exclude: null, + }, + }, + } + ) + + expect(errors).toEqual([]) + expect(isValid).toEqual(true) + }) +}) diff --git a/packages/gatsby-source-wordpress/docs/community-and-support.md b/packages/gatsby-source-wordpress/docs/community-and-support.md index f12ce16e9b53a..eba55cca1a4a3 100644 --- a/packages/gatsby-source-wordpress/docs/community-and-support.md +++ b/packages/gatsby-source-wordpress/docs/community-and-support.md @@ -4,7 +4,7 @@ Fortunately there are very strong WPGraphQL and Gatsby communities! Check out this [GatsbyJS page](https://www.gatsbyjs.org/contributing/community/) or this [WPGraphQL page](https://www.wpgraphql.com/community-and-support/) on community for more information about each community. -The WPGraphQL Slack is a great place to get help. Feel free to[ open an issue in this repo](https://github.com/gatsbyjs/gatsby/issues/new) as well (after you've searched for a previously existing issue). +The WPGraphQL Slack is a great place to get help. Feel free to [open an issue in this repo](https://github.com/gatsbyjs/gatsby/issues/new) as well (after you've searched for a previously existing issue). # That's all folks! :smile_cat: diff --git a/packages/gatsby-source-wordpress/docs/debugging-and-troubleshooting.md b/packages/gatsby-source-wordpress/docs/debugging-and-troubleshooting.md index ed1b8dfdae051..83c43c270118c 100644 --- a/packages/gatsby-source-wordpress/docs/debugging-and-troubleshooting.md +++ b/packages/gatsby-source-wordpress/docs/debugging-and-troubleshooting.md @@ -39,7 +39,7 @@ Take that query and make the query directly to your WP instance GraphQL API like { pages { nodes { - id + id title } } @@ -54,10 +54,10 @@ Take that query and make the query directly to your WP instance GraphQL API like ```js { resolve: `gatsby-source-wordpress`, - options: { - debug: { + options: { + debug: { graphql: { - writeQueriesToDisk: true, + writeQueriesToDisk: true, }, }, }, @@ -87,14 +87,14 @@ Take that query and make the query directly to your WP instance GraphQL API like #### If it does have missing data: - this means you're experiencing a bug on the WPGraphQL side of things. Seek help in the [WPGraphQL Slack](https://wpgql-slack.herokuapp.com/) or open an issue in the [WPGraphQL Github repo](https://github.com/wp-graphql/wp-graphql), or the Github repo for the WPGraphQL extension that manages the fields you're having trouble with. + this means you're experiencing a bug on the WPGraphQL side of things. Seek help in the [WPGraphQL Slack](https://wpgql-slack.herokuapp.com/) or open an issue in the [WPGraphQL GitHub repo](https://github.com/wp-graphql/wp-graphql), or the GitHub repo for the WPGraphQL extension that manages the fields you're having trouble with. To help them debug you should narrow down exactly which combination of fields in the generated query you copied is causing issues. Comment out fields 1 by 1 until the problem goes away to determine which combination of fields isn't working. **Note:** A common cause of this problem is that you're using ACF and you've named multiple fields with the same name but in different field groups. Identify conflicting field names and rename them. #### If it does not have missing data: - This means it's a `gatsby-source-wordpress` bug. Open an issue in the [Github repo](https://github.com/gatsbyjs/gatsby/issues/new). + This means it's a `gatsby-source-wordpress` bug. Open an issue in the [GitHub repo](https://github.com/gatsbyjs/gatsby/issues/new). ### Node Sourcing GraphQL errors @@ -103,10 +103,10 @@ If your build is erroring on a GraphQL error returned in the response from a Gra ```js { resolve: `gatsby-source-wordpress`, - options: { - debug: { + options: { + debug: { graphql: { - writeQueriesToDisk: true, + writeQueriesToDisk: true, }, }, }, @@ -117,7 +117,7 @@ Now run `gatsby develop` or `gatsby build` again. When the process exits on your Within this file will be the query made during node sourcing to fetch data from WPGraphQL into Gatsby. -You can use this query to reproduce your error message and debug your error message outside of Gatsby. If you're stuck seek help in the [WPGraphQL Slack](https://wpgql-slack.herokuapp.com/) or open an issue in the [WPGraphQL Github repo](https://github.com/wp-graphql/wp-graphql), or the Github repo for the WPGraphQL extension that manages the fields you're having trouble with. +You can use this query to reproduce your error message and debug your error message outside of Gatsby. If you're stuck seek help in the [WPGraphQL Slack](https://wpgql-slack.herokuapp.com/) or open an issue in the [WPGraphQL GitHub repo](https://github.com/wp-graphql/wp-graphql), or the GitHub repo for the WPGraphQL extension that manages the fields you're having trouble with. ### WordPress 50\* errors @@ -136,8 +136,8 @@ To determine how many concurrent GraphQL requests your server can handle, enable ```js { resolve: `gatsby-source-wordpress`, - options: { - verbose: true, + options: { + verbose: true, }, }, ``` diff --git a/packages/gatsby-source-wordpress/docs/features/graphql-wordpress-and-gatsby.md b/packages/gatsby-source-wordpress/docs/features/graphql-wordpress-and-gatsby.md index b749d850ea5d4..60cbc8f99e9f9 100644 --- a/packages/gatsby-source-wordpress/docs/features/graphql-wordpress-and-gatsby.md +++ b/packages/gatsby-source-wordpress/docs/features/graphql-wordpress-and-gatsby.md @@ -117,7 +117,7 @@ But a similar query for a single post by database ID in Gatsby would look like: ```graphql { - wpPost(databaseId: { eq: 1747 }) { + wpPost(databaseId: { eq: 123 }) { id title content diff --git a/packages/gatsby-source-wordpress/docs/migrating-from-other-wp-source-plugins.md b/packages/gatsby-source-wordpress/docs/migrating-from-other-wp-source-plugins.md index c72ae830b3070..bf7b6c0573e33 100644 --- a/packages/gatsby-source-wordpress/docs/migrating-from-other-wp-source-plugins.md +++ b/packages/gatsby-source-wordpress/docs/migrating-from-other-wp-source-plugins.md @@ -34,7 +34,7 @@ For example, if you're querying for a list of pages: ```js { - wp { + wp { pages { nodes { title @@ -50,11 +50,11 @@ So your query would change to look like this: ``` { - allWpPage { - nodes { - title - } - } + allWpPage { + nodes { + title + } + } } ``` diff --git a/packages/gatsby-source-wordpress/package.json b/packages/gatsby-source-wordpress/package.json index dc5f6f62f5548..01259ef097cbb 100644 --- a/packages/gatsby-source-wordpress/package.json +++ b/packages/gatsby-source-wordpress/package.json @@ -2,7 +2,7 @@ "name": "gatsby-source-wordpress", "description": "Source data from WordPress in an efficient and scalable way.", "author": "Tyler Barnes ", - "version": "5.0.0-next.4", + "version": "5.0.0-next.8", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" }, @@ -28,10 +28,10 @@ "file-type": "^15.0.1", "filesize": "^6.1.0", "fs-extra": "^9.0.1", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "gatsby-image": "^3.0.0-next.0", "gatsby-plugin-catch-links": "^3.0.0-next.0", - "gatsby-source-filesystem": "^3.0.0-next.2", + "gatsby-source-filesystem": "^3.0.0-next.3", "glob": "^7.1.6", "got": "^11.7.0", "graphql-query-compress": "^1.2.2", @@ -53,7 +53,7 @@ "@types/semver": "^7.3.4", "babel-plugin-import-globals": "^2.0.0", "babel-plugin-module-resolver": "4.0.0", - "babel-preset-gatsby": "^1.0.0-next.2", + "babel-preset-gatsby": "^1.0.0-next.3", "babel-preset-gatsby-package": "^1.0.0-next.0", "cross-env": "^5.2.1", "identity-obj-proxy": "^3.0.0", diff --git a/packages/gatsby-source-wordpress/src/models/logger.ts b/packages/gatsby-source-wordpress/src/models/logger.ts index 37928e02c6705..6a2e9d252b988 100644 --- a/packages/gatsby-source-wordpress/src/models/logger.ts +++ b/packages/gatsby-source-wordpress/src/models/logger.ts @@ -1,4 +1,4 @@ -import { Reporter } from "gatsby" +import { Reporter } from "gatsby/reporter" import { formatLogMessage } from "~/utils/format-log-message" import { IPluginOptions } from "./gatsby-api" 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 9a3a35f6e1f2f..bdce362fde9df 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 @@ -134,7 +134,10 @@ const objectType = typeBuilderApi => { }) // if all child fields are excluded, this type shouldn't exist. - if (!Object.keys(transformedFields).length) { + // check null first, otherwise cause: + // TypeError: Cannot convert undefined or null to object at Function.keys () + // Also cause wordpress blog site build failure in createSchemaCustomization step + if (!transformedFields || !Object.keys(transformedFields).length) { return } 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 6c23ef581df32..cc33a60d30d3e 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 @@ -3,6 +3,7 @@ import { fetchAndCreateSingleNode } from "~/steps/source-nodes/update-nodes/wp-a import { getQueryInfoByTypeName } from "~/steps/source-nodes/helpers" import { getGatsbyApi } from "~/utils/get-gatsby-api" import { inPreviewMode } from "~/steps/preview/index" +import { getPluginOptions } from "../../../utils/get-gatsby-api" export const transformListOfGatsbyNodes = ({ field, fieldName }) => { const typeName = buildTypeName(field.type.ofType.name) @@ -49,6 +50,14 @@ export const buildGatsbyNodeObjectResolver = ({ field, fieldName }) => async ( type: typeName, }) + const { + schema: { typePrefix: prefix }, + } = getPluginOptions() + + if (!existingNode.__typename.startsWith(prefix)) { + existingNode.__typename = buildTypeName(existingNode.__typename) + } + if (existingNode) { return existingNode } diff --git a/packages/gatsby-source-wordpress/src/steps/preview/index.ts b/packages/gatsby-source-wordpress/src/steps/preview/index.ts index e2a4454ab4c49..ab3496ebbd0a2 100644 --- a/packages/gatsby-source-wordpress/src/steps/preview/index.ts +++ b/packages/gatsby-source-wordpress/src/steps/preview/index.ts @@ -17,7 +17,7 @@ import { formatLogMessage } from "~/utils/format-log-message" import { touchValidNodes } from "../source-nodes/update-nodes/fetch-node-updates" import { IPluginOptions } from "~/models/gatsby-api" -import { Reporter } from "gatsby" +import { Reporter } from "gatsby/reporter" export const inPreviewMode = (): boolean => !!process.env.ENABLE_GATSBY_REFRESH_ENDPOINT && diff --git a/packages/gatsby-source-wordpress/src/steps/temp-prevent-multiple-instances.ts b/packages/gatsby-source-wordpress/src/steps/temp-prevent-multiple-instances.ts index c6e8a3571abcb..2932eea2fcf2b 100644 --- a/packages/gatsby-source-wordpress/src/steps/temp-prevent-multiple-instances.ts +++ b/packages/gatsby-source-wordpress/src/steps/temp-prevent-multiple-instances.ts @@ -1,5 +1,6 @@ -import { Reporter } from "gatsby" +import { Reporter } from "gatsby/reporter" import { formatLogMessage } from "../utils/format-log-message" + let isWpSourcePluginInstalled = false /** diff --git a/packages/gatsby-telemetry/CHANGELOG.md b/packages/gatsby-telemetry/CHANGELOG.md index cf24b7eeebf17..472ed8280b074 100644 --- a/packages/gatsby-telemetry/CHANGELOG.md +++ b/packages/gatsby-telemetry/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [2.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-telemetry@2.0.0-next.0...gatsby-telemetry@2.0.0-next.1) (2021-02-22) + +**Note:** Version bump only for package gatsby-telemetry + # [2.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-telemetry@1.11.0-next.0...gatsby-telemetry@2.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-telemetry diff --git a/packages/gatsby-telemetry/package.json b/packages/gatsby-telemetry/package.json index 3545ea31a3fd3..b2a5bcfe8a573 100644 --- a/packages/gatsby-telemetry/package.json +++ b/packages/gatsby-telemetry/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-telemetry", "description": "Gatsby Telemetry", - "version": "2.0.0-next.0", + "version": "2.0.0-next.1", "author": "Jarmo Isotalo ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -15,7 +15,7 @@ "boxen": "^4.2.0", "configstore": "^5.0.1", "fs-extra": "^8.1.0", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "git-up": "^4.0.2", "is-docker": "^2.1.1", "lodash": "^4.17.20", @@ -32,7 +32,7 @@ "jest-cli": "^24.9.0", "jest-junit": "^6.4.0", "rimraf": "^3.0.2", - "typescript": "^3.9.7" + "typescript": "^4.1.5" }, "files": [ "lib/", diff --git a/packages/gatsby-telemetry/src/event-storage.ts b/packages/gatsby-telemetry/src/event-storage.ts index 177dd6fe3e9aa..a1eb51deb5499 100644 --- a/packages/gatsby-telemetry/src/event-storage.ts +++ b/packages/gatsby-telemetry/src/event-storage.ts @@ -3,7 +3,7 @@ import Configstore from "configstore" import createFetch from "@turist/fetch" import { Store } from "./store" import { ensureDirSync } from "fs-extra" -import { isTruthy } from "./is-truthy" +import { isTruthy } from "gatsby-core-utils" import { InMemoryConfigStore } from "./in-memory-store" const fetch = createFetch() diff --git a/packages/gatsby-telemetry/src/get-dependencies.ts b/packages/gatsby-telemetry/src/get-dependencies.ts index 6c7c311d9939e..c853bff29f546 100644 --- a/packages/gatsby-telemetry/src/get-dependencies.ts +++ b/packages/gatsby-telemetry/src/get-dependencies.ts @@ -12,7 +12,7 @@ export function getDependencies(): { } } -function mapData(deps: object): Array | undefined { +function mapData(deps: Record): Array | undefined { if (!deps) { return undefined } @@ -26,7 +26,10 @@ function mapData(deps: object): Array | undefined { .map(({ name, version }) => `${name}@${version}`) } -function parsePackageJson(): { dependencies: object; devDependencies: object } { +function parsePackageJson(): { + dependencies: Record + devDependencies: Record +} { try { const packageJson = readFileSync(`./package.json`, `utf8`) if (!packageJson) { diff --git a/packages/gatsby-telemetry/src/store.ts b/packages/gatsby-telemetry/src/store.ts index 4f2698183d49d..d1f351901e536 100644 --- a/packages/gatsby-telemetry/src/store.ts +++ b/packages/gatsby-telemetry/src/store.ts @@ -28,7 +28,7 @@ export class Store { async flushFile( filePath: string, - flushOperation: Function + flushOperation: (contents: string) => Promise ): Promise { const now = `${Date.now()}-${process.pid}` let success = false @@ -57,7 +57,9 @@ export class Store { return true } - async startFlushEvents(flushOperation: Function): Promise { + async startFlushEvents( + flushOperation: (contents: string) => Promise + ): Promise { try { await this.flushFile(this.bufferFilePath, flushOperation) const files = readdirSync(this.baseDir) diff --git a/packages/gatsby-transformer-hjson/CHANGELOG.md b/packages/gatsby-transformer-hjson/CHANGELOG.md index 9a6e75e7aea7b..bd2cd1e48a3d1 100644 --- a/packages/gatsby-transformer-hjson/CHANGELOG.md +++ b/packages/gatsby-transformer-hjson/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-hjson@3.0.0-next.0...gatsby-transformer-hjson@3.0.0-next.1) (2021-02-22) + +### Bug Fixes + +- **deps:** update minor and patch for gatsby-transformer-hjson ([#28231](https://github.com/gatsbyjs/gatsby/issues/28231)) ([dbb5faf](https://github.com/gatsbyjs/gatsby/commit/dbb5fafbfe2d098b9200b675a9dc9f00d449d73b)) + # [3.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-hjson@2.12.0-next.0...gatsby-transformer-hjson@3.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-transformer-hjson diff --git a/packages/gatsby-transformer-hjson/package.json b/packages/gatsby-transformer-hjson/package.json index 2e381da6f7d20..6d6f2d781a6cc 100644 --- a/packages/gatsby-transformer-hjson/package.json +++ b/packages/gatsby-transformer-hjson/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-transformer-hjson", "description": "Gatsby transformer plugin for HJSON files", - "version": "3.0.0-next.0", + "version": "3.0.0-next.1", "author": "Remi Barraquand ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -9,7 +9,7 @@ "dependencies": { "@babel/runtime": "^7.12.5", "bluebird": "^3.7.2", - "hjson": "^3.2.1" + "hjson": "^3.2.2" }, "devDependencies": { "@babel/cli": "^7.12.1", diff --git a/packages/gatsby-transformer-remark/CHANGELOG.md b/packages/gatsby-transformer-remark/CHANGELOG.md index 756bfae142c83..ae931ad99fdb2 100644 --- a/packages/gatsby-transformer-remark/CHANGELOG.md +++ b/packages/gatsby-transformer-remark/CHANGELOG.md @@ -3,6 +3,14 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-remark@3.0.0-next.1...gatsby-transformer-remark@3.0.0-next.2) (2021-02-22) + +**Note:** Version bump only for package gatsby-transformer-remark + +# [3.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-remark@3.0.0-next.0...gatsby-transformer-remark@3.0.0-next.1) (2021-02-19) + +**Note:** Version bump only for package gatsby-transformer-remark + # [3.0.0-next.0](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-remark@2.17.0-next.0...gatsby-transformer-remark@3.0.0-next.0) (2021-02-05) **Note:** Version bump only for package gatsby-transformer-remark diff --git a/packages/gatsby-transformer-remark/README.md b/packages/gatsby-transformer-remark/README.md index 678b212c90b5b..f1308879837e9 100644 --- a/packages/gatsby-transformer-remark/README.md +++ b/packages/gatsby-transformer-remark/README.md @@ -102,7 +102,7 @@ Using the following GraphQL query you'll be able to get the table of contents ### Configuring the tableOfContents -By default the tableOfContents is using the field `slug` to generate absolute URLs. You can however provide another field using the pathToSlugField parameter. **Note** that providing a non existing field will cause the result to be null. You can also pass `absolute: false` to generate relative path. To alter the default values for tableOfContents generation, include values for `heading` (string) and/or `maxDepth` (number 1 to 6) in GraphQL query. If a value for `heading` is given, the first heading that matches will be omitted and the toc is generated from the next heading of the same depth onwards. Value for `maxDepth` sets the maximum depth of the toc (i.e. if a maxDepth of 3 is set, only h1 to h3 headings will appear in the toc). +By default, `absolute` is set to false, generating a relative path. If you'd like to generate an absolute path, pass `absolute: true`. In that case, be sure to pass the `pathToSlugField` parameter, often `fields.slug`, to create absolute URLs. **Note** that providing a non-existent field will cause the result to be null. To alter the default values for tableOfContents generation, include values for `heading` (string) and/or `maxDepth` (number 1 to 6) in GraphQL query. If a value for `heading` is given, the first heading that matches will be omitted and the toc is generated from the next heading of the same depth onwards. Value for `maxDepth` sets the maximum depth of the toc (i.e. if a maxDepth of 3 is set, only h1 to h3 headings will appear in the toc). ```graphql { diff --git a/packages/gatsby-transformer-remark/package.json b/packages/gatsby-transformer-remark/package.json index 5d13becb32f91..eec7544624245 100644 --- a/packages/gatsby-transformer-remark/package.json +++ b/packages/gatsby-transformer-remark/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-transformer-remark", "description": "Gatsby transformer plugin for Markdown using the Remark library and ecosystem", - "version": "3.0.0-next.0", + "version": "3.0.0-next.2", "author": "Kyle Mathews ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -9,7 +9,7 @@ "dependencies": { "@babel/runtime": "^7.12.5", "bluebird": "^3.7.2", - "gatsby-core-utils": "^2.0.0-next.0", + "gatsby-core-utils": "^2.0.0-next.1", "gray-matter": "^4.0.2", "hast-util-raw": "^4.0.0", "hast-util-to-html": "^4.0.1", diff --git a/packages/gatsby-transformer-remark/src/__tests__/extend-node.js b/packages/gatsby-transformer-remark/src/__tests__/extend-node.js index a2a85eadee18c..aae314bfdff02 100644 --- a/packages/gatsby-transformer-remark/src/__tests__/extend-node.js +++ b/packages/gatsby-transformer-remark/src/__tests__/extend-node.js @@ -4,7 +4,7 @@ const extendNodeType = require(`../extend-node-type`) const { createContentDigest } = require(`gatsby-core-utils`) const { typeDefs } = require(`../create-schema-customization`) -jest.mock(`gatsby-cli/lib/reporter`, () => { +jest.mock(`gatsby/reporter`, () => { return { log: jest.fn(), info: jest.fn(), @@ -26,14 +26,16 @@ async function queryResult( fragment, { additionalParameters = {}, pluginOptions = {} } ) { + const cache = { + // GatsbyCache + get: async () => null, + set: async () => null, + } const extendNodeTypeFields = await extendNodeType( { type: { name: `MarkdownRemark` }, - cache: { - // GatsbyCache - get: async () => null, - set: async () => null, - }, + cache, + getCache: () => cache, getNodesByType: type => [], ...additionalParameters, }, @@ -935,7 +937,7 @@ some text some other text `, - `tableOfContents + `tableOfContents(absolute: true, pathToSlugField: "fields.slug") frontmatter { title }`, @@ -963,7 +965,7 @@ some other text final text `, - `tableOfContents(pathToSlugField: "frontmatter.title") + `tableOfContents(pathToSlugField: "frontmatter.title", absolute: true) frontmatter { title }`, @@ -990,7 +992,7 @@ some other text final text `, - `tableOfContents(absolute: false) + `tableOfContents frontmatter { title }`, @@ -1012,7 +1014,7 @@ some text ## second title some other text`, - `tableOfContents(pathToSlugField: "frontmatter.title", maxDepth: 1) + `tableOfContents(pathToSlugField: "frontmatter.title", maxDepth: 1, absolute: true) frontmatter { title }`, @@ -1036,7 +1038,7 @@ some text ## second title some other text`, - `tableOfContents(pathToSlugField: "frontmatter.title") + `tableOfContents(pathToSlugField: "frontmatter.title", absolute: true) frontmatter { title }`, @@ -1071,7 +1073,7 @@ some other text # third title final text`, - `tableOfContents(pathToSlugField: "frontmatter.title", heading: "first title") + `tableOfContents(pathToSlugField: "frontmatter.title", heading: "first title", absolute: true) frontmatter { title }`, @@ -1101,7 +1103,7 @@ Content - content ### Embedding \`\` Tags It's easier than you may imagine`, - `tableOfContents(pathToSlugField: "frontmatter.title") + `tableOfContents(pathToSlugField: "frontmatter.title", absolute: true) frontmatter { title }`, @@ -1125,7 +1127,7 @@ Content - content ### Embedding \`\` Tags It's easier than you may imagine`, - `tableOfContents(pathToSlugField: "frontmatter.title") + `tableOfContents(pathToSlugField: "frontmatter.title", absolute: true) frontmatter { title }`, diff --git a/packages/gatsby-transformer-remark/src/extend-node-type.js b/packages/gatsby-transformer-remark/src/extend-node-type.js index c29b8cc7fa4f7..109d1ed0a76af 100644 --- a/packages/gatsby-transformer-remark/src/extend-node-type.js +++ b/packages/gatsby-transformer-remark/src/extend-node-type.js @@ -46,14 +46,6 @@ const tableOfContentsCacheKey = (node, appliedTocOptions) => const withPathPrefix = (url, pathPrefix) => (pathPrefix + url).replace(/\/\//, `/`) -// TODO: remove this check with next major release -const safeGetCache = ({ getCache, cache }) => id => { - if (!getCache) { - return cache - } - return getCache(id) -} - /** * Map that keeps track of generation of AST to not generate it multiple * times in parallel. @@ -87,7 +79,7 @@ module.exports = function remarkExtendNodeType( getNode, getNodesByType, cache, - getCache: possibleGetCache, + getCache, reporter, ...rest }, @@ -99,8 +91,6 @@ module.exports = function remarkExtendNodeType( pluginsCacheStr = pluginOptions.plugins.map(p => p.name).join(``) pathPrefixCacheStr = basePath || `` - const getCache = safeGetCache({ cache, getCache: possibleGetCache }) - return new Promise((resolve, reject) => { // Setup Remark. const { @@ -645,15 +635,13 @@ module.exports = function remarkExtendNodeType( tableOfContents: { type: `String`, args: { - // TODO:(v3) set default value to false absolute: { type: `Boolean`, - defaultValue: true, + defaultValue: false, }, - // TODO:(v3) set default value to empty string pathToSlugField: { type: `String`, - defaultValue: `fields.slug`, + defaultValue: ``, }, maxDepth: `Int`, heading: `String`, diff --git a/packages/gatsby-transformer-screenshot/CHANGELOG.md b/packages/gatsby-transformer-screenshot/CHANGELOG.md index 94442e81da0c9..9992cccc16bce 100644 --- a/packages/gatsby-transformer-screenshot/CHANGELOG.md +++ b/packages/gatsby-transformer-screenshot/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.2](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-screenshot@3.0.0-next.1...gatsby-transformer-screenshot@3.0.0-next.2) (2021-02-22) + +**Note:** Version bump only for package gatsby-transformer-screenshot + # [3.0.0-next.1](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-screenshot@3.0.0-next.0...gatsby-transformer-screenshot@3.0.0-next.1) (2021-02-11) ### Features diff --git a/packages/gatsby-transformer-screenshot/lambda/package.json b/packages/gatsby-transformer-screenshot/lambda/package.json index 7353f1d0cc4b6..8491fcafc9aa3 100644 --- a/packages/gatsby-transformer-screenshot/lambda/package.json +++ b/packages/gatsby-transformer-screenshot/lambda/package.json @@ -1,11 +1,11 @@ { "dependencies": { "chrome-aws-lambda": "^2.1.1", - "gatsby-core-utils": "^1.8.0", + "gatsby-core-utils": "^2.0.0-next.0", "puppeteer-core": "^3.3.0" }, "devDependencies": { - "aws-sdk": "^2.824.0" + "aws-sdk": "^2.848.0" }, "keywords": [], "engines": { diff --git a/packages/gatsby-transformer-screenshot/package.json b/packages/gatsby-transformer-screenshot/package.json index 56b0d3b74a62b..ddc86619f0bfe 100644 --- a/packages/gatsby-transformer-screenshot/package.json +++ b/packages/gatsby-transformer-screenshot/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-transformer-screenshot", "description": "Gatsby transformer plugin that uses AWS Lambda to take screenshots of websites", - "version": "3.0.0-next.1", + "version": "3.0.0-next.2", "author": "David Beckley ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" diff --git a/packages/gatsby-transformer-sharp/src/customize-schema.js b/packages/gatsby-transformer-sharp/src/customize-schema.js index 9c2f3a0fb023b..262e5c8a04385 100644 --- a/packages/gatsby-transformer-sharp/src/customize-schema.js +++ b/packages/gatsby-transformer-sharp/src/customize-schema.js @@ -44,6 +44,18 @@ const { const { stripIndent } = require(`common-tags`) const { prefixId, CODES } = require(`./error-utils`) +let warnedForDeprecation = false + +function warnForDeprecation() { + if (warnedForDeprecation) { + return + } + warnedForDeprecation = true + console.warn( + `[gatsby-transformer-sharp] The "fixed" and "fluid" resolvers are now deprecated. Switch to "gatsby-plugin-image" for better performance and a simpler API. See https://gatsby.dev/migrate-images to learn how.` + ) +} + function toArray(buf) { const arr = new Array(buf.length) @@ -200,6 +212,7 @@ const fixedNodeType = ({ }, }, resolve: (image, fieldArgs, context) => { + warnForDeprecation() const file = getNodeAndSavePathDependency(image.parent, context.path) const args = { ...fieldArgs, pathPrefix } return Promise.resolve( @@ -366,6 +379,7 @@ const fluidNodeType = ({ }, }, resolve: (image, fieldArgs, context) => { + warnForDeprecation() const file = getNodeAndSavePathDependency(image.parent, context.path) const args = { ...fieldArgs, pathPrefix } return Promise.resolve( @@ -386,8 +400,6 @@ const fluidNodeType = ({ } } -let warnedForBeta = false - const imageNodeType = ({ pathPrefix, getNodeAndSavePathDependency, @@ -515,13 +527,6 @@ const imageNodeType = ({ reporter.warn(`Please upgrade gatsby-plugin-sharp`) return null } - if (!warnedForBeta) { - reporter.warn( - stripIndent` - Thank you for trying the beta version of the \`gatsbyImageData\` API. Please provide feedback and report any issues at: https://github.com/gatsbyjs/gatsby/discussions/27950` - ) - warnedForBeta = true - } const imageData = await generateImageData({ file, args: fieldArgs, diff --git a/packages/gatsby-transformer-sqip/CHANGELOG.md b/packages/gatsby-transformer-sqip/CHANGELOG.md index f17ee1db1113b..8ed1d65a5a36e 100644 --- a/packages/gatsby-transformer-sqip/CHANGELOG.md +++ b/packages/gatsby-transformer-sqip/CHANGELOG.md @@ -3,6 +3,26 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.8](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-sqip@3.0.0-next.7...gatsby-transformer-sqip@3.0.0-next.8) (2021-02-22) + +**Note:** Version bump only for package gatsby-transformer-sqip + +# [3.0.0-next.7](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-sqip@3.0.0-next.6...gatsby-transformer-sqip@3.0.0-next.7) (2021-02-19) + +**Note:** Version bump only for package gatsby-transformer-sqip + +# [3.0.0-next.6](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-sqip@3.0.0-next.5...gatsby-transformer-sqip@3.0.0-next.6) (2021-02-19) + +**Note:** Version bump only for package gatsby-transformer-sqip + +# [3.0.0-next.5](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-sqip@3.0.0-next.4...gatsby-transformer-sqip@3.0.0-next.5) (2021-02-18) + +**Note:** Version bump only for package gatsby-transformer-sqip + +# [3.0.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-sqip@3.0.0-next.3...gatsby-transformer-sqip@3.0.0-next.4) (2021-02-17) + +**Note:** Version bump only for package gatsby-transformer-sqip + # [3.0.0-next.3](https://github.com/gatsbyjs/gatsby/compare/gatsby-transformer-sqip@3.0.0-next.2...gatsby-transformer-sqip@3.0.0-next.3) (2021-02-12) **Note:** Version bump only for package gatsby-transformer-sqip diff --git a/packages/gatsby-transformer-sqip/package.json b/packages/gatsby-transformer-sqip/package.json index a4dfabeb5d882..65b3adcf802db 100644 --- a/packages/gatsby-transformer-sqip/package.json +++ b/packages/gatsby-transformer-sqip/package.json @@ -1,7 +1,7 @@ { "name": "gatsby-transformer-sqip", "description": "Generates geometric primitive version of images", - "version": "3.0.0-next.3", + "version": "3.0.0-next.8", "author": "Benedikt Rötsch ", "bugs": { "url": "https://github.com/gatsbyjs/gatsby/issues" @@ -9,7 +9,7 @@ "dependencies": { "@babel/runtime": "^7.12.5", "fs-extra": "^8.1.0", - "gatsby-plugin-sharp": "^3.0.0-next.3", + "gatsby-plugin-sharp": "^3.0.0-next.8", "md5-file": "^5.0.0", "mini-svg-data-uri": "^1.2.3", "p-queue": "^6.6.2", diff --git a/packages/gatsby/CHANGELOG.md b/packages/gatsby/CHANGELOG.md index a12c6051ed1e0..04c1d30ab37b2 100644 --- a/packages/gatsby/CHANGELOG.md +++ b/packages/gatsby/CHANGELOG.md @@ -3,6 +3,46 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.0.0-next.8](https://github.com/gatsbyjs/gatsby/compare/gatsby@3.0.0-next.7...gatsby@3.0.0-next.8) (2021-02-22) + +### Bug Fixes + +- **gatsby:** cleanup fullySpecified resolving ([#29576](https://github.com/gatsbyjs/gatsby/issues/29576)) ([1343d38](https://github.com/gatsbyjs/gatsby/commit/1343d38a6f22e8919eacbfdcb718fbdc409a03dc)) + +### Features + +- **gatsby-core-utils:** Add file download functions ([#29531](https://github.com/gatsbyjs/gatsby/issues/29531)) ([1a9469d](https://github.com/gatsbyjs/gatsby/commit/1a9469d67a19007faebebfb8ce876970c5e0ffaf)) + +# [3.0.0-next.7](https://github.com/gatsbyjs/gatsby/compare/gatsby@3.0.0-next.6...gatsby@3.0.0-next.7) (2021-02-19) + +### Bug Fixes + +- **css-modules:** fix webpack config for css modules ([#29596](https://github.com/gatsbyjs/gatsby/issues/29596)) ([c43fb52](https://github.com/gatsbyjs/gatsby/commit/c43fb520ae7f7e028ac77ac39e89c411cbaf1452)) +- **gatsby:** fix deprecation export messages ([#29563](https://github.com/gatsbyjs/gatsby/issues/29563)) ([15b55f0](https://github.com/gatsbyjs/gatsby/commit/15b55f09ba97c7cabe368900bcdc4c120f988d47)) +- **gatsby:** prevent errors when backwards compat node.nodeId is for a deleted node in touchNode ([#29575](https://github.com/gatsbyjs/gatsby/issues/29575)) ([077eb16](https://github.com/gatsbyjs/gatsby/commit/077eb16f78cf72f2f4291bd4e51de61a5d6d826c)) + +### Features + +- remove react-hot-loader ([#29540](https://github.com/gatsbyjs/gatsby/issues/29540)) ([a5210b2](https://github.com/gatsbyjs/gatsby/commit/a5210b2550b9646656aae28c28cb5be580cd5677)) + +# [3.0.0-next.6](https://github.com/gatsbyjs/gatsby/compare/gatsby@3.0.0-next.5...gatsby@3.0.0-next.6) (2021-02-18) + +### Features + +- **conditional-page-builds:** make it default ([#29548](https://github.com/gatsbyjs/gatsby/issues/29548)) ([348a5bf](https://github.com/gatsbyjs/gatsby/commit/348a5bf989a955345d1b958e25978ed90864cd72)) + +# [3.0.0-next.5](https://github.com/gatsbyjs/gatsby/compare/gatsby@3.0.0-next.4...gatsby@3.0.0-next.5) (2021-02-17) + +### Bug Fixes + +- **conditional-page-builds:** track page data and not page query ([#29498](https://github.com/gatsbyjs/gatsby/issues/29498)) ([31a23d8](https://github.com/gatsbyjs/gatsby/commit/31a23d873d4b1fa76d4c432fcecfe54876c0af1d)) + +### Features + +- **conditional-page-builds:** track ssr compilation hash ([#29482](https://github.com/gatsbyjs/gatsby/issues/29482)) ([2157ca9](https://github.com/gatsbyjs/gatsby/commit/2157ca9a08887256e22bb75e899b3964ba5d675c)) +- **conditional-page-builds:** track static query results ([#29486](https://github.com/gatsbyjs/gatsby/issues/29486)) ([16d16ce](https://github.com/gatsbyjs/gatsby/commit/16d16ce0824006c25576f32772cecb8fa3101c75)) +- **gatsby:** upgrade webpack to version 5 ([#29145](https://github.com/gatsbyjs/gatsby/issues/29145)) ([a7a3991](https://github.com/gatsbyjs/gatsby/commit/a7a3991ca2ad450abaacdc168e9900dad995b584)) + # [3.0.0-next.4](https://github.com/gatsbyjs/gatsby/compare/gatsby@3.0.0-next.3...gatsby@3.0.0-next.4) (2021-02-15) ### Bug Fixes @@ -1280,7 +1320,7 @@ The migration is as simple as adding \_\_typename field to the query manually. ### Bug Fixes - **gatsby:** don't fail validation on fragments that are not used ([#24032](https://github.com/gatsbyjs/gatsby/issues/24032)) ([61d0ef4](https://github.com/gatsbyjs/gatsby/commit/61d0ef4)) -- **gatsby:** update script to generate apis.json to accommodate Typescript ([#24023](https://github.com/gatsbyjs/gatsby/issues/24023)) ([7878d0f](https://github.com/gatsbyjs/gatsby/commit/7878d0f)) +- **gatsby:** update script to generate apis.json to accommodate TypeScript ([#24023](https://github.com/gatsbyjs/gatsby/issues/24023)) ([7878d0f](https://github.com/gatsbyjs/gatsby/commit/7878d0f)) ## [2.21.28](https://github.com/gatsbyjs/gatsby/compare/gatsby@2.21.27...gatsby@2.21.28) (2020-05-13) diff --git a/packages/gatsby/cache-dir/__tests__/__snapshots__/dev-loader.js.snap b/packages/gatsby/cache-dir/__tests__/__snapshots__/dev-loader.js.snap index 6073b701836fb..b8e48f1681c55 100644 --- a/packages/gatsby/cache-dir/__tests__/__snapshots__/dev-loader.js.snap +++ b/packages/gatsby/cache-dir/__tests__/__snapshots__/dev-loader.js.snap @@ -2,7 +2,7 @@ exports[`Dev loader loadPage should be successful when component can be loaded 1`] = ` Object { - "component": "instance", + "component": [Function], "json": Object { "pageContext": "something something", }, diff --git a/packages/gatsby/cache-dir/__tests__/__snapshots__/static-entry.js.snap b/packages/gatsby/cache-dir/__tests__/__snapshots__/static-entry.js.snap index 1a2b6021ebb85..78706199ce5b9 100644 --- a/packages/gatsby/cache-dir/__tests__/__snapshots__/static-entry.js.snap +++ b/packages/gatsby/cache-dir/__tests__/__snapshots__/static-entry.js.snap @@ -1,19 +1,34 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`develop-static-entry SSR: onPreRenderHTML can be used to replace headComponents 1`] = `"
"`; +exports[`develop-static-entry SSR: onPreRenderHTML can be used to replace headComponents 1`] = `"
"`; -exports[`develop-static-entry SSR: onPreRenderHTML can be used to replace postBodyComponents 1`] = `"
div3
div2
div1
"`; +exports[`develop-static-entry SSR: onPreRenderHTML can be used to replace postBodyComponents 1`] = `"
div3
div2
div1
"`; -exports[`develop-static-entry SSR: onPreRenderHTML can be used to replace preBodyComponents 1`] = `"
div3
div2
div1
"`; +exports[`develop-static-entry SSR: onPreRenderHTML can be used to replace preBodyComponents 1`] = `"
div3
div2
div1
"`; -exports[`develop-static-entry onPreRenderHTML can be used to replace headComponents 1`] = `"
"`; +exports[`develop-static-entry onPreRenderHTML can be used to replace headComponents 1`] = `"
"`; -exports[`develop-static-entry onPreRenderHTML can be used to replace postBodyComponents 1`] = `"
div3
div2
div1
"`; +exports[`develop-static-entry onPreRenderHTML can be used to replace postBodyComponents 1`] = `"
div3
div2
div1
"`; -exports[`develop-static-entry onPreRenderHTML can be used to replace preBodyComponents 1`] = `"
div3
div2
div1
"`; +exports[`develop-static-entry onPreRenderHTML can be used to replace preBodyComponents 1`] = `"
div3
div2
div1
"`; -exports[`static-entry onPreRenderHTML can be used to replace headComponents 1`] = `"
"`; +exports[`static-entry onPreRenderHTML can be used to replace headComponents 1`] = ` +Object { + "html": "
", + "unsafeBuiltinsUsage": Array [], +} +`; -exports[`static-entry onPreRenderHTML can be used to replace postBodyComponents 1`] = `"
div3
div2
div1
"`; +exports[`static-entry onPreRenderHTML can be used to replace postBodyComponents 1`] = ` +Object { + "html": "
div3
div2
div1
", + "unsafeBuiltinsUsage": Array [], +} +`; -exports[`static-entry onPreRenderHTML can be used to replace preBodyComponents 1`] = `"
div3
div2
div1
"`; +exports[`static-entry onPreRenderHTML can be used to replace preBodyComponents 1`] = ` +Object { + "html": "
div3
div2
div1
", + "unsafeBuiltinsUsage": Array [], +} +`; diff --git a/packages/gatsby/cache-dir/__tests__/dev-loader.js b/packages/gatsby/cache-dir/__tests__/dev-loader.js index 62ffacb02dac6..0fde1ce6f08dc 100644 --- a/packages/gatsby/cache-dir/__tests__/dev-loader.js +++ b/packages/gatsby/cache-dir/__tests__/dev-loader.js @@ -21,6 +21,10 @@ describe(`Dev loader`, () => { global.__PATH_PREFIX__ = originalPathPrefix }) + const asyncRequires = { + components: {}, + } + describe(`loadPageDataJson`, () => { let xhrCount @@ -63,7 +67,7 @@ describe(`Dev loader`, () => { }) it(`should return a pageData json on success`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) mockPageData(`/mypage`, 200, defaultPayload, true) @@ -78,7 +82,7 @@ describe(`Dev loader`, () => { }) it(`should return a pageData json on success without contentType`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) mockPageData(`/mypage`, 200, defaultPayload) @@ -93,7 +97,7 @@ describe(`Dev loader`, () => { }) it(`should return a pageData json with an empty compilation hash (gatsby develop)`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) const payload = { ...defaultPayload, webpackCompilationHash: `` } mockPageData(`/mypage`, 200, payload) @@ -109,7 +113,7 @@ describe(`Dev loader`, () => { }) it(`should load a 404 page when page-path file is not a gatsby json`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) const payload = { ...defaultPayload, path: `/404.html/` } mockPageData(`/unknown-page`, 200, { random: `string` }, true) @@ -129,7 +133,7 @@ describe(`Dev loader`, () => { }) it(`should load a 404 page when page-path file is not a json`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) const payload = { ...defaultPayload, path: `/404.html/` } mockPageData(`/unknown-page`, 200) @@ -149,7 +153,7 @@ describe(`Dev loader`, () => { }) it(`should load a 404 page when path returns a 404`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) const payload = { ...defaultPayload, path: `/404.html/` } mockPageData(`/unknown-page`, 200) @@ -169,7 +173,7 @@ describe(`Dev loader`, () => { }) it(`should return the dev-404-page when no 404 page can be found`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) const payload = { ...defaultPayload, path: `/dev-404-page/` } mockPageData(`/unknown-page`, 404) @@ -195,7 +199,7 @@ describe(`Dev loader`, () => { }) it(`should return an error when status is 500`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) mockPageData(`/error-page`, 500) @@ -213,7 +217,7 @@ describe(`Dev loader`, () => { }) it(`should retry 3 times before returning an error`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) mockPageData(`/blocked-page`, 0) @@ -232,7 +236,7 @@ describe(`Dev loader`, () => { }) it(`should recover if we get 1 failure`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) const payload = { path: `/blocked-page/`, } @@ -261,7 +265,7 @@ describe(`Dev loader`, () => { }) it(`shouldn't load pageData multiple times`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) mockPageData(`/mypage`, 200, defaultPayload, true) @@ -272,7 +276,7 @@ describe(`Dev loader`, () => { }) describe(`loadPage`, () => { - const createSyncRequires = components => { + const createAsyncRequires = components => { return { components, } @@ -303,10 +307,10 @@ describe(`Dev loader`, () => { }) it(`should be successful when component can be loaded`, async () => { - const syncRequires = createSyncRequires({ - chunk: `instance`, + const asyncRequires = createAsyncRequires({ + chunk: () => Promise.resolve({ default: () => {} }), }) - const devLoader = new DevLoader(syncRequires, []) + const devLoader = new DevLoader(asyncRequires, []) const pageData = { path: `/mypage/`, componentChunkName: `chunk`, @@ -344,10 +348,10 @@ describe(`Dev loader`, () => { }) it(`should set not found on finalResult`, async () => { - const syncRequires = createSyncRequires({ - chunk: `instance`, + const asyncRequires = createAsyncRequires({ + chunk: () => Promise.resolve({ default: () => {} }), }) - const devLoader = new DevLoader(syncRequires, []) + const devLoader = new DevLoader(asyncRequires, []) const pageData = { path: `/mypage/`, componentChunkName: `chunk`, @@ -371,10 +375,10 @@ describe(`Dev loader`, () => { }) it(`should return an error when component cannot be loaded`, async () => { - const syncRequires = createSyncRequires({ + const asyncRequires = createAsyncRequires({ chunk: false, }) - const devLoader = new DevLoader(syncRequires, []) + const devLoader = new DevLoader(asyncRequires, []) const pageData = { path: `/mypage/`, componentChunkName: `chunk`, @@ -394,10 +398,10 @@ describe(`Dev loader`, () => { }) it(`should return an error pageData contains an error`, async () => { - const syncRequires = createSyncRequires({ - chunk: `instance`, + const asyncRequires = createAsyncRequires({ + chunk: () => Promise.resolve({ default: () => {} }), }) - const devLoader = new DevLoader(syncRequires, []) + const devLoader = new DevLoader(asyncRequires, []) const pageData = { path: `/mypage/`, componentChunkName: `chunk`, @@ -416,7 +420,7 @@ describe(`Dev loader`, () => { }) it(`should log an error when 404 cannot be fetched`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) const consoleErrorSpy = jest.spyOn(console, `error`) const defaultXHRMockErrorHandler = XMLHttpRequest.errorCallback mock.error(() => {}) @@ -436,10 +440,10 @@ describe(`Dev loader`, () => { }) it(`should cache the result of loadPage`, async () => { - const syncRequires = createSyncRequires({ - chunk: `instance`, + const asyncRequires = createAsyncRequires({ + chunk: () => Promise.resolve({ default: () => {} }), }) - const devLoader = new DevLoader(syncRequires, []) + const devLoader = new DevLoader(asyncRequires, []) devLoader.loadPageDataJson = jest.fn(() => Promise.resolve({ payload: { @@ -458,14 +462,14 @@ describe(`Dev loader`, () => { describe(`loadPageSync`, () => { it(`returns page resources when already fetched`, () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) devLoader.pageDb.set(`/mypage`, { payload: true }) expect(devLoader.loadPageSync(`/mypage/`)).toBe(true) }) it(`returns page resources when already fetched`, () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) expect(devLoader.loadPageSync(`/mypage/`)).toBeUndefined() }) @@ -475,7 +479,7 @@ describe(`Dev loader`, () => { const flushPromises = () => new Promise(resolve => setImmediate(resolve)) it(`shouldn't prefetch when shouldPrefetch is false`, () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) devLoader.shouldPrefetch = jest.fn(() => false) devLoader.doPrefetch = jest.fn() devLoader.apiRunner = jest.fn() @@ -487,7 +491,7 @@ describe(`Dev loader`, () => { }) it(`should trigger custom prefetch logic when core is disabled`, () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) devLoader.shouldPrefetch = jest.fn(() => true) devLoader.doPrefetch = jest.fn() devLoader.apiRunner = jest.fn() @@ -503,7 +507,7 @@ describe(`Dev loader`, () => { it(`should prefetch when not yet triggered`, async () => { jest.useFakeTimers() - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) devLoader.shouldPrefetch = jest.fn(() => true) devLoader.apiRunner = jest.fn() devLoader.doPrefetch = jest.fn(() => Promise.resolve({})) @@ -526,7 +530,7 @@ describe(`Dev loader`, () => { }) it(`should only run apis once`, async () => { - const devLoader = new DevLoader(null, []) + const devLoader = new DevLoader(asyncRequires, []) devLoader.shouldPrefetch = jest.fn(() => true) devLoader.apiRunner = jest.fn() devLoader.doPrefetch = jest.fn(() => Promise.resolve({})) diff --git a/packages/gatsby/cache-dir/__tests__/error-overlay-handler.js b/packages/gatsby/cache-dir/__tests__/error-overlay-handler.js deleted file mode 100644 index 34a195ef61f87..0000000000000 --- a/packages/gatsby/cache-dir/__tests__/error-overlay-handler.js +++ /dev/null @@ -1,58 +0,0 @@ -const { - reportError, - clearError, - errorMap, -} = require(`../error-overlay-handler`) - -import * as ErrorOverlay from "react-error-overlay" - -jest.mock(`react-error-overlay`, () => { - return { - reportBuildError: jest.fn(), - dismissBuildError: jest.fn(), - startReportingRuntimeErrors: jest.fn(), - setEditorHandler: jest.fn(), - } -}) - -beforeEach(() => { - ErrorOverlay.reportBuildError.mockClear() - ErrorOverlay.dismissBuildError.mockClear() -}) - -describe(`errorOverlayHandler`, () => { - describe(`clearError()`, () => { - beforeEach(() => { - reportError(`foo`, `error`) - reportError(`bar`, `error`) - }) - afterAll(() => { - clearError(`foo`) - clearError(`bar`) - }) - it(`should clear specific error type`, () => { - expect(Object.keys(errorMap)).toHaveLength(2) - clearError(`foo`) - expect(Object.keys(errorMap)).toHaveLength(1) - expect(ErrorOverlay.dismissBuildError).not.toHaveBeenCalled() - }) - - it(`should call ErrorOverlay to dismiss build errors`, () => { - clearError(`foo`) - clearError(`bar`) - expect(ErrorOverlay.dismissBuildError).toHaveBeenCalled() - }) - }) - describe(`reportErrorOverlay()`, () => { - it(`should not add error if it's empty and not call ErrorOverlay`, () => { - reportError(`foo`, null) - expect(Object.keys(errorMap)).toHaveLength(0) - expect(ErrorOverlay.reportBuildError).not.toHaveBeenCalled() - }) - it(`should add error if it has a truthy value and call ErrorOverlay`, () => { - reportError(`foo`, `bar`) - expect(Object.keys(errorMap)).toHaveLength(1) - expect(ErrorOverlay.reportBuildError).toHaveBeenCalled() - }) - }) -}) diff --git a/packages/gatsby/cache-dir/app.js b/packages/gatsby/cache-dir/app.js index 0927b5999202f..3676dd72be5e0 100644 --- a/packages/gatsby/cache-dir/app.js +++ b/packages/gatsby/cache-dir/app.js @@ -9,19 +9,24 @@ import { apiRunner, apiRunnerAsync } from "./api-runner-browser" import { setLoader, publicLoader } from "./loader" import { Indicator } from "./loading-indicator/indicator" import DevLoader from "./dev-loader" -import syncRequires from "$virtual/sync-requires" +import asyncRequires from "$virtual/async-requires" // Generated during bootstrap import matchPaths from "$virtual/match-paths.json" +import { LoadingIndicatorEventHandler } from "./loading-indicator" -if (process.env.GATSBY_HOT_LOADER === `fast-refresh` && module.hot) { - module.hot.accept(`$virtual/sync-requires`, () => { - // Manually reload - }) -} +// ensure in develop we have at least some .css (even if it's empty). +// this is so there is no warning about not matching content-type when site doesn't include any regular css (for example when css-in-js is used) +// this also make sure that if all css is removed in develop we are not left with stale commons.css that have stale content +import "./blank.css" + +// Enable fast-refresh for virtual sync-requires +module.hot.accept(`$virtual/async-requires`, () => { + // Manually reload +}) window.___emitter = emitter -const loader = new DevLoader(syncRequires, matchPaths) +const loader = new DevLoader(asyncRequires, matchPaths) setLoader(loader) loader.setApiRunner(apiRunner) @@ -164,6 +169,23 @@ apiRunnerAsync(`onClientEntry`).then(() => { renderer(, rootElement, () => { apiRunner(`onInitialClientRender`) + + // Render query on demand overlay + if ( + process.env.GATSBY_QUERY_ON_DEMAND_LOADING_INDICATOR && + process.env.GATSBY_QUERY_ON_DEMAND_LOADING_INDICATOR === `true` + ) { + const indicatorMountElement = document.createElement(`div`) + indicatorMountElement.setAttribute( + `id`, + `query-on-demand-indicator-element` + ) + document.body.append(indicatorMountElement) + ReactDOM.render( + , + indicatorMountElement + ) + } }) }) }) diff --git a/packages/gatsby/cache-dir/blank.css b/packages/gatsby/cache-dir/blank.css new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/packages/gatsby/cache-dir/create-react-context.js b/packages/gatsby/cache-dir/create-react-context.js deleted file mode 100644 index 8e4f972d134c0..0000000000000 --- a/packages/gatsby/cache-dir/create-react-context.js +++ /dev/null @@ -1,26 +0,0 @@ -/* - Why commonjs and not ES imports/exports? - - This module is used to alias `create-react-context` package, but drop the the actual implementation part - because Gatsby requires version of react that has implementatoin baked in. - - Package source is using ES modules: - - https://github.com/jamiebuilds/create-react-context/blob/v0.3.0/src/index.js - - But to build this package `babel-plugin-add-module-exports` is used ( https://www.npmjs.com/package/babel-plugin-add-module-exports). - Which result in both `module.exports` and `exports.default` being set to same thing. - - We don't use that babel plugin so we only have `exports.default`. - - This cause problems in various 3rd party react components that rely on `module.exports` being set. - See https://github.com/gatsbyjs/gatsby/issues/23645 for example of it. - - Instead of adding same babel plugin we mimic output here. Adding babel plugin just for this would: - a) unnecesairly slow down compilation for all other files (if we just apply it everywhere) - b) or complicate babel-loader configuration with overwrite specifically for this file -*/ - -const { createContext } = require(`react`) - -module.exports = createContext -module.exports.default = createContext diff --git a/packages/gatsby/cache-dir/dev-loader.js b/packages/gatsby/cache-dir/dev-loader.js index 5f8e84b2fef0f..d3a32968f5c19 100644 --- a/packages/gatsby/cache-dir/dev-loader.js +++ b/packages/gatsby/cache-dir/dev-loader.js @@ -7,6 +7,8 @@ import normalizePagePath from "./normalize-page-path" // TODO move away from lodash import isEqual from "lodash/isEqual" +const preferDefault = m => (m && m.default) || m + function mergePageEntry(cachedPage, newPageData) { return { ...cachedPage, @@ -22,10 +24,14 @@ function mergePageEntry(cachedPage, newPageData) { } class DevLoader extends BaseLoader { - constructor(syncRequires, matchPaths) { + constructor(asyncRequires, matchPaths) { const loadComponent = chunkName => - Promise.resolve(syncRequires.components[chunkName]) - + asyncRequires.components[chunkName] + ? asyncRequires.components[chunkName]() + .then(preferDefault) + // loader will handle the case when component is null + .catch(() => null) + : Promise.resolve() super(loadComponent, matchPaths) const socket = getSocket() diff --git a/packages/gatsby/cache-dir/develop-static-entry.js b/packages/gatsby/cache-dir/develop-static-entry.js index 3b0493a4fed4a..b00d7250a11a8 100644 --- a/packages/gatsby/cache-dir/develop-static-entry.js +++ b/packages/gatsby/cache-dir/develop-static-entry.js @@ -104,12 +104,14 @@ export default ({ pagePath }) => { body: ``, headComponents: headComponents.concat([