Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[WIP] Replace global data.json with page-data.json per page #13004

Closed
wants to merge 44 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
4e6091e
refactor query runner to allow running static/page queries separately
Moocar Mar 24, 2019
071320f
documenting
Moocar Mar 26, 2019
722c45a
Create queue configurations for build/develop
Moocar Mar 27, 2019
8868072
moved page-query-runner to index
Moocar Mar 24, 2019
d7dc21e
move src/internal-plugins/query-runner to src/query
Moocar Mar 27, 2019
6f036a5
add match paths json
Moocar Mar 23, 2019
330b2ba
write page data on query completion
Moocar Mar 24, 2019
034cc78
run page queries after bootstrap
Moocar Mar 25, 2019
9caff6a
use page data instead of data.json
Moocar Mar 25, 2019
d64e6bf
add webpack compilation hash
Moocar Mar 25, 2019
2b1b3c6
use compilation hash to refresh production-app
Moocar Mar 25, 2019
64bd2b5
remove develop-html (use build-html)
Moocar Mar 25, 2019
f3292ff
query-handler -> job handler. And ref ws manager from develop.js
Moocar Mar 25, 2019
738fbb6
invoke dev-404 correctly. Fix loader to handle develop mode
Moocar Mar 26, 2019
854e7b2
post merge fixes
Moocar Mar 28, 2019
54f79eb
only refresh page on compilation hash in production
Moocar Mar 28, 2019
05fe38a
get fetch 404 working
Moocar Mar 28, 2019
76e0b29
serve pages from gatsby develop
Moocar Mar 28, 2019
f35ae9c
404 page is fully working. Introduced loadPage, getPage
Moocar Mar 28, 2019
21aa5b8
bump gatsbygram gatsby version
Moocar Mar 29, 2019
7a12d71
misc fixes
Moocar Mar 30, 2019
ae210a9
fix 404 loader race condition
Moocar Mar 31, 2019
13204aa
add dev loader for 404 pages
Moocar Mar 31, 2019
ae5ddab
deprecate loader functions (getResources...)
Moocar Apr 1, 2019
406f26d
app load pages in parallel
Moocar Apr 1, 2019
21c325e
cleaning up for PR review
Moocar Apr 1, 2019
8a0ed10
remove failed history stuff
Moocar Apr 1, 2019
dcd65ea
cleanup for PR
Moocar Apr 1, 2019
6dd6e1e
standardize staticQueryResult.result
Moocar Apr 1, 2019
6d7504e
dataAndContext => pageData
Moocar Apr 1, 2019
a148f19
add activity back to build html pages
Moocar Apr 1, 2019
ee6a4c8
remove jsonName from Gatsby
Moocar Apr 1, 2019
1ed5e9f
add loadPageDataSync for guess
Moocar Apr 1, 2019
2c9b446
clean up bootstrap
Moocar Apr 1, 2019
ca2b0c4
explicitly save db state post bootstrap and develop
Moocar Apr 1, 2019
2af3786
watch for page deletes during develop
Moocar Apr 1, 2019
4b158e6
move query running out of bootstrap
Moocar Apr 1, 2019
7110cb7
ascertainPort => selectPort
Moocar Apr 1, 2019
2ed38d5
processPageQueries and processStaticQueries
Moocar Apr 1, 2019
8e90225
rewrite compilation hashes when changed
Moocar Apr 1, 2019
227b683
perform page queries before js compilation in develop
Moocar Apr 1, 2019
19fbb00
daemon -> listener
Moocar Apr 1, 2019
bc7118f
minor
Moocar Apr 1, 2019
ce46689
Merge branch 'master' into per-page-manifest2
Moocar Apr 3, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/gatsbygram/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"author": "Kyle Mathews <mathews.kyle@gmail.com>",
"dependencies": {
"core-js": "^2.5.5",
"gatsby": "^2.0.0",
"gatsby": "^2.3.4",
"gatsby-image": "^2.0.5",
"gatsby-plugin-glamor": "^2.0.5",
"gatsby-plugin-google-analytics": "^2.0.5",
Expand Down
20 changes: 2 additions & 18 deletions packages/gatsby-plugin-guess-js/src/gatsby-ssr.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const _ = require(`lodash`)
const nodePath = require(`path`)
const fs = require(`fs`)
const React = require(`react`)

Expand All @@ -12,18 +11,6 @@ function urlJoin(...parts) {
}, ``)
}

let pd = []
const readPageData = () => {
if (pd.length > 0) {
return pd
} else {
pd = JSON.parse(
fs.readFileSync(nodePath.join(process.cwd(), `.cache`, `data.json`))
)
return pd
}
}

