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

feat: support pre-compressed-assets #100

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"extends": "hexo",
"root": true
}
}
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ server:
cache: false
header: true
serveStatic:
extensions:
- html
Comment on lines -41 to -42
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed as they are not the default. User can always refer to https://github.com/expressjs/serve-static#options.

pre_compressed: false
```

- **port**: Server port
Expand All @@ -51,6 +50,7 @@ server:
- Suitable for production environment only.
- **header**: Add `X-Powered-By: Hexo` header
- **serveStatic**: Extra options passed to [serve-static](https://github.com/expressjs/serve-static#options)
- **pre_compressed**: Serve pre-compressed assets, requires a [minifier plugin](https://hexo.io/plugins/) that supports gzip or brotli

## License

Expand Down
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ hexo.config.server = Object.assign({
// `undefined` uses Node's default (try `::` with fallback to `0.0.0.0`)
ip: undefined,
compress: false,
header: true
header: true,
pre_compressed: false
}, hexo.config.server);

hexo.extend.console.register('server', 'Start the server.', {
Expand All @@ -23,6 +24,7 @@ hexo.extend.console.register('server', 'Start the server.', {
}, require('./lib/server'));

hexo.extend.filter.register('server_middleware', require('./lib/middlewares/header'));
hexo.extend.filter.register('server_middleware', require('./lib/middlewares/pre_compressed'));
hexo.extend.filter.register('server_middleware', require('./lib/middlewares/gzip'));
hexo.extend.filter.register('server_middleware', require('./lib/middlewares/logger'));
hexo.extend.filter.register('server_middleware', require('./lib/middlewares/route'));
Expand Down
60 changes: 60 additions & 0 deletions lib/middlewares/pre_compressed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'use strict';

const { getType } = require('mime');

module.exports = function(app) {
const { config, route } = this;
const { root } = config;
const { pretty_urls } = config;
const { trailing_index, trailing_html } = pretty_urls ? pretty_urls : {};

if (!config.server.pre_compressed) return;

app.use(root, (req, res, next) => {
const { headers, method, url: requestUrl } = req;
const acceptEncoding = headers['accept-encoding'] || '';
const vary = res.getHeader('Vary');
const url = route.format(decodeURIComponent(requestUrl));
const data = route.get(url);

if (method !== 'GET' && method !== 'HEAD') return next();

const preFn = (acceptEncoding, url, req, res) => {
res.setHeader('Content-Type', getType(url) + '; charset=utf-8');

if (acceptEncoding.includes('br') && route.get(url + '.br')) {
req.url = encodeURI('/' + url + '.br');
res.setHeader('Content-Encoding', 'br');
} else if (acceptEncoding.includes('gzip') && route.get(url + '.gz')) {
req.url = encodeURI('/' + url + '.gz');
res.setHeader('Content-Encoding', 'gzip');
}
};

if (data) {
if ((trailing_html === false && !requestUrl.endsWith('/index.html') && requestUrl.endsWith('.html')) || (trailing_index === false && requestUrl.endsWith('/index.html'))) {
// location `foo/bar.html`; request `foo/bar.html`; redirect to `foo/bar`
// location `foo/index.html`; request `foo/index.html`; redirect to `foo/`
return next();
}
// location `foo/bar/index.html`; request `foo/bar/` or `foo/bar/index.html; proxy to the location
// also applies to non-html
preFn(acceptEncoding, url, req, res);
} else {
if (route.get(url + '.html')) {
// location `foo/bar.html`; request `foo/bar`; proxy to the `foo/bar.html.br`
preFn(acceptEncoding, url + '.html', req, res);
} else {
return next();
}
}

if (!vary) {
res.setHeader('Vary', 'Accept-Encoding');
} else if (!vary.includes('Accept-Encoding')) {
res.setHeader('Vary', vary + ', Accept-Encoding');
}

