Compare commits

...

39 Commits

Author SHA1 Message Date
Rich Harris
0fe93cd177 -> v0.0.19 2017-12-15 18:27:04 -05:00
Rich Harris
67fe570f6d dont try to prevent event where none exists 2017-12-15 18:26:55 -05:00
Rich Harris
a3d44aba31 -> v0.0.18 2017-12-15 17:20:36 -05:00
Rich Harris
80ae909b73 serve assets from memory, use caching 2017-12-15 17:20:24 -05:00
Rich Harris
892b18cf80 -> v0.0.17 2017-12-15 16:47:34 -05:00
Rich Harris
0eb96bf01f oops, remove logging 2017-12-15 16:47:29 -05:00
Rich Harris
419f5c5235 -> v0.0.16 2017-12-15 16:46:27 -05:00
Rich Harris
4c61ed5fdd better link click handling, track scroll position 2017-12-15 16:46:11 -05:00
Rich Harris
c19447cf05 -> v0.0.15 2017-12-15 15:29:30 -05:00
Rich Harris
cb2364f476 add noscript message (todo - make it configurable) 2017-12-15 15:29:08 -05:00
Rich Harris
de427d400e -> v0.0.14 2017-12-15 14:49:56 -05:00
Rich Harris
e810ead93f move files around 2017-12-15 14:46:23 -05:00
Rich Harris
f5a19ef34b tweak service worker stuff 2017-12-15 14:43:38 -05:00
Rich Harris
b8c03d330b refactor some webpack stuff, support service worker generation 2017-12-14 15:38:41 -05:00
Rich Harris
6e769496ec -> v0.0.13 2017-12-14 08:23:00 -05:00
Rich Harris
e46aceb2fe implement prefetching anchors with rel=prefetch 2017-12-14 08:21:32 -05:00
Rich Harris
a87cac2481 refactor some stuff 2017-12-14 07:53:17 -05:00
Rich Harris
608fdb7533 -> v0.0.12 2017-12-14 07:15:07 -05:00
Rich Harris
80166b5a7d -> v0.0.11 2017-12-14 07:12:01 -05:00
Rich Harris
24b259f80b fix location, so that runtime can be found from /tmp 2017-12-14 07:11:52 -05:00
Rich Harris
8a9f4bd268 -> v0.0.10 2017-12-14 07:07:47 -05:00
Rich Harris
d940da1a77 serve errors 2017-12-14 07:07:29 -05:00
Rich Harris
91269f5705 -> v0.0.9 2017-12-13 22:38:18 -05:00
Rich Harris
80a9818e95 dont assume error was caught 2017-12-13 22:38:09 -05:00
Rich Harris
478ccf53cc -> v0.0.8 2017-12-13 22:33:24 -05:00
Rich Harris
b32278e88b argh 2017-12-13 22:33:12 -05:00
Rich Harris
881d411db0 -> v0.0.7 2017-12-13 22:30:15 -05:00
Rich Harris
2a5786d7d7 -> v0.0.6 2017-12-13 22:22:03 -05:00
Rich Harris
8b89a5f27e make now-friendly 2017-12-13 22:21:55 -05:00
Rich Harris
d46a270cf0 remove requires 2017-12-13 22:11:28 -05:00
Rich Harris
72efde9515 -> v0.0.5 2017-12-13 22:08:29 -05:00
Rich Harris
7c0789cabf move webpack config out of sapper, into the app 2017-12-13 21:35:56 -05:00
Rich Harris
bffffe0035 detach SSRd <head> contents 2017-12-13 20:24:58 -05:00
Rich Harris
22d3cb2b1e serve 404 pages etc 2017-12-13 14:22:46 -05:00
Rich Harris
e1ed1896e6 easier templates 2017-12-13 14:14:06 -05:00
Rich Harris
6d4c26d15d server-side preloading, and critical CSS rendering 2017-12-13 13:30:27 -05:00
Rich Harris
941867f0a4 add client-side preloading logic, move router into runtime module 2017-12-13 13:29:38 -05:00
Rich Harris
c7e3fc4493 handle errors. (TODO: handle errors *nicely*) 2017-12-13 12:24:12 -05:00
Rich Harris
a8373c1568 always create valid route id 2017-12-13 12:23:49 -05:00
16 changed files with 525 additions and 352 deletions

View File

