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

SSR and Serverless experiments [DO NOT MERGE] #812

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion greenwood.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ const FAVICON_HREF = '/assets/favicon.ico';

module.exports = {
workspace: path.join(__dirname, 'www'),
mode: 'mpa',
mode: 'ssr',
prerender: false,
optimization: 'inline',
title: 'Greenwood',
meta: [
Expand Down
1 change: 1 addition & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"bin": {
"greenwood": "./src/index.js"
},
"main": "./src/index.js",
"files": [
"src/"
],
Expand Down
9 changes: 5 additions & 4 deletions packages/cli/src/commands/serve.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const generateCompilation = require('../lifecycles/compile');
const { prodServer } = require('../lifecycles/serve');
const { staticServer, hybridServer } = require('../lifecycles/serve');

module.exports = runProdServer = async () => {

Expand All @@ -8,9 +8,10 @@ module.exports = runProdServer = async () => {
try {
const compilation = await generateCompilation();
const port = 8080;

prodServer(compilation).listen(port, () => {
console.info(`Started production test server at localhost:${port}`);
const server = compilation.config.mode === 'ssr' ? hybridServer : staticServer;

server(compilation).listen(port, () => {
console.info(`Started server at localhost:${port}`);
});
} catch (err) {
reject(err);
Expand Down
52 changes: 43 additions & 9 deletions packages/cli/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ program
command = cmd._name;
});

program
.command('serverless')
.description('Build a one off route and return the HTML.')
.action((cmd) => {
command = cmd._name;
});


program
.command('develop')
.description('Start a local development server.')
Expand Down Expand Up @@ -60,24 +68,24 @@ if (program.parse.length === 0) {
program.help();
}

const run = async() => {
const run = async() => {
try {
console.info(`Running Greenwood with the ${command} command.`);
process.env.__GWD_COMMAND__ = command;

switch (command) {

case 'build':
case 'build':
await runProductionBuild();

break;
case 'develop':
await runDevServer();

break;
case 'serve':
process.env.__GWD_COMMAND__ = 'build';

await runProductionBuild();
await runProdServer();

Expand All @@ -86,20 +94,46 @@ const run = async() => {
await ejectConfiguration();

break;
default:
default:
console.warn(`
Error: not able to detect command. try using the --help flag if
you're encountering issues running Greenwood. Visit our docs for more
Error: not able to detect command. try using the --help flag if
you're encountering issues running Greenwood. Visit our docs for more
info at https://www.greenwoodjs.io/docs/.
`);
break;

}
process.exit(0); // eslint-disable-line no-process-exit

} catch (err) {
console.error(err);
process.exit(1); // eslint-disable-line no-process-exit
}
};

run();
if (command === 'serverless') {
Copy link
Member Author

@thescientist13 thescientist13 Nov 9, 2022

Choose a reason for hiding this comment

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

Maybe this would be helpful for detecting if run from JS or run from the CLI; import.meta.main - https://github.com/nodejs/modules/issues/274#issuecomment-1302971322

process.env.__GWD_COMMAND__ = 'serverless';
} else {
run();
}

async function buildRoute(route) {
const compilation = await generateCompilation();

return `
<html>
<head>
<title>Greenwood The Edge - ${route}</title>
</head>
<body>
<h1>HTML from AWS Lambda</h1>
<pre>
${JSON.stringify(compilation)}
</pre>
</body>
</html>
`.replace(/\n/g, '');
}

module.exports = {
buildRoute
};
2 changes: 1 addition & 1 deletion packages/cli/src/lib/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* Wraps Puppeteer's interface to Headless Chrome to expose high level rendering
* APIs that are able to handle web components and PWAs.
*/
const puppeteer = require('puppeteer');
// const puppeteer = require('puppeteer');

class BrowserRunner {

Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/lifecycles/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const greenwoodPlugins = [
};
});

const modes = ['ssg', 'mpa', 'spa'];
const modes = ['ssg', 'mpa', 'spa', 'ssr'];
const optimizations = ['default', 'none', 'static', 'inline'];
const pluginTypes = ['copy', 'context', 'resource', 'rollup', 'server'];
const defaultConfig = {
Expand All @@ -43,6 +43,7 @@ const defaultConfig = {
markdown: { plugins: [], settings: {} },
prerender: true,
pagesDirectory: 'pages',
routesDirectory: 'routes',
templatesDirectory: 'templates'
};

Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/lifecycles/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ module.exports = initContexts = async({ config }) => {
const projectDirectory = process.cwd();
const userWorkspace = path.join(config.workspace);
const pagesDir = path.join(userWorkspace, `${config.pagesDirectory}/`);
const routesDir = path.join(userWorkspace, `${config.routesDirectory}/`);
const userTemplatesDir = path.join(userWorkspace, `${config.templatesDirectory}/`);

const context = {
dataDir,
outputDir,
userWorkspace,
pagesDir,
routesDir,
userTemplatesDir,
scratchDir,
projectDirectory
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/lifecycles/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ module.exports = generateGraph = async (compilation) => {
await fs.promises.mkdir(context.scratchDir);
}

await fs.promises.writeFile(`${context.scratchDir}/graph.json`, JSON.stringify(compilation.graph));
// serverless (Lambda) doesnt like writing to files
// await fs.promises.writeFile(`${context.scratchDir}/graph.json`, JSON.stringify(compilation.graph));

resolve(compilation);
} catch (err) {
Expand Down
56 changes: 48 additions & 8 deletions packages/cli/src/lifecycles/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ function getDevServer(compilation) {
return app;
}

function getProdServer(compilation) {
function getStaticServer(compilation, composable) {
const app = new Koa();
const standardResources = compilation.config.plugins.filter((plugin) => {
// html is intentionally omitted
Expand All @@ -141,16 +141,20 @@ function getProdServer(compilation) {
const { mode } = compilation.config;
const url = ctx.request.url.replace(/\?(.*)/, ''); // get rid of things like query string parameters

// only handle static output routes, eg. public/about.html
if (url.endsWith('/') || url.endsWith('.html')) {
const barePath = mode === 'spa'
? 'index.html'
: url.endsWith('/')
? path.join(url, 'index.html')
: url;
const contents = await fs.promises.readFile(path.join(outputDir, barePath), 'utf-8');

ctx.set('content-type', 'text/html');
ctx.body = contents;

if (fs.existsSync(path.join(outputDir, barePath))) {
const contents = await fs.promises.readFile(path.join(outputDir, barePath), 'utf-8');

ctx.set('content-type', 'text/html');
ctx.body = contents;
}
}

await next();
Expand All @@ -174,7 +178,7 @@ function getProdServer(compilation) {
await next();
});

app.use(async (ctx) => {
app.use(async (ctx, next) => {
const responseAccumulator = {
body: ctx.body,
contentType: ctx.response.header['content-type']
Expand Down Expand Up @@ -207,12 +211,48 @@ function getProdServer(compilation) {

ctx.set('content-type', reducedResponse.contentType);
ctx.body = reducedResponse.body;

if (composable) {
await next();
}
});

return app;
}

function getHybridServer(compilation) {
const app = getStaticServer(compilation, true);

app.use(async (ctx, next) => {
const { routesDir } = compilation.context;
const { mode } = compilation.config;
const url = ctx.request.url.replace(/\?(.*)/, ''); // get rid of things like query string parameters

if (url.endsWith('/') && mode === 'ssr') {
if (fs.existsSync(path.join(routesDir, `${url.replace(/\//g, '')}.js`))) {
const standardHtmlResource = compilation.config.plugins.filter((plugin) => {
// html is intentionally omitted
return plugin.isGreenwoodDefaultPlugin
&& plugin.type === 'resource'
&& plugin.name.indexOf('plugin-standard-html') === 0;
}).map((plugin) => {
return plugin.provider(compilation);
})[0];
const response = await standardHtmlResource.serve(url);

ctx.status = 200;
ctx.set('content-type', response.contentType);
ctx.body = response.body;
}
};
});

return app;
}


module.exports = {
devServer: getDevServer,
prodServer: getProdServer
};
staticServer: getStaticServer,
hybridServer: getHybridServer
}
27 changes: 23 additions & 4 deletions packages/cli/src/plugins/resource/plugin-standard-html.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,12 @@ class StandardHtmlResource extends ResourceInterface {
}

async shouldServe(url, headers) {
const { pagesDir } = this.compilation.context;
const { pagesDir, routesDir } = this.compilation.context;
const relativeUrl = this.getRelativeUserworkspaceUrl(url);
const isClientSideRoute = this.compilation.config.mode === 'spa' && path.extname(url) === '' && (headers.request.accept || '').indexOf(this.contentType) >= 0;
const isServerSideRoute = this.compilation.config.mode === 'ssr' && path.extname(url) === ''
&& (headers.request.accept || '').indexOf(this.contentType) >= 0
&& fs.existsSync(path.join(routesDir, `${url.replace(/\//g, '')}.js`));
const barePath = relativeUrl.endsWith(path.sep)
? `${pagesDir}${relativeUrl}index`
: `${pagesDir}${relativeUrl.replace('.html', '')}`;
Expand All @@ -325,14 +328,15 @@ class StandardHtmlResource extends ResourceInterface {
|| path.extname(relativeUrl) === '') && (fs.existsSync(`${barePath}.html`) || barePath.substring(barePath.length - 5, barePath.length) === 'index')
|| fs.existsSync(`${barePath}.md`)
|| fs.existsSync(`${barePath.substring(0, barePath.lastIndexOf(`${path.sep}index`))}.md`)
|| isClientSideRoute;
|| isClientSideRoute
|| isServerSideRoute;
}

async serve(url) {
return new Promise(async (resolve, reject) => {
try {
const config = Object.assign({}, this.compilation.config);
const { pagesDir, userTemplatesDir, userWorkspace } = this.compilation.context;
const { pagesDir, routesDir, userTemplatesDir, userWorkspace } = this.compilation.context;
const { mode } = this.compilation.config;
const normalizedUrl = this.getRelativeUserworkspaceUrl(url);
const userHasOwn404 = fs.existsSync(path.join(userWorkspace, 'pages/404.html')) || fs.existsSync(path.join(userWorkspace, 'pages/404.md'));
Expand All @@ -349,6 +353,7 @@ class StandardHtmlResource extends ResourceInterface {
const isMarkdownContent = fs.existsSync(`${barePath}.md`)
|| fs.existsSync(`${barePath.substring(0, barePath.lastIndexOf(`${path.sep}index`))}.md`)
|| fs.existsSync(`${barePath.replace(`${path.sep}index`, '.md')}`);
const isServerSideRoute = this.compilation.config.mode === 'ssr' && fs.existsSync(path.join(routesDir, `${url.replace(/\//g, '')}.js`));

if (isMarkdownContent) {
const markdownPath = fs.existsSync(`${barePath}.md`)
Expand Down Expand Up @@ -410,7 +415,21 @@ class StandardHtmlResource extends ResourceInterface {
if (mode === 'spa') {
body = fs.readFileSync(this.compilation.graph[0].path, 'utf-8');
} else {
body = getPageTemplate(barePath, userTemplatesDir, template, contextPlugins, pagesDir);
if (isServerSideRoute) {
const routeLocation = path.join(routesDir, `${url.replace(/\//g, '')}.js`);

if (process.env.__GWD_COMMAND__ === 'develop') { // eslint-disable-line no-underscore-dangle
delete require.cache[routeLocation];
}

const { getTemplate } = require(path.join(routesDir, `${url.replace(/\//g, '')}.js`));

if (getTemplate) {
body = await getTemplate();
}
} else {
body = getPageTemplate(barePath, userTemplatesDir, template, contextPlugins, pagesDir);
}
}

body = getAppTemplate(body, userTemplatesDir, customImports, contextPlugins, config.devServer.hud);
Expand Down
Loading