return next();
});
};
7 changes: 5 additions & 2 deletions lib/middlewares/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ const mime = require('mime');
module.exports = function(app) {
const { config, route } = this;
const { args = {} } = this.env;
const { root } = config;
const { root, server } = config;
const preCompressed = server.pre_compressed ? server.pre_compressed : false;

if (args.s || args.static) return;

Expand Down Expand Up @@ -63,7 +64,9 @@ module.exports = function(app) {
return;
}

res.setHeader('Content-Type', extname ? mime.getType(extname) : 'application/octet-stream');
if (!preCompressed || (!req.url.endsWith('.br') && !req.url.endsWith('.gz'))) {
res.setHeader('Content-Type', extname ? mime.getType(extname) : 'application/octet-stream');
}

if (method === 'GET') {
data.pipe(res).on('error', next);
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"eslint": "^7.0.0",
"eslint-config-hexo": "^4.0.0",
"eslint-config-hexo": "^4.1.0",
"hexo": "^5.0.0",
"hexo-fs": "^3.0.1",
"hexo-util": "^2.1.0",
Expand Down
80 changes: 79 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,24 @@ describe('server', () => {

// Register fake generator
hexo.extend.generator.register('test', () => [
{path: '', data: 'index'},
{path: 'index.html', data: 'index'},
{path: 'foo/index.html', data: 'foo'},
{path: 'foo/index.html.gz', data: 'foo'},
{path: 'bar/baz.html', data: 'baz'},
{path: 'bar.jpg', data: 'bar'}
{path: 'bar/baz.html.gz', data: 'baz'},
{path: 'bar.jpg', data: 'bar'},
{path: 'foo/', data: 'foo'},
{path: 'foo bar.js', data: 'file'},
{path: 'foo bar.js.gz', data: ''},
{path: 'foo bar.js.br', data: ''},
{path: 'foo/index.html.br', data: ''},
{path: 'foo/index.html.gz', data: ''}
]);

// Register middlewares
hexo.extend.filter.register('server_middleware', require('../lib/middlewares/header'));
hexo.extend.filter.register('server_middleware', require('../lib/middlewares/pre_compressed'));
hexo.extend.filter.register('server_middleware', require('../lib/middlewares/gzip'));
hexo.extend.filter.register('server_middleware', require('../lib/middlewares/logger'));
hexo.extend.filter.register('server_middleware', require('../lib/middlewares/route'));
Expand Down Expand Up @@ -102,6 +112,74 @@ describe('server', () => {
.expect('Content-Type', 'image/jpeg')
.expect(200)));

describe('options.pre_compressed', () => {
beforeEach(() => { hexo.config.server.pre_compressed = false; });

it('Serve brotli (br) if supported', async () => {
hexo.config.server.pre_compressed = true;

await Promise.using(
prepareServer(),
app => request(app)
.get('/foo%20bar.js')
.set('Accept-Encoding', 'gzip, br')
.expect('Content-Encoding', 'br')
.expect('Content-Type', 'application/javascript; charset=utf-8')
);
});

it('Serve gzip if br is not supported', async () => {
hexo.config.server.pre_compressed = true;

return Promise.using(
prepareServer(),
app => request(app)
.get('/foo%20bar.js')
.set('Accept-Encoding', 'gzip')
.expect('Content-Encoding', 'gzip')
.expect('Content-Type', 'application/javascript; charset=utf-8')
);
});

it('Disable', async () => {
hexo.config.server.pre_compressed = false;

await Promise.using(
prepareServer(),
app => request(app)
.get('/foo%20bar.js')
.set('Accept-Encoding', 'gzip, br')
.then(res => {
res.headers.should.not.have.property('Content-Encoding');
})
);
});

it('route / to /index.html.br', async () => {
hexo.config.server.pre_compressed = true;

await Promise.using(
prepareServer(),
app => request(app)
.get('/foo/')
.set('Accept-Encoding', 'gzip, br')
.expect('Content-Encoding', 'br')
);
});

it('route / to /index.html.gz', async () => {
hexo.config.server.pre_compressed = true;

await Promise.using(
prepareServer(),
app => request(app)
.get('/foo/')
.set('Accept-Encoding', 'gzip')
.expect('Content-Encoding', 'gzip')
);
});
});

it('Enable compression if options.compress is true', () => {
hexo.config.server.compress = true;

Expand Down