@@ -4,20 +4,21 @@ const fs = require('fs');
const path = require('path');
const glob = require('glob');
const rimraf = require('rimraf');
const create_routes = require('./utils/create_routes.js');
const create_app = require('./utils/create_app.js');
const create_webpack_compiler = require('./utils/create_webpack_compiler.js');
const mkdirp = require('mkdirp');
const create_routes = require('./lib/utils/create_routes.js');
const templates = require('./lib/templates.js');
const create_app = require('./lib/utils/create_app.js');
const create_compiler = require('./lib/utils/create_compiler.js');
const escape_html = require('escape-html');
const { src, dest, dev } = require('./lib/config.js');
const esmRequire = esm(module, {
esm: 'js'
});
module.exports = function connect(opts) {
const src = path.resolve('routes');
const dest = path.resolve(opts.tmpDir || '.sapper');
rimraf.sync(dest);
fs.mkdirSync(dest);
mkdirp(dest);
rimraf.sync(path.join(dest, '**/*'));
let routes = create_routes(
glob.sync('**/*.+(html|js|mjs)', { cwd: src })
@@ -25,69 +26,110 @@ module.exports = function connect(opts) {
create_app(src, dest, routes, opts);
const webpack_compiler = create_webpack_compiler(
const compiler = create_compiler(
dest,
routes,
opts.dev
dev
);
return async function(req, res, next) {
const url = req.url.replace(/\?.+/, '');
if (url.startsWith('/client/')) {
fs.createReadStream(`${dest}${url}`).pipe(res);
return;
if (url === '/service-worker.js') {
await compiler.ready;
res.set({
'Content-Type': 'application/javascript',
'Cache-Control': 'max-age=600'
});
res.end(compiler.service_worker);
}
for (const route of routes) {
if (route.test(url)) {
req.params = route.exec(url);
else if (url === '/index.html') {
await compiler.ready;
res.set({
'Content-Type': 'text/html',
'Cache-Control': 'max-age=600'
});
res.end(compiler.shell);
}
const chunk = await webpack_compiler.get_chunk(route.id);
const mod = require(chunk);
else if (url.startsWith('/client/')) {
await compiler.ready;
res.set({
'Content-Type': 'application/javascript',
'Cache-Control': 'max-age=31536000'
});
res.end(compiler.asset_cache[url]);
}
if (route.type === 'page') {
const main = await webpack_compiler.client_main;
else {
// whatever happens, we're going to serve some HTML
res.set({
'Content-Type': 'text/html'
});
const page = opts.template({
main,
html: mod.default.render({
params: req.params,
query: req.query
})
});
try {
for (const route of routes) {
if (route.test(url)) {
await compiler.ready;
res.status(200);
res.set({
// TODO etag stuff
'Content-Length': page.length,
'Content-Type': 'text/html'
});
res.end(page);
}
req.params = route.exec(url);
else {
const handler = mod[req.method.toLowerCase()];
if (handler) {
if (handler.length === 2) {
handler(req, res);
} else {
const data = await handler(req);
const chunk = compiler.chunks[route.id];
const mod = require(path.resolve(dest, 'server', chunk));
// TODO headers, error handling
if (typeof data === 'string') {
res.end(data);
if (route.type === 'page') {
let data = { params: req.params, query: req.query };
if (mod.default.preload) data = Object.assign(data, await mod.default.preload(data));
const { html, head, css } = mod.default.render(data);
const page = templates.render(200, {
main: compiler.client_main,
html,
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
styles: (css && css.code ? `<style>${css.code}</style>` : '')
});
res.status(200);
res.end(page);
}
else {
const handler = mod[req.method.toLowerCase()];
if (handler) {
if (handler.length === 2) {
handler(req, res);
} else {
res.end(JSON.stringify(data));
const data = await handler(req);
// TODO headers, error handling
if (typeof data === 'string') {
res.end(data);
} else {
res.end(JSON.stringify(data));
}
}
}
}
return;
}
}
return;
res.status(404).end(templates.render(404, {
title: 'Not found',
status: 404,
method: req.method,
url
}));
} catch(err) {
res.status(500).end(templates.render(500, {
title: err.name || 'Internal server error',
url,
error: escape_html(err.details || err.message || err || 'Unknown error')
}));
}
}
next();
};
};

12
lib/config.js Normal file
View File

@@ -0,0 +1,12 @@
const path = require('path');
exports.dev = process.env.NODE_ENV !== 'production';
exports.templates = path.resolve(process.env.SAPPER_TEMPLATES || 'templates');
exports.src = path.resolve(process.env.SAPPER_ROUTES || 'routes');
exports.dest = path.resolve(
process.env.NOW ? '/tmp' :
process.env.SAPPER_DEST || '.sapper'
);

16
lib/route_manager.js Normal file
View File

@@ -0,0 +1,16 @@
const glob = require('glob');
const create_routes = require('./utils/create_routes.js');
const { src } = require('./config.js');
const route_manager = {
routes: create_routes(
glob.sync('**/*.+(html|js|mjs)', { cwd: src })
),
onchange(fn) {
// TODO in dev mode, keep this updated, and allow
// webpack compiler etc to hook into it
}
};
module.exports = route_manager;

43
lib/templates.js Normal file
View File

@@ -0,0 +1,43 @@
const fs = require('fs');
const glob = require('glob');
const templates = glob.sync('*.html', { cwd: 'templates' })
.map(file => {
const template = fs.readFileSync(`templates/${file}`, 'utf-8');
const status = file.replace('.html', '').toLowerCase();
if (!/^[0-9x]{3}$/.test(status)) {
throw new Error(`Bad template — should be a valid status code like 404.html, or a wildcard like 2xx.html`);
}
const specificity = (
(status[0] === 'x' ? 0 : 4) +
(status[1] === 'x' ? 0 : 2) +
(status[2] === 'x' ? 0 : 1)
);
const pattern = new RegExp(`^${status.split('').map(d => d === 'x' ? '\\d' : d).join('')}$`);
return {
test: status => pattern.test(status),
specificity,
render(data) {
return template.replace(/%sapper\.(\w+)%/g, (match, key) => {
return key in data ? data[key] : '';
});
}
}
})
.sort((a, b) => b.specificity - a.specificity);
exports.render = (status, data) => {
const template = templates.find(template => template.test(status));
if (template) return template.render(data);
return `Missing template for status code ${status}`;
};
exports.onchange = fn => {
// TODO in dev mode, keep this updated, and allow
// webpack compiler etc to hook into it
};

26
lib/utils/create_app.js Normal file
View File

@@ -0,0 +1,26 @@
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.resolve(__dirname, '../../templates/main.js'), 'utf-8');
module.exports = function create_app(src, dest, routes, options) {
// TODO in dev mode, watch files
const code = routes
.filter(route => route.type === 'page')
.map(route => {
const params = route.dynamic.length === 0 ?
'{}' :
`{ ${route.dynamic.map((part, i) => `${part}: match[${i + 1}]`).join(', ') } }`;
return `{ pattern: ${route.pattern}, params: match => (${params}), load: () => import(/* webpackChunkName: "${route.id}" */ '${src}/${route.file}') }`
})
.join(',\n\t');
const main = template
.replace('__app__', path.resolve(__dirname, '../../runtime/app.js'))
.replace('__selector__', options.selector || 'main')
.replace('__routes__', code);
fs.writeFileSync(path.join(dest, 'main.js'), main);
};

View File

@@ -0,0 +1,104 @@
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const templates = require('../templates.js');
module.exports = function create_webpack_compiler(dest, routes, dev) {
const compiler = {};
const client = webpack(
require(path.resolve('webpack.client.config.js'))
);
const server = webpack(
require(path.resolve('webpack.server.config.js'))
);
if (false) { // TODO watch in dev
// TODO how can we invalidate compiler.client_main when watcher restarts?
compiler.client_main = new Promise((fulfil, reject) => {
client.watch({}, (err, stats) => {
if (err || stats.hasErrors()) {
// TODO handle errors
}
const filename = stats.toJson().assetsByChunkName.main;
fulfil(`/client/${filename}`);
});
});
// TODO server
} else {
compiler.ready = Promise.all([
new Promise((fulfil, reject) => {
client.run((err, stats) => {
console.log(stats.toString({ colors: true }));
const info = stats.toJson();
if (err || stats.hasErrors()) {
reject(err || info.errors[0]);
}
compiler.client_main = `/client/${info.assetsByChunkName.main}`;
compiler.assets = info.assets.map(asset => `/client/${asset.name}`);
compiler.asset_cache = {};
compiler.assets.forEach(file => {
compiler.asset_cache[file] = fs.readFileSync(path.join(dest, file), 'utf-8');
});
fulfil();
});
}),
new Promise((fulfil, reject) => {
server.run((err, stats) => {
console.log(stats.toString({ colors: true }));
const info = stats.toJson();
if (err || stats.hasErrors()) {
reject(err || info.errors[0]);
}
compiler.chunks = info.assetsByChunkName;
fulfil();
});
})
]).then(() => {
const assets = glob.sync('**', { cwd: 'assets' });
const route_code = `[${
routes
.filter(route => route.type === 'page')
.map(route => `{ pattern: ${route.pattern} }`)
.join(', ')
}]`;
compiler.service_worker = fs.readFileSync('templates/service-worker.js', 'utf-8')
.replace('__timestamp__', Date.now())
.replace('__assets__', JSON.stringify(assets))
.replace('__shell__', JSON.stringify(compiler.assets.concat('/index.html')))
.replace('__routes__', route_code);
compiler.shell = templates.render(200, {
styles: '',
head: '',
html: '<noscript>Please enable JavaScript!</noscript>',
main: compiler.client_main
});
// useful for debugging, but the files are served from memory
fs.writeFileSync(path.resolve(dest, 'service-worker.js'), compiler.service_worker);
fs.writeFileSync(path.resolve(dest, 'index.html'), compiler.shell);
});
compiler.get_chunk = async id => {
return path.resolve(dest, 'server', compiler.chunks[id]);
};
}
return compiler;
};

View File

@@ -8,7 +8,7 @@ module.exports = function create_matchers(files) {
const parts = file.replace(/\.(html|js|mjs)$/, '').split(path.sep);
if (parts[parts.length - 1] === 'index') parts.pop();
const id = parts.join('_').replace(/[[\]]/g, '$');
const id = parts.join('_').replace(/[[\]]/g, '$') || '_';
const dynamic = parts
.filter(part => part[0] === '[')

53
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{
"name": "sapper",
"version": "0.0.3",
"version": "0.0.9",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -578,6 +578,11 @@
"es6-symbol": "3.1.1"
}
},
"escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"escape-string-regexp": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
@@ -670,18 +675,6 @@
"is-extglob": "1.0.0"
}
},
"extract-text-webpack-plugin": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extract-text-webpack-plugin/-/extract-text-webpack-plugin-3.0.2.tgz",
"integrity": "sha512-bt/LZ4m5Rqt/Crl2HiKuAl/oqg0psx1tsTLkvWbJen1CtD+fftkZhMaQ9HOtY2gWsl2Wq+sABmMVi9z3DhKWQQ==",
"dev": true,
"requires": {
"async": "2.6.0",
"loader-utils": "1.1.0",
"schema-utils": "0.3.0",
"webpack-sources": "1.1.0"
}
},
"fast-deep-equal": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz",
@@ -2095,12 +2088,6 @@
"mem": "1.1.0"
}
},
"os-tmpdir": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
"integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=",
"dev": true
},
"p-finally": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
@@ -2413,15 +2400,6 @@
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz",
"integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg=="
},
"schema-utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.3.0.tgz",
"integrity": "sha1-9YdyIs4+kx7a4DnxfrNxbnE3+M8=",
"dev": true,
"requires": {
"ajv": "5.5.1"
}
},
"semver": {
"version": "5.4.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz",
@@ -2587,16 +2565,6 @@
"integrity": "sha512-xRw4pjF19XKfeTxp+TOTE/MQmRS7tRzm0hhh0dr/nc3NuHBfCBXnfve0ZymF8tZ+J/WM0cqfZ83RxZid2zf7qA==",
"dev": true
},
"svelte-loader": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/svelte-loader/-/svelte-loader-2.2.1.tgz",
"integrity": "sha512-SNdEPwLpoWqKMk5wjJUVd7LUFK9rQoMPxQ8uJoszWSgTpbYICSnxFCEDvhDvcHbmAFSOOXnoJAdvoCTnBw3+kg==",
"dev": true,
"requires": {
"loader-utils": "1.1.0",
"tmp": "0.0.31"
}
},
"tapable": {
"version": "0.2.8",
"resolved": "https://registry.npmjs.org/tapable/-/tapable-0.2.8.tgz",
@@ -2610,15 +2578,6 @@
"setimmediate": "1.0.5"
}
},
"tmp": {
"version": "0.0.31",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.31.tgz",
"integrity": "sha1-jzirlDjhcxXl29izZX6L+yd65Kc=",
"dev": true,
"requires": {
"os-tmpdir": "1.0.2"
}
},
"to-arraybuffer": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "sapper",
"version": "0.0.4",
"version": "0.0.19",
"description": "Combat-ready apps, engineered by Svelte",
"main": "connect.js",
"directories": {
@@ -8,19 +8,17 @@
},
"dependencies": {
"@std/esm": "^0.18.0",
"escape-html": "^1.0.3",
"mkdirp": "^0.5.1",
"rimraf": "^2.6.2",
"webpack": "^3.10.0"
},
"devDependencies": {
"extract-text-webpack-plugin": "^3.0.2",
"mocha": "^4.0.1",
"svelte": "^1.47.1",
"svelte-loader": "^2.2.1"
"svelte": "^1.47.1"
},
"peerDependencies": {
"extract-text-webpack-plugin": "^3.0.2",
"svelte": "^1.47.1",
"svelte-loader": "^2.2.1"
"svelte": "^1.47.1"
},
"scripts": {
"test": "mocha --opts mocha.opts"

170
runtime/app.js Normal file
View File

@@ -0,0 +1,170 @@
const detach = node => {
node.parentNode.removeChild(node);
};
let component;
const scroll_history = {};
let uid = 1;
let cid;
window.scroll_history = scroll_history;
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual'
}
const app = {
init(target, routes) {
function select_route(url) {
if (url.origin !== window.location.origin) return null;
for (const route of routes) {
const match = route.pattern.exec(url.pathname);
if (match) {
const params = route.params(match);
const query = {};
for (const [key, value] of url.searchParams) query[key] = value || true;
return { route, data: { params, query } };
}
}
}
function render(Component, data, scroll) {
Promise.resolve(
Component.preload ? Component.preload(data) : {}
).then(preloaded => {
if (component) {
component.destroy();
} else {
// first load — remove SSR'd <head> contents
const start = document.querySelector('#sapper-head-start');
let end = document.querySelector('#sapper-head-end');
if (start && end) {
while (start.nextSibling !== end) detach(start.nextSibling);
detach(start);
detach(end);
}
// preload additional routes
routes.reduce((promise, route) => promise.then(route.load), Promise.resolve());
}
component = new Component({
target,
data: Object.assign(data, preloaded),
hydrate: !!component
});
window.scrollTo(scroll.x, scroll.y);
});
}
function navigate(url, id) {
const selected = select_route(url);
if (selected) {
if (id) {
// popstate or initial navigation
cid = id;
} else {
// clicked on a link. preserve scroll state
scroll_history[cid] = scroll_state();
id = cid = ++uid;
scroll_history[cid] = { x: 0, y: 0 };
history.pushState({ id }, '', url.href);
}
selected.route.load().then(mod => {
render(mod.default, selected.data, scroll_history[id]);
});
cid = id;
return true;
}
}
function findAnchor(node) {
while (node && node.nodeName.toUpperCase() !== 'A') node = node.parentNode; // SVG <a> elements have a lowercase name
return node;
}
window.addEventListener('click', event => {
// Adapted from https://github.com/visionmedia/page.js
// MIT license https://github.com/visionmedia/page.js#license
if (which(event) !== 1) return;
if (event.metaKey || event.ctrlKey || event.shiftKey) return;
if (event.defaultPrevented) return;
const a = findAnchor(event.target);
if (!a) return;
event.preventDefault();
// check if link is inside an svg
// in this case, both href and target are always inside an object
const svg = typeof a.href === 'object' && a.href.constructor.name === 'SVGAnimatedString';
const href = svg ? a.href.baseVal : a.href;
// Ignore if tag has
// 1. 'download' attribute
// 2. rel='external' attribute
if (a.hasAttribute('download') || a.getAttribute('rel') === 'external') return;
// Ignore if <a> has a target
if (svg ? a.target.baseVal : a.target) return;
const scroll = scroll_state();
if (navigate(new URL(a.href), null)) {
event.preventDefault();
}
});
function preload(event) {
const a = findAnchor(event.target);
if (!a || a.rel !== 'prefetch') return;
const selected = select_route(new URL(a.href));
if (selected) {
selected.route.load().then(mod => {
if (mod.default.preload) mod.default.preload(selected.data);
});
}
}
window.addEventListener('touchstart', preload);
window.addEventListener('mouseover', preload);
window.addEventListener('popstate', event => {
if (!event.state) return; // hashchange, or otherwise outside sapper's control
scroll_history[cid] = scroll_state();
navigate(new URL(window.location), event.state.id);
});
const scroll = scroll_history[uid] = scroll_state();
history.replaceState({ id: uid }, '', window.location.href);
navigate(new URL(window.location), uid);
}
};
function which(event) {
event = event || window.event;
return event.which === null ? event.button : event.which;
}
function scroll_state() {
return {
x: window.scrollX,
y: window.scrollY
};
}
export default app;

