Skip to content
This repository has been archived by the owner on May 17, 2019. It is now read-only.

Commit

Permalink
Migrate to DI
Browse files Browse the repository at this point in the history
  • Loading branch information
ganemone authored and fusion-bot[bot] committed Jan 22, 2018
1 parent 3725f89 commit 9ee814a
Show file tree
Hide file tree
Showing 16 changed files with 215 additions and 229 deletions.
25 changes: 14 additions & 11 deletions entries/server-entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@
import http from 'http';
// eslint-disable-next-line import/no-unresolved, import/no-extraneous-dependencies
import main from '__FRAMEWORK_SHARED_ENTRY__';
import CompilationMetaDataFactory from '../plugins/compilation-metadata-plugin';
import getCompilationMetaData from '../plugins/compilation-metadata-plugin';
import AssetsFactory from '../plugins/assets-plugin';
import ContextFactory from '../plugins/context-plugin';
import ServerErrorFactory from '../plugins/server-error-plugin';
import ContextPlugin from '../plugins/context-plugin';
import ServerErrorPlugin from '../plugins/server-error-plugin';

const CompilationMetaData = CompilationMetaDataFactory();
let Assets;
const Context = ContextFactory();
const ServerErrorHandling = ServerErrorFactory();
let AssetsPlugin;

/*
Webpack has a configuration option called `publicPath`, which determines the
Expand All @@ -31,7 +28,7 @@ Webpack compiles the `__webpack_public_path__ = ...` assignment expression
into `__webpack_require__.p = ...` and uses it for HMR manifest requests
*/
// eslint-disable-next-line
__webpack_public_path__ = CompilationMetaData.of().webpackPublicPath + '/';
__webpack_public_path__ = getCompilationMetaData().webpackPublicPath + '/';

const state = {serve: null};
const initialize = main
Expand All @@ -41,7 +38,7 @@ const initialize = main
};

