Skip to content

Commit

Permalink
refactoring pagePath to pageHref
Browse files Browse the repository at this point in the history
  • Loading branch information
thescientist13 committed Sep 21, 2024
1 parent ce9109f commit d1e1ce7
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 36 deletions.
12 changes: 5 additions & 7 deletions packages/cli/src/config/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -353,8 +353,9 @@ function greenwoodImportMetaUrl(compilation) {
if (`${compilation.context.apisDir.pathname}${idAssetName}`.indexOf(normalizedId) >= 0) {
for (const entry of compilation.manifest.apis.keys()) {
const apiRoute = compilation.manifest.apis.get(entry);
const pagePath = new URL(apiRoute.pageHref).pathname.replace(`${compilation.context.pagesDir}/api/`, '');

if (normalizedId.endsWith(apiRoute.pagePath.replace('.', ''))) {
if (normalizedId.endsWith(pagePath)) {
const assets = apiRoute.assets || [];

assets.push(assetUrl.url.href);
Expand Down Expand Up @@ -643,16 +644,13 @@ const getRollupConfigForBrowserScripts = async (compilation) => {
};

const getRollupConfigForApiRoutes = async (compilation) => {
const { outputDir, pagesDir } = compilation.context;
const { outputDir } = compilation.context;

return [...compilation.manifest.apis.values()]
.map((api) => {
const { id, pagePath } = api;
const { id, pageHref } = api;

return {
id,
inputPath: normalizePathnameForWindows(new URL(pagePath, pagesDir))
};
return { id, inputPath: normalizePathnameForWindows(new URL(pageHref)) };
})
.map(({ id, inputPath }) => {
return {
Expand Down
13 changes: 6 additions & 7 deletions packages/cli/src/lib/layout-utils.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
/* eslint-disable complexity */
import fs from 'fs/promises';
import htmlparser from 'node-html-parser';
import { checkResourceExists } from './resource-utils.js';
import { Worker } from 'worker_threads';

async function getCustomPageLayoutsFromPlugins(compilation, layoutName) {
// TODO confirm context plugins work for SSR
// TODO support context plugins for more than just HTML files
const contextPlugins = compilation.config.plugins.filter((plugin) => {
return plugin.type === 'context';
}).map((plugin) => {
Expand All @@ -30,10 +29,10 @@ async function getCustomPageLayoutsFromPlugins(compilation, layoutName) {
return customLayoutLocations;
}

async function getPageLayout(filePath = '', compilation, layout) {
async function getPageLayout(pageHref = '', compilation, layout) {
const { config, context } = compilation;
const { layoutsDir, userLayoutsDir, pagesDir } = context;
const filePathUrl = new URL(filePath, pagesDir);
const filePathUrl = pageHref && pageHref !== '' ? new URL(pageHref) : pageHref;
const customPageFormatPlugins = config.plugins
.filter(plugin => plugin.type === 'resource' && !plugin.isGreenwoodDefaultPlugin)
.map(plugin => plugin.provider(compilation));
Expand All @@ -43,13 +42,13 @@ async function getPageLayout(filePath = '', compilation, layout) {
&& await customPageFormatPlugins[0].shouldServe(filePathUrl);
const customPluginDefaultPageLayouts = await getCustomPageLayoutsFromPlugins(compilation, 'page');
const customPluginPageLayouts = await getCustomPageLayoutsFromPlugins(compilation, layout);
const extension = filePath?.split('.')?.pop();
const is404Page = filePath?.endsWith('404.html') && extension === 'html';
const extension = pageHref?.split('.')?.pop();
const is404Page = pageHref?.endsWith('404.html') && extension === 'html';
const hasCustomStaticLayout = await checkResourceExists(new URL(`./${layout}.html`, userLayoutsDir));
const hasCustomDynamicLayout = await checkResourceExists(new URL(`./${layout}.js`, userLayoutsDir));
const hasPageLayout = await checkResourceExists(new URL('./page.html', userLayoutsDir));
const hasCustom404Page = await checkResourceExists(new URL('./404.html', pagesDir));
const isHtmlPage = extension === 'html' && await checkResourceExists(new URL(filePath, pagesDir));
const isHtmlPage = extension === 'html' && await checkResourceExists(new URL(pageHref));
let contents;

if (layout && (customPluginPageLayouts.length > 0 || hasCustomStaticLayout)) {
Expand Down
11 changes: 6 additions & 5 deletions packages/cli/src/lifecycles/bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,13 +243,13 @@ async function bundleSsrPages(compilation, optimizePlugins) {
// and before we optimize so that all bundled assets can tracked up front
// would be nice to see if this can be done in a single pass though...
for (const page of ssrPages) {
const { imports, route, layout, pagePath } = page;
const moduleUrl = new URL(pagePath, pagesDir);
const { imports, route, layout, pageHref } = page;
const moduleUrl = new URL(pageHref);
const request = new Request(moduleUrl);
const data = await executeRouteModule({ moduleUrl, compilation, page, prerender: false, htmlContents: null, scripts: [], request });
let staticHtml = '';

staticHtml = data.layout ? data.layout : await getPageLayout(pagePath, compilation, layout);
staticHtml = data.layout ? data.layout : await getPageLayout(pageHref, compilation, layout);
staticHtml = await getAppLayout(staticHtml, compilation, imports, page);
staticHtml = await getUserScripts(staticHtml, compilation);
staticHtml = await (await interceptPage(new URL(`http://localhost:8080${route}`), new Request(new URL(`http://localhost:8080${route}`)), getPluginInstances(compilation), staticHtml)).text();
Expand All @@ -266,8 +266,9 @@ async function bundleSsrPages(compilation, optimizePlugins) {

// second pass to link all bundled assets to their resources before optimizing and generating SSR bundles
for (const page of ssrPages) {
const { id, route, pagePath } = page;
const entryFileUrl = new URL(pagePath, pagesDir);
const { id, route, pageHref } = page;
const pagePath = new URL(pageHref).pathname.replace(pagesDir.pathname, './');
const entryFileUrl = new URL(pageHref);
const entryFileOutputUrl = new URL(`file://${entryFileUrl.pathname.replace(pagesDir.pathname, scratchDir.pathname)}`);
const outputPathRootUrl = new URL(`file://${path.dirname(entryFileOutputUrl.pathname)}/`);
const htmlOptimizer = config.plugins.find(plugin => plugin.name === 'plugin-standard-html').provider(compilation);
Expand Down
15 changes: 7 additions & 8 deletions packages/cli/src/lifecycles/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ const generateGraph = async (compilation) => {
let graph = [{
id: 'index',
outputPath: '/index.html',
pagePath: './index.html',
route: `${basePath}/`,
label: 'Home',
title: null,
Expand Down Expand Up @@ -107,14 +106,14 @@ const generateGraph = async (compilation) => {
* API Properties (per route)
*----------------------
* id: unique hyphen delimited string of the filename, relative to the page/api directory
* pagePath: path to the page file relative to context.pagesDirectory
* pageHref: href to the page's filesystem file
* outputPath: the filename to write to when generating a build
* route: URL route for a given page on outputFilePath
* isolation: if this should be run in isolated mode
*/
apiRoutes.set(`${basePath}${route}`, {
id: getIdFromRelativePathPath(relativePagePath, `.${extension}`).replace('api-', ''),
pagePath: relativePagePath,
pageHref: new URL(relativePagePath, pagesDir).href,
outputPath: relativePagePath,
route: `${basePath}${route}`,
isolation
Expand Down Expand Up @@ -256,7 +255,7 @@ const generateGraph = async (compilation) => {
* imports: per page JS or CSS file imports specified from frontmatter
* resources: all script, style, etc resources for the entire page as URLs
* outputPath: the name of the file in the output folder
* pagePath: path to the page file relative to context.pagesDirectory
* pageHref: href to the page's filesystem file
* isSSR: if this is a server side route
* prerender: if this page should be statically exported
* isolation: if this page should be run in isolated mode
Expand All @@ -272,7 +271,7 @@ const generateGraph = async (compilation) => {
data: customData || {},
imports,
resources: [],
pagePath: relativePagePath,
pageHref: new URL(relativePagePath, pagesDir).href,
outputPath: route === '/404/'
? '/404.html'
: `${route}index.html`,
Expand Down Expand Up @@ -312,7 +311,7 @@ const generateGraph = async (compilation) => {
if (await checkResourceExists(new URL('./index.html', userWorkspace))) {
graph = [{
...graph[0],
path: `${userWorkspace.pathname}index.html`,
pageHref: new URL('./index.html', userWorkspace).href,
isSPA: true
}];
} else {
Expand All @@ -337,7 +336,7 @@ const generateGraph = async (compilation) => {
...oldGraph,
id: '404',
outputPath: '/404.html',
pagePath: './404.html',
pageHref: new URL('./404.html', pagesDir).href,
route: `${basePath}/404/`,
path: '404.html',
label: 'Not Found',
Expand All @@ -363,7 +362,7 @@ const generateGraph = async (compilation) => {
}

graph.push({
pagePath: null,
pageHref: null,
data: {},
imports: [],
resources: [],
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/plugins/resource/plugin-api-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ApiRoutesResource extends ResourceInterface {

async serve(url, request) {
const api = this.compilation.manifest.apis.get(url.pathname);
const apiUrl = new URL(api.pagePath, this.compilation.context.pagesDir);
const apiUrl = new URL(api.pageHref);
const href = apiUrl.href;

if (process.env.__GWD_COMMAND__ === 'develop') { // eslint-disable-line no-underscore-dangle
Expand Down
14 changes: 7 additions & 7 deletions packages/cli/src/plugins/resource/plugin-standard-html.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ class StandardHtmlResource extends ResourceInterface {

async serve(url, request) {
const { config, context } = this.compilation;
const { userWorkspace, pagesDir } = context;
const { userWorkspace } = context;
const { activeFrontmatter } = config;
const { pathname } = url;
const isSpaRoute = this.compilation.graph.find(node => node.isSPA);
const matchingRoute = this.compilation.graph.find((node) => node.route === pathname) || {};
const { pagePath } = matchingRoute;
const filePath = !matchingRoute.external ? pagePath : '';
const { pageHref } = matchingRoute;
const filePath = !matchingRoute.external && pageHref ? new URL(pageHref).pathname.replace(userWorkspace.pathname, './') : '';
const isMarkdownContent = (filePath || '').split('.').pop() === 'md';
let body = '';
let layout = matchingRoute.layout || null;
Expand All @@ -56,7 +56,7 @@ class StandardHtmlResource extends ResourceInterface {
}

if (isMarkdownContent) {
const markdownContents = await fs.readFile(new URL(pagePath, pagesDir), 'utf-8');
const markdownContents = await fs.readFile(new URL(pageHref), 'utf-8');
const rehypePlugins = [];
const remarkPlugins = [];

Expand Down Expand Up @@ -84,7 +84,7 @@ class StandardHtmlResource extends ResourceInterface {
}

if (matchingRoute.isSSR) {
const routeModuleLocationUrl = new URL(pagePath, pagesDir);
const routeModuleLocationUrl = new URL(pageHref);
const routeWorkerUrl = this.compilation.config.plugins.find(plugin => plugin.type === 'renderer').provider().executeModuleUrl;

await new Promise(async (resolve, reject) => {
Expand Down Expand Up @@ -118,9 +118,9 @@ class StandardHtmlResource extends ResourceInterface {
}

if (isSpaRoute) {
body = await fs.readFile(new URL(isSpaRoute.pagePath, userWorkspace), 'utf-8');
body = await fs.readFile(new URL(isSpaRoute.pageHref), 'utf-8');
} else {
body = ssrLayout ? ssrLayout : await getPageLayout(pagePath, this.compilation, layout);
body = ssrLayout ? ssrLayout : await getPageLayout(pageHref, this.compilation, layout);
}

body = await getAppLayout(body, this.compilation, customImports, matchingRoute);
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/plugins/resource/plugin-static-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class StaticRouterResource extends ResourceInterface {
.filter(page => !page.isSSR)
.filter(page => !page.route.endsWith('/404/'))
.map((page) => {
const layout = page.pagePath && page.pagePath.split('.').pop() === this.extensions[0]
const layout = page.pageHref && page.pageHref.split('.').pop() === this.extensions[0]
? page.route
: page.layout;
const key = page.route === '/'
Expand Down

0 comments on commit d1e1ce7

Please sign in to comment.