View File

@@ -1,45 +1,5 @@
window.addEventListener('click', event => {
let a = event.target;
while (a && a.nodeName !== 'A') a = a.parentNode;
if (!a) return;
import app from '__app__';
if (navigate(new URL(a.href))) {
event.preventDefault();
history.pushState({}, '', a.href);
}
});
window.addEventListener('popstate', event => {
navigate(window.location);
});
const target = document.querySelector('__selector__');
let component;
function navigate(url) {
if (url.origin !== window.location.origin) return;
let match;
let params = {};
const query = {};
function render(mod) {
if (component) {
component.destroy();
} else {
target.innerHTML = '';
}
component = new mod.default({
target,
data: { query, params },
hydrate: !!component
});
}
// ROUTES
return true;
}
navigate(window.location);
app.init(document.querySelector('__selector__'), [
__routes__
]);

View File

@@ -1,41 +0,0 @@
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.resolve(__dirname, '../templates/main.js'), 'utf-8');
module.exports = function create_app(src, dest, routes, options) {
// TODO in dev mode, watch files
const code = routes
.filter(route => route.type === 'page')
.map(route => {
const condition = route.dynamic.length === 0 ?
`url.pathname === '/${route.parts.join('/')}'` :
`match = ${route.pattern}.exec(url.pathname)`;
const lines = [];
route.dynamic.forEach((part, i) => {
lines.push(
`params.${part} = match[${i + 1}];`
);
});
lines.push(
`import('${src}/${route.file}').then(render);`
);
return `
if (${condition}) {
${lines.join(`\n\t\t\t\t\t`)}
}
`.replace(/^\t{3}/gm, '').trim();
})
.join(' else ') + ' else return false;';
const main = template
.replace('__selector__', options.selector || 'main')
.replace('// ROUTES', code);
fs.writeFileSync(path.join(dest, 'main.js'), main);
};