let s
const readStats = () => {
if (s) {
Expand All @@ -37,19 +24,16 @@ const readStats = () => {
}

exports.onRenderBody = (
{ setHeadComponents, pathname, pathPrefix },
{ setHeadComponents, pathname, pathPrefix, loadPageDataSync },
pluginOptions
) => {
if (process.env.NODE_ENV === `production`) {
const pagesData = readPageData()
const stats = readStats()
const matchedPaths = Object.keys(
guess({ path: pathname, threshold: pluginOptions.minimumThreshold })
)
if (!_.isEmpty(matchedPaths)) {
const matchedPages = matchedPaths.map(match =>
_.find(pagesData.pages, page => page.path === match)
)
const matchedPages = matchedPaths.map(loadPageDataSync)
let componentUrls = []
matchedPages.forEach(p => {
if (p && p.componentChunkName) {
Expand Down
22 changes: 5 additions & 17 deletions packages/gatsby-plugin-offline/src/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
exports.registerServiceWorker = () => true

const prefetchedPathnames = []
const prefetchedResources = []
const whitelistedPathnames = []

exports.onServiceWorkerActive = ({
getResourceURLsForPathname,
serviceWorker,
}) => {
exports.onServiceWorkerActive = ({ serviceWorker }) => {
// if the SW has just updated then reset whitelisted paths and don't cache
// stuff, since we're on the old revision until we navigate to another page
if (window.___swUpdated) {
Expand All @@ -26,15 +23,6 @@ exports.onServiceWorkerActive = ({
.call(nodes)
.map(node => node.src || node.href || node.getAttribute(`data-href`))

// Loop over all resources and fetch the page component and JSON
// to add it to the sw cache.
const prefetchedResources = []
prefetchedPathnames.forEach(path =>
getResourceURLsForPathname(path).forEach(resource =>
prefetchedResources.push(resource)
)
)

const resources = [...headerResources, ...prefetchedResources]
resources.forEach(resource => {
// Create a prefetch link for each resource, so Workbox runtime-caches them
Expand Down Expand Up @@ -69,12 +57,12 @@ function whitelistPathname(pathname, includesPrefix) {
}
}

exports.onPostPrefetchPathname = ({ pathname }) => {
exports.onPostPrefetch = ({ path, resourceUrls }) => {
// do nothing if the SW has just updated, since we still have old pages in
// memory which we don't want to be whitelisted
if (window.___swUpdated) return

whitelistPathname(pathname, false)
whitelistPathname(path, false)

// if SW is not installed, we need to record any prefetches
// that happen so we can then add them to SW cache once installed
Expand All @@ -85,6 +73,6 @@ exports.onPostPrefetchPathname = ({ pathname }) => {
navigator.serviceWorker.controller.state === `activated`
)
) {
prefetchedPathnames.push(pathname)
Array.prototype.push.apply(prefetchedResources, resourceUrls)
}
}
5 changes: 0 additions & 5 deletions packages/gatsby/cache-dir/__tests__/find-page.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,19 @@ describe(`find-page`, () => {
{
path: `/about/`,
componentChunkName: `page-component---src-pages-test-js`,
jsonName: `about.json`,
},
{
path: `/about/me/`,
componentChunkName: `page-component---src-pages-test-js`,
jsonName: `about-me.json`,
},
{
path: `/about/the best/`,
componentChunkName: `page-component---src-pages-test-js`,
jsonName: `the-best.json`,
},
{
path: `/app/`,
matchPath: `/app/*`,
componentChunkName: `page-component---src-pages-app-js`,
jsonName: `app.json`,
},
]
findPage = pageFinderFactory(newPages)
Expand Down Expand Up @@ -58,7 +54,6 @@ describe(`find-page`, () => {
{
path: `/about/`,
componentChunkName: `page-component---src-pages-test-js`,
jsonName: `about.json`,
},
]
const findPage2 = pageFinderFactory(newPages, `/my-test-prefix`)
Expand Down
23 changes: 0 additions & 23 deletions packages/gatsby/cache-dir/__tests__/static-entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,6 @@ jest.mock(
}
)

jest.mock(
`../data.json`,
() => {
return {
dataPaths: [
{
[`about.json`]: `/400/about`,
},
],
pages: [
{
path: `/about/`,
componentChunkName: `page-component---src-pages-test-js`,
jsonName: `about.json`,
},
],
}
},
{
virtual: true,
}
)

const MOCK_FILE_INFO = {
[`${process.cwd()}/public/webpack.stats.json`]: `{}`,
[`${process.cwd()}/public/chunk-map.json`]: `{}`,
Expand Down
7 changes: 7 additions & 0 deletions packages/gatsby/cache-dir/api-runner-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const {
getResourcesForPathname,
getResourcesForPathnameSync,
getResourceURLsForPathname,
loadPage,
getPage,
} = require(`./loader`).publicLoader

exports.apiRunner = (api, args = {}, defaultReturn, argTransform) => {
Expand All @@ -22,9 +24,14 @@ exports.apiRunner = (api, args = {}, defaultReturn, argTransform) => {
return undefined
}

// Deprecated April 2019. Use `getPage` instead
args.getResourcesForPathnameSync = getResourcesForPathnameSync
// Deprecated April 2019. Use `loadPage` instead
args.getResourcesForPathname = getResourcesForPathname
// Deprecated April 2019. Use resources passed in `onPostPrefetch` instead
args.getResourceURLsForPathname = getResourceURLsForPathname
args.loadPage = loadPage
args.getPage = getPage

const result = plugin.plugin[api](args, plugin.options)
if (result && argTransform) {
Expand Down
29 changes: 18 additions & 11 deletions packages/gatsby/cache-dir/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import domReady from "@mikaelkristiansson/domready"
import socketIo from "./socketIo"
import emitter from "./emitter"
import { apiRunner, apiRunnerAsync } from "./api-runner-browser"
import loader, { setApiRunnerForLoader, postInitialRenderWork } from "./loader"
import loader, { setApiRunnerForLoader } from "./loader"
import devLoader from "./dev-loader"
import syncRequires from "./sync-requires"
import pages from "./pages.json"

window.___emitter = emitter
setApiRunnerForLoader(apiRunner)
Expand Down Expand Up @@ -46,19 +46,26 @@ apiRunnerAsync(`onClientEntry`).then(() => {
ReactDOM.render
)[0]

loader.addPagesArray(pages)
loader.addDevRequires(syncRequires)

loader.getResourcesForPathname(window.location.pathname).then(() => {
const preferDefault = m => (m && m.default) || m
let Root = preferDefault(require(`./root`))
domReady(() => {
renderer(<Root />, rootElement, () => {
postInitialRenderWork()
apiRunner(`onInitialClientRender`)
Promise.all([
loader.loadPage(window.location.pathname),
loader.loadPage(`/dev-404-page/`),
loader.loadPage(`/404.html`).catch(err => null),
devLoader.loadPages(),
])
.then(() => {
const preferDefault = m => (m && m.default) || m
let Root = preferDefault(require(`./root`))
domReady(() => {
renderer(<Root />, rootElement, () => {
apiRunner(`onInitialClientRender`)
})
})
})
})
.catch(err => {
console.log(err)
})
})

function supportsServiceWorkers(location, navigator) {
Expand Down
49 changes: 49 additions & 0 deletions packages/gatsby/cache-dir/dev-loader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Initialized by calling loadPages
let pagesManifest = null

const fetchPages = () =>
new Promise((resolve, reject) => {
const req = new XMLHttpRequest()
req.open(`GET`, `/___pages`, true)
req.onreadystatechange = () => {
if (req.readyState == 4) {
if (req.status === 200) {
// TODO is this safe? Maybe just do this check in dev mode?
const contentType = req.getResponseHeader(`content-type`)
if (!contentType || !contentType.startsWith(`application/json`)) {
reject()
} else {
resolve(JSON.parse(req.responseText))
}
} else {
reject()
}
}
}
req.send(null)
})

// Returns a promise that fetches the `/___pages` resource from the
// running `gatsby develop` server. It contains a map of all pages on
// the site (path -> page). Call `getPagesManifest()` to retrieve the
// pages. Used by dev-404-page to present a list of all pages
const loadPages = () =>
fetchPages().then(pages => {
pagesManifest = pages
})

// Returns the map of all pages on the site (path -> page)
const getPagesManifest = () => {
if (pagesManifest === null) {
throw new Error(
`pages-manifest hasn't been initialized. Ensure the dev-loader/loadPages has been called first`
)
} else {
return pagesManifest
}
}

module.exports = {
loadPages,
getPagesManifest,
}
10 changes: 4 additions & 6 deletions packages/gatsby/cache-dir/ensure-resources.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class EnsureResources extends React.Component {

this.state = {
location: { ...location },
pageResources: loader.getResourcesForPathnameSync(location.pathname),
pageResources: loader.getPageOr404(location.pathname),
}
}

Expand All @@ -34,9 +34,7 @@ class EnsureResources extends React.Component {

static getDerivedStateFromProps({ location }, prevState) {
if (prevState.location !== location) {
const pageResources = loader.getResourcesForPathnameSync(
location.pathname
)
const pageResources = loader.getPageOr404(location.pathname)

return {
pageResources,
Expand All @@ -62,15 +60,15 @@ class EnsureResources extends React.Component {
retryResources(nextProps) {
const { pathname } = nextProps.location

if (!loader.getResourcesForPathnameSync(pathname)) {
if (!loader.getPage(pathname)) {
// Store the previous and next location before resolving resources
const prevLocation = this.props.location
this.nextLocation = nextProps.location

// Page resources won't be set in cases where the browser back button
// or forward button is pushed as we can't wait as normal for resources
// to load before changing the page.
loader.getResourcesForPathname(pathname).then(pageResources => {
loader.loadPage(pathname).then(pageResources => {
// The page may have changed since we started this, in which case doesn't update
if (this.nextLocation !== nextProps.location) {
return
Expand Down
55 changes: 0 additions & 55 deletions packages/gatsby/cache-dir/find-page.js

This file was deleted.

Loading