export async function start({port, dir = '.'}) {
Assets = AssetsFactory(dir);
AssetsPlugin = AssetsFactory(dir);
await reload();

// TODO(#21): support https.createServer(credentials, listener);
Expand All @@ -61,14 +58,20 @@ export async function start({port, dir = '.'}) {

async function reload() {
const app = await initialize();
app.plugins = [Assets, Context].concat(app.plugins);
reverseRegister(app, AssetsPlugin);
reverseRegister(app, ContextPlugin);
if (__DEV__) {
app.plugins.unshift(ServerErrorHandling);
reverseRegister(app, ServerErrorPlugin);
}
state.serve = app.callback();
state.app = app;
}

function reverseRegister(app, token, plugin) {
app.register(token, plugin);
app.plugins.unshift(app.plugins.pop());
}

if (module.hot) {
module.hot.accept('__FRAMEWORK_SHARED_ENTRY__', reload);
module.hot.accept('__SECRET_BUNDLE_MAP_LOADER__!');
Expand Down
24 changes: 13 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,17 @@
"es6-object-assign": "1.1.0",
"express": "4.16.2",
"fast-async": "6.3.0",
"fusion-plugin-universal-events": "^0.3.0",
"fusion-tokens": "^0.0.5",
"get-port": "3.2.0",
"gzip-size": "4.1.0",
"iltorb": "2.0.3",
"imagemin": "5.3.1",
"imagemin-svgo": "6.0.0",
"istanbul-api": "1.2.1",
"istanbul-lib-coverage": "1.1.1",
"jest": "22.1.3",
"jest-cli": "22.1.3",
"jest": "22.1.4",
"jest-cli": "22.1.4",
"just-snake-case": "1.0.0",
"koa": "2.4.1",
"koa-mount": "3.0.0",
Expand All @@ -64,23 +66,23 @@
"path-is-absolute": "1.0.1",
"progress-bar-webpack-plugin": "1.10.0",
"range-parser": "1.2.0",
"react-dev-utils": "4.2.1",
"react-error-overlay": "3.0.0",
"react-dev-utils": "5.0.0",
"react-error-overlay": "4.0.0",
"react-hot-loader": "3.1.3",
"redbox-react": "1.5.0",
"request": "2.83.0",
"resolve-from": "4.0.0",
"rimraf": "2.6.2",
"source-map-explorer": "1.5.0",
"source-map-support": "0.5.1",
"source-map-support": "0.5.2",
"ua-parser-js": "0.7.17",
"uglifyjs-webpack-plugin": "1.1.6",
"unitest": "2.1.1",
"uuid": "3.2.1",
"webpack": "3.10.0",
"webpack-chunk-hash": "0.5.0",
"webpack-dev-middleware": "2.0.4",
"webpack-dev-server": "2.10.1",
"webpack-dev-server": "2.11.1",
"webpack-hot-middleware": "2.21.0",
"webpack-node-externals": "1.6.0",
"webpack-sources": "1.1.0",
Expand All @@ -98,11 +100,11 @@
"eslint-plugin-prettier": "2.5.0",
"eslint-plugin-react": "7.5.1",
"flow-bin": "0.63.1",
"fusion-core": "0.2.8",
"fusion-plugin-react-router": "0.2.3",
"fusion-react": "0.3.0",
"fusion-core": "0.3.0-5",
"fusion-plugin-react-router": "0.4.0",
"fusion-react": "0.4.1",
"fusion-react-async": "0.1.4",
"fusion-test-utils": "0.3.0",
"fusion-test-utils": "0.4.0",
"globby": "7.1.1",
"prettier": "1.10.2",
"react": "16.2.0",
Expand All @@ -114,7 +116,7 @@
},
"peerDependencies": {
"enzyme": "^3.3.0",
"fusion-core": "^0.2.7"
"fusion-core": "^0.3.0-5"
},
"engines": {
"node": ">= 8.9.0"
Expand Down
21 changes: 13 additions & 8 deletions plugins/assets-plugin.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
//@flow
/* eslint-env node */
const envVarsPlugin = require('./environment-variables-plugin');
const getEnv = require('./environment-variables-plugin');
const {createPlugin} = require('fusion-core');

const path = require('path');
const mount = require('koa-mount');
const serve = require('koa-static');

module.exports = function(dir /* : string */) {
const {assetPath, env} = envVarsPlugin().of();
// setting defer here tells the `serve` middleware to `await next` first before
// setting the response. This allows composition with user middleware
return mount(
assetPath,
serve(path.resolve(dir, `.fusion/dist/${env}/client`), {defer: true})
);
return createPlugin({
middleware: () => {
const {assetPath, env} = getEnv();
// setting defer here tells the `serve` middleware to `await next` first before
// setting the response. This allows composition with user middleware
return mount(
assetPath,
serve(path.resolve(dir, `.fusion/dist/${env}/client`), {defer: true})
);
},
});
};
24 changes: 9 additions & 15 deletions plugins/compilation-metadata-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,19 @@ This is where webpack-related things should be defined
*/

const path = require('path');
const {Plugin} = require('fusion-core');
const envVarsPlugin = require('./environment-variables-plugin');

const getEnv = require('./environment-variables-plugin');
// custom loaders: see build/compiler.js
// eslint-disable-next-line import/no-unresolved, import/no-extraneous-dependencies
const chunkUrlMap = require('__SECRET_BUNDLE_MAP_LOADER__!');
// eslint-disable-next-line import/no-unresolved, import/no-extraneous-dependencies
const syncChunks = require('__SECRET_SYNC_CHUNK_IDS_LOADER__!');

module.exports = function() {
const {prefix, assetPath, cdnUrl} = envVarsPlugin().of();
return new Plugin({
Service: class CompilationMetaData {
constructor() {
this.syncChunks = syncChunks;
this.preloadChunks = [];
this.chunkUrlMap = chunkUrlMap;
this.webpackPublicPath = cdnUrl || path.join(prefix, assetPath);
}
},
});
module.exports = () => {
const {prefix, assetPath, cdnUrl} = getEnv();
return {
syncChunks,
preloadChunks: [],
chunkUrlMap,
webpackPublicPath: cdnUrl || path.join(prefix, assetPath),
};
};
53 changes: 28 additions & 25 deletions plugins/context-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,37 @@
This is where new ctx properties should be initialized
*/

const envVarsPlugin = require('./environment-variables-plugin');
const compilationMetaDataPlugin = require('./compilation-metadata-plugin');
const getEnv = require('./environment-variables-plugin');
const getCompilationMetaData = require('./compilation-metadata-plugin');
const {createPlugin} = require('fusion-core');
const uuidv4 = require('uuid/v4');
const UAParser = require('ua-parser-js');

module.exports = function() {
const envVars = envVarsPlugin().of();
const compilationMetaData = compilationMetaDataPlugin().of();
return function middleware(ctx, next) {
// env vars
ctx.rootDir = envVars.rootDir;
ctx.env = envVars.env;
ctx.prefix = envVars.prefix;
ctx.assetPath = envVars.assetPath;
ctx.cdnUrl = envVars.cdnUrl;
module.exports = createPlugin({
middleware: () => {
const envVars = getEnv();
const compilationMetaData = getCompilationMetaData();
return function middleware(ctx, next) {
// env vars
ctx.rootDir = envVars.rootDir;
ctx.env = envVars.env;
ctx.prefix = envVars.prefix;
ctx.assetPath = envVars.assetPath;
ctx.cdnUrl = envVars.cdnUrl;

// webpack-related things
ctx.syncChunks = compilationMetaData.syncChunks;
ctx.preloadChunks = [];
ctx.chunkUrlMap = compilationMetaData.chunkUrlMap;
ctx.webpackPublicPath = compilationMetaData.webpackPublicPath;
// webpack-related things
ctx.syncChunks = compilationMetaData.syncChunks;
ctx.preloadChunks = [];
ctx.chunkUrlMap = compilationMetaData.chunkUrlMap;
ctx.webpackPublicPath = compilationMetaData.webpackPublicPath;

// fusion-specific things
ctx.nonce = uuidv4();
ctx.useragent = new UAParser(ctx.headers['user-agent']).getResult();
ctx.element = null;
ctx.rendered = null;
// fusion-specific things
ctx.nonce = uuidv4();
ctx.useragent = new UAParser(ctx.headers['user-agent']).getResult();
ctx.element = null;
ctx.rendered = null;

return next();
};
};
return next();
};
},
});
29 changes: 8 additions & 21 deletions plugins/environment-variables-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ This is where environment variables should be defined
*/

const assert = require('assert');
const {SingletonPlugin} = require('fusion-core');

const rootDir = load('ROOT_DIR', '.');
const env = load('NODE_ENV', 'development');
Expand All @@ -18,26 +17,14 @@ const assetPath = '/_static';
const cdnUrl = load('CDN_URL', '');
assert(!cdnUrl.endsWith('/'), 'ROUTE_PREFIX must not end with /');

module.exports = function() {
return new SingletonPlugin({
Service: class EnvVarPlugin {
/*::
rootDir: string;
env: 'development' | 'production';
prefix: string;
assetPath: string;
cdnUrl: string;
*/

constructor() {
this.rootDir = rootDir;
this.env = env;
this.prefix = prefix;
this.assetPath = assetPath;
this.cdnUrl = cdnUrl;
}
},
});
module.exports = () => {
return {
rootDir,
env,
prefix,
assetPath,
cdnUrl,
};
};

function load(key, value) {
Expand Down
22 changes: 12 additions & 10 deletions plugins/server-error-plugin.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
/* eslint-env node */

const renderError = require('../build/server-error').renderError;
const {createPlugin} = require('fusion-core');

module.exports = function() {
return async function middleware(ctx, next) {
try {
await next();
} catch (err) {
ctx.status = err.statusCode || err.status || 500;
ctx.body = renderError(err);
}
};
};
module.exports = createPlugin({
middleware: () =>
async function middleware(ctx, next) {
try {
await next();
} catch (err) {
ctx.status = err.statusCode || err.status || 500;
ctx.body = renderError(err);
}
},
});
5 changes: 2 additions & 3 deletions test/compiler/api.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-env node */

const fs = require('fs');
const path = require('path');
const test = require('tape');
Expand Down Expand Up @@ -54,7 +53,7 @@ test('development/production env globals', async t => {
const clientContent = await readFile(clientEntryPath, 'utf8');

const expectedClientBrowser = {
development: 'main __BROWSER__ is " + true',
development: `main __BROWSER__ is ' + true`,
production: 'main __BROWSER__ is "+!0',
};
t.ok(
Expand All @@ -63,7 +62,7 @@ test('development/production env globals', async t => {
);

const expectedClientNode = {
development: 'main __NODE__ is " + false',
development: `main __NODE__ is ' + false`,
production: 'main __NODE__ is "+!1',
};
t.ok(
Expand Down
2 changes: 1 addition & 1 deletion test/fixtures/assets/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import App from 'fusion-core';
import {assetUrl} from 'fusion-core';
export default async function() {
const app = new App('element', el => el);
__NODE__ && app.plugin(() => (ctx, next) => {
__NODE__ && app.middleware((ctx, next) => {
if (ctx.url.startsWith('/_static')) {
ctx.set('x-test', 'test');
} else if (ctx.url === '/test') {
Expand Down
6 changes: 2 additions & 4 deletions test/fixtures/custom-babel/src/main.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
console.log('helloworld');
import App from 'fusion-core';

export default async function() {
return {
plugins: [],
callback() {},
};
return new App('el', el => el);
}
16 changes: 7 additions & 9 deletions test/fixtures/noop-test/src/main.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
export default function() {
return {
plugins: [],
callback() {
console.log(`main __BROWSER__ is ${__BROWSER__}`);
console.log(`main __DEV__ is ${__DEV__}`);
console.log(`main __NODE__ is ${__NODE__}`);
},
};
import App from 'fusion-core';

export default async function() {
console.log(`main __BROWSER__ is ${__BROWSER__}`);
console.log(`main __DEV__ is ${__DEV__}`);
console.log(`main __NODE__ is ${__NODE__}`);
return new App('el', el => el);
}
Loading

0 comments on commit 9ee814a

Please sign in to comment.