View File

@@ -1,138 +0,0 @@
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
// TODO make the webpack config, err, configurable
module.exports = function create_webpack_compiler(out, routes, dev) {
const compiler = {};
const client = webpack({
entry: {
main: `${out}/main`
},
resolve: {
extensions: ['.js', '.html']
},
output: {
path: `${out}/client`,
filename: '[name].[hash].js',
chunkFilename: '[name].[id].js',
publicPath: '/client/'
},
module: {
rules: [
{
test: /\.html$/,
exclude: /node_modules/,
use: {
loader: 'svelte-loader',
options: {
emitCss: true,
cascade: false,
store: true
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [{ loader: 'css-loader', options: { sourceMap: dev } }]
})
}
]
},
plugins: [
new ExtractTextPlugin('main.css'),
!dev && new webpack.optimize.ModuleConcatenationPlugin(),
!dev && new UglifyJSPlugin()
].filter(Boolean),
devtool: dev ? 'inline-source-map' : false
});
const server_entries = {};
routes.forEach(route => {
server_entries[route.id] = path.resolve('routes', route.file);
});
const server = webpack({
entry: server_entries,
target: 'node',
resolve: {
extensions: ['.js', '.html']
},
output: {
path: `${out}/server`,
filename: '[name].[hash].js',
chunkFilename: '[name].[id].js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.html$/,
exclude: /node_modules/,
use: {
loader: 'svelte-loader',
options: {
css: false,
cascade: false,
store: true,
generate: 'ssr'
}
}
}
]
}
});
if (false) { // TODO watch in dev
// TODO how can we invalidate compiler.client_main when watcher restarts?
compiler.client_main = new Promise((fulfil, reject) => {
client.watch({}, (err, stats) => {
if (err || stats.hasErrors()) {
// TODO handle errors
}
const filename = stats.toJson().assetsByChunkName.main;
fulfil(`/client/${filename}`);
});
});
// TODO server
} else {
compiler.client_main = new Promise((fulfil, reject) => {
client.run((err, stats) => {
if (err || stats.hasErrors()) {
console.log(stats.toString());
reject(err);
}
const filename = stats.toJson().assetsByChunkName.main;
fulfil(`/client/${filename}`);
});
});
const chunks = new Promise((fulfil, reject) => {
server.run((err, stats) => {
if (err || stats.hasErrors()) {
// TODO deal with hasErrors
console.log(stats.toString());
reject(err);
}
fulfil(stats.toJson().assetsByChunkName);
});
});
compiler.get_chunk = async id => {
const assetsByChunkName = await chunks;
return path.resolve(out, 'server', assetsByChunkName[id]);
};
}
return compiler;
};

43
webpack/config.js Normal file
View File

@@ -0,0 +1,43 @@
const path = require('path');
const route_manager = require('../lib/route_manager.js');
const { src, dest, dev } = require('../lib/config.js');
module.exports = {
dev,
client: {
entry: () => {
return {
main: `${dest}/main.js`
};
},
output: () => {
return {
path: `${dest}/client`,
filename: '[name].[hash].js',
chunkFilename: '[name].[id].[hash].js',
publicPath: '/client/'
};
}
},
server: {
entry: () => {
const entries = {};
route_manager.routes.forEach(route => {
entries[route.id] = path.resolve(src, route.file);
});
return entries;
},
output: () => {
return {
path: `${dest}/server`,
filename: '[name].[hash].js',
chunkFilename: '[name].[id].[hash].js',
libraryTarget: 'commonjs2'
};
}
}
};

View File

@@ -35,7 +35,7 @@ ajv@^4.9.1:
co "^4.6.0"
json-stable-stringify "^1.0.1"
ajv@^5.0.0, ajv@^5.1.5:
ajv@^5.1.5:
version "5.5.1"
resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.5.1.tgz#b38bb8876d9e86bee994956a04e721e88b248eb2"
dependencies:
@@ -122,7 +122,7 @@ async-each@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.1.tgz#19d386a1d9edc6e7c1c85d388aedbcc56d33602d"
async@^2.1.2, async@^2.4.1:
async@^2.1.2:
version "2.6.0"
resolved "https://registry.yarnpkg.com/async/-/async-2.6.0.tgz#61a29abb6fcc026fea77e56d1c6ec53a795951f4"
dependencies:
@@ -669,15 +669,6 @@ extglob@^0.3.1:
dependencies:
is-extglob "^1.0.0"
extract-text-webpack-plugin@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/extract-text-webpack-plugin/-/extract-text-webpack-plugin-3.0.2.tgz#5f043eaa02f9750a9258b78c0a6e0dc1408fb2f7"
dependencies:
async "^2.4.1"
loader-utils "^1.1.0"
schema-utils "^0.3.0"
webpack-sources "^1.0.1"
extsprintf@1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05"
@@ -1378,7 +1369,7 @@ os-locale@^2.0.0:
lcid "^1.0.0"
mem "^1.1.0"
os-tmpdir@^1.0.0, os-tmpdir@~1.0.2:
os-tmpdir@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274"
@@ -1646,7 +1637,7 @@ right-align@^0.1.1:
dependencies:
align-text "^0.1.1"
rimraf@2, rimraf@^2.5.1, rimraf@^2.6.1:
rimraf@2, rimraf@^2.5.1, rimraf@^2.6.1, rimraf@^2.6.2:
version "2.6.2"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36"
dependencies:
@@ -1663,12 +1654,6 @@ safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@~5.1.0,
version "5.1.1"
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853"
schema-utils@^0.3.0:
version "0.3.0"
resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-0.3.0.tgz#f5877222ce3e931edae039f17eb3716e7137f8cf"
dependencies:
ajv "^5.0.0"
"semver@2 || 3 || 4 || 5", semver@^5.3.0:
version "5.4.1"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.4.1.tgz#e059c09d8571f0540823733433505d3a2f00b18e"
@@ -1865,12 +1850,6 @@ timers-browserify@^2.0.4:
dependencies:
setimmediate "^1.0.4"
tmp@0.0.33:
version "0.0.33"
resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9"
dependencies:
os-tmpdir "~1.0.2"
to-arraybuffer@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz#7d229b1fcc637e466ca081180836a7aabff83f43"